Changeset 2e9b59b for doc/theses
- Timestamp:
- Apr 19, 2022, 3:00:04 PM (3 years ago)
- Branches:
- ADT, ast-experimental, master, pthread-emulation, qualifiedEnum
- Children:
- 5b84a321
- Parents:
- ba897d21 (diff), bb7c77d (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the(diff)
links above to see all the changes relative to each parent. - Location:
- doc/theses
- Files:
-
- 39 added
- 19 edited
Legend:
- Unmodified
- Added
- Removed
-
doc/theses/mubeen_zulfiqar_MMath/Makefile
rba897d21 r2e9b59b 1 # directory for latex clutter files 1 # Configuration variables 2 2 3 Build = build 3 4 Figures = figures 4 5 Pictures = pictures 6 7 LaTMac = ../../LaTeXmacros 8 BibRep = ../../bibliography 9 5 10 TeXSRC = ${wildcard *.tex} 6 11 FigSRC = ${notdir ${wildcard ${Figures}/*.fig}} 7 12 PicSRC = ${notdir ${wildcard ${Pictures}/*.fig}} 8 BIBSRC = ${wildcard *.bib} 9 TeXLIB = .:../../LaTeXmacros:${Build}: # common latex macros 10 BibLIB = .:../../bibliography # common citation repository 13 BibSRC = ${wildcard *.bib} 14 15 TeXLIB = .:${LaTMac}:${Build}: 16 BibLIB = .:${BibRep}: 11 17 12 18 MAKEFLAGS = --no-print-directory # --silent 13 19 VPATH = ${Build} ${Figures} ${Pictures} # extra search path for file names used in document 14 20 15 ### Special Rules: 21 DOCUMENT = uw-ethesis.pdf 22 BASE = ${basename ${DOCUMENT}} # remove suffix 16 23 17 .PHONY: all clean 18 .PRECIOUS: %.dvi %.ps # do not delete intermediate files 19 20 ### Commands: 24 # Commands 21 25 22 26 LaTeX = TEXINPUTS=${TeXLIB} && export TEXINPUTS && latex -halt-on-error -output-directory=${Build} 23 BibTeX = BIBINPUTS=${BibLIB} bibtex27 BibTeX = BIBINPUTS=${BibLIB} && export BIBINPUTS && bibtex 24 28 #Glossary = INDEXSTYLE=${Build} makeglossaries-lite 25 29 26 # ## Rules and Recipes:30 # Rules and Recipes 27 31 28 DOC = uw-ethesis.pdf 29 BASE = ${DOC:%.pdf=%} # remove suffix 32 .PHONY : all clean # not file names 33 .PRECIOUS: %.dvi %.ps # do not delete intermediate files 34 .ONESHELL : 30 35 31 all : ${DOC}36 all : ${DOCUMENT} 32 37 33 clean :34 @rm -frv ${DOC } ${Build}38 clean : 39 @rm -frv ${DOCUMENT} ${Build} 35 40 36 # File Dependencies #41 # File Dependencies 37 42 38 ${Build}/%.dvi : ${TeXSRC} ${FigSRC:%.fig=%.tex} ${PicSRC:%.fig=%.pstex} ${BIBSRC}Makefile | ${Build}43 %.dvi : ${TeXSRC} ${FigSRC:%.fig=%.tex} ${PicSRC:%.fig=%.pstex} ${BibSRC} ${BibRep}/pl.bib ${LaTMac}/common.tex Makefile | ${Build} 39 44 ${LaTeX} ${BASE} 40 45 ${BibTeX} ${Build}/${BASE} 41 46 ${LaTeX} ${BASE} 42 # if ne dded, run latex again to get citations47 # if needed, run latex again to get citations 43 48 if fgrep -s "LaTeX Warning: Citation" ${basename $@}.log ; then ${LaTeX} ${BASE} ; fi 44 49 # ${Glossary} ${Build}/${BASE} … … 46 51 47 52 ${Build}: 48 mkdir $@53 mkdir -p $@ 49 54 50 55 %.pdf : ${Build}/%.ps | ${Build} -
doc/theses/mubeen_zulfiqar_MMath/allocator.tex
rba897d21 r2e9b59b 1 1 \chapter{Allocator} 2 2 3 \section{uHeap} 4 uHeap is a lightweight memory allocator. The objective behind uHeap is to design a minimal concurrent memory allocator that has new features and also fulfills GNU C Library requirements (FIX ME: cite requirements). 5 6 The objective of uHeap's new design was to fulfill following requirements: 7 \begin{itemize} 8 \item It should be concurrent and thread-safe for multi-threaded programs. 9 \item It should avoid global locks, on resources shared across all threads, as much as possible. 10 \item It's performance (FIX ME: cite performance benchmarks) should be comparable to the commonly used allocators (FIX ME: cite common allocators). 11 \item It should be a lightweight memory allocator. 12 \end{itemize} 3 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). 4 The new allocator fulfills the GNU C Library allocator API~\cite{GNUallocAPI}. 5 6 7 \section{llheap} 8 9 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. 10 (Large allocations requiring initialization, \eg zero fill, and/or copying are not covered by the low-latency objective.) 11 A direct consequence of this objective is very simple or no storage coalescing; 12 hence, llheap's design is willing to use more storage to lower latency. 13 This objective is apropos because systems research and industrial applications are striving for low latency and computers have huge amounts of RAM memory. 14 Finally, llheap's performance should be comparable with the current best allocators (see performance comparison in \VRef[Chapter]{c:Performance}). 15 16 % The objective of llheap's new design was to fulfill following requirements: 17 % \begin{itemize} 18 % \item It should be concurrent and thread-safe for multi-threaded programs. 19 % \item It should avoid global locks, on resources shared across all threads, as much as possible. 20 % \item It's performance (FIX ME: cite performance benchmarks) should be comparable to the commonly used allocators (FIX ME: cite common allocators). 21 % \item It should be a lightweight memory allocator. 22 % \end{itemize} 13 23 14 24 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 15 25 26 <<<<<<< HEAD 16 27 \section{Design choices for uHeap}\label{sec:allocatorSec} 17 28 uHeap's design was reviewed and changed to fulfill new requirements (FIX ME: cite allocator philosophy). For this purpose, following two designs of uHeapLmm were proposed: 18 19 \paragraph{Design 1: Centralized} 20 One heap, but lower bucket sizes are N-shared across KTs. 21 This design leverages the fact that 95\% of allocation requests are less than 512 bytes and there are only 3--5 different request sizes. 22 When KTs $\le$ N, the important bucket sizes are uncontented. 23 When KTs $>$ N, the free buckets are contented. 24 Therefore, threads are only contending for a small number of buckets, which are distributed among them to reduce contention. 25 \begin{cquote} 29 ======= 30 \section{Design Choices} 31 >>>>>>> bb7c77dc425e289ed60aa638529b3e5c7c3e4961 32 33 llheap's design was reviewed and changed multiple times throughout the thesis. 34 Some of the rejected designs are discussed because they show the path to the final design (see discussion in \VRef{s:MultipleHeaps}). 35 Note, a few simples tests for a design choice were compared with the current best allocators to determine the viability of a design. 36 37 38 \subsection{Allocation Fastpath} 39 \label{s:AllocationFastpath} 40 41 These designs look at the allocation/free \newterm{fastpath}, \ie when an allocation can immediately return free storage or returned storage is not coalesced. 42 \paragraph{T:1 model} 43 \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. 44 This design leverages the fact that 95\% of allocation requests are less than 1024 bytes and there are only 3--5 different request sizes. 45 When KTs $\le$ N, the common bucket sizes are uncontented; 46 when KTs $>$ N, the free buckets are contented and latency increases significantly. 47 In all cases, a KT must acquire/release a lock, contented or uncontented, along the fast allocation path because a bucket is shared. 48 Therefore, while threads are contending for a small number of buckets sizes, the buckets are distributed among them to reduce contention, which lowers latency; 49 however, picking N is workload specific. 50 51 \begin{figure} 52 \centering 53 \input{AllocDS1} 54 \caption{T:1 with Shared Buckets} 55 \label{f:T1SharedBuckets} 56 \end{figure} 57 58 Problems: 59 \begin{itemize} 60 \item 61 Need to know when a KT is created/destroyed to assign/unassign a shared bucket-number from the memory allocator. 62 \item 63 When no thread is assigned a bucket number, its free storage is unavailable. 64 \item 65 All KTs contend for the global-pool lock for initial allocations, before free-lists get populated. 66 \end{itemize} 67 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. 68 69 \paragraph{T:H model} 70 \VRef[Figure]{f:THSharedHeaps} shows a fixed number of heaps (N), each a local free pool, where the heaps are sharded across the KTs. 71 A KT can point directly to its assigned heap or indirectly through the corresponding heap bucket. 72 When KT $\le$ N, the heaps are uncontented; 73 when KTs $>$ N, the heaps are contented. 74 In all cases, a KT must acquire/release a lock, contented or uncontented along the fast allocation path because a heap is shared. 75 By adjusting N upwards, this approach reduces contention but increases storage (time versus space); 76 however, picking N is workload specific. 77 78 \begin{figure} 26 79 \centering 27 80 \input{AllocDS2} 28 \end{cquote} 29 Problems: need to know when a kernel thread (KT) is created and destroyed to know when to assign a shared bucket-number. 30 When no thread is assigned a bucket number, its free storage is unavailable. All KTs will be contended for one lock on sbrk for their initial allocations (before free-lists gets populated). 31 32 \paragraph{Design 2: Decentralized N Heaps} 33 Fixed number of heaps: shard the heap into N heaps each with a bump-area allocated from the @sbrk@ area. 34 Kernel threads (KT) are assigned to the N heaps. 35 When KTs $\le$ N, the heaps are uncontented. 36 When KTs $>$ N, the heaps are contented. 37 By adjusting N, this approach reduces storage at the cost of speed due to contention. 38 In all cases, a thread acquires/releases a lock, contented or uncontented. 39 \begin{cquote} 40 \centering 41 \input{AllocDS1} 42 \end{cquote} 43 Problems: need to know when a KT is created and destroyed to know when to assign/un-assign a heap to the KT. 44 45 \paragraph{Design 3: Decentralized Per-thread Heaps} 46 Design 3 is similar to design 2 but instead of having an M:N model, it uses a 1:1 model. So, instead of having N heaos and sharing them among M KTs, Design 3 has one heap for each KT. 47 Dynamic number of heaps: create a thread-local heap for each kernel thread (KT) with a bump-area allocated from the @sbrk@ area. 48 Each KT will have its own exclusive thread-local heap. Heap will be uncontended between KTs regardless how many KTs have been created. 49 Operations on @sbrk@ area will still be protected by locks. 50 %\begin{cquote} 51 %\centering 52 %\input{AllocDS3} FIXME add figs 53 %\end{cquote} 54 Problems: We cannot destroy the heap when a KT exits because our dynamic objects have ownership and they are returned to the heap that created them when the program frees a dynamic object. All dynamic objects point back to their owner heap. If a thread A creates an object O, passes it to another thread B, and A itself exits. When B will free object O, O should return to A's heap so A's heap should be preserved for the lifetime of the whole program as their might be objects in-use of other threads that were allocated by A. Also, we need to know when a KT is created and destroyed to know when to create/destroy a heap for the KT. 55 56 \paragraph{Design 4: Decentralized Per-CPU Heaps} 57 Design 4 is similar to Design 3 but instead of having a heap for each thread, it creates a heap for each CPU. 58 Fixed number of heaps for a machine: create a heap for each CPU with a bump-area allocated from the @sbrk@ area. 59 Each CPU will have its own CPU-local heap. When the program does a dynamic memory operation, it will be entertained by the heap of the CPU where the process is currently running on. 60 Each CPU will have its own exclusive heap. Just like Design 3(FIXME cite), heap will be uncontended between KTs regardless how many KTs have been created. 61 Operations on @sbrk@ area will still be protected by locks. 62 To deal with preemtion during a dynamic memory operation, librseq(FIXME cite) will be used to make sure that the whole dynamic memory operation completes on one CPU. librseq's restartable sequences can make it possible to re-run a critical section and undo the current writes if a preemption happened during the critical section's execution. 63 %\begin{cquote} 64 %\centering 65 %\input{AllocDS4} FIXME add figs 66 %\end{cquote} 67 68 Problems: This approach was slower than the per-thread model. Also, librseq does not provide such restartable sequences to detect preemtions in user-level threading system which is important to us as CFA(FIXME cite) has its own threading system that we want to support. 69 70 Out of the four designs, Design 3 was chosen because of the following reasons. 71 \begin{itemize} 72 \item 73 Decentralized designes are better in general as compared 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 designes shard the whole heap which has all the buckets with the addition of sharding sbrk area. So Design 1 was eliminated. 74 \item 75 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 scenerio. 76 \item 77 Design 4 was eliminated because it was slower than Design 3 and it provided no way to achieve user-threading safety using librseq. We had to use CFA interruption handling to achive user-threading safety which has some cost to it. Desing 4 was already slower than Design 3, adding cost of interruption handling on top of that would have made it even slower. 78 \end{itemize} 79 80 81 \subsection{Advantages of distributed design} 82 83 The distributed design of uHeap is concurrent to work in multi-threaded applications. 84 85 Some key benefits of the distributed design of uHeap are as follows: 86 87 \begin{itemize} 88 \item 89 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. 90 \item 91 Low or almost no contention on heap resources. 92 \item 93 It is possible to use sharing and stealing techniques to share/find unused storage, when a free list is unused or empty. 94 \item 95 Distributed design avoids unnecassry locks on resources shared across all KTs. 96 \end{itemize} 81 \caption{T:H with Shared Heaps} 82 \label{f:THSharedHeaps} 83 \end{figure} 84 85 Problems: 86 \begin{itemize} 87 \item 88 Need to know when a KT is created/destroyed to assign/unassign a heap from the memory allocator. 89 \item 90 When no thread is assigned to a heap, its free storage is unavailable. 91 \item 92 Ownership issues arise (see \VRef{s:Ownership}). 93 \item 94 All KTs contend for the local/global-pool lock for initial allocations, before free-lists get populated. 95 \end{itemize} 96 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. 97 98 \paragraph{T:H model, H = number of CPUs} 99 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@. 100 (See \VRef[Figure]{f:THSharedHeaps} but with a heap bucket per CPU.) 101 Hence, each CPU logically has its own private heap and local pool. 102 A memory operation is serviced from the heap associated with the CPU executing the operation. 103 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). 104 This approach is essentially an M:N approach where M is the number if KTs and N is the number of CPUs. 105 106 Problems: 107 \begin{itemize} 108 \item 109 Need to know when a CPU is added/removed from the @taskset@. 110 \item 111 Need a fast way to determine the CPU a KT is executing on to access the appropriate heap. 112 \item 113 Need to prevent preemption during a dynamic memory operation because of the \newterm{serially-reusable problem}. 114 \begin{quote} 115 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} 116 \end{quote} 117 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. 118 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. 119 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. 120 121 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. 122 \end{itemize} 123 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. 124 Also, the number of undoable writes in @librseq@ is limited and restartable sequences cannot deal with user-level thread (UT) migration across KTs. 125 For example, UT$_1$ is executing a memory operation by KT$_1$ on CPU$_1$ and a time-slice preemption occurs. 126 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. 127 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. 128 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. 129 If @librseq@ had an @rseq_abort@ which: 130 \begin{enumerate} 131 \item 132 Marked the current restartable critical-section as cancelled so it restarts when attempting to commit. 133 \item 134 Do nothing if there is no current restartable critical section in progress. 135 \end{enumerate} 136 Then @rseq_abort@ could be called on the backside of a user-level context-switching. 137 A feature similar to this idea might exist for hardware transactional-memory. 138 A significant effort was made to make this approach work but its complexity, lack of robustness, and performance costs resulted in its rejection. 139 140 \paragraph{1:1 model} 141 This design is the T:H model with T = H, where there is one thread-local heap for each KT. 142 (See \VRef[Figure]{f:THSharedHeaps} but with a heap bucket per KT and no bucket or local-pool lock.) 143 Hence, immediately after a KT starts, its heap is created and just before a KT terminates, its heap is (logically) deleted. 144 Heaps are uncontended for a KTs memory operations to its heap (modulo operations on the global pool and ownership). 145 146 Problems: 147 \begin{itemize} 148 \item 149 Need to know when a KT is starts/terminates to create/delete its heap. 150 151 \noindent 152 It is possible to leverage constructors/destructors for thread-local objects to get a general handle on when a KT starts/terminates. 153 \item 154 There is a classic \newterm{memory-reclamation} problem for ownership because storage passed to another thread can be returned to a terminated heap. 155 156 \noindent 157 The classic solution only deletes a heap after all referents are returned, which is complex. 158 The cheap alternative is for heaps to persist for program duration to handle outstanding referent frees. 159 If old referents return storage to a terminated heap, it is handled in the same way as an active heap. 160 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). 161 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. 162 \item 163 There can be significant external fragmentation as the number of KTs increases. 164 165 \noindent 166 In many concurrent applications, good performance is achieved with the number of KTs proportional to the number of CPUs. 167 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. 168 \item 169 There is the same serially-reusable problem with UTs migrating across KTs. 170 \end{itemize} 171 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. 172 173 174 \vspace{5pt} 175 \noindent 176 The conclusion from this design exercise is: any atomic fence, atomic instruction (lock free), or lock along the allocation fastpath produces significant slowdown. 177 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. 178 For the T:H=CPU and 1:1 models, locking is eliminated along the allocation fastpath. 179 However, T:H=CPU has poor operating-system support to determine the CPU id (heap id) and prevent the serially-reusable problem for KTs. 180 More operating system support is required to make this model viable, but there is still the serially-reusable problem with user-level threading. 181 Leaving the 1:1 model with no atomic actions along the fastpath and no special operating-system support required. 182 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. 183 184 185 % \begin{itemize} 186 % \item 187 % 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. 188 % \item 189 % 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. 190 % \item 191 % 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. 192 % 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. 193 % \end{itemize} 194 % Of the four designs for a low-latency memory allocator, the 1:1 model was chosen for the following reasons: 195 196 % \subsection{Advantages of distributed design} 197 % 198 % The distributed design of llheap is concurrent to work in multi-threaded applications. 199 % Some key benefits of the distributed design of llheap are as follows: 200 % \begin{itemize} 201 % \item 202 % 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. 203 % \item 204 % Low or almost no contention on heap resources. 205 % \item 206 % It is possible to use sharing and stealing techniques to share/find unused storage, when a free list is unused or empty. 207 % \item 208 % Distributed design avoids unnecessary locks on resources shared across all KTs. 209 % \end{itemize} 210 211 \subsection{Allocation Latency} 212 213 A primary goal of llheap is low latency. 214 Two forms of latency are internal and external. 215 Internal latency is the time to perform an allocation, while external latency is time to obtain/return storage from/to the operating system. 216 Ideally latency is $O(1)$ with a small constant. 217 218 To obtain $O(1)$ internal latency means no searching on the allocation fastpath, largely prohibits coalescing, which leads to external fragmentation. 219 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). 220 221 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. 222 Excluding real-time operating-systems, operating-system operations are unbounded, and hence some external latency is unavoidable. 223 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}). 224 Furthermore, while operating-system calls are unbounded, many are now reasonably fast, so their latency is tolerable and infrequent. 225 97 226 98 227 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 99 228 100 \section{uHeap Structure} 101 102 As described in (FIXME cite 2.4) uHeap uses following features of multi-threaded memory allocators. 103 \begin{itemize} 104 \item 105 uHeap has multiple heaps without a global heap and uses 1:1 model. (FIXME cite 2.5 1:1 model) 106 \item 107 uHeap uses object ownership. (FIXME cite 2.5.2) 108 \item 109 uHeap does not use object containers (FIXME cite 2.6) or any coalescing technique. Instead each dynamic object allocated by uHeap has a header than contains bookkeeping information. 110 \item 111 Each thread-local heap in uHeap has its own allocation buffer that is taken from the system using sbrk() call. (FIXME cite 2.7) 112 \item 113 Unless a heap is freeing an object that is owned by another thread's heap or heap is using sbrk() system call, uHeap is mostly lock-free which eliminates most of the contention on shared resources. (FIXME cite 2.8) 114 \end{itemize} 115 116 As uHeap uses a heap per-thread model to reduce contention on heap resources, we manage a list of heaps (heap-list) that can be used by threads. The list is empty at the start of the program. When a kernel thread (KT) is created, we check if heap-list is empty. If no then a heap is removed from the heap-list and is given to this new KT to use exclusively. If yes then a new heap object is created in dynamic memory and is given to this new KT to use exclusively. When a KT exits, its heap is not destroyed but instead its heap is put on the heap-list and is ready to be reused by new KTs. 117 118 This reduces the memory footprint as the objects on free-lists of a KT that has exited can be reused by a new KT. Also, we preserve all the heaps that were created during the lifetime of the program till the end of the program. uHeap uses object ownership where an object is freed to the free-buckets of the heap that allocated it. Even after a KT A has exited, its heap has to be preserved as there might be objects in-use of other threads that were initially allocated by A and the passed to other threads. 229 \section{llheap Structure} 230 231 \VRef[Figure]{f:llheapStructure} shows the design of llheap, which uses the following features: 232 \begin{itemize} 233 \item 234 1:1 multiple-heap model to minimize the fastpath, 235 \item 236 can be built with or without heap ownership, 237 \item 238 headers per allocation versus containers, 239 \item 240 no coalescing to minimize latency, 241 \item 242 global heap memory (pool) obtained from the operating system using @mmap@ to create and reuse heaps needed by threads, 243 \item 244 local reserved memory (pool) per heap obtained from global pool, 245 \item 246 global reserved memory (pool) obtained from the operating system using @sbrk@ call, 247 \item 248 optional fast-lookup table for converting allocation requests into bucket sizes, 249 \item 250 optional statistic-counters table for accumulating counts of allocation operations. 251 \end{itemize} 119 252 120 253 \begin{figure} 121 254 \centering 255 <<<<<<< HEAD 122 256 \includegraphics[width=0.65\textwidth]{figures/NewHeapStructure.eps} 123 257 \caption{uHeap Structure} 124 258 \label{fig:heapStructureFig} 259 ======= 260 % \includegraphics[width=0.65\textwidth]{figures/NewHeapStructure.eps} 261 \input{llheap} 262 \caption{llheap Structure} 263 \label{f:llheapStructure} 264 >>>>>>> bb7c77dc425e289ed60aa638529b3e5c7c3e4961 125 265 \end{figure} 126 266 127 Each heap uses seggregated free-buckets that have free objects of a specific size. Each free-bucket of a specific size has following 2 lists in it: 128 \begin{itemize} 129 \item 130 Free list is used when a thread is freeing an object that is owned by its own heap so free list does not use any locks/atomic-operations as it is only used by the owner KT. 131 \item 132 Away list is used when a thread A is freeing an object that is owned by another KT B's heap. This object should be freed to the owner heap (B's heap) so A will place the object on the away list of B. Away list is lock protected as it is shared by all other threads. 133 \end{itemize} 134 135 When a dynamic object of a size S is requested. The thread-local heap will check if S is greater than or equal to the mmap threshhold. Any request larger than the mmap threshhold is fulfilled by allocating an mmap area of that size and such requests are not allocated on sbrk area. The value of this threshhold can be changed using mallopt routine but the new value should not be larger than our biggest free-bucket size. 136 137 Algorithm~\ref{alg:heapObjectAlloc} briefly shows how an allocation request is fulfilled. 138 139 \begin{algorithm} 140 \caption{Dynamic object allocation of size S}\label{alg:heapObjectAlloc} 267 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. 268 There is a global bump-pointer to the next free heap in the array. 269 When this array is exhausted, another array is allocated. 270 There is a global top pointer for a heap intrusive link to chain free heaps from terminated threads. 271 When statistics are turned on, there is a global top pointer for a heap intrusive link to chain \emph{all} the heaps, which is traversed to accumulate statistics counters across heaps using @malloc_stats@. 272 273 When a KT starts, a heap is allocated from the current array for exclusive use by the KT. 274 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. 275 The free heaps is a stack so hot storage is reused first. 276 Preserving all heaps created during the program lifetime, solves the storage lifetime problem, when ownership is used. 277 This approach wastes storage if a large number of KTs are created/terminated at program start and then the program continues sequentially. 278 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. 279 280 Each heap uses segregated free-buckets that have free objects distributed across 91 different sizes from 16 to 4M. 281 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. 282 Each free bucket of a specific size has the following two lists: 283 \begin{itemize} 284 \item 285 A free stack used solely by the KT heap-owner, so push/pop operations do not require locking. 286 The free objects are a stack so hot storage is reused first. 287 \item 288 For ownership, a shared away-stack for KTs to return storage allocated by other KTs, so push/pop operations require locking. 289 When the free stack is empty, the entire ownership stack is removed and becomes the head of the corresponding free stack. 290 \end{itemize} 291 292 Algorithm~\ref{alg:heapObjectAlloc} shows the allocation outline for an object of size $S$. 293 First, the allocation is divided into small (@sbrk@) or large (@mmap@). 294 For large allocations, the storage is mapped directly from the operating system. 295 For small allocations, $S$ is quantized into a bucket size. 296 Quantizing is performed using a binary search over the ordered bucket array. 297 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. 298 (Type @char@ restricts the number of bucket sizes to 256.) 299 For $S$ > 64K, a binary search is used. 300 Then, the allocation storage is obtained from the following locations (in order), with increasing latency. 301 \begin{enumerate}[topsep=0pt,itemsep=0pt,parsep=0pt] 302 \item 303 bucket's free stack, 304 \item 305 bucket's away stack, 306 \item 307 heap's local pool 308 \item 309 global pool 310 \item 311 operating system (@sbrk@) 312 \end{enumerate} 313 314 \begin{figure} 315 \vspace*{-10pt} 316 \begin{algorithm}[H] 317 \small 318 \caption{Dynamic object allocation of size $S$}\label{alg:heapObjectAlloc} 141 319 \begin{algorithmic}[1] 142 320 \State $\textit{O} \gets \text{NULL}$ 143 \If {$S < \textit{mmap-threshhold}$} 144 \State $\textit{B} \gets (\text{smallest free-bucket} \geq S)$ 321 \If {$S >= \textit{mmap-threshhold}$} 322 \State $\textit{O} \gets \text{allocate dynamic memory using system call mmap with size S}$ 323 \Else 324 \State $\textit{B} \gets \text{smallest free-bucket} \geq S$ 145 325 \If {$\textit{B's free-list is empty}$} 146 326 \If {$\textit{B's away-list is empty}$} 147 327 \If {$\textit{heap's allocation buffer} < S$} 148 \State $\text{get allocation buffer using system call sbrk()}$328 \State $\text{get allocation from global pool (which might call \lstinline{sbrk})}$ 149 329 \EndIf 150 330 \State $\textit{O} \gets \text{bump allocate an object of size S from allocation buffer}$ … … 157 337 \EndIf 158 338 \State $\textit{O's owner} \gets \text{B}$ 159 \Else160 \State $\textit{O} \gets \text{allocate dynamic memory using system call mmap with size S}$161 339 \EndIf 162 340 \State $\Return \textit{ O}$ … … 164 342 \end{algorithm} 165 343 344 <<<<<<< HEAD 166 345 Algorithm~\ref{alg:heapObjectFreeOwn} shows how a free request is fulfilled if object ownership is turned on. Algorithm~\ref{alg:heapObjectFreeNoOwn} shows how the same free request is fulfilled without object ownership. 167 346 … … 171 350 \If {$\textit{A was mmap-ed}$} 172 351 \State $\text{return A's dynamic memory to system using system call munmap}$ 352 ======= 353 \vspace*{-15pt} 354 \begin{algorithm}[H] 355 \small 356 \caption{Dynamic object free at address $A$ with object ownership}\label{alg:heapObjectFreeOwn} 357 \begin{algorithmic}[1] 358 \If {$\textit{A mapped allocation}$} 359 \State $\text{return A's dynamic memory to system using system call \lstinline{munmap}}$ 360 >>>>>>> bb7c77dc425e289ed60aa638529b3e5c7c3e4961 173 361 \Else 174 362 \State $\text{B} \gets \textit{O's owner}$ … … 181 369 \end{algorithmic} 182 370 \end{algorithm} 371 <<<<<<< HEAD 183 372 184 373 \begin{algorithm} … … 199 388 \end{algorithm} 200 389 390 ======= 391 >>>>>>> bb7c77dc425e289ed60aa638529b3e5c7c3e4961 392 393 \vspace*{-15pt} 394 \begin{algorithm}[H] 395 \small 396 \caption{Dynamic object free at address $A$ without object ownership}\label{alg:heapObjectFreeNoOwn} 397 \begin{algorithmic}[1] 398 \If {$\textit{A mapped allocation}$} 399 \State $\text{return A's dynamic memory to system using system call \lstinline{munmap}}$ 400 \Else 401 \State $\text{B} \gets \textit{O's owner}$ 402 \If {$\textit{B is thread-local heap's bucket}$} 403 \State $\text{push A to B's free-list}$ 404 \Else 405 \State $\text{C} \gets \textit{thread local heap's bucket with same size as B}$ 406 \State $\text{push A to C's free-list}$ 407 \EndIf 408 \EndIf 409 \end{algorithmic} 410 \end{algorithm} 411 \end{figure} 412 413 Algorithm~\ref{alg:heapObjectFreeOwn} shows the de-allocation (free) outline for an object at address $A$ with ownership. 414 First, the address is divided into small (@sbrk@) or large (@mmap@). 415 For large allocations, the storage is unmapped back to the operating system. 416 For small allocations, the bucket associated with the request size is retrieved. 417 If the bucket is local to the thread, the allocation is pushed onto the thread's associated bucket. 418 If the bucket is not local to the thread, the allocation is pushed onto the owning thread's associated away stack. 419 420 Algorithm~\ref{alg:heapObjectFreeNoOwn} shows the de-allocation (free) outline for an object at address $A$ without ownership. 421 The algorithm is the same as for ownership except if the bucket is not local to the thread. 422 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. 423 424 Finally, the llheap design funnels \label{p:FunnelRoutine} all allocation/deallocation operations through routines @malloc@/@free@, which are the only routines to directly access and manage the internal data structures of the heap. 425 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. 426 This design simplifies heap-management code during development and maintenance. 427 428 429 \subsection{Alignment} 430 431 All dynamic memory allocations must have a minimum storage alignment for the contained object(s). 432 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). 433 In general, the minimum storage alignment is 8/16-byte boundary on 32/64-bit computers. 434 For consistency, the object header is normally aligned at this same boundary. 435 Larger alignments must be a power of 2, such page alignment (4/8K). 436 Any alignment request, N, $\le$ the minimum alignment is handled as a normal allocation with minimal alignment. 437 438 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'@. 439 \begin{center} 440 \input{Alignment1} 441 \end{center} 442 The storage between @E@ and @H@ is chained onto the appropriate free list for future allocations. 443 This approach is also valid within any sufficiently large free block, where @E@ is the start of the free block, and any unused storage before @H@ or after the allocated object becomes free storage. 444 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. 445 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. 446 As well, it does not work for large allocations, where many memory allocators switch from program @sbrk@ to operating-system @mmap@. 447 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. 448 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. 449 450 Instead, llheap alignment is accomplished by making a \emph{pessimistically} allocation request for sufficient storage to ensure that \emph{both} the alignment and size request are satisfied, \eg: 451 \begin{center} 452 \input{Alignment2} 453 \end{center} 454 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. 455 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@. 456 For this special case, there is @alignment - M@ bytes of unused storage after the data object, which subsequently can be used by @realloc@. 457 458 Note, the address returned is @A@, which is subsequently returned to @free@. 459 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@. 460 Hence, there must be a mechanism to detect when @P@ $\neq$ @A@ and how to compute @P@ from @A@. 461 462 The llheap approach uses two headers: 463 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.: 464 \begin{center} 465 \input{Alignment2Impl} 466 \end{center} 467 Since @malloc@ has a minimum alignment of @M@, @P@ $\neq$ @A@ only holds for alignments of @M@ or greater. 468 When @P@ $\neq$ @A@, the minimum distance between @P@ and @A@ is @M@ bytes, due to the pessimistic storage-allocation. 469 Therefore, there is always room for an @M@-byte fake header before @A@. 470 471 The fake header must supply an indicator to distinguish it from a normal header and the location of address @P@ generated by @malloc@. 472 This information is encoded as an offset from A to P and the initialize alignment (discussed in \VRef{s:ReallocStickyProperties}). 473 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. 474 \begin{center} 475 \input{FakeHeader} 476 \end{center} 477 478 479 \subsection{\lstinline{realloc} and Sticky Properties} 480 \label{s:ReallocStickyProperties} 481 482 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. 483 \begin{flushleft} 484 \begin{tabular}{ll} 485 \multicolumn{1}{c}{\textbf{realloc pattern}} & \multicolumn{1}{c}{\textbf{manually}} \\ 486 \begin{lstlisting} 487 T * naddr = realloc( oaddr, newSize ); 488 489 490 491 \end{lstlisting} 492 & 493 \begin{lstlisting} 494 T * naddr = (T *)malloc( newSize ); $\C[2.4in]{// new storage}$ 495 memcpy( naddr, addr, oldSize ); $\C{// copy old bytes}$ 496 free( addr ); $\C{// free old storage}$ 497 addr = naddr; $\C{// change pointer}\CRT$ 498 \end{lstlisting} 499 \end{tabular} 500 \end{flushleft} 501 The realloc pattern leverages available storage at the end of an allocation due to bucket sizes, possibly eliminating a new allocation and copying. 502 This pattern is not used enough to reduce storage management costs. 503 In fact, if @oaddr@ is @nullptr@, @realloc@ does a @malloc@, so even the initial @malloc@ can be a @realloc@ for consistency in the pattern. 504 505 The hidden problem for this pattern is the effect of zero fill and alignment with respect to reallocation. 506 Are these properties transient or persistent (``sticky'')? 507 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. 508 That is, if @realloc@ logically extends storage into unused bucket space or allocates new storage to satisfy a size change, are initial allocation properties preserve? 509 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. 510 This silent problem is unintuitive to programmers and difficult to locate because it is transient. 511 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. 512 This change makes the realloc pattern efficient and safe. 513 514 515 \subsection{Header} 516 517 To preserve allocation properties requires storing additional information with an allocation, 518 The only available location is the header, where \VRef[Figure]{f:llheapNormalHeader} shows the llheap storage layout. 519 The header has two data field sized appropriately for 32/64-bit alignment requirements. 520 The first field is a union of three values: 521 \begin{description} 522 \item[bucket pointer] 523 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). 524 \item[mapped size] 525 is for mapped storage and is the storage size for use in unmapping. 526 \item[next free block] 527 is for free storage and is an intrusive pointer chaining same-size free blocks onto a bucket's free stack. 528 \end{description} 529 The second field remembers the request size versus the allocation (bucket) size, \eg request 42 bytes which is rounded up to 64 bytes. 530 Since programmers think in request sizes rather than allocation sizes, the request size allows better generation of statistics or errors. 531 532 \begin{figure} 533 \centering 534 \input{Header} 535 \caption{llheap Normal Header} 536 \label{f:llheapNormalHeader} 537 \end{figure} 538 539 The low-order 3-bits of the first field are \emph{unused} for any stored values, whereas the second field may use all of its bits. 540 The 3 unused bits are used to represent mapped allocation, zero filled, and alignment, respectively. 541 Note, the alignment bit is not used in the normal header and the zero-filled/mapped bits are not used in the fake header. 542 This implementation allows a fast test if any of the lower 3-bits are on (@&@ and compare). 543 If no bits are on, it implies a basic allocation, which is handled quickly; 544 otherwise, the bits are analysed and appropriate actions are taken for the complex cases. 545 Since most allocations are basic, this implementation results in a significant performance gain along the allocation and free fastpath. 546 547 548 \section{Statistics and Debugging} 549 550 llheap can be built to accumulate fast and largely contention-free allocation statistics to help understand allocation behaviour. 551 Incrementing statistic counters must appear on the allocation fastpath. 552 As noted, any atomic operation along the fastpath produces a significant increase in allocation costs. 553 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. 554 555 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. 556 Note, the list is locked to prevent errors traversing an active list; 557 the statistics counters are not locked and can flicker during accumulation, which is not an issue with atomic read/write. 558 \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. 559 No other memory allocator studied provides as comprehensive statistical information. 560 Finally, these statistics were invaluable during the development of this thesis for debugging and verifying correctness, and hence, should be equally valuable to application developers. 561 562 \begin{figure} 563 \begin{lstlisting} 564 Heap statistics: (storage request / allocation) 565 malloc >0 calls 2,766; 0 calls 2,064; storage 12,715 / 13,367 bytes 566 aalloc >0 calls 0; 0 calls 0; storage 0 / 0 bytes 567 calloc >0 calls 6; 0 calls 0; storage 1,008 / 1,104 bytes 568 memalign >0 calls 0; 0 calls 0; storage 0 / 0 bytes 569 amemalign >0 calls 0; 0 calls 0; storage 0 / 0 bytes 570 cmemalign >0 calls 0; 0 calls 0; storage 0 / 0 bytes 571 resize >0 calls 0; 0 calls 0; storage 0 / 0 bytes 572 realloc >0 calls 0; 0 calls 0; storage 0 / 0 bytes 573 free !null calls 2,766; null calls 4,064; storage 12,715 / 13,367 bytes 574 away pulls 0; pushes 0; storage 0 / 0 bytes 575 sbrk calls 1; storage 10,485,760 bytes 576 mmap calls 10,000; storage 10,000 / 10,035 bytes 577 munmap calls 10,000; storage 10,000 / 10,035 bytes 578 threads started 4; exited 3 579 heaps new 4; reused 0 580 \end{lstlisting} 581 \caption{Statistics Output} 582 \label{f:StatiticsOutput} 583 \end{figure} 584 585 llheap can also be built with debug checking, which inserts many asserts along all allocation paths. 586 These assertions detect incorrect allocation usage, like double frees, unfreed storage, or memory corruptions because internal values (like header fields) are overwritten. 587 These checks are best effort as opposed to complete allocation checking as in @valgrind@. 588 Nevertheless, the checks detect many allocation problems. 589 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. 590 For example, @printf@ allocates a 1024 buffer on first call and never deletes this buffer. 591 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. 592 Determining the amount of never-freed storage is annoying, but once done, any warnings of unfreed storage are application related. 593 594 Tests indicate only a 30\% performance increase 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. 595 596 597 \section{User-level Threading Support} 598 \label{s:UserlevelThreadingSupport} 599 600 The serially-reusable problem (see \VRef{s:AllocationFastpath}) 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. 601 The solution is to prevent interrupts that can result in CPU or KT change during operations that are logically critical sections. 602 Locking these critical sections negates any attempt for a quick fastpath and results in high contention. 603 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. 604 Without time slicing, a user thread performing a long computation can prevent execution (starve) other threads. 605 To prevent starvation for an allocation-active thread, \ie the time slice always triggers in an allocation critical-section for one thread, a thread-local \newterm{rollforward} flag is set in the signal handler when it aborts a time slice. 606 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. 607 608 llheap uses two techniques to detect when execution is in a allocation operation or routine called from allocation operation, to abort any time slice during this period. 609 On the slowpath when executing expensive operations, like @sbrk@ or @mmap@, interrupts are disabled/enabled by setting thread-local flags so the signal handler aborts immediately. 610 On the fastpath, disabling/enabling interrupts is too expensive as accessing thread-local storage can be expensive and not thread-safe. 611 For example, the ARM processor stores the thread-local pointer in a coprocessor register that cannot perform atomic base-displacement addressing. 612 Hence, there is a window between loading the thread-local pointer from the coprocessor register into a normal register and adding the displacement when a time slice can move a thread. 613 614 The fast technique defines a special code section and places all non-interruptible routines in this section. 615 The linker places all code in this section into a contiguous block of memory, but the order of routines within the block is unspecified. 616 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. 617 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. 618 Hence, for correctness, this approach requires inspection of generated assembler code for routines placed in the non-interruptible section. 619 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. 620 These techniques are used in both the \uC and \CFA versions of llheap, where both of these systems have user-level threading. 621 622 623 \section{Bootstrapping} 624 625 There are problems bootstrapping a memory allocator. 626 \begin{enumerate} 627 \item 628 Programs can be statically or dynamically linked. 629 \item 630 The order the linker schedules startup code is poorly supported. 631 \item 632 Knowing a KT's start and end independently from the KT code is difficult. 633 \end{enumerate} 634 635 For static linking, the allocator is loaded with the program. 636 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. 637 This approach allows allocator substitution by placing an allocation library before any other in the linked/load path. 638 639 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. 640 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. 641 Hence, some part of the @sbrk@ area may be used by the default allocator and statistics about allocation operations cannot be correct. 642 Furthermore, dynamic linking goes through trampolines, so there is an additional cost along the allocator fastpath for all allocation operations. 643 Testing showed up to a 5\% performance increase for dynamic linking over static linking, even when using @tls_model("initial-exec")@ so the dynamic loader can obtain tighter binding. 644 645 All allocator libraries need to perform startup code to initialize data structures, such as the heap array for llheap. 646 The problem is getting initialized done before the first allocator call. 647 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. 648 As a result, calls to allocation routines occur without initialization. 649 To deal with this problem, it is necessary to put a conditional initialization check along the allocation fastpath to trigger initialization (singleton pattern). 650 651 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. 652 For example, dynamic-memory allocations before/after the application starts should not be considered in statistics because the application does not make these calls. 653 llheap establishes these two points using routines: 654 \begin{lstlisting} 655 __attribute__(( constructor( 100 ) )) static void startup( void ) { 656 // clear statistic counters 657 // reset allocUnfreed counter 658 } 659 __attribute__(( destructor( 100 ) )) static void shutdown( void ) { 660 // sum allocUnfreed for all heaps 661 // subtract global unfreed storage 662 // if allocUnfreed > 0 then print warning message 663 } 664 \end{lstlisting} 665 which use global constructor/destructor priority 100, where the linker calls these routines at program prologue/epilogue in increasing/decreasing order of priority. 666 Application programs may only use global constructor/destructor priorities greater than 100. 667 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. 668 By resetting counters in @startup@, prologue allocations are ignored, and checking unfreed storage in @shutdown@ checks only application memory management, ignoring the program epilogue. 669 670 While @startup@/@shutdown@ apply to the program KT, a concurrent program creates additional KTs that do not trigger these routines. 671 However, it is essential for the allocator to know when each KT is started/terminated. 672 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. 673 \begin{lstlisting} 674 struct ThreadManager { 675 volatile bool pgm_thread; 676 ThreadManager() {} // unusable 677 ~ThreadManager() { if ( pgm_thread ) heapManagerDtor(); } 678 }; 679 static thread_local ThreadManager threadManager; 680 \end{lstlisting} 681 Unfortunately, thread-local variables are created lazily, \ie on the first dereference of @threadManager@, which then triggers its constructor. 682 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. 683 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. 684 Now when a KT terminates, @~ThreadManager@ is called to chained it onto the global-heap free-stack, where @pgm_thread@ is set to true only for the program KT. 685 The conditional destructor call prevents closing down the program heap, which must remain available because epilogue code may free more storage. 686 687 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. 688 This recursion is handled with another thread-local flag to prevent double initialization. 689 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@. 690 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. 691 692 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. 693 The following API was created to provide interaction between the language runtime and the allocator. 694 \begin{lstlisting} 695 void startTask(); $\C{// KT starts}$ 696 void finishTask(); $\C{// KT ends}$ 697 void startup(); $\C{// when application code starts}$ 698 void shutdown(); $\C{// when application code ends}$ 699 bool traceHeap(); $\C{// enable allocation/free printing for debugging}$ 700 bool traceHeapOn(); $\C{// start printing allocation/free calls}$ 701 bool traceHeapOff(); $\C{// stop printing allocation/free calls}$ 702 \end{lstlisting} 703 This kind of API is necessary to allow concurrent runtime systems to interact with difference memory allocators in a consistent way. 201 704 202 705 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 203 706 204 707 \section{Added Features and Methods} 205 To improve the uHeap allocator (FIX ME: cite uHeap) 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. 206 207 \subsection{C Interface} 208 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. 708 709 The C dynamic-allocation API (see \VRef[Figure]{f:CDynamicAllocationAPI}) is neither orthogonal nor complete. 710 For example, 711 \begin{itemize} 712 \item 713 It is possible to zero fill or align an allocation but not both. 714 \item 715 It is \emph{only} possible to zero fill an array allocation. 716 \item 717 It is not possible to resize a memory allocation without data copying. 718 \item 719 @realloc@ does not preserve initial allocation properties. 720 \end{itemize} 721 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. 722 Furthermore, newer programming languages have better type systems that can provide safer and more powerful APIs for memory allocation. 723 724 \begin{figure} 725 \begin{lstlisting} 726 void * malloc( size_t size ); 727 void * calloc( size_t nmemb, size_t size ); 728 void * realloc( void * ptr, size_t size ); 729 void * reallocarray( void * ptr, size_t nmemb, size_t size ); 730 void free( void * ptr ); 731 void * memalign( size_t alignment, size_t size ); 732 void * aligned_alloc( size_t alignment, size_t size ); 733 int posix_memalign( void ** memptr, size_t alignment, size_t size ); 734 void * valloc( size_t size ); 735 void * pvalloc( size_t size ); 736 737 struct mallinfo mallinfo( void ); 738 int mallopt( int param, int val ); 739 int malloc_trim( size_t pad ); 740 size_t malloc_usable_size( void * ptr ); 741 void malloc_stats( void ); 742 int malloc_info( int options, FILE * fp ); 743 \end{lstlisting} 744 \caption{C Dynamic-Allocation API} 745 \label{f:CDynamicAllocationAPI} 746 \end{figure} 747 748 The following presents design and API changes for C, \CC (\uC), and \CFA, all of which are implemented in llheap. 749 209 750 210 751 \subsection{Out of Memory} … … 212 753 Most allocators use @nullptr@ to indicate an allocation failure, specifically out of memory; 213 754 hence the need to return an alternate value for a zero-sized allocation. 214 The alternative is to abort a program when out of memory. 215 In theory, notifying the programmer allows recovery; 216 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. 217 218 219 \subsection{\lstinline{void * aalloc( size_t dim, size_t elemSize )}} 220 @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. 221 \paragraph{Usage} 755 A different approach allowed by the C API is to abort a program when out of memory and return @nullptr@ for a zero-sized allocation. 756 In theory, notifying the programmer of memory failure allows recovery; 757 in practice, it is almost impossible to gracefully recover when out of memory. 758 Hence, the cheaper approach of returning @nullptr@ for a zero-sized allocation is chosen because no pseudo allocation is necessary. 759 760 761 \subsection{C Interface} 762 763 For C, it is possible to increase functionality and orthogonality of the dynamic-memory API to make allocation better for programmers. 764 765 For existing C allocation routines: 766 \begin{itemize} 767 \item 768 @calloc@ sets the sticky zero-fill property. 769 \item 770 @memalign@, @aligned_alloc@, @posix_memalign@, @valloc@ and @pvalloc@ set the sticky alignment property. 771 \item 772 @realloc@ and @reallocarray@ preserve sticky properties. 773 \end{itemize} 774 775 The C dynamic-memory API is extended with the following routines: 776 777 \paragraph{\lstinline{void * aalloc( size_t dim, size_t elemSize )}} 778 extends @calloc@ for allocating a dynamic array of objects without calculating the total size of array explicitly but \emph{without} zero-filling the memory. 779 @aalloc@ is significantly faster than @calloc@, which is the only alternative. 780 781 \noindent\textbf{Usage} 222 782 @aalloc@ takes two parameters. 223 224 \begin{itemize} 225 \item 226 @dim@: number of objects in the array 227 \item 228 @elemSize@: size of the object in the array. 229 \end{itemize} 230 It returns address of dynamic object allocatoed on heap that can contain dim number of objects of the size elemSize. On failure, it returns a @NULL@ pointer. 231 232 \subsection{\lstinline{void * resize( void * oaddr, size_t size )}} 233 @resize@ is an extension of relloc. It allows programmer to reuse a cuurently 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. 234 \paragraph{Usage} 783 \begin{itemize} 784 \item 785 @dim@: number of array objects 786 \item 787 @elemSize@: size of array object 788 \end{itemize} 789 It returns the address of the dynamic array or @NULL@ if either @dim@ or @elemSize@ are zero. 790 791 \paragraph{\lstinline{void * resize( void * oaddr, size_t size )}} 792 extends @realloc@ for resizing an existing allocation \emph{without} copying previous data into the new allocation or preserving sticky properties. 793 @resize@ is significantly faster than @realloc@, which is the only alternative. 794 795 \noindent\textbf{Usage} 235 796 @resize@ takes two parameters. 236 237 \begin{itemize} 238 \item 239 @oaddr@: the address of the old object that needs to be resized. 240 \item 241 @size@: the new size requirement of the to which the old object needs to be resized. 242 \end{itemize} 243 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. 244 245 \subsection{\lstinline{void * resize( void * oaddr, size_t nalign, size_t size )}} 246 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. 247 \paragraph{Usage} 248 This resize takes three parameters. It takes an additional parameter of nalign as compared to the above resize (FIX ME: cite above resize). 249 250 \begin{itemize} 251 \item 252 @oaddr@: the address of the old object that needs to be resized. 253 \item 254 @nalign@: the new alignment to which the old object needs to be realigned. 255 \item 256 @size@: the new size requirement of the to which the old object needs to be resized. 257 \end{itemize} 258 It returns an object with the size and alignment given in the parameters. On failure, it returns a @NULL@ pointer. 259 260 \subsection{\lstinline{void * amemalign( size_t alignment, size_t dim, size_t elemSize )}} 261 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. 262 \paragraph{Usage} 263 amemalign takes three parameters. 264 265 \begin{itemize} 266 \item 267 @alignment@: the alignment to which the dynamic array needs to be aligned. 268 \item 269 @dim@: number of objects in the array 270 \item 271 @elemSize@: size of the object in the array. 272 \end{itemize} 273 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. 274 275 \subsection{\lstinline{void * cmemalign( size_t alignment, size_t dim, size_t elemSize )}} 276 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. 277 \paragraph{Usage} 278 cmemalign takes three parameters. 279 280 \begin{itemize} 281 \item 282 @alignment@: the alignment to which the dynamic array needs to be aligned. 283 \item 284 @dim@: number of objects in the array 285 \item 286 @elemSize@: size of the object in the array. 287 \end{itemize} 288 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. 289 290 \subsection{\lstinline{size_t malloc_alignment( void * addr )}} 291 @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 verofying the alignment of a dynamic object especially in a scenerio similar to prudcer-consumer where a producer allocates a dynamic object and the consumer needs to assure that the dynamic object was allocated with the required alignment. 292 \paragraph{Usage} 293 @malloc_alignment@ takes one parameters. 294 295 \begin{itemize} 296 \item 297 @addr@: the address of the currently allocated dynamic object. 298 \end{itemize} 299 @malloc_alignment@ returns the alignment of the given dynamic object. On failure, it return the value of default alignment of the uHeap allocator. 300 301 \subsection{\lstinline{bool malloc_zero_fill( void * addr )}} 302 @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 scenerio similar to prudcer-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. 303 \paragraph{Usage} 797 \begin{itemize} 798 \item 799 @oaddr@: address to be resized 800 \item 801 @size@: new allocation size (smaller or larger than previous) 802 \end{itemize} 803 It returns the address of the old or new storage with the specified new size or @NULL@ if @size@ is zero. 804 805 \paragraph{\lstinline{void * amemalign( size_t alignment, size_t dim, size_t elemSize )}} 806 extends @aalloc@ and @memalign@ for allocating an aligned dynamic array of objects. 807 Sets sticky alignment property. 808 809 \noindent\textbf{Usage} 810 @amemalign@ takes three parameters. 811 \begin{itemize} 812 \item 813 @alignment@: alignment requirement 814 \item 815 @dim@: number of array objects 816 \item 817 @elemSize@: size of array object 818 \end{itemize} 819 It returns the address of the aligned dynamic-array or @NULL@ if either @dim@ or @elemSize@ are zero. 820 821 \paragraph{\lstinline{void * cmemalign( size_t alignment, size_t dim, size_t elemSize )}} 822 extends @amemalign@ with zero fill and has the same usage as @amemalign@. 823 Sets sticky zero-fill and alignment property. 824 It returns the address of the aligned, zero-filled dynamic-array or @NULL@ if either @dim@ or @elemSize@ are zero. 825 826 \paragraph{\lstinline{size_t malloc_alignment( void * addr )}} 827 returns the alignment of the dynamic object for use in aligning similar allocations. 828 829 \noindent\textbf{Usage} 830 @malloc_alignment@ takes one parameter. 831 \begin{itemize} 832 \item 833 @addr@: address of an allocated object. 834 \end{itemize} 835 It returns the alignment of the given object, where objects not allocated with alignment return the minimal allocation alignment. 836 837 \paragraph{\lstinline{bool malloc_zero_fill( void * addr )}} 838 returns true if the object has the zero-fill sticky property for use in zero filling similar allocations. 839 840 \noindent\textbf{Usage} 304 841 @malloc_zero_fill@ takes one parameters. 305 842 306 843 \begin{itemize} 307 844 \item 308 @addr@: the address of the currently allocated dynamic object. 309 \end{itemize} 310 @malloc_zero_fill@ returns true if the dynamic object was initially zero filled and return false otherwise. On failure, it returns false. 311 312 \subsection{\lstinline{size_t malloc_size( void * addr )}} 313 @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 verofying the alignment of a dynamic object especially in a scenerio similar to prudcer-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. 314 \paragraph{Usage} 845 @addr@: address of an allocated object. 846 \end{itemize} 847 It returns true if the zero-fill sticky property is set and false otherwise. 848 849 \paragraph{\lstinline{size_t malloc_size( void * addr )}} 850 returns the request size of the dynamic object (updated when an object is resized) for use in similar allocations. 851 See also @malloc_usable_size@. 852 853 \noindent\textbf{Usage} 315 854 @malloc_size@ takes one parameters. 316 317 \begin{itemize} 318 \item 319 @addr@: the address of the currently allocated dynamic object. 320 \end{itemize} 321 @malloc_size@ returns the allocation size of the given dynamic object. On failure, it return zero. 322 323 \subsection{\lstinline{void * realloc( void * oaddr, size_t nalign, size_t size )}} 324 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. 325 \paragraph{Usage} 326 This @realloc@ takes three parameters. It takes an additional parameter of nalign as compared to the default @realloc@. 327 328 \begin{itemize} 329 \item 330 @oaddr@: the address of the old object that needs to be reallocated. 331 \item 332 @nalign@: the new alignment to which the old object needs to be realigned. 333 \item 334 @size@: the new size requirement of the to which the old object needs to be resized. 335 \end{itemize} 336 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. 337 338 \subsection{\CFA Malloc Interface} 339 We added some routines to the malloc interface of \CFA. These routines can only be used in \CFA and not in our standalone uHeap 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. 340 \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. 341 342 \subsection{\lstinline{T * malloc( void )}} 343 This malloc is a simplified polymorphic form of defualt malloc (FIX ME: cite malloc). It does not take any parameter as compared to default malloc that takes one parameter. 344 \paragraph{Usage} 345 This malloc takes no parameters. 346 It returns a dynamic object of the size of type @T@. On failure, it returns a @NULL@ pointer. 347 348 \subsection{\lstinline{T * aalloc( size_t dim )}} 349 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. 350 \paragraph{Usage} 351 aalloc takes one parameters. 352 353 \begin{itemize} 354 \item 355 @dim@: required number of objects in the array. 356 \end{itemize} 357 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. 358 359 \subsection{\lstinline{T * calloc( size_t dim )}} 360 This calloc is a simplified polymorphic form of defualt calloc (FIX ME: cite calloc). It takes one parameter as compared to the default calloc that takes two parameters. 361 \paragraph{Usage} 362 This calloc takes one parameter. 363 364 \begin{itemize} 365 \item 366 @dim@: required number of objects in the array. 367 \end{itemize} 368 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. 369 370 \subsection{\lstinline{T * resize( T * ptr, size_t size )}} 371 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. 372 \paragraph{Usage} 373 This resize takes two parameters. 374 375 \begin{itemize} 376 \item 377 @ptr@: address of the old object. 378 \item 379 @size@: the required size of the new object. 380 \end{itemize} 381 It returns a dynamic object of the size given in paramters. The returned object is aligned to the alignemtn of type @T@. On failure, it returns a @NULL@ pointer. 382 383 \subsection{\lstinline{T * realloc( T * ptr, size_t size )}} 384 This @realloc@ is a simplified polymorphic form of defualt @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. 385 \paragraph{Usage} 386 This @realloc@ takes two parameters. 387 388 \begin{itemize} 389 \item 390 @ptr@: address of the old object. 391 \item 392 @size@: the required size of the new object. 393 \end{itemize} 394 It returns a dynamic object of the size given in paramters that preserves the data in the given object. The returned object is aligned to the alignemtn of type @T@. On failure, it returns a @NULL@ pointer. 395 396 \subsection{\lstinline{T * memalign( size_t align )}} 397 This memalign is a simplified polymorphic form of defualt memalign (FIX ME: cite memalign). It takes one parameters as compared to the default memalign that takes two parameters. 398 \paragraph{Usage} 399 memalign takes one parameters. 400 401 \begin{itemize} 402 \item 403 @align@: the required alignment of the dynamic object. 404 \end{itemize} 405 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. 406 407 \subsection{\lstinline{T * amemalign( size_t align, size_t dim )}} 408 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. 409 \paragraph{Usage} 410 amemalign takes two parameters. 411 412 \begin{itemize} 413 \item 414 @align@: required alignment of the dynamic array. 415 \item 416 @dim@: required number of objects in the array. 417 \end{itemize} 418 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. 419 420 \subsection{\lstinline{T * cmemalign( size_t align, size_t dim )}} 421 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. 422 \paragraph{Usage} 423 cmemalign takes two parameters. 424 425 \begin{itemize} 426 \item 427 @align@: required alignment of the dynamic array. 428 \item 429 @dim@: required number of objects in the array. 430 \end{itemize} 431 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. 432 433 \subsection{\lstinline{T * aligned_alloc( size_t align )}} 434 This @aligned_alloc@ is a simplified polymorphic form of defualt @aligned_alloc@ (FIX ME: cite @aligned_alloc@). It takes one parameter as compared to the default @aligned_alloc@ that takes two parameters. 435 \paragraph{Usage} 436 This @aligned_alloc@ takes one parameter. 437 438 \begin{itemize} 439 \item 440 @align@: required alignment of the dynamic object. 441 \end{itemize} 442 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. 443 444 \subsection{\lstinline{int posix_memalign( T ** ptr, size_t align )}} 445 This @posix_memalign@ is a simplified polymorphic form of defualt @posix_memalign@ (FIX ME: cite @posix_memalign@). It takes two parameters as compared to the default @posix_memalign@ that takes three parameters. 446 \paragraph{Usage} 447 This @posix_memalign@ takes two parameter. 448 449 \begin{itemize} 450 \item 451 @ptr@: variable address to store the address of the allocated object. 452 \item 453 @align@: required alignment of the dynamic object. 454 \end{itemize} 455 456 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. 457 458 \subsection{\lstinline{T * valloc( void )}} 459 This @valloc@ is a simplified polymorphic form of defualt @valloc@ (FIX ME: cite @valloc@). It takes no parameters as compared to the default @valloc@ that takes one parameter. 460 \paragraph{Usage} 461 @valloc@ takes no parameters. 462 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. 463 464 \subsection{\lstinline{T * pvalloc( void )}} 465 \paragraph{Usage} 466 @pvalloc@ takes no parameters. 467 It returns a dynamic object of the size that is calcutaed by rouding the size of type @T@. The returned object is also aligned to the page size. On failure, it returns a @NULL@ pointer. 468 469 \subsection{Alloc Interface} 470 In addition to improve allocator interface both for \CFA and our standalone allocator uHeap in C. We also added a new alloc interface in \CFA that increases usability of dynamic memory allocation. 471 This interface helps programmers in three major ways. 472 473 \begin{itemize} 474 \item 475 Routine Name: alloc interfce frees programmers from remmebring different routine names for different kind of dynamic allocations. 476 \item 477 Parametre Positions: alloc interface frees programmers from remembering parameter postions in call to routines. 478 \item 479 Object Size: alloc interface does not require programmer to mention the object size as \CFA allows allocator to determince the object size from returned type of alloc call. 480 \end{itemize} 481 482 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 interfece 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. 483 484 \subsection{Routine: \lstinline{T * alloc( ... )}} 485 Call to alloc wihout any parameter returns one object of size of type @T@ allocated dynamically. 486 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. 487 alocc routine accepts six kinds of arguments. Using different combinations of tha parameters, different kind of allocations can be performed. Any combincation of parameters can be used together except @`realloc@ and @`resize@ that should not be used simultanously 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. 488 489 \paragraph{Dim} 490 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@. 491 It represents the required number of members in the array allocation as in \CFA's aalloc (FIX ME: cite aalloc). 492 This parameter should be of type @size_t@. 493 494 Example: @int a = alloc( 5 )@ 495 This call will return a dynamic array of five integers. 496 497 \paragraph{Align} 498 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. 499 500 Example: @int b = alloc( 5 , 64`align )@ 501 This call will return a dynamic array of five integers. It will align the allocated object to 64. 502 503 \paragraph{Fill} 504 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. 505 Three types of parameters can be passed using `fill. 506 507 \begin{itemize} 508 \item 509 @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. 510 \item 511 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. 512 \item 513 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 untill the end object passed to @`fill@ or the end of requested allocation reaches. 514 \end{itemize} 515 516 Example: @int b = alloc( 5 , 'a'`fill )@ 517 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. 518 519 Example: @int b = alloc( 5 , 4`fill )@ 520 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. 521 522 Example: @int b = alloc( 5 , a`fill )@ where @a@ is a pointer of int type 523 This call will return a dynamic array of five integers. It will copy data in a to the returned object non-recursively untill end of a or the newly allocated object is reached. 524 525 \paragraph{Resize} 526 This parameter is position-free and uses a backtick routine resize (@`resize@). It represents the old dynamic object (oaddr) that the programmer wants to 527 \begin{itemize} 528 \item 529 resize to a new size. 530 \item 531 realign to a new alignment 532 \item 533 fill with something. 534 \end{itemize} 535 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. 536 537 Example: @int b = alloc( 5 , a`resize )@ 538 This call will resize object a to a dynamic array that can contain 5 integers. 539 540 Example: @int b = alloc( 5 , a`resize , 32`align )@ 541 This call will resize object a to a dynamic array that can contain 5 integers. The returned object will also be aligned to 32. 542 543 Example: @int b = alloc( 5 , a`resize , 32`align , 2`fill )@ 544 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. 545 546 \paragraph{Realloc} 547 This parameter is position-free and uses a backtick routine @realloc@ (@`realloc@). It represents the old dynamic object (oaddr) that the programmer wants to 548 \begin{itemize} 549 \item 550 realloc to a new size. 551 \item 552 realign to a new alignment 553 \item 554 fill with something. 555 \end{itemize} 556 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. 557 558 Example: @int b = alloc( 5 , a`realloc )@ 559 This call will realloc object a to a dynamic array that can contain 5 integers. 560 561 Example: @int b = alloc( 5 , a`realloc , 32`align )@ 562 This call will realloc object a to a dynamic array that can contain 5 integers. The returned object will also be aligned to 32. 563 564 Example: @int b = alloc( 5 , a`realloc , 32`align , 2`fill )@ 565 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. 855 \begin{itemize} 856 \item 857 @addr@: address of an allocated object. 858 \end{itemize} 859 It returns the request size or zero if @addr@ is @NULL@. 860 861 \paragraph{\lstinline{int malloc_stats_fd( int fd )}} 862 changes the file descriptor where @malloc_stats@ writes statistics (default @stdout@). 863 864 \noindent\textbf{Usage} 865 @malloc_stats_fd@ takes one parameters. 866 \begin{itemize} 867 \item 868 @fd@: files description. 869 \end{itemize} 870 It returns the previous file descriptor. 871 872 \paragraph{\lstinline{size_t malloc_expansion()}} 873 \label{p:malloc_expansion} 874 set the amount (bytes) to extend the heap when there is insufficient free storage to service an allocation request. 875 It returns the heap extension size used throughout a program, \ie called once at heap initialization. 876 877 \paragraph{\lstinline{size_t malloc_mmap_start()}} 878 set the crossover between allocations occurring in the @sbrk@ area or separately mapped. 879 It returns the crossover point used throughout a program, \ie called once at heap initialization. 880 881 \paragraph{\lstinline{size_t malloc_unfreed()}} 882 \label{p:malloc_unfreed} 883 amount subtracted to adjust for unfreed program storage (debug only). 884 It returns the new subtraction amount and called by @malloc_stats@. 885 886 887 \subsection{\CC Interface} 888 889 The following extensions take advantage of overload polymorphism in the \CC type-system. 890 891 \paragraph{\lstinline{void * resize( void * oaddr, size_t nalign, size_t size )}} 892 extends @resize@ with an alignment re\-quirement. 893 894 \noindent\textbf{Usage} 895 takes three parameters. 896 \begin{itemize} 897 \item 898 @oaddr@: address to be resized 899 \item 900 @nalign@: alignment requirement 901 \item 902 @size@: new allocation size (smaller or larger than previous) 903 \end{itemize} 904 It returns the address of the old or new storage with the specified new size and alignment, or @NULL@ if @size@ is zero. 905 906 \paragraph{\lstinline{void * realloc( void * oaddr, size_t nalign, size_t size )}} 907 extends @realloc@ with an alignment re\-quirement and has the same usage as aligned @resize@. 908 909 910 \subsection{\CFA Interface} 911 912 The following extensions take advantage of overload polymorphism in the \CFA type-system. 913 The key safety advantage of the \CFA type system is using the return type to select overloads; 914 hence, a polymorphic routine knows the returned type and its size. 915 This capability is used to remove the object size parameter and correctly cast the return storage to match the result type. 916 For example, the following is the \CFA wrapper for C @malloc@: 917 \begin{cfa} 918 forall( T & | sized(T) ) { 919 T * malloc( void ) { 920 if ( _Alignof(T) <= libAlign() ) return @(T *)@malloc( @sizeof(T)@ ); // C allocation 921 else return @(T *)@memalign( @_Alignof(T)@, @sizeof(T)@ ); // C allocation 922 } // malloc 923 \end{cfa} 924 and is used as follows: 925 \begin{lstlisting} 926 int * i = malloc(); 927 double * d = malloc(); 928 struct Spinlock { ... } __attribute__(( aligned(128) )); 929 Spinlock * sl = malloc(); 930 \end{lstlisting} 931 where each @malloc@ call provides the return type as @T@, which is used with @sizeof@, @_Alignof@, and casting the storage to the correct type. 932 This interface removes many of the common allocation errors in C programs. 933 \VRef[Figure]{f:CFADynamicAllocationAPI} show the \CFA wrappers for the equivalent C/\CC allocation routines with same semantic behaviour. 934 935 \begin{figure} 936 \begin{lstlisting} 937 T * malloc( void ); 938 T * aalloc( size_t dim ); 939 T * calloc( size_t dim ); 940 T * resize( T * ptr, size_t size ); 941 T * realloc( T * ptr, size_t size ); 942 T * memalign( size_t align ); 943 T * amemalign( size_t align, size_t dim ); 944 T * cmemalign( size_t align, size_t dim ); 945 T * aligned_alloc( size_t align ); 946 int posix_memalign( T ** ptr, size_t align ); 947 T * valloc( void ); 948 T * pvalloc( void ); 949 \end{lstlisting} 950 \caption{\CFA C-Style Dynamic-Allocation API} 951 \label{f:CFADynamicAllocationAPI} 952 \end{figure} 953 954 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. 955 This interface helps programmers in three ways. 956 \begin{itemize} 957 \item 958 naming: \CFA regular and @ttype@ polymorphism 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. 959 \item 960 named arguments: individual allocation properties are specified using postfix function call, so programmers do have to remember parameter positions in allocation calls. 961 \item 962 object size: like the \CFA C-style interface, programmers do not have to specify object size or cast allocation results. 963 \end{itemize} 964 Note, postfix function call is an alternative call syntax, using backtick @`@, where the argument appears before the function name, \eg 965 \begin{cfa} 966 duration ?@`@h( int h ); // ? denote the position of the function operand 967 duration ?@`@m( int m ); 968 duration ?@`@s( int s ); 969 duration dur = 3@`@h + 42@`@m + 17@`@s; 970 \end{cfa} 971 @ttype@ polymorphism is similar to \CC variadic templates. 972 973 \paragraph{\lstinline{T * alloc( ... )} or \lstinline{T * alloc( size_t dim, ... )}} 974 is overloaded with a variable number of specific allocation routines, or an integer dimension parameter followed by a variable number specific allocation routines. 975 A call without parameters returns a dynamically allocated object of type @T@ (@malloc@). 976 A call with only the dimension (dim) parameter returns a dynamically allocated array of objects of type @T@ (@aalloc@). 977 The variable number of arguments consist of allocation properties, which can be combined to produce different kinds of allocations. 978 The only restriction is for properties @realloc@ and @resize@, which cannot be combined. 979 980 The allocation property functions are: 981 \subparagraph{\lstinline{T_align ?`align( size_t alignment )}} 982 to align the allocation. 983 The alignment parameter must be $\ge$ the default alignment (@libAlign()@ in \CFA) and a power of two, \eg: 984 \begin{cfa} 985 int * i0 = alloc( @4096`align@ ); sout | i0 | nl; 986 int * i1 = alloc( 3, @4096`align@ ); sout | i1; for (i; 3 ) sout | &i1[i]; sout | nl; 987 988 0x555555572000 989 0x555555574000 0x555555574000 0x555555574004 0x555555574008 990 \end{cfa} 991 returns a dynamic object and object array aligned on a 4096-byte boundary. 992 993 \subparagraph{\lstinline{S_fill(T) ?`fill ( /* various types */ )}} 994 to initialize storage. 995 There are three ways to fill storage: 996 \begin{enumerate} 997 \item 998 A char fills each byte of each object. 999 \item 1000 An object of the returned type fills each object. 1001 \item 1002 An object array pointer fills some or all of the corresponding object array. 1003 \end{enumerate} 1004 For example: 1005 \begin{cfa}[numbers=left] 1006 int * i0 = alloc( @0n`fill@ ); sout | *i0 | nl; // disambiguate 0 1007 int * i1 = alloc( @5`fill@ ); sout | *i1 | nl; 1008 int * i2 = alloc( @'\xfe'`fill@ ); sout | hex( *i2 ) | nl; 1009 int * i3 = alloc( 5, @5`fill@ ); for ( i; 5 ) sout | i3[i]; sout | nl; 1010 int * i4 = alloc( 5, @0xdeadbeefN`fill@ ); for ( i; 5 ) sout | hex( i4[i] ); sout | nl; 1011 int * i5 = alloc( 5, @i3`fill@ ); for ( i; 5 ) sout | i5[i]; sout | nl; 1012 int * i6 = alloc( 5, @[i3, 3]`fill@ ); for ( i; 5 ) sout | i6[i]; sout | nl; 1013 \end{cfa} 1014 \begin{lstlisting}[numbers=left] 1015 0 1016 5 1017 0xfefefefe 1018 5 5 5 5 5 1019 0xdeadbeef 0xdeadbeef 0xdeadbeef 0xdeadbeef 0xdeadbeef 1020 5 5 5 5 5 1021 5 5 5 -555819298 -555819298 // two undefined values 1022 \end{lstlisting} 1023 Examples 1 to 3, fill an object with a value or characters. 1024 Examples 4 to 7, fill an array of objects with values, another array, or part of an array. 1025 1026 \subparagraph{\lstinline{S_resize(T) ?`resize( void * oaddr )}} 1027 used to resize, realign, and fill, where the old object data is not copied to the new object. 1028 The old object type may be different from the new object type, since the values are not used. 1029 For example: 1030 \begin{cfa}[numbers=left] 1031 int * i = alloc( @5`fill@ ); sout | i | *i; 1032 i = alloc( @i`resize@, @256`align@, @7`fill@ ); sout | i | *i; 1033 double * d = alloc( @i`resize@, @4096`align@, @13.5`fill@ ); sout | d | *d; 1034 \end{cfa} 1035 \begin{lstlisting}[numbers=left] 1036 0x55555556d5c0 5 1037 0x555555570000 7 1038 0x555555571000 13.5 1039 \end{lstlisting} 1040 Examples 2 to 3 change the alignment, fill, and size for the initial storage of @i@. 1041 1042 \begin{cfa}[numbers=left] 1043 int * ia = alloc( 5, @5`fill@ ); for ( i; 5 ) sout | ia[i]; sout | nl; 1044 ia = alloc( 10, @ia`resize@, @7`fill@ ); for ( i; 10 ) sout | ia[i]; sout | nl; 1045 sout | ia; ia = alloc( 5, @ia`resize@, @512`align@, @13`fill@ ); sout | ia; for ( i; 5 ) sout | ia[i]; sout | nl;; 1046 ia = alloc( 3, @ia`resize@, @4096`align@, @2`fill@ ); sout | ia; for ( i; 3 ) sout | &ia[i] | ia[i]; sout | nl; 1047 \end{cfa} 1048 \begin{lstlisting}[numbers=left] 1049 5 5 5 5 5 1050 7 7 7 7 7 7 7 7 7 7 1051 0x55555556d560 0x555555571a00 13 13 13 13 13 1052 0x555555572000 0x555555572000 2 0x555555572004 2 0x555555572008 2 1053 \end{lstlisting} 1054 Examples 2 to 4 change the array size, alignment and fill for the initial storage of @ia@. 1055 1056 \subparagraph{\lstinline{S_realloc(T) ?`realloc( T * a ))}} 1057 used to resize, realign, and fill, where the old object data is copied to the new object. 1058 The old object type must be the same as the new object type, since the values used. 1059 Note, for @fill@, only the extra space after copying the data from the old object is filled with the given parameter. 1060 For example: 1061 \begin{cfa}[numbers=left] 1062 int * i = alloc( @5`fill@ ); sout | i | *i; 1063 i = alloc( @i`realloc@, @256`align@ ); sout | i | *i; 1064 i = alloc( @i`realloc@, @4096`align@, @13`fill@ ); sout | i | *i; 1065 \end{cfa} 1066 \begin{lstlisting}[numbers=left] 1067 0x55555556d5c0 5 1068 0x555555570000 5 1069 0x555555571000 5 1070 \end{lstlisting} 1071 Examples 2 to 3 change the alignment for the initial storage of @i@. 1072 The @13`fill@ for example 3 does nothing because no extra space is added. 1073 1074 \begin{cfa}[numbers=left] 1075 int * ia = alloc( 5, @5`fill@ ); for ( i; 5 ) sout | ia[i]; sout | nl; 1076 ia = alloc( 10, @ia`realloc@, @7`fill@ ); for ( i; 10 ) sout | ia[i]; sout | nl; 1077 sout | ia; ia = alloc( 1, @ia`realloc@, @512`align@, @13`fill@ ); sout | ia; for ( i; 1 ) sout | ia[i]; sout | nl;; 1078 ia = alloc( 3, @ia`realloc@, @4096`align@, @2`fill@ ); sout | ia; for ( i; 3 ) sout | &ia[i] | ia[i]; sout | nl; 1079 \end{cfa} 1080 \begin{lstlisting}[numbers=left] 1081 5 5 5 5 5 1082 5 5 5 5 5 7 7 7 7 7 1083 0x55555556c560 0x555555570a00 5 1084 0x555555571000 0x555555571000 5 0x555555571004 2 0x555555571008 2 1085 \end{lstlisting} 1086 Examples 2 to 4 change the array size, alignment and fill for the initial storage of @ia@. 1087 The @13`fill@ for example 3 does nothing because no extra space is added. 1088 1089 These \CFA allocation features are used extensively in the development of the \CFA runtime. -
doc/theses/mubeen_zulfiqar_MMath/background.tex
rba897d21 r2e9b59b 34 34 \VRef[Figure]{f:AllocatorComponents} shows the two important data components for a memory allocator, management and storage, collectively called the \newterm{heap}. 35 35 The \newterm{management data} is a data structure located at a known memory address and contains all information necessary to manage the storage data. 36 The management data starts with fixed-sized information in the static-data memory that flows intothe dynamic-allocation memory.36 The management data starts with fixed-sized information in the static-data memory that references components in the dynamic-allocation memory. 37 37 The \newterm{storage data} is composed of allocated and freed objects, and \newterm{reserved memory}. 38 Allocated objects ( white) are variable sized, and allocated and maintained by the program;38 Allocated objects (light grey) are variable sized, and allocated and maintained by the program; 39 39 \ie only the program knows the location of allocated storage, not the memory allocator. 40 40 \begin{figure}[h] … … 44 44 \label{f:AllocatorComponents} 45 45 \end{figure} 46 Freed objects ( light grey) are memory deallocated by the program, which are linked into one or more lists facilitating easy location fornew allocations.46 Freed objects (white) represent memory deallocated by the program, which are linked into one or more lists facilitating easy location of new allocations. 47 47 Often the free list is chained internally so it does not consume additional storage, \ie the link fields are placed at known locations in the unused memory blocks. 48 48 Reserved memory (dark grey) is one or more blocks of memory obtained from the operating system but not yet allocated to the program; … … 54 54 The trailer may be used to simplify an allocation implementation, \eg coalescing, and/or for security purposes to mark the end of an object. 55 55 An object may be preceded by padding to ensure proper alignment. 56 Some algorithms quantize allocation requests into distinct sizes resulting in additional spacing after objects less than the quantized value. 56 Some algorithms quantize allocation requests into distinct sizes, called \newterm{buckets}, resulting in additional spacing after objects less than the quantized value. 57 (Note, the buckets are often organized as an array of ascending bucket sizes for fast searching, \eg binary search, and the array is stored in the heap management-area, where each bucket is a top point to the freed objects of that size.) 57 58 When padding and spacing are necessary, neither can be used to satisfy a future allocation request while the current allocation exists. 58 59 A free object also contains management data, \eg size, chaining, etc. … … 81 82 Fragmentation is memory requested from the operating system but not used by the program; 82 83 hence, allocated objects are not fragmentation. 83 \VRef[Figure]{f:InternalExternalFragmentation} )shows fragmentation is divided into two forms: internal or external.84 \VRef[Figure]{f:InternalExternalFragmentation} shows fragmentation is divided into two forms: internal or external. 84 85 85 86 \begin{figure} … … 96 97 An allocator should strive to keep internal management information to a minimum. 97 98 98 \newterm{External fragmentation} is all memory space reserved from the operating system but not allocated to the program~\cite{Wilson95,Lim98,Siebert00}, which includes freed objects, all external management data, and reserved memory.99 \newterm{External fragmentation} is all memory space reserved from the operating system but not allocated to the program~\cite{Wilson95,Lim98,Siebert00}, which includes all external management data, freed objects, and reserved memory. 99 100 This memory is problematic in two ways: heap blowup and highly fragmented memory. 100 101 \newterm{Heap blowup} occurs when memory freed by the program is not reused for future allocations leading to potentially unbounded external fragmentation growth~\cite{Berger00}. … … 125 126 \end{figure} 126 127 127 For a single-threaded memory allocator, three basic approaches for controlling fragmentation have beenidentified~\cite{Johnstone99}.128 For a single-threaded memory allocator, three basic approaches for controlling fragmentation are identified~\cite{Johnstone99}. 128 129 The first approach is a \newterm{sequential-fit algorithm} with one list of free objects that is searched for a block large enough to fit a requested object size. 129 130 Different search policies determine the free object selected, \eg the first free object large enough or closest to the requested size. … … 132 133 133 134 The second approach is a \newterm{segregated} or \newterm{binning algorithm} with a set of lists for different sized freed objects. 134 When an object is allocated, the requested size is rounded up to the nearest bin-size, possibly withspacing after the object.135 When an object is allocated, the requested size is rounded up to the nearest bin-size, often leading to spacing after the object. 135 136 A binning algorithm is fast at finding free memory of the appropriate size and allocating it, since the first free object on the free list is used. 136 137 The fewer bin-sizes, the fewer lists need to be searched and maintained; … … 158 159 Temporal locality commonly occurs during an iterative computation with a fix set of disjoint variables, while spatial locality commonly occurs when traversing an array. 159 160 160 Hardware takes advantage of temporal and spatial locality through multiple levels of caching (\ie memory hierarchy).161 Hardware takes advantage of temporal and spatial locality through multiple levels of caching, \ie memory hierarchy. 161 162 When an object is accessed, the memory physically located around the object is also cached with the expectation that the current and nearby objects will be referenced within a short period of time. 162 163 For example, entire cache lines are transferred between memory and cache and entire virtual-memory pages are transferred between disk and memory. … … 171 172 172 173 There are a number of ways a memory allocator can degrade locality by increasing the working set. 173 For example, a memory allocator may access multiple free objects before finding one to satisfy an allocation request (\eg sequential-fit algorithm).174 For example, a memory allocator may access multiple free objects before finding one to satisfy an allocation request, \eg sequential-fit algorithm. 174 175 If there are a (large) number of objects accessed in very different areas of memory, the allocator may perturb the program's memory hierarchy causing multiple cache or page misses~\cite{Grunwald93}. 175 176 Another way locality can be degraded is by spatially separating related data. … … 181 182 182 183 A multi-threaded memory-allocator does not run any threads itself, but is used by a multi-threaded program. 183 In addition to single-threaded design issues of locality and fragmentation, a multi-threaded allocator may besimultaneously accessed by multiple threads, and hence, must deal with concurrency issues such as mutual exclusion, false sharing, and additional forms of heap blowup.184 In addition to single-threaded design issues of fragmentation and locality, a multi-threaded allocator is simultaneously accessed by multiple threads, and hence, must deal with concurrency issues such as mutual exclusion, false sharing, and additional forms of heap blowup. 184 185 185 186 … … 192 193 Second is when multiple threads contend for a shared resource simultaneously, and hence, some threads must wait until the resource is released. 193 194 Contention can be reduced in a number of ways: 195 \begin{itemize}[itemsep=0pt] 196 \item 194 197 using multiple fine-grained locks versus a single lock, spreading the contention across a number of locks; 198 \item 195 199 using trylock and generating new storage if the lock is busy, yielding a classic space versus time tradeoff; 200 \item 196 201 using one of the many lock-free approaches for reducing contention on basic data-structure operations~\cite{Oyama99}. 197 However, all of these approaches have degenerate cases where contention occurs. 202 \end{itemize} 203 However, all of these approaches have degenerate cases where program contention is high, which occurs outside of the allocator. 198 204 199 205 … … 275 281 \label{s:MultipleHeaps} 276 282 277 A single-threaded allocator has at most one thread and heap, while amulti-threaded allocator has potentially multiple threads and heaps.283 A multi-threaded allocator has potentially multiple threads and heaps. 278 284 The multiple threads cause complexity, and multiple heaps are a mechanism for dealing with the complexity. 279 285 The spectrum ranges from multiple threads using a single heap, denoted as T:1 (see \VRef[Figure]{f:SingleHeap}), to multiple threads sharing multiple heaps, denoted as T:H (see \VRef[Figure]{f:SharedHeaps}), to one thread per heap, denoted as 1:1 (see \VRef[Figure]{f:PerThreadHeap}), which is almost back to a single-threaded allocator. … … 339 345 An alternative implementation is for all heaps to share one reserved memory, which requires a separate lock for the reserved storage to ensure mutual exclusion when acquiring new memory. 340 346 Because multiple threads can allocate/free/reallocate adjacent storage, all forms of false sharing may occur. 341 Other storage-management options are to use @mmap@ to set aside (large) areas of virtual memory for each heap and suballocate each heap's storage within that area .347 Other storage-management options are to use @mmap@ to set aside (large) areas of virtual memory for each heap and suballocate each heap's storage within that area, pushing part of the storage management complexity back to the operating system. 342 348 343 349 \begin{figure} … … 368 374 369 375 370 \paragraph{1:1 model (thread heaps)} where each thread has its own heap , which eliminates most contention and locking because threads seldom accesses another thread's heap (see ownership in \VRef{s:Ownership}).376 \paragraph{1:1 model (thread heaps)} where each thread has its own heap eliminating most contention and locking because threads seldom access another thread's heap (see ownership in \VRef{s:Ownership}). 371 377 An additional benefit of thread heaps is improved locality due to better memory layout. 372 378 As each thread only allocates from its heap, all objects for a thread are consolidated in the storage area for that heap, better utilizing each CPUs cache and accessing fewer pages. … … 380 386 Second is to place the thread heap on a list of available heaps and reuse it for a new thread in the future. 381 387 Destroying the thread heap immediately may reduce external fragmentation sooner, since all free objects are freed to the global heap and may be reused by other threads. 382 Alternatively, reusing thread heaps may improve performance if the inheriting thread makes similar allocation requests as the thread that previously held the thread heap .388 Alternatively, reusing thread heaps may improve performance if the inheriting thread makes similar allocation requests as the thread that previously held the thread heap because any unfreed storage is immediately accessible.. 383 389 384 390 … … 388 394 However, an important goal of user-level threading is for fast operations (creation/termination/context-switching) by not interacting with the operating system, which allows the ability to create large numbers of high-performance interacting threads ($>$ 10,000). 389 395 It is difficult to retain this goal, if the user-threading model is directly involved with the heap model. 390 \VRef[Figure]{f:UserLevelKernelHeaps} shows that virtually all user-level threading systems use whatever kernel-level heap-model provided by the language runtime.396 \VRef[Figure]{f:UserLevelKernelHeaps} shows that virtually all user-level threading systems use whatever kernel-level heap-model is provided by the language runtime. 391 397 Hence, a user thread allocates/deallocates from/to the heap of the kernel thread on which it is currently executing. 392 398 … … 400 406 Adopting this model results in a subtle problem with shared heaps. 401 407 With kernel threading, an operation that is started by a kernel thread is always completed by that thread. 402 For example, if a kernel thread starts an allocation/deallocation on a shared heap, it always completes that operation with that heap even if preempted. 403 Any correctness locking associated with the shared heap is preserved across preemption. 408 For example, if a kernel thread starts an allocation/deallocation on a shared heap, it always completes that operation with that heap even if preempted, \ie any locking correctness associated with the shared heap is preserved across preemption. 404 409 405 410 However, this correctness property is not preserved for user-level threading. … … 409 414 However, eagerly disabling/enabling time-slicing on the allocation/deallocation fast path is expensive, because preemption is rare (10--100 milliseconds). 410 415 Instead, techniques exist to lazily detect this case in the interrupt handler, abort the preemption, and return to the operation so it can complete atomically. 411 Occasionally ignoring a preemption should be benign .416 Occasionally ignoring a preemption should be benign, but a persistent lack of preemption can result in both short and long term starvation. 412 417 413 418 … … 430 435 431 436 \newterm{Ownership} defines which heap an object is returned-to on deallocation. 432 If a thread returns an object to the heap it was originally allocated from, theheap has ownership of its objects.433 Alternatively, a thread can return an object to the heap it is currently a llocating from, which can be any heap accessible during a thread's lifetime.437 If a thread returns an object to the heap it was originally allocated from, a heap has ownership of its objects. 438 Alternatively, a thread can return an object to the heap it is currently associated with, which can be any heap accessible during a thread's lifetime. 434 439 \VRef[Figure]{f:HeapsOwnership} shows an example of multiple heaps (minus the global heap) with and without ownership. 435 440 Again, the arrows indicate the direction memory conceptually moves for each kind of operation. … … 539 544 Only with the 1:1 model and ownership is active and passive false-sharing avoided (see \VRef{s:Ownership}). 540 545 Passive false-sharing may still occur, if delayed ownership is used. 546 Finally, a completely free container can become reserved storage and be reset to allocate objects of a new size or freed to the global heap. 541 547 542 548 \begin{figure} … … 553 559 \caption{Free-list Structure with Container Ownership} 554 560 \end{figure} 555 556 A fragmented heap has multiple containers that may be partially or completely free.557 A completely free container can become reserved storage and be reset to allocate objects of a new size.558 When a heap reaches a threshold of free objects, it moves some free storage to the global heap for reuse to prevent heap blowup.559 Without ownership, when a heap frees objects to the global heap, individual objects must be passed, and placed on the global-heap's free-list.560 Containers cannot be freed to the global heap unless completely free because561 561 562 562 When a container changes ownership, the ownership of all objects within it change as well. … … 569 569 Note, once the object is freed by Task$_1$, no more false sharing can occur until the container changes ownership again. 570 570 To prevent this form of false sharing, container movement may be restricted to when all objects in the container are free. 571 One implementation approach that increases the freedom to return a free container to the operating system involves allocating containers using a call like @mmap@, which allows memory at an arbitrary address to be returned versus only storage at the end of the contiguous @sbrk@ area .571 One implementation approach that increases the freedom to return a free container to the operating system involves allocating containers using a call like @mmap@, which allows memory at an arbitrary address to be returned versus only storage at the end of the contiguous @sbrk@ area, again pushing storage management complexity back to the operating system. 572 572 573 573 \begin{figure} … … 700 700 \end{figure} 701 701 702 As mentioned, an implementation may have only one heap dealwith the global heap, so the other heap can be simplified.702 As mentioned, an implementation may have only one heap interact with the global heap, so the other heap can be simplified. 703 703 For example, if only the private heap interacts with the global heap, the public heap can be reduced to a lock-protected free-list of objects deallocated by other threads due to ownership, called a \newterm{remote free-list}. 704 704 To avoid heap blowup, the private heap allocates from the remote free-list when it reaches some threshold or it has no free storage. … … 721 721 An allocation buffer is reserved memory (see~\VRef{s:AllocatorComponents}) not yet allocated to the program, and is used for allocating objects when the free list is empty. 722 722 That is, rather than requesting new storage for a single object, an entire buffer is requested from which multiple objects are allocated later. 723 Both any heap may use an allocation buffer, resulting in allocation from the buffer before requesting objects (containers) from the global heap or operating system, respectively.723 Any heap may use an allocation buffer, resulting in allocation from the buffer before requesting objects (containers) from the global heap or operating system, respectively. 724 724 The allocation buffer reduces contention and the number of global/operating-system calls. 725 725 For coalescing, a buffer is split into smaller objects by allocations, and recomposed into larger buffer areas during deallocations. 726 726 727 Allocation buffers are useful initially when there are no freed objects in a heap because many allocations usually occur when a thread starts .727 Allocation buffers are useful initially when there are no freed objects in a heap because many allocations usually occur when a thread starts (simple bump allocation). 728 728 Furthermore, to prevent heap blowup, objects should be reused before allocating a new allocation buffer. 729 Thus, allocation buffers are often allocated more frequently at program/thread start, and then their use often diminishes.729 Thus, allocation buffers are often allocated more frequently at program/thread start, and then allocations often diminish. 730 730 731 731 Using an allocation buffer with a thread heap avoids active false-sharing, since all objects in the allocation buffer are allocated to the same thread. … … 746 746 \label{s:LockFreeOperations} 747 747 748 A lock-free algorithm guarantees safe concurrent-access to a data structure, so that at least one thread can make progress in the system, but an individual task has no bound to execution, and hence,may starve~\cite[pp.~745--746]{Herlihy93}.749 % A wait-free algorithm puts a finite bound on the number of steps any thread takes to complete an operation, so an individual task cannot starve 748 A \newterm{lock-free algorithm} guarantees safe concurrent-access to a data structure, so that at least one thread makes progress, but an individual task has no execution bound and may starve~\cite[pp.~745--746]{Herlihy93}. 749 (A \newterm{wait-free algorithm} puts a bound on the number of steps any thread takes to complete an operation to prevent starvation.) 750 750 Lock-free operations can be used in an allocator to reduce or eliminate the use of locks. 751 Locks are a problem for high contention or if the thread holding the lock is preempted and other threads attempt to use that lock.752 With respect to the heap, these situations are unlikely unless all threads make sextremely high use of dynamic-memory allocation, which can be an indication of poor design.751 While locks and lock-free data-structures often have equal performance, lock-free has the advantage of not holding a lock across preemption so other threads can continue to make progress. 752 With respect to the heap, these situations are unlikely unless all threads make extremely high use of dynamic-memory allocation, which can be an indication of poor design. 753 753 Nevertheless, lock-free algorithms can reduce the number of context switches, since a thread does not yield/block while waiting for a lock; 754 on the other hand, a thread may busy-wait for an unbounded period .754 on the other hand, a thread may busy-wait for an unbounded period holding a processor. 755 755 Finally, lock-free implementations have greater complexity and hardware dependency. 756 756 Lock-free algorithms can be applied most easily to simple free-lists, \eg remote free-list, to allow lock-free insertion and removal from the head of a stack. 757 Implementing lock-free operations for more complex data-structures (queue~\cite{Valois94}/deque~\cite{Sundell08}) is more complex.757 Implementing lock-free operations for more complex data-structures (queue~\cite{Valois94}/deque~\cite{Sundell08}) is correspondingly more complex. 758 758 Michael~\cite{Michael04} and Gidenstam \etal \cite{Gidenstam05} have created lock-free variations of the Hoard allocator. 759 759 -
doc/theses/mubeen_zulfiqar_MMath/figures/AllocDS1.fig
rba897d21 r2e9b59b 8 8 -2 9 9 1200 2 10 6 4200 1575 4500 172511 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 4275 1650 20 20 4275 1650 4295 165012 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 4350 1650 20 20 4350 1650 4370 165013 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 4425 1650 20 20 4425 1650 4445 165010 6 2850 2100 3150 2250 11 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 2925 2175 20 20 2925 2175 2945 2175 12 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 3000 2175 20 20 3000 2175 3020 2175 13 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 3075 2175 20 20 3075 2175 3095 2175 14 14 -6 15 6 2850 2475 3150 2850 15 6 4050 2100 4350 2250 16 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 4125 2175 20 20 4125 2175 4145 2175 17 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 4200 2175 20 20 4200 2175 4220 2175 18 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 4275 2175 20 20 4275 2175 4295 2175 19 -6 20 6 4650 2100 4950 2250 21 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 4725 2175 20 20 4725 2175 4745 2175 22 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 4800 2175 20 20 4800 2175 4820 2175 23 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 4875 2175 20 20 4875 2175 4895 2175 24 -6 25 6 3450 2100 3750 2250 26 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 3525 2175 20 20 3525 2175 3545 2175 27 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 3600 2175 20 20 3600 2175 3620 2175 28 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 3675 2175 20 20 3675 2175 3695 2175 29 -6 30 6 3300 2175 3600 2550 16 31 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 2 17 32 1 1 1.00 45.00 90.00 18 2925 2475 2925 270033 3375 2175 3375 2400 19 34 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 20 2850 2700 3150 2700 3150 2850 2850 2850 2850 270035 3300 2400 3600 2400 3600 2550 3300 2550 3300 2400 21 36 -6 22 6 4350 2475 4650 2850 37 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 38 3150 1800 3150 2250 39 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 40 2850 1800 2850 2250 41 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 42 4650 1800 4650 2250 43 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 44 4950 1800 4950 2250 45 2 1 0 3 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 46 4500 1725 4500 2250 47 2 1 0 3 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 48 5100 1725 5100 2250 49 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 50 3450 1800 3450 2250 51 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 52 3750 1800 3750 2250 53 2 1 0 3 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 54 3300 1725 3300 2250 55 2 1 0 3 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 56 3900 1725 3900 2250 57 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 58 5250 1800 5250 2250 59 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 60 5400 1800 5400 2250 61 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 62 5550 1800 5550 2250 63 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 64 5700 1800 5700 2250 65 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 66 5850 1800 5850 2250 67 2 1 0 3 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 68 2700 1725 2700 2250 23 69 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 2 24 70 1 1 1.00 45.00 90.00 25 4425 2475 4425 2700 26 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 27 4350 2700 4650 2700 4650 2850 4350 2850 4350 2700 28 -6 29 6 3600 2475 3825 3150 71 3375 1275 3375 1575 30 72 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 2 31 73 1 1 1.00 45.00 90.00 32 3675 2475 3675 2700 33 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 34 3600 2700 3825 2700 3825 2850 3600 2850 3600 2700 35 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 36 3600 3000 3825 3000 3825 3150 3600 3150 3600 3000 74 2700 1275 2700 1575 75 2 1 1 1 0 7 50 -1 -1 4.000 0 0 -1 1 0 2 76 1 1 1.00 45.00 90.00 77 2775 1275 2775 1575 37 78 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 2 38 79 1 1 1.00 45.00 90.00 39 3675 2775 3675 3000 40 -6 41 6 4875 3600 5175 3750 42 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 4950 3675 20 20 4950 3675 4970 3675 43 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 5025 3675 20 20 5025 3675 5045 3675 44 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 5100 3675 20 20 5100 3675 5120 3675 45 -6 46 6 4875 2325 5175 2475 47 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 4950 2400 20 20 4950 2400 4970 2400 48 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 5025 2400 20 20 5025 2400 5045 2400 49 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 5100 2400 20 20 5100 2400 5120 2400 50 -6 51 6 5625 2325 5925 2475 52 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 5700 2400 20 20 5700 2400 5720 2400 53 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 5775 2400 20 20 5775 2400 5795 2400 54 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 5850 2400 20 20 5850 2400 5870 2400 55 -6 56 6 5625 3600 5925 3750 57 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 5700 3675 20 20 5700 3675 5720 3675 58 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 5775 3675 20 20 5775 3675 5795 3675 59 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 5850 3675 20 20 5850 3675 5870 3675 60 -6 61 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 62 2400 2100 2400 2550 63 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 64 2550 2100 2550 2550 65 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 66 2700 2100 2700 2550 67 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 68 2850 2100 2850 2550 69 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 70 3000 2100 3000 2550 71 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 72 3600 2100 3600 2550 73 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 74 3900 2100 3900 2550 75 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 76 4050 2100 4050 2550 77 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 78 4200 2100 4200 2550 79 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 80 4350 2100 4350 2550 81 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 82 4500 2100 4500 2550 83 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 84 3300 1500 3300 1800 85 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 86 3600 1500 3600 1800 87 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 88 3900 1500 3900 1800 89 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 90 3000 1500 4800 1500 4800 1800 3000 1800 3000 1500 80 5175 1275 5175 1575 81 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 2 82 1 1 1.00 45.00 90.00 83 5625 1275 5625 1575 84 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 2 85 1 1 1.00 45.00 90.00 86 3750 1275 3750 1575 91 87 2 1 1 1 0 7 50 -1 -1 4.000 0 0 -1 1 0 2 92 88 1 1 1.00 45.00 90.00 93 3225 1650 2625 2100 89 3825 1275 3825 1575 90 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 91 2700 1950 6000 1950 92 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 93 2700 2100 6000 2100 94 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 95 2700 1800 6000 1800 6000 2250 2700 2250 2700 1800 94 96 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 2 95 97 1 1 1.00 45.00 90.00 96 3150 1650 2550 210098 2775 2175 2775 2400 97 99 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 2 98 100 1 1 1.00 45.00 90.00 99 3450 1650 4050 2100 100 2 1 1 1 0 7 50 -1 -1 4.000 0 0 -1 1 0 2 101 1 1 1.00 45.00 90.00 102 3375 1650 3975 2100 103 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 104 2100 2100 2100 2550 105 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 106 1950 2250 3150 2250 107 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 108 3450 2250 4650 2250 101 2775 2475 2775 2700 109 102 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 110 1950 2100 3150 2100 3150 2550 1950 2550 1950 2100103 2700 2700 2850 2700 2850 2850 2700 2850 2700 2700 111 104 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 112 3450 2100 4650 2100 4650 2550 3450 2550 3450 2100 113 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 114 2250 2100 2250 2550 115 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 116 3750 2100 3750 2550 105 2700 2400 2850 2400 2850 2550 2700 2550 2700 2400 117 106 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 2 118 107 1 1 1.00 45.00 90.00 119 2025 2475 2025 2700 120 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 2 121 1 1 1.00 45.00 90.00 122 2025 2775 2025 3000 108 4575 2175 4575 2400 123 109 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 124 1950 3000 2100 3000 2100 3150 1950 3150 1950 3000 125 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 126 1950 2700 2100 2700 2100 2850 1950 2850 1950 2700 110 4500 2400 5025 2400 5025 2550 4500 2550 4500 2400 127 111 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 3 128 112 1 1 1.00 45.00 90.00 129 1950 3750 2700 3750 2700 3525113 3600 3375 4350 3375 4350 3150 130 114 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 131 1950 3525 3150 3525 3150 3900 1950 3900 1950 3525 132 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 3 133 1 1 1.00 45.00 90.00 134 3450 3750 4200 3750 4200 3525 135 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 136 3450 3525 4650 3525 4650 3900 3450 3900 3450 3525 137 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 3 138 1 1 1.00 45.00 90.00 139 3150 4650 4200 4650 4200 4275 140 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 141 3150 4275 4650 4275 4650 4875 3150 4875 3150 4275 142 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 143 1950 2400 3150 2400 144 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 145 3450 2400 4650 2400 146 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 147 5400 2100 5400 3900 148 4 2 0 50 -1 0 11 0.0000 2 120 300 1875 2250 lock\001 149 4 1 0 50 -1 0 12 0.0000 2 135 1935 3900 1425 N kernel-thread buckets\001 150 4 1 0 50 -1 0 12 0.0000 2 195 810 4425 2025 heap$_2$\001 151 4 1 0 50 -1 0 12 0.0000 2 195 810 2175 2025 heap$_1$\001 152 4 2 0 50 -1 0 11 0.0000 2 120 270 1875 2400 size\001 153 4 2 0 50 -1 0 11 0.0000 2 120 270 1875 2550 free\001 154 4 1 0 50 -1 0 12 0.0000 2 180 825 2550 3450 local pool\001 155 4 0 0 50 -1 0 12 0.0000 2 135 360 3525 3700 lock\001 156 4 0 0 50 -1 0 12 0.0000 2 135 360 3225 4450 lock\001 157 4 2 0 50 -1 0 12 0.0000 2 135 600 1875 3000 free list\001 158 4 1 0 50 -1 0 12 0.0000 2 180 825 4050 3450 local pool\001 159 4 1 0 50 -1 0 12 0.0000 2 180 1455 3900 4200 global pool (sbrk)\001 160 4 0 0 50 -1 0 12 0.0000 2 135 360 2025 3700 lock\001 161 4 1 0 50 -1 0 12 0.0000 2 180 720 6450 3150 free pool\001 162 4 1 0 50 -1 0 12 0.0000 2 180 390 6450 2925 heap\001 115 3600 3150 5100 3150 5100 3525 3600 3525 3600 3150 116 4 2 0 50 -1 0 11 0.0000 2 135 300 2625 1950 lock\001 117 4 1 0 50 -1 0 11 0.0000 2 150 1155 3000 1725 N$\\times$S$_1$\001 118 4 1 0 50 -1 0 11 0.0000 2 150 1155 3600 1725 N$\\times$S$_2$\001 119 4 1 0 50 -1 0 12 0.0000 2 180 390 4425 1500 heap\001 120 4 2 0 50 -1 0 12 0.0000 2 135 1140 2550 1425 kernel threads\001 121 4 2 0 50 -1 0 11 0.0000 2 120 270 2625 2100 size\001 122 4 2 0 50 -1 0 11 0.0000 2 120 270 2625 2250 free\001 123 4 2 0 50 -1 0 12 0.0000 2 135 600 2625 2700 free list\001 124 4 0 0 50 -1 0 12 0.0000 2 135 360 3675 3325 lock\001 125 4 1 0 50 -1 0 12 0.0000 2 180 1455 4350 3075 global pool (sbrk)\001 126 4 1 0 50 -1 0 11 0.0000 2 150 1110 4800 1725 N$\\times$S$_t$\001 -
doc/theses/mubeen_zulfiqar_MMath/figures/AllocDS2.fig
rba897d21 r2e9b59b 8 8 -2 9 9 1200 2 10 6 2850 2100 3150 2250 11 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 2925 2175 20 20 2925 2175 2945 2175 12 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 3000 2175 20 20 3000 2175 3020 2175 13 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 3075 2175 20 20 3075 2175 3095 2175 14 -6 15 6 4050 2100 4350 2250 16 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 4125 2175 20 20 4125 2175 4145 2175 17 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 4200 2175 20 20 4200 2175 4220 2175 18 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 4275 2175 20 20 4275 2175 4295 2175 19 -6 20 6 4650 2100 4950 2250 21 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 4725 2175 20 20 4725 2175 4745 2175 22 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 4800 2175 20 20 4800 2175 4820 2175 23 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 4875 2175 20 20 4875 2175 4895 2175 24 -6 25 6 3450 2100 3750 2250 26 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 3525 2175 20 20 3525 2175 3545 2175 27 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 3600 2175 20 20 3600 2175 3620 2175 28 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 3675 2175 20 20 3675 2175 3695 2175 29 -6 30 6 3300 2175 3600 2550 10 6 2850 2475 3150 2850 31 11 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 2 32 12 1 1 1.00 45.00 90.00 33 3375 2175 3375 240013 2925 2475 2925 2700 34 14 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 35 3300 2400 3600 2400 3600 2550 3300 2550 3300 2400 15 2850 2700 3150 2700 3150 2850 2850 2850 2850 2700 16 -6 17 6 4350 2475 4650 2850 18 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 2 19 1 1 1.00 45.00 90.00 20 4425 2475 4425 2700 21 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 22 4350 2700 4650 2700 4650 2850 4350 2850 4350 2700 23 -6 24 6 3600 2475 3825 3150 25 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 2 26 1 1 1.00 45.00 90.00 27 3675 2475 3675 2700 28 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 29 3600 2700 3825 2700 3825 2850 3600 2850 3600 2700 30 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 31 3600 3000 3825 3000 3825 3150 3600 3150 3600 3000 32 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 2 33 1 1 1.00 45.00 90.00 34 3675 2775 3675 3000 35 -6 36 6 1950 3525 3150 3900 37 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 3 38 1 1 1.00 45.00 90.00 39 1950 3750 2700 3750 2700 3525 40 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 41 1950 3525 3150 3525 3150 3900 1950 3900 1950 3525 42 4 0 0 50 -1 0 12 0.0000 2 135 360 2025 3700 lock\001 43 -6 44 6 4050 1575 4350 1725 45 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 4125 1650 20 20 4125 1650 4145 1650 46 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 4200 1650 20 20 4200 1650 4220 1650 47 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 4275 1650 20 20 4275 1650 4295 1650 48 -6 49 6 4875 2325 6150 3750 50 6 4875 2325 5175 2475 51 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 4950 2400 20 20 4950 2400 4970 2400 52 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 5025 2400 20 20 5025 2400 5045 2400 53 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 5100 2400 20 20 5100 2400 5120 2400 54 -6 55 6 4875 3600 5175 3750 56 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 4950 3675 20 20 4950 3675 4970 3675 57 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 5025 3675 20 20 5025 3675 5045 3675 58 1 3 0 1 0 0 50 -1 20 0.000 1 0.0000 5100 3675 20 20 5100 3675 5120 3675 59 -6 60 4 1 0 50 -1 0 12 0.0000 2 180 900 5700 3150 local pools\001 61 4 1 0 50 -1 0 12 0.0000 2 180 465 5700 2925 heaps\001 62 -6 63 6 3600 4050 5100 4650 64 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 3 65 1 1 1.00 45.00 90.00 66 3600 4500 4350 4500 4350 4275 67 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 68 3600 4275 5100 4275 5100 4650 3600 4650 3600 4275 69 4 1 0 50 -1 0 12 0.0000 2 180 1455 4350 4200 global pool (sbrk)\001 70 4 0 0 50 -1 0 12 0.0000 2 135 360 3675 4450 lock\001 36 71 -6 37 72 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 38 3150 1800 3150 225073 2400 2100 2400 2550 39 74 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 40 2 850 1800 2850 225075 2550 2100 2550 2550 41 76 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 42 4650 1800 4650 225077 2700 2100 2700 2550 43 78 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 44 4950 1800 4950 2250 45 2 1 0 3 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 46 4500 1725 4500 2250 47 2 1 0 3 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 48 5100 1725 5100 2250 79 2850 2100 2850 2550 49 80 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 50 3 450 1800 3450 225081 3000 2100 3000 2550 51 82 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 52 3750 1800 3750 2250 53 2 1 0 3 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 54 3300 1725 3300 2250 55 2 1 0 3 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 56 3900 1725 3900 2250 83 3600 2100 3600 2550 57 84 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 58 5250 1800 5250 225085 3900 2100 3900 2550 59 86 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 60 5400 1800 5400 225087 4050 2100 4050 2550 61 88 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 62 5550 1800 5550 225089 4200 2100 4200 2550 63 90 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 64 5700 1800 5700 225091 4350 2100 4350 2550 65 92 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 66 5850 1800 5850 2250 67 2 1 0 3 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 68 2700 1725 2700 2250 93 4500 2100 4500 2550 94 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 95 3300 1500 3300 1800 96 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 97 3600 1500 3600 1800 98 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 99 3000 1500 4800 1500 4800 1800 3000 1800 3000 1500 69 100 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 2 70 101 1 1 1.00 45.00 90.00 71 3 375 1275 3375 1575102 3150 1650 2550 2100 72 103 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 2 73 104 1 1 1.00 45.00 90.00 74 2700 1275 2700 1575 75 2 1 1 1 0 7 50 -1 -1 4.000 0 0 -1 1 0 2 76 1 1 1.00 45.00 90.00 77 2775 1275 2775 1575 105 3450 1650 4050 2100 106 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 107 2100 2100 2100 2550 108 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 109 1950 2250 3150 2250 110 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 111 3450 2250 4650 2250 112 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 113 1950 2100 3150 2100 3150 2550 1950 2550 1950 2100 114 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 115 3450 2100 4650 2100 4650 2550 3450 2550 3450 2100 116 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 117 2250 2100 2250 2550 118 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 119 3750 2100 3750 2550 78 120 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 2 79 121 1 1 1.00 45.00 90.00 80 5175 1275 5175 1575122 2025 2475 2025 2700 81 123 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 2 82 124 1 1 1.00 45.00 90.00 83 5625 1275 5625 1575 84 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 2 85 1 1 1.00 45.00 90.00 86 3750 1275 3750 1575 87 2 1 1 1 0 7 50 -1 -1 4.000 0 0 -1 1 0 2 88 1 1 1.00 45.00 90.00 89 3825 1275 3825 1575 90 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 91 2700 1950 6000 1950 92 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 93 2700 2100 6000 2100 125 2025 2775 2025 3000 94 126 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 95 2700 1800 6000 1800 6000 2250 2700 2250 2700 1800 96 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 2 97 1 1 1.00 45.00 90.00 98 2775 2175 2775 2400 99 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 2 100 1 1 1.00 45.00 90.00 101 2775 2475 2775 2700 127 1950 3000 2100 3000 2100 3150 1950 3150 1950 3000 102 128 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 103 2700 2700 2850 2700 2850 2850 2700 2850 2700 2700 104 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 105 2700 2400 2850 2400 2850 2550 2700 2550 2700 2400 106 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 2 107 1 1 1.00 45.00 90.00 108 4575 2175 4575 2400 109 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 110 4500 2400 5025 2400 5025 2550 4500 2550 4500 2400 129 1950 2700 2100 2700 2100 2850 1950 2850 1950 2700 111 130 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 1 0 3 112 131 1 1 1.00 45.00 90.00 113 3 600 3525 4650 3525 4650 3150132 3450 3750 4200 3750 4200 3525 114 133 2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5 115 3600 3150 5100 3150 5100 3750 3600 3750 3600 3150 116 4 2 0 50 -1 0 11 0.0000 2 120 300 2625 1950 lock\001 117 4 1 0 50 -1 0 10 0.0000 2 150 1155 3000 1725 N$\\times$S$_1$\001 118 4 1 0 50 -1 0 10 0.0000 2 150 1155 3600 1725 N$\\times$S$_2$\001 119 4 1 0 50 -1 0 12 0.0000 2 180 390 4425 1500 heap\001 120 4 2 0 50 -1 0 12 0.0000 2 135 1140 2550 1425 kernel threads\001 121 4 2 0 50 -1 0 11 0.0000 2 120 270 2625 2100 size\001 122 4 2 0 50 -1 0 11 0.0000 2 120 270 2625 2250 free\001 123 4 2 0 50 -1 0 12 0.0000 2 135 600 2625 2700 free list\001 124 4 0 0 50 -1 0 12 0.0000 2 135 360 3675 3325 lock\001 125 4 1 0 50 -1 0 12 0.0000 2 180 1455 4350 3075 global pool (sbrk)\001 126 4 1 0 50 -1 0 10 0.0000 2 150 1110 4800 1725 N$\\times$S$_t$\001 134 3450 3525 4650 3525 4650 3900 3450 3900 3450 3525 135 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 136 1950 2400 3150 2400 137 2 1 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 2 138 3450 2400 4650 2400 139 4 2 0 50 -1 0 11 0.0000 2 135 300 1875 2250 lock\001 140 4 1 0 50 -1 0 12 0.0000 2 180 1245 3900 1425 H heap buckets\001 141 4 1 0 50 -1 0 12 0.0000 2 180 810 4425 2025 heap$_2$\001 142 4 1 0 50 -1 0 12 0.0000 2 180 810 2175 2025 heap$_1$\001 143 4 2 0 50 -1 0 11 0.0000 2 120 270 1875 2400 size\001 144 4 2 0 50 -1 0 11 0.0000 2 120 270 1875 2550 free\001 145 4 1 0 50 -1 0 12 0.0000 2 180 825 2550 3450 local pool\001 146 4 0 0 50 -1 0 12 0.0000 2 135 360 3525 3700 lock\001 147 4 2 0 50 -1 0 12 0.0000 2 135 600 1875 3000 free list\001 148 4 1 0 50 -1 0 12 0.0000 2 180 825 4050 3450 local pool\001 -
doc/theses/mubeen_zulfiqar_MMath/intro.tex
rba897d21 r2e9b59b 48 48 Attempts have been made to perform quasi garbage collection in C/\CC~\cite{Boehm88}, but it is a compromise. 49 49 This thesis only examines dynamic memory-management with \emph{explicit} deallocation. 50 While garbage collection and compaction are not part this work, many of the results are applicable to the allocation phase in any memory-management approach.50 While garbage collection and compaction are not part this work, many of the work's results are applicable to the allocation phase in any memory-management approach. 51 51 52 52 Most programs use a general-purpose allocator, often the one provided implicitly by the programming-language's runtime. … … 65 65 \begin{enumerate}[leftmargin=*] 66 66 \item 67 Implementation of a new stand-lone concurrent low-latency memory-allocator ($\approx$1,200 lines of code) for C/\CC programs using kernel threads (1:1 threading), and specialized versions of the allocator for programming languages \uC and \CFA using user-level threads running over multiple kernel threads (M:N threading). 68 69 \item 70 Adopt returning of @nullptr@ for a zero-sized allocation, rather than an actual memory address, both of which can be passed to @free@. 71 72 \item 73 Extended the standard C heap functionality by preserving with each allocation its original request size versus the amount allocated, if an allocation is zero fill, and the allocation alignment. 74 75 \item 76 Use the zero fill and alignment as \emph{sticky} properties for @realloc@, to realign existing storage, or preserve existing zero-fill and alignment when storage is copied. 67 Implementation of a new stand-lone concurrent low-latency memory-allocator ($\approx$1,200 lines of code) 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). 68 69 \item 70 Adopt @nullptr@ return for a zero-sized allocation, rather than an actual memory address, which can be passed to @free@. 71 72 \item 73 Extend the standard C heap functionality by preserving with each allocation: 74 \begin{itemize}[itemsep=0pt] 75 \item 76 its request size plus the amount allocated, 77 \item 78 whether an allocation is zero fill, 79 \item 80 and allocation alignment. 81 \end{itemize} 82 83 \item 84 Use the preserved zero fill and alignment as \emph{sticky} properties for @realloc@ to zero-fill and align when storage is extended or copied. 77 85 Without this extension, it is unsafe to @realloc@ storage initially allocated with zero-fill/alignment as these properties are not preserved when copying. 78 86 This silent generation of a problem is unintuitive to programmers and difficult to locate because it is transient. … … 86 94 @resize( oaddr, alignment, size )@ re-purpose an old allocation with new alignment but \emph{without} preserving fill. 87 95 \item 88 @realloc( oaddr, alignment, size )@ same as previous@realloc@ but adding or changing alignment.96 @realloc( oaddr, alignment, size )@ same as @realloc@ but adding or changing alignment. 89 97 \item 90 98 @aalloc( dim, elemSize )@ same as @calloc@ except memory is \emph{not} zero filled. … … 96 104 97 105 \item 98 Provide additional heap wrapper functions in \CFA to provide a completeorthogonal set of allocation operations and properties.106 Provide additional heap wrapper functions in \CFA creating an orthogonal set of allocation operations and properties. 99 107 100 108 \item … … 109 117 @malloc_size( addr )@ returns the size of the memory allocation pointed-to by @addr@. 110 118 \item 111 @malloc_usable_size( addr )@ returns the usable size of the memory pointed-to by @addr@, i.e., the bin size containing the allocation, where @malloc_size( addr )@ $\le$ @malloc_usable_size( addr )@.119 @malloc_usable_size( addr )@ returns the usable (total) size of the memory pointed-to by @addr@, i.e., the bin size containing the allocation, where @malloc_size( addr )@ $\le$ @malloc_usable_size( addr )@. 112 120 \end{itemize} 113 121 … … 116 124 117 125 \item 118 Provide complete, fast, and contention-free allocation statistics to help understand programbehaviour:126 Provide complete, fast, and contention-free allocation statistics to help understand allocation behaviour: 119 127 \begin{itemize} 120 128 \item -
doc/theses/mubeen_zulfiqar_MMath/performance.tex
rba897d21 r2e9b59b 1 1 \chapter{Performance} 2 \label{c:Performance} 2 3 3 4 \section{Machine Specification} -
doc/theses/mubeen_zulfiqar_MMath/uw-ethesis.bib
rba897d21 r2e9b59b 124 124 } 125 125 126 @misc{nedmalloc, 127 author = {Niall Douglas}, 128 title = {nedmalloc version 1.06 Beta}, 129 month = jan, 130 year = 2010, 131 note = {\textsf{http://\-prdownloads.\-sourceforge.\-net/\-nedmalloc/\-nedmalloc\_v1.06beta1\_svn1151.zip}}, 126 @misc{ptmalloc2, 127 author = {Wolfram Gloger}, 128 title = {ptmalloc version 2}, 129 month = jun, 130 year = 2006, 131 note = {\href{http://www.malloc.de/malloc/ptmalloc2-current.tar.gz}{http://www.malloc.de/\-malloc/\-ptmalloc2-current.tar.gz}}, 132 } 133 134 @misc{GNUallocAPI, 135 author = {GNU}, 136 title = {Summary of malloc-Related Functions}, 137 year = 2020, 138 note = {\href{https://www.gnu.org/software/libc/manual/html\_node/Summary-of-Malloc.html}{https://www.gnu.org/\-software/\-libc/\-manual/\-html\_node/\-Summary-of-Malloc.html}}, 139 } 140 141 @misc{SeriallyReusable, 142 author = {IBM}, 143 title = {Serially reusable programs}, 144 month = mar, 145 year = 2021, 146 note = {\href{https://www.ibm.com/docs/en/ztpf/1.1.0.15?topic=structures-serially-reusable-programs}{https://www.ibm.com/\-docs/\-en/\-ztpf/\-1.1.0.15?\-topic=structures-serially-reusable-programs}}, 147 } 148 149 @misc{librseq, 150 author = {Mathieu Desnoyers}, 151 title = {Library for Restartable Sequences}, 152 month = mar, 153 year = 2022, 154 note = {\href{https://github.com/compudj/librseq}{https://github.com/compudj/librseq}}, 132 155 } 133 156 -
doc/theses/mubeen_zulfiqar_MMath/uw-ethesis.tex
rba897d21 r2e9b59b 60 60 % For hyperlinked PDF, suitable for viewing on a computer, use this: 61 61 \documentclass[letterpaper,12pt,titlepage,oneside,final]{book} 62 \usepackage[T1]{fontenc} % Latin-1 => 256-bit characters, => | not dash, <> not Spanish question marks 62 63 63 64 % For PDF, suitable for double-sided printing, change the PrintVersion variable below to "true" and use this \documentclass line instead of the one above: … … 94 95 % Use the "hyperref" package 95 96 % N.B. HYPERREF MUST BE THE LAST PACKAGE LOADED; ADD ADDITIONAL PKGS ABOVE 96 \usepackage[pagebackref=true]{hyperref} % with basic options 97 \usepackage{url} 98 \usepackage[dvips,pagebackref=true]{hyperref} % with basic options 97 99 %\usepackage[pdftex,pagebackref=true]{hyperref} 98 100 % N.B. pagebackref=true provides links back from the References to the body text. This can cause trouble for printing. … … 113 115 citecolor=blue, % color of links to bibliography 114 116 filecolor=magenta, % color of file links 115 urlcolor=blue % color of external links 117 urlcolor=blue, % color of external links 118 breaklinks=true 116 119 } 117 120 \ifthenelse{\boolean{PrintVersion}}{ % for improved print quality, change some hyperref options … … 122 125 urlcolor=black 123 126 }}{} % end of ifthenelse (no else) 127 %\usepackage[dvips,plainpages=false,pdfpagelabels,pdfpagemode=UseNone,pagebackref=true,breaklinks=true,colorlinks=true,linkcolor=blue,citecolor=blue,urlcolor=blue]{hyperref} 128 \usepackage{breakurl} 129 \urlstyle{sf} 124 130 125 131 %\usepackage[automake,toc,abbreviations]{glossaries-extra} % Exception to the rule of hyperref being the last add-on package … … 171 177 \input{common} 172 178 %\usepackageinput{common} 173 \CFAStyle % CFA code-style for all languages 179 \CFAStyle % CFA code-style 180 \lstset{language=CFA} % default language 174 181 \lstset{basicstyle=\linespread{0.9}\sf} % CFA typewriter font 175 182 \newcommand{\uC}{$\mu$\CC} -
doc/theses/thierry_delisle_PhD/thesis/Makefile
rba897d21 r2e9b59b 29 29 PICTURES = ${addsuffix .pstex, \ 30 30 base \ 31 base_avg \ 32 cache-share \ 33 cache-noshare \ 31 34 empty \ 32 35 emptybit \ … … 38 41 system \ 39 42 cycle \ 43 result.cycle.jax.ops \ 40 44 } 41 45 … … 112 116 python3 $< $@ 113 117 118 build/result.%.ns.svg : data/% | ${Build} 119 ../../../../benchmark/plot.py -f $< -o $@ -y "ns per ops" 120 121 build/result.%.ops.svg : data/% | ${Build} 122 ../../../../benchmark/plot.py -f $< -o $@ -y "Ops per second" 123 114 124 ## pstex with inverted colors 115 125 %.dark.pstex : fig/%.fig Makefile | ${Build} -
doc/theses/thierry_delisle_PhD/thesis/fig/base.fig
rba897d21 r2e9b59b 89 89 5700 5210 5550 4950 5250 4950 5100 5210 5250 5470 5550 5470 90 90 5700 5210 91 2 1 1 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2 92 3600 5700 3600 1200 93 2 1 1 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2 94 4800 5700 4800 1200 95 2 1 1 1 0 7 50 -1 -1 4.000 0 0 -1 0 0 2 96 6000 5700 6000 1200 91 97 4 2 -1 50 -1 0 12 0.0000 2 135 630 2100 3075 Threads\001 92 98 4 2 -1 50 -1 0 12 0.0000 2 165 450 2100 2850 Ready\001 -
doc/theses/thierry_delisle_PhD/thesis/glossary.tex
rba897d21 r2e9b59b 101 101 102 102 \longnewglossaryentry{at} 103 {name={ fred}}103 {name={task}} 104 104 { 105 105 Abstract object representing an unit of work. Systems will offer one or more concrete implementations of this concept (\eg \gls{kthrd}, \gls{job}), however, most of the concept of schedulings are independent of the particular implementations of the work representation. For this reason, this document use the term \Gls{at} to mean any representation and not one in particular. -
doc/theses/thierry_delisle_PhD/thesis/local.bib
rba897d21 r2e9b59b 685 685 note = "[Online; accessed 9-February-2021]" 686 686 } 687 688 @misc{wiki:rcu, 689 author = "{Wikipedia contributors}", 690 title = "Read-copy-update --- {W}ikipedia{,} The Free Encyclopedia", 691 year = "2022", 692 url = "https://en.wikipedia.org/wiki/Linear_congruential_generator", 693 note = "[Online; accessed 12-April-2022]" 694 } 695 696 @misc{wiki:rwlock, 697 author = "{Wikipedia contributors}", 698 title = "Readers-writer lock --- {W}ikipedia{,} The Free Encyclopedia", 699 year = "2021", 700 url = "https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock", 701 note = "[Online; accessed 12-April-2022]" 702 } -
doc/theses/thierry_delisle_PhD/thesis/text/core.tex
rba897d21 r2e9b59b 3 3 Before discussing scheduling in general, where it is important to address systems that are changing states, this document discusses scheduling in a somewhat ideal scenario, where the system has reached a steady state. For this purpose, a steady state is loosely defined as a state where there are always \glspl{thrd} ready to run and the system has the resources necessary to accomplish the work, \eg, enough workers. In short, the system is neither overloaded nor underloaded. 4 4 5 I believe it is important to discuss the steady state first because it is the easiest case to handle and, relatedly, the case in which the best performance is to be expected. As such, when the system is either overloaded or underloaded, a common approach is to try to adapt the system to this new load and return to the steady state, \eg, by adding or removing workers. Therefore, flaws in scheduling the steady state canto be pervasive in all states.5 It is important to discuss the steady state first because it is the easiest case to handle and, relatedly, the case in which the best performance is to be expected. As such, when the system is either overloaded or underloaded, a common approach is to try to adapt the system to this new load and return to the steady state, \eg, by adding or removing workers. Therefore, flaws in scheduling the steady state tend to be pervasive in all states. 6 6 7 7 \section{Design Goals} … … 25 25 It is important to note that these guarantees are expected only up to a point. \Glspl{thrd} that are ready to run should not be prevented to do so, but they still share the limited hardware resources. Therefore, the guarantee is considered respected if a \gls{thrd} gets access to a \emph{fair share} of the hardware resources, even if that share is very small. 26 26 27 Similarly the performance guarantee, the lack of interference among threads, is only relevant up to a point. Ideally, the cost of running and blocking should be constant regardless of contention, but the guarantee is considered satisfied if the cost is not \emph{too high} with or without contention. How much is an acceptable cost is obviously highly variable. For this document, the performance experimentation attempts to show the cost of scheduling is at worst equivalent to existing algorithms used in popular languages. This demonstration can be made by comparing applications built in \CFA to applications built with other languages or other models. Recall programmer expectation is that the impact of the scheduler can be ignored. Therefore, if the cost of scheduling is equivalent to or lower than other popular languages, I consider the guaranteeachieved.27 Similarly the performance guarantee, the lack of interference among threads, is only relevant up to a point. Ideally, the cost of running and blocking should be constant regardless of contention, but the guarantee is considered satisfied if the cost is not \emph{too high} with or without contention. How much is an acceptable cost is obviously highly variable. For this document, the performance experimentation attempts to show the cost of scheduling is at worst equivalent to existing algorithms used in popular languages. This demonstration can be made by comparing applications built in \CFA to applications built with other languages or other models. Recall programmer expectation is that the impact of the scheduler can be ignored. Therefore, if the cost of scheduling is compatitive to other popular languages, the guarantee will be consider achieved. 28 28 29 29 More precisely the scheduler should be: … … 33 33 \end{itemize} 34 34 35 \subsection{Fairness vs Scheduler Locality} 35 \subsection{Fairness Goals} 36 For this work fairness will be considered as having two strongly related requirements: true starvation freedom and ``fast'' load balancing. 37 38 \paragraph{True starvation freedom} is more easily defined: As long as at least one \proc continues to dequeue \ats, all read \ats should be able to run eventually. 39 In any running system, \procs can stop dequeing \ats if they start running a \at that will simply never park. 40 Traditional workstealing schedulers do not have starvation freedom in these cases. 41 Now this requirement begs the question, what about preemption? 42 Generally speaking preemption happens on the timescale of several milliseconds, which brings us to the next requirement: ``fast'' load balancing. 43 44 \paragraph{Fast load balancing} means that load balancing should happen faster than preemption would normally allow. 45 For interactive applications that need to run at 60, 90, 120 frames per second, \ats having to wait for several millseconds to run are effectively starved. 46 Therefore load-balancing should be done at a faster pace, one that can detect starvation at the microsecond scale. 47 With that said, this is a much fuzzier requirement since it depends on the number of \procs, the number of \ats and the general load of the system. 48 49 \subsection{Fairness vs Scheduler Locality} \label{fairnessvlocal} 36 50 An important performance factor in modern architectures is cache locality. Waiting for data at lower levels or not present in the cache can have a major impact on performance. Having multiple \glspl{hthrd} writing to the same cache lines also leads to cache lines that must be waited on. It is therefore preferable to divide data among each \gls{hthrd}\footnote{This partitioning can be an explicit division up front or using data structures where different \glspl{hthrd} are naturally routed to different cache lines.}. 37 51 38 For a scheduler, having good locality\footnote{This section discusses \emph{internal locality}, \ie, the locality of the data used by the scheduler versus \emph{external locality}, \ie, how the data used by the application is affected by scheduling. External locality is a much more complicated subject and is discussed in part~\ref{Evaluation} on evaluation.}, \ie, having the data local to each \gls{hthrd}, generally conflicts with fairness. Indeed, good locality often requires avoiding the movement of cache lines, while fairness requires dynamically moving a \gls{thrd}, and as consequence cache lines, to a \gls{hthrd} that is currently available.52 For a scheduler, having good locality\footnote{This section discusses \emph{internal locality}, \ie, the locality of the data used by the scheduler versus \emph{external locality}, \ie, how the data used by the application is affected by scheduling. External locality is a much more complicated subject and is discussed in the next section.}, \ie, having the data local to each \gls{hthrd}, generally conflicts with fairness. Indeed, good locality often requires avoiding the movement of cache lines, while fairness requires dynamically moving a \gls{thrd}, and as consequence cache lines, to a \gls{hthrd} that is currently available. 39 53 40 54 However, I claim that in practice it is possible to strike a balance between fairness and performance because these goals do not necessarily overlap temporally, where Figure~\ref{fig:fair} shows a visual representation of this behaviour. As mentioned, some unfairness is acceptable; therefore it is desirable to have an algorithm that prioritizes cache locality as long as thread delay does not exceed the execution mental-model. … … 48 62 \end{figure} 49 63 50 \section{Design} 64 \subsection{Performance Challenges}\label{pref:challenge} 65 While there exists a multitude of potential scheduling algorithms, they generally always have to contend with the same performance challenges. Since these challenges are recurring themes in the design of a scheduler it is relevant to describe the central ones here before looking at the design. 66 67 \subsubsection{Scalability} 68 The most basic performance challenge of a scheduler is scalability. 69 Given a large number of \procs and an even larger number of \ats, scalability measures how fast \procs can enqueue and dequeues \ats. 70 One could expect that doubling the number of \procs would double the rate at which \ats are dequeued, but contention on the internal data structure of the scheduler can lead to worst improvements. 71 While the ready-queue itself can be sharded to alleviate the main source of contention, auxillary scheduling features, \eg counting ready \ats, can also be sources of contention. 72 73 \subsubsection{Migration Cost} 74 Another important source of latency in scheduling is migration. 75 An \at is said to have migrated if it is executed by two different \proc consecutively, which is the process discussed in \ref{fairnessvlocal}. 76 Migrations can have many different causes, but it certain programs it can be all but impossible to limit migrations. 77 Chapter~\ref{microbench} for example, has a benchmark where any \at can potentially unblock any other \at, which can leat to \ats migrating more often than not. 78 Because of this it is important to design the internal data structures of the scheduler to limit the latency penalty from migrations. 79 80 81 \section{Inspirations} 51 82 In general, a na\"{i}ve \glsxtrshort{fifo} ready-queue does not scale with increased parallelism from \glspl{hthrd}, resulting in decreased performance. The problem is adding/removing \glspl{thrd} is a single point of contention. As shown in the evaluation sections, most production schedulers do scale when adding \glspl{hthrd}. The solution to this problem is to shard the ready-queue : create multiple sub-ready-queues that multiple \glspl{hthrd} can access and modify without interfering. 52 83 53 Before going into the design of \CFA's scheduler proper, I want to discuss two sharding solutions which served as the inspiration scheduler in this thesis.84 Before going into the design of \CFA's scheduler proper, it is relevant to discuss two sharding solutions which served as the inspiration scheduler in this thesis. 54 85 55 86 \subsection{Work-Stealing} 56 87 57 As I mentioned in \ref{existing:workstealing}, a popular pattern shard the ready-queue is work-stealing. As mentionned, in this pattern each \gls{proc} has its own ready-queue and \glspl{proc} only access each other's ready-queue if they run out of work. 58 The interesting aspect of workstealing happen in easier scheduling cases, \ie enough work for everyone but no more and no load balancing needed. In these cases, work-stealing is close to optimal scheduling: it can achieve perfect locality and have no contention. 88 As mentioned in \ref{existing:workstealing}, a popular pattern shard the ready-queue is work-stealing. 89 In this pattern each \gls{proc} has its own local ready-queue and \glspl{proc} only access each other's ready-queue if they run out of work on their local ready-queue. 90 The interesting aspect of workstealing happen in easier scheduling cases, \ie enough work for everyone but no more and no load balancing needed. 91 In these cases, work-stealing is close to optimal scheduling: it can achieve perfect locality and have no contention. 59 92 On the other hand, work-stealing schedulers only attempt to do load-balancing when a \gls{proc} runs out of work. 60 This means that the scheduler may never balance unfairness that does notresult in a \gls{proc} running out of work.93 This means that the scheduler never balances unfair loads unless they result in a \gls{proc} running out of work. 61 94 Chapter~\ref{microbench} shows that in pathological cases this problem can lead to indefinite starvation. 62 95 63 96 64 Based on these observation, I conclude that\emph{perfect} scheduler should behave very similarly to work-stealing in the easy cases, but should have more proactive load-balancing if the need arises.97 Based on these observation, the conclusion is that a \emph{perfect} scheduler should behave very similarly to work-stealing in the easy cases, but should have more proactive load-balancing if the need arises. 65 98 66 99 \subsection{Relaxed-Fifo} 67 100 An entirely different scheme is to create a ``relaxed-FIFO'' queue as in \todo{cite Trevor's paper}. This approach forgos any ownership between \gls{proc} and ready-queue, and simply creates a pool of ready-queues from which the \glspl{proc} can pick from. 68 101 \Glspl{proc} choose ready-queus at random, but timestamps are added to all elements of the queue and dequeues are done by picking two queues and dequeing the oldest element. 102 All subqueues are protected by TryLocks and \procs simply pick a different subqueue if they fail to acquire the TryLock. 69 103 The result is a queue that has both decent scalability and sufficient fairness. 70 104 The lack of ownership means that as long as one \gls{proc} is still able to repeatedly dequeue elements, it is unlikely that any element will stay on the queue for much longer than any other element. … … 75 109 76 110 While the fairness, of this scheme is good, it does suffer in terms of performance. 77 It requires very wide sharding, \eg at least 4 queues per \gls{hthrd}, and the randomness means locality can suffer significantly and finding non-empty queues can be difficult. 78 79 \section{\CFA} 80 The \CFA is effectively attempting to merge these two approaches, keeping the best of both. 81 It is based on the 111 It requires very wide sharding, \eg at least 4 queues per \gls{hthrd}, and finding non-empty queues can be difficult if there are too few ready \ats. 112 113 \section{Relaxed-FIFO++} 114 Since it has inherent fairness quelities and decent performance in the presence of many \ats, the relaxed-FIFO queue appears as a good candidate to form the basis of a scheduler. 115 The most obvious problems is for workloads where the number of \ats is barely greater than the number of \procs. 116 In these situations, the wide sharding means most of the sub-queues from which the relaxed queue is formed will be empty. 117 The consequence is that when a dequeue operations attempts to pick a sub-queue at random, it is likely that it picks an empty sub-queue and will have to pick again. 118 This problem can repeat an unbounded number of times. 119 120 As this is the most obvious challenge, it is worth addressing first. 121 The obvious solution is to supplement each subqueue with some sharded data structure that keeps track of which subqueues are empty. 122 This data structure can take many forms, for example simple bitmask or a binary tree that tracks which branch are empty. 123 Following a binary tree on each pick has fairly good Big O complexity and many modern architectures have powerful bitmask manipulation instructions. 124 However, precisely tracking which sub-queues are empty is actually fundamentally problematic. 125 The reason is that each subqueues are already a form of sharding and the sharding width has presumably already chosen to avoid contention. 126 However, tracking which ready queue is empty is only useful if the tracking mechanism uses denser sharding than the sub queues, then it will invariably create a new source of contention. 127 But if the tracking mechanism is not denser than the sub-queues, then it will generally not provide useful because reading this new data structure risks being as costly as simply picking a sub-queue at random. 128 Early experiments with this approach have shown that even with low success rates, randomly picking a sub-queue can be faster than a simple tree walk. 129 130 The exception to this rule is using local tracking. 131 If each \proc keeps track locally of which sub-queue is empty, then this can be done with a very dense data structure without introducing a new source of contention. 132 The consequence of local tracking however, is that the information is not complete. 133 Each \proc is only aware of the last state it saw each subqueues but does not have any information about freshness. 134 Even on systems with low \gls{hthrd} count, \eg 4 or 8, this can quickly lead to the local information being no better than the random pick. 135 This is due in part to the cost of this maintaining this information and its poor quality. 136 137 However, using a very low cost approach to local tracking may actually be beneficial. 138 If the local tracking is no more costly than the random pick, than \emph{any} improvement to the succes rate, however low it is, would lead to a performance benefits. 139 This leads to the following approach: 140 141 \subsection{Dynamic Entropy}\cit{https://xkcd.com/2318/} 142 The Relaxed-FIFO approach can be made to handle the case of mostly empty sub-queues by tweaking the \glsxtrlong{prng}. 143 The \glsxtrshort{prng} state can be seen as containing a list of all the future sub-queues that will be accessed. 144 While this is not particularly useful on its own, the consequence is that if the \glsxtrshort{prng} algorithm can be run \emph{backwards}, then the state also contains a list of all the subqueues that were accessed. 145 Luckily, bidirectional \glsxtrshort{prng} algorithms do exist, for example some Linear Congruential Generators\cit{https://en.wikipedia.org/wiki/Linear\_congruential\_generator} support running the algorithm backwards while offering good quality and performance. 146 This particular \glsxtrshort{prng} can be used as follows: 147 148 Each \proc maintains two \glsxtrshort{prng} states, which whill be refered to as \texttt{F} and \texttt{B}. 149 150 When a \proc attempts to dequeue a \at, it picks the subqueues by running the \texttt{B} backwards. 151 When a \proc attempts to enqueue a \at, it runs \texttt{F} forward to pick to subqueue to enqueue to. 152 If the enqueue is successful, the state \texttt{B} is overwritten with the content of \texttt{F}. 153 154 The result is that each \proc will tend to dequeue \ats that it has itself enqueued. 155 When most sub-queues are empty, this technique increases the odds of finding \ats at very low cost, while also offering an improvement on locality in many cases. 156 157 However, while this approach does notably improve performance in many cases, this algorithm is still not competitive with work-stealing algorithms. 158 The fundamental problem is that the constant randomness limits how much locality the scheduler offers. 159 This becomes problematic both because the scheduler is likely to get cache misses on internal data-structures and because migration become very frequent. 160 Therefore since the approach of modifying to relaxed-FIFO algorithm to behave more like work stealing does not seem to pan out, the alternative is to do it the other way around. 161 162 \section{Work Stealing++} 163 To add stronger fairness guarantees to workstealing a few changes. 164 First, the relaxed-FIFO algorithm has fundamentally better fairness because each \proc always monitors all subqueues. 165 Therefore the workstealing algorithm must be prepended with some monitoring. 166 Before attempting to dequeue from a \proc's local queue, the \proc must make some effort to make sure remote queues are not being neglected. 167 To make this possible, \procs must be able to determie which \at has been on the ready-queue the longest. 168 Which is the second aspect that much be added. 169 The relaxed-FIFO approach uses timestamps for each \at and this is also what is done here. 170 82 171 \begin{figure} 83 172 \centering 84 173 \input{base.pstex_t} 85 \caption[Base \CFA design]{Base \CFA design \smallskip\newline A list of sub-ready queues offers the sharding, two per \glspl{proc}. However, \glspl{proc} can access any of the sub-queues.}174 \caption[Base \CFA design]{Base \CFA design \smallskip\newline A Pool of sub-ready queues offers the sharding, two per \glspl{proc}. Each \gls{proc} have local subqueues, however \glspl{proc} can access any of the sub-queues. Each \at is timestamped when enqueued.} 86 175 \label{fig:base} 87 176 \end{figure} 88 89 90 91 % The common solution to the single point of contention is to shard the ready-queue so each \gls{hthrd} can access the ready-queue without contention, increasing performance. 92 93 % \subsection{Sharding} \label{sec:sharding} 94 % An interesting approach to sharding a queue is presented in \cit{Trevors paper}. This algorithm presents a queue with a relaxed \glsxtrshort{fifo} guarantee using an array of strictly \glsxtrshort{fifo} sublists as shown in Figure~\ref{fig:base}. Each \emph{cell} of the array has a timestamp for the last operation and a pointer to a linked-list with a lock. Each node in the list is marked with a timestamp indicating when it is added to the list. A push operation is done by picking a random cell, acquiring the list lock, and pushing to the list. If the cell is locked, the operation is simply retried on another random cell until a lock is acquired. A pop operation is done in a similar fashion except two random cells are picked. If both cells are unlocked with non-empty lists, the operation pops the node with the oldest timestamp. If one of the cells is unlocked and non-empty, the operation pops from that cell. If both cells are either locked or empty, the operation picks two new random cells and tries again. 95 96 % \begin{figure} 97 % \centering 98 % \input{base.pstex_t} 99 % \caption[Relaxed FIFO list]{Relaxed FIFO list \smallskip\newline List at the base of the scheduler: an array of strictly FIFO lists. The timestamp is in all nodes and cell arrays.} 100 % \label{fig:base} 101 % \end{figure} 102 103 % \subsection{Finding threads} 104 % Once threads have been distributed onto multiple queues, identifying empty queues becomes a problem. Indeed, if the number of \glspl{thrd} does not far exceed the number of queues, it is probable that several of the cell queues are empty. Figure~\ref{fig:empty} shows an example with 2 \glspl{thrd} running on 8 queues, where the chances of getting an empty queue is 75\% per pick, meaning two random picks yield a \gls{thrd} only half the time. This scenario leads to performance problems since picks that do not yield a \gls{thrd} are not useful and do not necessarily help make more informed guesses. 105 106 % \begin{figure} 107 % \centering 108 % \input{empty.pstex_t} 109 % \caption[``More empty'' Relaxed FIFO list]{``More empty'' Relaxed FIFO list \smallskip\newline Emptier state of the queue: the array contains many empty cells, that is strictly FIFO lists containing no elements.} 110 % \label{fig:empty} 111 % \end{figure} 112 113 % There are several solutions to this problem, but they ultimately all have to encode if a cell has an empty list. My results show the density and locality of this encoding is generally the dominating factor in these scheme. Classic solutions to this problem use one of three techniques to encode the information: 114 115 % \paragraph{Dense Information} Figure~\ref{fig:emptybit} shows a dense bitmask to identify the cell queues currently in use. This approach means processors can often find \glspl{thrd} in constant time, regardless of how many underlying queues are empty. Furthermore, modern x86 CPUs have extended bit manipulation instructions (BMI2) that allow searching the bitmask with very little overhead compared to the randomized selection approach for a filled ready queue, offering good performance even in cases with many empty inner queues. However, this technique has its limits: with a single word\footnote{Word refers here to however many bits can be written atomically.} bitmask, the total amount of ready-queue sharding is limited to the number of bits in the word. With a multi-word bitmask, this maximum limit can be increased arbitrarily, but the look-up time increases. Finally, a dense bitmap, either single or multi-word, causes additional contention problems that reduces performance because of cache misses after updates. This central update bottleneck also means the information in the bitmask is more often stale before a processor can use it to find an item, \ie mask read says there are available \glspl{thrd} but none on queue when the subsequent atomic check is done. 116 117 % \begin{figure} 118 % \centering 119 % \vspace*{-5pt} 120 % {\resizebox{0.75\textwidth}{!}{\input{emptybit.pstex_t}}} 121 % \vspace*{-5pt} 122 % \caption[Underloaded queue with bitmask]{Underloaded queue with bitmask indicating array cells with items.} 123 % \label{fig:emptybit} 124 125 % \vspace*{10pt} 126 % {\resizebox{0.75\textwidth}{!}{\input{emptytree.pstex_t}}} 127 % \vspace*{-5pt} 128 % \caption[Underloaded queue with binary search-tree]{Underloaded queue with binary search-tree indicating array cells with items.} 129 % \label{fig:emptytree} 130 131 % \vspace*{10pt} 132 % {\resizebox{0.95\textwidth}{!}{\input{emptytls.pstex_t}}} 133 % \vspace*{-5pt} 134 % \caption[Underloaded queue with per processor bitmask]{Underloaded queue with per processor bitmask indicating array cells with items.} 135 % \label{fig:emptytls} 136 % \end{figure} 137 138 % \paragraph{Sparse Information} Figure~\ref{fig:emptytree} shows an approach using a hierarchical tree data-structure to reduce contention and has been shown to work in similar cases~\cite{ellen2007snzi}. However, this approach may lead to poorer performance due to the inherent pointer chasing cost while still allowing significant contention on the nodes of the tree if the tree is shallow. 139 140 % \paragraph{Local Information} Figure~\ref{fig:emptytls} shows an approach using dense information, similar to the bitmap, but each \gls{hthrd} keeps its own independent copy. While this approach can offer good scalability \emph{and} low latency, the liveliness and discovery of the information can become a problem. This case is made worst in systems with few processors where even blind random picks can find \glspl{thrd} in a few tries. 141 142 % I built a prototype of these approaches and none of these techniques offer satisfying performance when few threads are present. All of these approach hit the same 2 problems. First, randomly picking sub-queues is very fast. That speed means any improvement to the hit rate can easily be countered by a slow-down in look-up speed, whether or not there are empty lists. Second, the array is already sharded to avoid contention bottlenecks, so any denser data structure tends to become a bottleneck. In all cases, these factors meant the best cases scenario, \ie many threads, would get worst throughput, and the worst-case scenario, few threads, would get a better hit rate, but an equivalent poor throughput. As a result I tried an entirely different approach. 143 144 % \subsection{Dynamic Entropy}\cit{https://xkcd.com/2318/} 145 % In the worst-case scenario there are only few \glspl{thrd} ready to run, or more precisely given $P$ \glspl{proc}\footnote{For simplicity, this assumes there is a one-to-one match between \glspl{proc} and \glspl{hthrd}.}, $T$ \glspl{thrd} and $\epsilon$ a very small number, than the worst case scenario can be represented by $T = P + \epsilon$, with $\epsilon \ll P$. It is important to note in this case that fairness is effectively irrelevant. Indeed, this case is close to \emph{actually matching} the model of the ``Ideal multi-tasking CPU'' on page \pageref{q:LinuxCFS}. In this context, it is possible to use a purely internal-locality based approach and still meet the fairness requirements. This approach simply has each \gls{proc} running a single \gls{thrd} repeatedly. Or from the shared ready-queue viewpoint, each \gls{proc} pushes to a given sub-queue and then pops from the \emph{same} subqueue. The challenge is for the the scheduler to achieve good performance in both the $T = P + \epsilon$ case and the $T \gg P$ case, without affecting the fairness guarantees in the later. 146 147 % To handle this case, I use a \glsxtrshort{prng}\todo{Fix missing long form} in a novel way. There exist \glsxtrshort{prng}s that are fast, compact and can be run forward \emph{and} backwards. Linear congruential generators~\cite{wiki:lcg} are an example of \glsxtrshort{prng}s of such \glsxtrshort{prng}s. The novel approach is to use the ability to run backwards to ``replay'' the \glsxtrshort{prng}. The scheduler uses an exclusive \glsxtrshort{prng} instance per \gls{proc}, the random-number seed effectively starts an encoding that produces a list of all accessed subqueues, from latest to oldest. Replaying the \glsxtrshort{prng} to identify cells accessed recently and which probably have data still cached. 148 149 % The algorithm works as follows: 150 % \begin{itemize} 151 % \item Each \gls{proc} has two \glsxtrshort{prng} instances, $F$ and $B$. 152 % \item Push and Pop operations occur as discussed in Section~\ref{sec:sharding} with the following exceptions: 153 % \begin{itemize} 154 % \item Push operations use $F$ going forward on each try and on success $F$ is copied into $B$. 155 % \item Pop operations use $B$ going backwards on each try. 156 % \end{itemize} 157 % \end{itemize} 158 159 % The main benefit of this technique is that it basically respects the desired properties of Figure~\ref{fig:fair}. When looking for work, a \gls{proc} first looks at the last cell they pushed to, if any, and then move backwards through its accessed cells. As the \gls{proc} continues looking for work, $F$ moves backwards and $B$ stays in place. As a result, the relation between the two becomes weaker, which means that the probablisitic fairness of the algorithm reverts to normal. Chapter~\ref{proofs} discusses more formally the fairness guarantees of this algorithm. 160 161 % \section{Details} 177 The algorithm is structure as shown in Figure~\ref{fig:base}. 178 This is very similar to classic workstealing except the local queues are placed in an array so \procs can access eachother's queue in constant time. 179 Sharding width can be adjusted based on need. 180 When a \proc attempts to dequeue a \at, it first picks a random remote queue and compares its timestamp to the timestamps of the local queue(s), dequeue from the remote queue if needed. 181 182 Implemented as as naively state above, this approach has some obvious performance problems. 183 First, it is necessary to have some damping effect on helping. 184 Random effects like cache misses and preemption can add spurious but short bursts of latency for which helping is not helpful, pun intended. 185 The effect of these bursts would be to cause more migrations than needed and make this workstealing approach slowdown to the match the relaxed-FIFO approach. 186 187 \begin{figure} 188 \centering 189 \input{base_avg.pstex_t} 190 \caption[\CFA design with Moving Average]{\CFA design with Moving Average \smallskip\newline A moving average is added to each subqueue.} 191 \label{fig:base-ma} 192 \end{figure} 193 194 A simple solution to this problem is to compare an exponential moving average\cit{https://en.wikipedia.org/wiki/Moving\_average\#Exponential\_moving\_average} instead if the raw timestamps, shown in Figure~\ref{fig:base-ma}. 195 Note that this is slightly more complex than it sounds because since the \at at the head of a subqueue is still waiting, its wait time has not ended. 196 Therefore the exponential moving average is actually an exponential moving average of how long each already dequeued \at have waited. 197 To compare subqueues, the timestamp at the head must be compared to the current time, yielding the bestcase wait time for the \at at the head of the queue. 198 This new waiting is averaged with the stored average. 199 To limit even more the amount of unnecessary migration, a bias can be added to the local queue, where a remote queue is helped only if its moving average is more than \emph{X} times the local queue's average. 200 None of the experimentation that I have run with these scheduler seem to indicate that the choice of the weight for the moving average or the choice of bis is particularly important. 201 Weigths and biases of similar \emph{magnitudes} have similar effects. 202 203 With these additions to workstealing, scheduling can be made as fair as the relaxed-FIFO approach, well avoiding the majority of unnecessary migrations. 204 Unfortunately, the performance of this approach does suffer in the cases with no risks of starvation. 205 The problem is that the constant polling of remote subqueues generally entail a cache miss. 206 To make things worst, remote subqueues that are very active, \ie \ats are frequently enqueued and dequeued from them, the higher the chances are that polling will incurr a cache-miss. 207 Conversly, the active subqueues do not benefit much from helping since starvation is already a non-issue. 208 This puts this algorithm in an akward situation where it is paying for a cost, but the cost itself suggests the operation was unnecessary. 209 The good news is that this problem can be mitigated 210 211 \subsection{Redundant Timestamps} 212 The problem with polling remote queues is due to a tension between the consistency requirement on the subqueue. 213 For the subqueues, correctness is critical. There must be a consensus among \procs on which subqueues hold which \ats. 214 Since the timestamps are use for fairness, it is alco important to have consensus and which \at is the oldest. 215 However, when deciding if a remote subqueue is worth polling, correctness is much less of a problem. 216 Since the only need is that a subqueue will eventually be polled, some data staleness can be acceptable. 217 This leads to a tension where stale timestamps are only problematic in some cases. 218 Furthermore, stale timestamps can be somewhat desirable since lower freshness requirements means less tension on the cache coherence protocol. 219 220 221 \begin{figure} 222 \centering 223 % \input{base_ts2.pstex_t} 224 \caption[\CFA design with Redundant Timestamps]{\CFA design with Redundant Timestamps \smallskip\newline A array is added containing a copy of the timestamps. These timestamps are written to with relaxed atomics, without fencing, leading to fewer cache invalidations.} 225 \label{fig:base-ts2} 226 \end{figure} 227 A solution to this is to create a second array containing a copy of the timestamps and average. 228 This copy is updated \emph{after} the subqueue's critical sections using relaxed atomics. 229 \Glspl{proc} now check if polling is needed by comparing the copy of the remote timestamp instead of the actual timestamp. 230 The result is that since there is no fencing, the writes can be buffered and cause fewer cache invalidations. 231 232 The correctness argument here is somewhat subtle. 233 The data used for deciding whether or not to poll a queue can be stale as long as it does not cause starvation. 234 Therefore, it is acceptable if stale data make queues appear older than they really are but not fresher. 235 For the timestamps, this means that missing writes to the timestamp is acceptable since they will make the head \at look older. 236 For the moving average, as long as the operation are RW-safe, the average is guaranteed to yield a value that is between the oldest and newest values written. 237 Therefore this unprotected read of the timestamp and average satisfy the limited correctness that is required. 238 239 \begin{figure} 240 \centering 241 \input{cache-share.pstex_t} 242 \caption[CPU design with wide L3 sharing]{CPU design with wide L3 sharing \smallskip\newline A very simple CPU with 4 \glspl{hthrd}. L1 and L2 are private to each \gls{hthrd} but the L3 is shared across to entire core.} 243 \label{fig:cache-share} 244 \end{figure} 245 246 \begin{figure} 247 \centering 248 \input{cache-noshare.pstex_t} 249 \caption[CPU design with a narrower L3 sharing]{CPU design with a narrower L3 sharing \smallskip\newline A different CPU design, still with 4 \glspl{hthrd}. L1 and L2 are still private to each \gls{hthrd} but the L3 is shared some of the CPU but there is still two distinct L3 instances.} 250 \label{fig:cache-noshare} 251 \end{figure} 252 253 With redundant tiemstamps this scheduling algorithm achieves both the fairness and performance requirements, on some machines. 254 The problem is that the cost of polling and helping is not necessarily consistent across each \gls{hthrd}. 255 For example, on machines where the motherboard holds multiple CPU, cache misses can be satisfied from a cache that belongs to the CPU that missed, the \emph{local} CPU, or by a different CPU, a \emph{remote} one. 256 Cache misses that are satisfied by a remote CPU will have higher latency than if it is satisfied by the local CPU. 257 However, this is not specific to systems with multiple CPUs. 258 Depending on the cache structure, cache-misses can have different latency for the same CPU. 259 The AMD EPYC 7662 CPUs that is described in Chapter~\ref{microbench} is an example of that. 260 Figure~\ref{fig:cache-share} and Figure~\ref{fig:cache-noshare} show two different cache topologies with highlight this difference. 261 In Figure~\ref{fig:cache-share}, all cache instances are either private to a \gls{hthrd} or shared to the entire system, this means latency due to cache-misses are likely fairly consistent. 262 By comparison, in Figure~\ref{fig:cache-noshare} misses in the L2 cache can be satisfied by a hit in either instance of the L3. 263 However, the memory access latency to the remote L3 instance will be notably higher than the memory access latency to the local L3. 264 The impact of these different design on this algorithm is that scheduling will scale very well on architectures similar to Figure~\ref{fig:cache-share}, both will have notably worst scalling with many narrower L3 instances. 265 This is simply because as the number of L3 instances grow, so two does the chances that the random helping will cause significant latency. 266 The solution is to have the scheduler be aware of the cache topology. 267 268 \subsection{Per CPU Sharding} 269 Building a scheduler that is aware of cache topology poses two main challenges: discovering cache topology and matching \procs to cache instance. 270 Sadly, there is no standard portable way to discover cache topology in C. 271 Therefore, while this is a significant portability challenge, it is outside the scope of this thesis to design a cross-platform cache discovery mechanisms. 272 The rest of this work assumes discovering the cache topology based on Linux's \texttt{/sys/devices/system/cpu} directory. 273 This leaves the challenge of matching \procs to cache instance, or more precisely identifying which subqueues of the ready queue are local to which cache instance. 274 Once this matching is available, the helping algorithm can be changed to add bias so that \procs more often help subqueues local to the same cache instance 275 \footnote{Note that like other biases mentioned in this section, the actual bias value does not appear to need precise tuinng.}. 276 277 The obvious approach to mapping cache instances to subqueues is to statically tie subqueues to CPUs. 278 Instead of having each subqueue local to a specific \proc, the system is initialized with subqueues for each \glspl{hthrd} up front. 279 Then \procs dequeue and enqueue by first asking which CPU id they are local to, in order to identify which subqueues are the local ones. 280 \Glspl{proc} can get the CPU id from \texttt{sched\_getcpu} or \texttt{librseq}. 281 282 This approach solves the performance problems on systems with topologies similar to Figure~\ref{fig:cache-noshare}. 283 However, it actually causes some subtle fairness problems in some systems, specifically systems with few \procs and many \glspl{hthrd}. 284 In these cases, the large number of subqueues and the bias agains subqueues tied to different cache instances make it so it is very unlikely any single subqueue is picked. 285 To make things worst, the small number of \procs mean that few helping attempts will be made. 286 This combination of few attempts and low chances make it so a \at stranded on a subqueue that is not actively dequeued from may wait very long before it gets randomly helped. 287 On a system with 2 \procs, 256 \glspl{hthrd} with narrow cache sharing, and a 100:1 bias, it can actually take multiple seconds for a \at to get dequeued from a remote queue. 288 Therefore, a more dynamic matching of subqueues to cache instance is needed. 289 290 \subsection{Topological Work Stealing} 291 The approach that is used in the \CFA scheduler is to have per-\proc subqueue, but have an excplicit data-structure track which cache instance each subqueue is tied to. 292 This is requires some finess because reading this data structure must lead to fewer cache misses than not having the data structure in the first place. 293 A key element however is that, like the timestamps for helping, reading the cache instance mapping only needs to give the correct result \emph{often enough}. 294 Therefore the algorithm can be built as follows: Before enqueuing or dequeing a \at, each \proc queries the CPU id and the corresponding cache instance. 295 Since subqueues are tied to \procs, each \proc can then update the cache instance mapped to the local subqueue(s). 296 To avoid unnecessary cache line invalidation, the map is only written to if the mapping changes. 297 -
doc/theses/thierry_delisle_PhD/thesis/text/eval_micro.tex
rba897d21 r2e9b59b 3 3 The first step of evaluation is always to test-out small controlled cases, to ensure that the basics are working properly. 4 4 This sections presents five different experimental setup, evaluating some of the basic features of \CFA's scheduler. 5 6 \section{Benchmark Environment} 7 All of these benchmarks are run on two distinct hardware environment, an AMD and an INTEL machine. 8 9 \paragraph{AMD} The AMD machine is a server with two AMD EPYC 7662 CPUs and 256GB of DDR4 RAM. 10 The server runs Ubuntu 20.04.2 LTS on top of Linux Kernel 5.8.0-55. 11 These EPYCs have 64 cores per CPUs and 2 \glspl{hthrd} per core, for a total of 256 \glspl{hthrd}. 12 The cpus each have 4 MB, 64 MB and 512 MB of L1, L2 and L3 caches respectively. 13 Each L1 and L2 instance are only shared by \glspl{hthrd} on a given core, but each L3 instance is shared by 4 cores, therefore 8 \glspl{hthrd}. 14 15 \paragraph{Intel} The Intel machine is a server with four Intel Xeon Platinum 8160 CPUs and 384GB of DDR4 RAM. 16 The server runs Ubuntu 20.04.2 LTS on top of Linux Kernel 5.8.0-55. 17 These Xeon Platinums have 24 cores per CPUs and 2 \glspl{hthrd} per core, for a total of 192 \glspl{hthrd}. 18 The cpus each have 3 MB, 96 MB and 132 MB of L1, L2 and L3 caches respectively. 19 Each L1 and L2 instance are only shared by \glspl{hthrd} on a given core, but each L3 instance is shared across the entire CPU, therefore 48 \glspl{hthrd}. 20 21 This limited sharing of the last level cache on the AMD machine is markedly different than the Intel machine. Indeed, while on both architectures L2 cache misses that are served by L3 caches on a different cpu incurr a significant latency, on AMD it is also the case that cache misses served by a different L3 instance on the same cpu still incur high latency. 22 5 23 6 24 \section{Cycling latency} … … 31 49 \end{figure} 32 50 33 \todo{check term ``idle sleep handling''}34 51 To avoid this benchmark from being dominated by the idle sleep handling, the number of rings is kept at least as high as the number of \glspl{proc} available. 35 52 Beyond this point, adding more rings serves to mitigate even more the idle sleep handling. 36 This is to avoid the case where one of the worker \glspl{at} runs out of work because of the variation on the number of ready \glspl{at} mentionned above.53 This is to avoid the case where one of the \glspl{proc} runs out of work because of the variation on the number of ready \glspl{at} mentionned above. 37 54 38 55 The actual benchmark is more complicated to handle termination, but that simply requires using a binary semphore or a channel instead of raw \texttt{park}/\texttt{unpark} and carefully picking the order of the \texttt{P} and \texttt{V} with respect to the loop condition. 39 56 40 \todo{code, setup, results}41 57 \begin{lstlisting} 42 58 Thread.main() { … … 52 68 \end{lstlisting} 53 69 70 \begin{figure} 71 \centering 72 \input{result.cycle.jax.ops.pstex_t} 73 \vspace*{-10pt} 74 \label{fig:cycle:ns:jax} 75 \end{figure} 54 76 55 77 \section{Yield} -
doc/theses/thierry_delisle_PhD/thesis/text/existing.tex
rba897d21 r2e9b59b 2 2 Scheduling is the process of assigning resources to incomming requests. 3 3 A very common form of this is assigning available workers to work-requests. 4 The need for scheduling is very common in Computer Science, \eg Operating Systems and Hypervisors schedule available CPUs, NICs schedule available bamdwith, but itis also common in other fields.5 For example, assmebly lines are an example of scheduling where parts needed assembly are assigned to line workers.4 The need for scheduling is very common in Computer Science, \eg Operating Systems and Hypervisors schedule available CPUs, NICs schedule available bamdwith, but scheduling is also common in other fields. 5 For example, in assmebly lines assigning parts in need of assembly to line workers is a form of scheduling. 6 6 7 7 In all these cases, the choice of a scheduling algorithm generally depends first and formost on how much information is available to the scheduler. … … 15 15 16 16 \section{Naming Convention} 17 Scheduling has been studied by various different communities concentrating on different incarnation of the same problems. As a result, their is no real naming convention for scheduling that is respected across these communities. For this document, I will use the term \newterm{ task} to refer to the abstract objects being scheduled and the term \newterm{worker} to refer to the objects which will execute these tasks.17 Scheduling has been studied by various different communities concentrating on different incarnation of the same problems. As a result, their is no real naming convention for scheduling that is respected across these communities. For this document, I will use the term \newterm{\Gls{at}} to refer to the abstract objects being scheduled and the term \newterm{\Gls{proc}} to refer to the objects which will execute these \glspl{at}. 18 18 19 19 \section{Static Scheduling} 20 Static schedulers require that taskshave their dependencies and costs explicitly and exhaustively specified prior schedule.20 Static schedulers require that \glspl{at} have their dependencies and costs explicitly and exhaustively specified prior schedule. 21 21 The scheduler then processes this input ahead of time and producess a \newterm{schedule} to which the system can later adhere. 22 22 This approach is generally popular in real-time systems since the need for strong guarantees justifies the cost of supplying this information. … … 26 26 27 27 \section{Dynamic Scheduling} 28 It may be difficult to fulfill the requirements of static scheduler if dependencies are conditionnal. In this case, it may be preferable to detect dependencies at runtime. This detection effectively takes the form of halting or suspending a task with unfulfilled dependencies and adding one or more new task(s) to the system. The new task(s) have the responsability of adding the dependent task back in the system once completed. As a consequence, the scheduler may have an incomplete view of the system, seeing only taskswe no pending dependencies. Schedulers that support this detection at runtime are referred to as \newterm{Dynamic Schedulers}.28 It may be difficult to fulfill the requirements of static scheduler if dependencies are conditionnal. In this case, it may be preferable to detect dependencies at runtime. This detection effectively takes the form of adding one or more new \gls{at}(s) to the system as their dependencies are resolved. As well as potentially halting or suspending a \gls{at} that dynamically detect unfulfilled dependencies. Each \gls{at} has the responsability of adding the dependent \glspl{at} back in the system once completed. As a consequence, the scheduler may have an incomplete view of the system, seeing only \glspl{at} we no pending dependencies. Schedulers that support this detection at runtime are referred to as \newterm{Dynamic Schedulers}. 29 29 30 30 \subsection{Explicitly Informed Dynamic Schedulers} 31 While dynamic schedulers do not have access to an exhaustive list of dependencies for a task, they may require to provide more or less information about each task, including for example: expected duration, required ressources, relative importance, etc. The scheduler can then use this information to direct the scheduling decisions. \cit{Examples of schedulers with more information} Precisely providing this information can be difficult for programmers, especially \emph{predicted} behaviour, and the scheduler may need to support some amount of imprecision in the provided information. For example, specifying that a tasks takes approximately 5 seconds to complete, rather than exactly 5 seconds. User provided information can also become a significant burden depending how the effort to provide the information scales with the number of tasks and there complexity. For example, providing an exhaustive list of files read by 5 tasks is an easier requirement the providing an exhaustive list of memory addresses accessed by 10'000 distinct tasks.31 While dynamic schedulers do not have access to an exhaustive list of dependencies for a \gls{at}, they may require to provide more or less information about each \gls{at}, including for example: expected duration, required ressources, relative importance, etc. The scheduler can then use this information to direct the scheduling decisions. \cit{Examples of schedulers with more information} Precisely providing this information can be difficult for programmers, especially \emph{predicted} behaviour, and the scheduler may need to support some amount of imprecision in the provided information. For example, specifying that a \glspl{at} takes approximately 5 seconds to complete, rather than exactly 5 seconds. User provided information can also become a significant burden depending how the effort to provide the information scales with the number of \glspl{at} and there complexity. For example, providing an exhaustive list of files read by 5 \glspl{at} is an easier requirement the providing an exhaustive list of memory addresses accessed by 10'000 distinct \glspl{at}. 32 32 33 33 Since the goal of this thesis is to provide a scheduler as a replacement for \CFA's existing \emph{uninformed} scheduler, Explicitly Informed schedulers are less relevant to this project. Nevertheless, some strategies are worth mentionnding. 34 34 35 35 \subsubsection{Prority Scheduling} 36 A commonly used information that schedulers used to direct the algorithm is priorities. Each Task is given a priority and higher-priority tasks are preferred to lower-priority ones. The simplest priority scheduling algorithm is to simply require that every task have a distinct pre-established priority and always run the available task with the highest priority. Asking programmers to provide an exhaustive set of unique priorities can be prohibitive when the system has a large number of tasks. It can therefore be diserable for schedulers to support tasks with identical priorities and/or automatically setting and adjusting priorites for tasks. 36 A commonly used information that schedulers used to direct the algorithm is priorities. Each Task is given a priority and higher-priority \glspl{at} are preferred to lower-priority ones. The simplest priority scheduling algorithm is to simply require that every \gls{at} have a distinct pre-established priority and always run the available \gls{at} with the highest priority. Asking programmers to provide an exhaustive set of unique priorities can be prohibitive when the system has a large number of \glspl{at}. It can therefore be diserable for schedulers to support \glspl{at} with identical priorities and/or automatically setting and adjusting priorites for \glspl{at}. The most common operating some variation on priorities with overlaps and dynamic priority adjustments. For example, Microsoft Windows uses a pair of priorities 37 \cit{https://docs.microsoft.com/en-us/windows/win32/procthread/scheduling-priorities,https://docs.microsoft.com/en-us/windows/win32/taskschd/taskschedulerschema-priority-settingstype-element}, one specified by users out of ten possible options and one adjusted by the system. 37 38 38 39 \subsection{Uninformed and Self-Informed Dynamic Schedulers} 39 Several scheduling algorithms do not require programmers to provide additionnal information on each task, and instead make scheduling decisions based solely on internal state and/or information implicitly gathered by the scheduler.40 Several scheduling algorithms do not require programmers to provide additionnal information on each \gls{at}, and instead make scheduling decisions based solely on internal state and/or information implicitly gathered by the scheduler. 40 41 41 42 42 43 \subsubsection{Feedback Scheduling} 43 As mentionned, Schedulers may also gather information about each tasks to direct their decisions. This design effectively moves the scheduler to some extent into the realm of \newterm{Control Theory}\cite{wiki:controltheory}. This gathering does not generally involve programmers and as such does not increase programmer burden the same way explicitly provided information may. However, some feedback schedulers do offer the option to programmers to offer additionnal information on certain tasks, in order to direct scheduling decision. The important distinction being whether or not the scheduler can function without this additionnal information.44 As mentionned, Schedulers may also gather information about each \glspl{at} to direct their decisions. This design effectively moves the scheduler to some extent into the realm of \newterm{Control Theory}\cite{wiki:controltheory}. This gathering does not generally involve programmers and as such does not increase programmer burden the same way explicitly provided information may. However, some feedback schedulers do offer the option to programmers to offer additionnal information on certain \glspl{at}, in order to direct scheduling decision. The important distinction being whether or not the scheduler can function without this additionnal information. 44 45 45 46 46 47 \section{Work Stealing}\label{existing:workstealing} 47 One of the most popular scheduling algorithm in practice (see~\ref{existing:prod}) is work-stealing. This idea, introduce by \cite{DBLP:conf/fpca/BurtonS81}, effectively has each worker work on its local tasks first, but allows the possibility for other workers to steal local tasks if they run out of tasks. \cite{DBLP:conf/focs/Blumofe94} introduced the more familiar incarnation of this, where each workers has queue of tasks to accomplish and workers without tasks steal tasks from random workers. (The Burton and Sleep algorithm had trees of tasksand stole only among neighbours). Blumofe and Leiserson also prove worst case space and time requirements for well-structured computations.48 One of the most popular scheduling algorithm in practice (see~\ref{existing:prod}) is work-stealing. This idea, introduce by \cite{DBLP:conf/fpca/BurtonS81}, effectively has each worker work on its local \glspl{at} first, but allows the possibility for other workers to steal local \glspl{at} if they run out of \glspl{at}. \cite{DBLP:conf/focs/Blumofe94} introduced the more familiar incarnation of this, where each workers has queue of \glspl{at} to accomplish and workers without \glspl{at} steal \glspl{at} from random workers. (The Burton and Sleep algorithm had trees of \glspl{at} and stole only among neighbours). Blumofe and Leiserson also prove worst case space and time requirements for well-structured computations. 48 49 49 50 Many variations of this algorithm have been proposed over the years\cite{DBLP:journals/ijpp/YangH18}, both optmizations of existing implementations and approaches that account for new metrics. … … 51 52 \paragraph{Granularity} A significant portion of early Work Stealing research was concentrating on \newterm{Implicit Parellelism}\cite{wiki:implicitpar}. Since the system was responsible to split the work, granularity is a challenge that cannot be left to the programmers (as opposed to \newterm{Explicit Parellelism}\cite{wiki:explicitpar} where the burden can be left to programmers). In general, fine granularity is better for load balancing and coarse granularity reduces communication overhead. The best performance generally means finding a middle ground between the two. Several methods can be employed, but I believe these are less relevant for threads, which are generally explicit and more coarse grained. 52 53 53 \paragraph{Task Placement} Since modern computers rely heavily on cache hierarchies\cit{Do I need a citation for this}, migrating tasksfrom one core to another can be . \cite{DBLP:journals/tpds/SquillanteL93}54 \paragraph{Task Placement} Since modern computers rely heavily on cache hierarchies\cit{Do I need a citation for this}, migrating \glspl{at} from one core to another can be . \cite{DBLP:journals/tpds/SquillanteL93} 54 55 55 56 \todo{The survey is not great on this subject} … … 58 59 59 60 \subsection{Theoretical Results} 60 There is also a large body of research on the theoretical aspects of work stealing. These evaluate, for example, the cost of migration\cite{DBLP:conf/sigmetrics/SquillanteN91,DBLP:journals/pe/EagerLZ86}, how affinity affects performance\cite{DBLP:journals/tpds/SquillanteL93,DBLP:journals/mst/AcarBB02,DBLP:journals/ipl/SuksompongLS16} and theoretical models for heterogenous systems\cite{DBLP:journals/jpdc/MirchandaneyTS90,DBLP:journals/mst/BenderR02,DBLP:conf/sigmetrics/GastG10}. \cite{DBLP:journals/jacm/BlellochGM99} examine the space bounds of Work Stealing and \cite{DBLP:journals/siamcomp/BerenbrinkFG03} show that for underloaded systems, the scheduler will complete computations in finite time, \ie is \newterm{stable}. Others show that Work-Stealing is applicable to various scheduling contexts\cite{DBLP:journals/mst/AroraBP01,DBLP:journals/anor/TchiboukdjianGT13,DBLP:conf/isaac/TchiboukdjianGTRB10,DBLP:conf/ppopp/AgrawalLS10,DBLP:conf/spaa/AgrawalFLSSU14}. \cite{DBLP:conf/ipps/ColeR13} also studied how Randomized Work Stealing affects false sharing among tasks.61 There is also a large body of research on the theoretical aspects of work stealing. These evaluate, for example, the cost of migration\cite{DBLP:conf/sigmetrics/SquillanteN91,DBLP:journals/pe/EagerLZ86}, how affinity affects performance\cite{DBLP:journals/tpds/SquillanteL93,DBLP:journals/mst/AcarBB02,DBLP:journals/ipl/SuksompongLS16} and theoretical models for heterogenous systems\cite{DBLP:journals/jpdc/MirchandaneyTS90,DBLP:journals/mst/BenderR02,DBLP:conf/sigmetrics/GastG10}. \cite{DBLP:journals/jacm/BlellochGM99} examine the space bounds of Work Stealing and \cite{DBLP:journals/siamcomp/BerenbrinkFG03} show that for underloaded systems, the scheduler will complete computations in finite time, \ie is \newterm{stable}. Others show that Work-Stealing is applicable to various scheduling contexts\cite{DBLP:journals/mst/AroraBP01,DBLP:journals/anor/TchiboukdjianGT13,DBLP:conf/isaac/TchiboukdjianGTRB10,DBLP:conf/ppopp/AgrawalLS10,DBLP:conf/spaa/AgrawalFLSSU14}. \cite{DBLP:conf/ipps/ColeR13} also studied how Randomized Work Stealing affects false sharing among \glspl{at}. 61 62 62 63 However, as \cite{DBLP:journals/ijpp/YangH18} highlights, it is worth mentionning that this theoretical research has mainly focused on ``fully-strict'' computations, \ie workloads that can be fully represented with a Direct Acyclic Graph. It is unclear how well these distributions represent workloads in real world scenarios. 63 64 64 65 \section{Preemption} 65 One last aspect of scheduling worth mentionning is preemption since many schedulers rely on it for some of their guarantees. Preemption is the idea of interrupting tasks that have been running for too long, effectively injecting suspend points in the applications. There are multiple techniques to achieve this but they all aim to have the effect of guaranteeing that suspend points in a task are never further apart than some fixed duration. While this helps schedulers guarantee that no taskswill unfairly monopolize a worker, preemption can effectively added to any scheduler. Therefore, the only interesting aspect of preemption for the design of scheduling is whether or not to require it.66 One last aspect of scheduling worth mentionning is preemption since many schedulers rely on it for some of their guarantees. Preemption is the idea of interrupting \glspl{at} that have been running for too long, effectively injecting suspend points in the applications. There are multiple techniques to achieve this but they all aim to have the effect of guaranteeing that suspend points in a \gls{at} are never further apart than some fixed duration. While this helps schedulers guarantee that no \glspl{at} will unfairly monopolize a worker, preemption can effectively added to any scheduler. Therefore, the only interesting aspect of preemption for the design of scheduling is whether or not to require it. 66 67 67 68 \section{Schedulers in Production}\label{existing:prod} … … 69 70 70 71 \subsection{Operating System Schedulers} 71 Operating System Schedulers tend to be fairly complex schedulers, they generally support some amount of real-time, aim to balance interactive and non-interactive tasksand support for multiple users sharing hardware without requiring these users to cooperate. Here are more details on a few schedulers used in the common operating systems: Linux, FreeBsd, Microsoft Windows and Apple's OS X. The information is less complete for operating systems behind closed source.72 Operating System Schedulers tend to be fairly complex schedulers, they generally support some amount of real-time, aim to balance interactive and non-interactive \glspl{at} and support for multiple users sharing hardware without requiring these users to cooperate. Here are more details on a few schedulers used in the common operating systems: Linux, FreeBsd, Microsoft Windows and Apple's OS X. The information is less complete for operating systems behind closed source. 72 73 73 74 \paragraph{Linux's CFS} 74 The default scheduler used by Linux (the Completely Fair Scheduler)\cite{MAN:linux/cfs,MAN:linux/cfs2} is a feedback scheduler based on CPU time. For each processor, it constructs a Red-Black tree of tasks waiting to run, ordering them by amount of CPU time spent. The scheduler schedules the task that has spent the least CPU time. It also supports the concept of \newterm{Nice values}, which are effectively multiplicative factors on the CPU time spent. The ordering of tasks is also impacted by a group based notion of fairness, where tasks belonging to groups having spent less CPU time are preferred to tasksbeloning to groups having spent more CPU time. Linux achieves load-balancing by regularly monitoring the system state\cite{MAN:linux/cfs/balancing} and using some heuristic on the load (currently CPU time spent in the last millisecond plus decayed version of the previous time slots\cite{MAN:linux/cfs/pelt}.).75 The default scheduler used by Linux (the Completely Fair Scheduler)\cite{MAN:linux/cfs,MAN:linux/cfs2} is a feedback scheduler based on CPU time. For each processor, it constructs a Red-Black tree of \glspl{at} waiting to run, ordering them by amount of CPU time spent. The scheduler schedules the \gls{at} that has spent the least CPU time. It also supports the concept of \newterm{Nice values}, which are effectively multiplicative factors on the CPU time spent. The ordering of \glspl{at} is also impacted by a group based notion of fairness, where \glspl{at} belonging to groups having spent less CPU time are preferred to \glspl{at} beloning to groups having spent more CPU time. Linux achieves load-balancing by regularly monitoring the system state\cite{MAN:linux/cfs/balancing} and using some heuristic on the load (currently CPU time spent in the last millisecond plus decayed version of the previous time slots\cite{MAN:linux/cfs/pelt}.). 75 76 76 \cite{DBLP:conf/eurosys/LoziLFGQF16} shows that Linux's CFS also does work-stealing to balance the workload of each processors, but the paper argues this aspect can be improved significantly. The issues highlighted sem to stem from Linux's need to support fairness across tasks \emph{and} across users\footnote{Enforcing fairness across users means, for example, that given two users: one with a single task and the other with one thousand tasks, the user with a single taskdoes not receive one one thousandth of the CPU time.}, increasing the complexity.77 \cite{DBLP:conf/eurosys/LoziLFGQF16} shows that Linux's CFS also does work-stealing to balance the workload of each processors, but the paper argues this aspect can be improved significantly. The issues highlighted sem to stem from Linux's need to support fairness across \glspl{at} \emph{and} across users\footnote{Enforcing fairness across users means, for example, that given two users: one with a single \gls{at} and the other with one thousand \glspl{at}, the user with a single \gls{at} does not receive one one thousandth of the CPU time.}, increasing the complexity. 77 78 78 Linux also offers a FIFO scheduler, a real-time schedulerwhich runs the highest-priority task, and a round-robin scheduler, which is an extension of the fifo-scheduler that adds fixed time slices. \cite{MAN:linux/sched}79 Linux also offers a FIFO scheduler, a real-time schedulerwhich runs the highest-priority \gls{at}, and a round-robin scheduler, which is an extension of the fifo-scheduler that adds fixed time slices. \cite{MAN:linux/sched} 79 80 80 81 \paragraph{FreeBSD} … … 82 83 83 84 \paragraph{Windows(OS)} 84 Microsoft's Operating System's Scheduler\cite{MAN:windows/scheduler} is a feedback scheduler with priorities. It supports 32 levels of priorities, some of which are reserved for real-time and prviliged applications. It schedules tasks based on the highest priorities (lowest number) and how much cpu time each taskshave used. The scheduler may also temporarily adjust priorities after certain effects like the completion of I/O requests.85 Microsoft's Operating System's Scheduler\cite{MAN:windows/scheduler} is a feedback scheduler with priorities. It supports 32 levels of priorities, some of which are reserved for real-time and prviliged applications. It schedules \glspl{at} based on the highest priorities (lowest number) and how much cpu time each \glspl{at} have used. The scheduler may also temporarily adjust priorities after certain effects like the completion of I/O requests. 85 86 86 87 \todo{load balancing} … … 99 100 100 101 \subsection{User-Level Schedulers} 101 By comparison, user level schedulers tend to be simpler, gathering fewer metrics and avoid complex notions of fairness. Part of the simplicity is due to the fact that all taskshave the same user, and therefore cooperation is both feasible and probable.102 By comparison, user level schedulers tend to be simpler, gathering fewer metrics and avoid complex notions of fairness. Part of the simplicity is due to the fact that all \glspl{at} have the same user, and therefore cooperation is both feasible and probable. 102 103 \paragraph{Go} 103 104 Go's scheduler uses a Randomized Work Stealing algorithm that has a global runqueue(\emph{GRQ}) and each processor(\emph{P}) has both a fixed-size runqueue(\emph{LRQ}) and a high-priority next ``chair'' holding a single element.\cite{GITHUB:go,YTUBE:go} Preemption is present, but only at function call boundaries. … … 116 117 117 118 \paragraph{Intel\textregistered ~Threading Building Blocks} 118 \newterm{Thread Building Blocks}(TBB) is Intel's task parellelism\cite{wiki:taskparallel} framework. It runs tasks or \newterm{jobs}, schedulable objects that must always run to completion, on a pool of worker threads. TBB's scheduler is a variation of Randomized Work Stealing that also supports higher-priority graph-like dependencies\cite{MAN:tbb/scheduler}. It schedules tasks as follows (where \textit{t} is the last taskcompleted):119 \newterm{Thread Building Blocks}(TBB) is Intel's task parellelism\cite{wiki:taskparallel} framework. It runs \newterm{jobs}, uninterruptable \glspl{at}, schedulable objects that must always run to completion, on a pool of worker threads. TBB's scheduler is a variation of Randomized Work Stealing that also supports higher-priority graph-like dependencies\cite{MAN:tbb/scheduler}. It schedules \glspl{at} as follows (where \textit{t} is the last \gls{at} completed): 119 120 \begin{displayquote} 120 121 \begin{enumerate} … … 136 137 137 138 \paragraph{Grand Central Dispatch} 138 This is an API produce by Apple\cit{Official GCD source} that offers task parellelism\cite{wiki:taskparallel}. Its distinctive aspect is that it uses multiple ``Dispatch Queues'', some of which are created by programmers. These queues each have their own local ordering guarantees, \eg taskson queue $A$ are executed in \emph{FIFO} order.139 This is an API produce by Apple\cit{Official GCD source} that offers task parellelism\cite{wiki:taskparallel}. Its distinctive aspect is that it uses multiple ``Dispatch Queues'', some of which are created by programmers. These queues each have their own local ordering guarantees, \eg \glspl{at} on queue $A$ are executed in \emph{FIFO} order. 139 140 140 141 \todo{load balancing and scheduling} -
doc/theses/thierry_delisle_PhD/thesis/text/io.tex
rba897d21 r2e9b59b 173 173 The consequence is that the amount of parallelism used to prepare submissions for the next system call is limited. 174 174 Beyond this limit, the length of the system call is the throughput limiting factor. 175 I concluded from early experiments that preparing submissions seems to take a bout as long as the system call itself, which means that with a single @io_uring@ instance, there is no benefit in terms of \io throughput to having more than two \glspl{hthrd}.175 I concluded from early experiments that preparing submissions seems to take at most as long as the system call itself, which means that with a single @io_uring@ instance, there is no benefit in terms of \io throughput to having more than two \glspl{hthrd}. 176 176 Therefore the design of the submission engine must manage multiple instances of @io_uring@ running in parallel, effectively sharding @io_uring@ instances. 177 177 Similarly to scheduling, this sharding can be done privately, \ie, one instance per \glspl{proc}, in decoupled pools, \ie, a pool of \glspl{proc} use a pool of @io_uring@ instances without one-to-one coupling between any given instance and any given \gls{proc}, or some mix of the two. … … 200 200 The only added complexity is that the number of SQEs is fixed, which means allocation can fail. 201 201 202 Allocation failures need to be pushed up to therouting algorithm: \glspl{thrd} attempting \io operations must not be directed to @io_uring@ instances without sufficient SQEs available.202 Allocation failures need to be pushed up to a routing algorithm: \glspl{thrd} attempting \io operations must not be directed to @io_uring@ instances without sufficient SQEs available. 203 203 Furthermore, the routing algorithm should block operations up-front if none of the instances have available SQEs. 204 204 … … 214 214 215 215 In the case of designating a \gls{thrd}, ideally, when multiple \glspl{thrd} attempt to submit operations to the same @io_uring@ instance, all requests would be batched together and one of the \glspl{thrd} would do the system call on behalf of the others, referred to as the \newterm{submitter}. 216 In practice however, it is important that the \io requests are not left pending indefinitely and as such, it may be required to have a current submitter and a next submitter.216 In practice however, it is important that the \io requests are not left pending indefinitely and as such, it may be required to have a ``next submitter'' that guarentees everything that is missed by the current submitter is seen by the next one. 217 217 Indeed, as long as there is a ``next'' submitter, \glspl{thrd} submitting new \io requests can move on, knowing that some future system call will include their request. 218 218 Once the system call is done, the submitter must also free SQEs so that the allocator can reused them. … … 223 223 If the submission side does not designate submitters, polling can also submit all SQEs as it is polling events. 224 224 A simple approach to polling is to allocate a \gls{thrd} per @io_uring@ instance and simply let the poller \glspl{thrd} poll their respective instances when scheduled. 225 This design is especially convenient for reasons explained in Chapter~\ref{practice}.226 225 227 226 With this pool of instances approach, the big advantage is that it is fairly flexible. 228 227 It does not impose restrictions on what \glspl{thrd} submitting \io operations can and cannot do between allocations and submissions. 229 It also can gracefully handle srunning out of ressources, SQEs or the kernel returning @EBUSY@.228 It also can gracefully handle running out of ressources, SQEs or the kernel returning @EBUSY@. 230 229 The down side to this is that many of the steps used for submitting need complex synchronization to work properly. 231 230 The routing and allocation algorithm needs to keep track of which ring instances have available SQEs, block incoming requests if no instance is available, prevent barging if \glspl{thrd} are already queued up waiting for SQEs and handle SQEs being freed. 232 231 The submission side needs to safely append SQEs to the ring buffer, correctly handle chains, make sure no SQE is dropped or left pending forever, notify the allocation side when SQEs can be reused and handle the kernel returning @EBUSY@. 233 All this synchronization may have a significant cost and, compare to the next approach presented, this synchronization is entirely overhead.232 All this synchronization may have a significant cost and, compared to the next approach presented, this synchronization is entirely overhead. 234 233 235 234 \subsubsection{Private Instances} 236 235 Another approach is to simply create one ring instance per \gls{proc}. 237 This alleviate the need for synchronization on the submissions, requiring only that \glspl{thrd} are not interrupted in between two submission steps.236 This alleviates the need for synchronization on the submissions, requiring only that \glspl{thrd} are not interrupted in between two submission steps. 238 237 This is effectively the same requirement as using @thread_local@ variables. 239 238 Since SQEs that are allocated must be submitted to the same ring, on the same \gls{proc}, this effectively forces the application to submit SQEs in allocation order … … 331 330 \paragraph{Pending Allocations} can be more complicated to handle. 332 331 If the arbiter has available instances, the arbiter can attempt to directly hand over the instance and satisfy the request. 333 Otherwise 332 Otherwise it must hold onto the list of threads until SQEs are made available again. 333 This handling becomes that much more complex if pending allocation require more than one SQE, since the arbiter must make a decision between statisfying requests in FIFO ordering or satisfy requests for fewer SQEs first. 334 335 While this arbiter has the potential to solve many of the problems mentionned in above, it also introduces a significant amount of complexity. 336 Tracking which processors are borrowing which instances and which instances have SQEs available ends-up adding a significant synchronization prelude to any I/O operation. 337 Any submission must start with a handshake that pins the currently borrowed instance, if available. 338 An attempt to allocate is then made, but the arbiter can concurrently be attempting to allocate from the same instance from a different \gls{hthrd}. 339 Once the allocation is completed, the submission must still check that the instance is still burrowed before attempt to flush. 340 These extra synchronization steps end-up having a similar cost to the multiple shared instances approach. 341 Furthermore, if the number of instances does not match the number of processors actively submitting I/O, the system can fall into a state where instances are constantly being revoked and end-up cycling the processors, which leads to significant cache deterioration. 342 Because of these reasons, this approach, which sounds promising on paper, does not improve on the private instance approach in practice. 343 344 \subsubsection{Private Instances V2} 345 334 346 335 347 … … 394 406 Finally, the last important part of the \io subsystem is it's interface. There are multiple approaches that can be offered to programmers, each with advantages and disadvantages. The new \io subsystem can replace the C runtime's API or extend it. And in the later case the interface can go from very similar to vastly different. The following sections discuss some useful options using @read@ as an example. The standard Linux interface for C is : 395 407 396 @ssize_t read(int fd, void *buf, size_t count);@ .408 @ssize_t read(int fd, void *buf, size_t count);@ 397 409 398 410 \subsection{Replacement} 399 Replacing the C \glsxtrshort{api} 411 Replacing the C \glsxtrshort{api} is the more intrusive and draconian approach. 412 The goal is to convince the compiler and linker to replace any calls to @read@ to direct them to the \CFA implementation instead of glibc's. 413 This has the advantage of potentially working transparently and supporting existing binaries without needing recompilation. 414 It also offers a, presumably, well known and familiar API that C programmers can simply continue to work with. 415 However, this approach also entails a plethora of subtle technical challenges which generally boils down to making a perfect replacement. 416 If the \CFA interface replaces only \emph{some} of the calls to glibc, then this can easily lead to esoteric concurrency bugs. 417 Since the gcc ecosystems does not offer a scheme for such perfect replacement, this approach was rejected as being laudable but infeasible. 400 418 401 419 \subsection{Synchronous Extension} 420 An other interface option is to simply offer an interface that is different in name only. For example: 421 422 @ssize_t cfa_read(int fd, void *buf, size_t count);@ 423 424 \noindent This is much more feasible but still familiar to C programmers. 425 It comes with the caveat that any code attempting to use it must be recompiled, which can be a big problem considering the amount of existing legacy C binaries. 426 However, it has the advantage of implementation simplicity. 402 427 403 428 \subsection{Asynchronous Extension} 429 It is important to mention that there is a certain irony to using only synchronous, therefore blocking, interfaces for a feature often referred to as ``non-blocking'' \io. 430 A fairly traditional way of doing this is using futures\cit{wikipedia futures}. 431 As simple way of doing so is as follows: 432 433 @future(ssize_t) read(int fd, void *buf, size_t count);@ 434 435 \noindent Note that this approach is not necessarily the most idiomatic usage of futures. 436 The definition of read above ``returns'' the read content through an output parameter which cannot be synchronized on. 437 A more classical asynchronous API could look more like: 438 439 @future([ssize_t, void *]) read(int fd, size_t count);@ 440 441 \noindent However, this interface immediately introduces memory lifetime challenges since the call must effectively allocate a buffer to be returned. 442 Because of the performance implications of this, the first approach is considered preferable as it is more familiar to C programmers. 404 443 405 444 \subsection{Interface directly to \lstinline{io_uring}} 445 Finally, an other interface that can be relevant is to simply expose directly the underlying \texttt{io\_uring} interface. For example: 446 447 @array(SQE, want) cfa_io_allocate(int want);@ 448 449 @void cfa_io_submit( const array(SQE, have) & );@ 450 451 \noindent This offers more flexibility to users wanting to fully use all of the \texttt{io\_uring} features. 452 However, it is not the most user-friendly option. 453 It obviously imposes a strong dependency between user code and \texttt{io\_uring} but at the same time restricting users to usages that are compatible with how \CFA internally uses \texttt{io\_uring}. 454 455 -
doc/theses/thierry_delisle_PhD/thesis/text/practice.tex
rba897d21 r2e9b59b 2 2 The scheduling algorithm discribed in Chapter~\ref{core} addresses scheduling in a stable state. 3 3 However, it does not address problems that occur when the system changes state. 4 Indeed the \CFA runtime, supports expanding and shrinking the number of KTHREAD\_place \todo{add kthrd to glossary}, both manually and, to some extentautomatically.4 Indeed the \CFA runtime, supports expanding and shrinking the number of \procs, both manually and, to some extent, automatically. 5 5 This entails that the scheduling algorithm must support these transitions. 6 6 7 \section{Resizing} 7 More precise \CFA supports adding \procs using the RAII object @processor@. 8 These objects can be created at any time and can be destroyed at any time. 9 They are normally create as automatic stack variables, but this is not a requirement. 10 11 The consequence is that the scheduler and \io subsystems must support \procs comming in and out of existence. 12 13 \section{Manual Resizing} 14 The consequence of dynamically changing the number of \procs is that all internal arrays that are sized based on the number of \procs neede to be \texttt{realloc}ed. 15 This also means that any references into these arrays, pointers or indexes, may need to be fixed when shrinking\footnote{Indexes may still need fixing because there is no guarantee the \proc causing the shrink had the highest index. Therefore indexes need to be reassigned to preserve contiguous indexes.}. 16 17 There are no performance requirements, within reason, for resizing since this is usually considered as part of setup and teardown. 18 However, this operation has strict correctness requirements since shrinking and idle sleep can easily lead to deadlocks. 19 It should also avoid as much as possible any effect on performance when the number of \procs remain constant. 20 This later requirement prehibits simple solutions, like simply adding a global lock to these arrays. 21 22 \subsection{Read-Copy-Update} 23 One solution is to use the Read-Copy-Update\cite{wiki:rcu} pattern. 24 In this pattern, resizing is done by creating a copy of the internal data strucures, updating the copy with the desired changes, and then attempt an Idiana Jones Switch to replace the original witht the copy. 25 This approach potentially has the advantage that it may not need any synchronization to do the switch. 26 The switch definitely implies a race where \procs could still use the previous, original, data structure after the copy was switched in. 27 The important question then becomes whether or not this race can be recovered from. 28 If the changes that arrived late can be transferred from the original to the copy then this solution works. 29 30 For linked-lists, dequeing is somewhat of a problem. 31 Dequeing from the original will not necessarily update the copy which could lead to multiple \procs dequeing the same \at. 32 Fixing this requires making the array contain pointers to subqueues rather than the subqueues themselves. 33 34 Another challenge is that the original must be kept until all \procs have witnessed the change. 35 This is a straight forward memory reclamation challenge but it does mean that every operation will need \emph{some} form of synchronization. 36 If each of these operation does need synchronization then it is possible a simpler solution achieves the same performance. 37 Because in addition to the classic challenge of memory reclamation, transferring the original data to the copy before reclaiming it poses additional challenges. 38 Especially merging subqueues while having a minimal impact on fairness and locality. 39 40 \subsection{Read-Writer Lock} 41 A simpler approach would be to use a \newterm{Readers-Writer Lock}\cite{wiki:rwlock} where the resizing requires acquiring the lock as a writer while simply enqueing/dequeing \ats requires acquiring the lock as a reader. 42 Using a Readers-Writer lock solves the problem of dynamically resizing and leaves the challenge of finding or building a lock with sufficient good read-side performance. 43 Since this is not a very complex challenge and an ad-hoc solution is perfectly acceptable, building a Readers-Writer lock was the path taken. 44 45 To maximize reader scalability, the readers should not contend with eachother when attempting to acquire and release the critical sections. 46 This effectively requires that each reader have its own piece of memory to mark as locked and unlocked. 47 Reades then acquire the lock wait for writers to finish the critical section and then acquire their local spinlocks. 48 Writers acquire the global lock, so writers have mutual exclusion among themselves, and then acquires each of the local reader locks. 49 Acquiring all the local locks guarantees mutual exclusion between the readers and the writer, while the wait on the read side prevents readers from continously starving the writer. 50 \todo{reference listings} 51 52 \begin{lstlisting} 53 void read_lock() { 54 // Step 1 : make sure no writers in 55 while write_lock { Pause(); } 56 57 // May need fence here 58 59 // Step 2 : acquire our local lock 60 while atomic_xchg( tls.lock ) { 61 Pause(); 62 } 63 } 64 65 void read_unlock() { 66 tls.lock = false; 67 } 68 \end{lstlisting} 69 70 \begin{lstlisting} 71 void write_lock() { 72 // Step 1 : lock global lock 73 while atomic_xchg( write_lock ) { 74 Pause(); 75 } 76 77 // Step 2 : lock per-proc locks 78 for t in all_tls { 79 while atomic_xchg( t.lock ) { 80 Pause(); 81 } 82 } 83 } 84 85 void write_unlock() { 86 // Step 1 : release local locks 87 for t in all_tls { 88 t.lock = false; 89 } 90 91 // Step 2 : release global lock 92 write_lock = false; 93 } 94 \end{lstlisting} 8 95 9 96 \section{Idle-Sleep} 97 In addition to users manually changing the number of \procs, it is desireable to support ``removing'' \procs when there is not enough \ats for all the \procs to be useful. 98 While manual resizing is expected to be rare, the number of \ats is expected to vary much more which means \procs may need to be ``removed'' for only short periods of time. 99 Furthermore, race conditions that spuriously lead to the impression no \ats are ready are actually common in practice. 100 Therefore \procs should not be actually \emph{removed} but simply put into an idle state where the \gls{kthrd} is blocked until more \ats become ready. 101 This state is referred to as \newterm{Idle-Sleep}. 102 103 Idle sleep effectively encompasses several challenges. 104 First some data structure needs to keep track of all \procs that are in idle sleep. 105 Because of idle sleep can be spurious, this data structure has strict performance requirements in addition to the strict correctness requirements. 106 Next, some tool must be used to block kernel threads \glspl{kthrd}, \eg \texttt{pthread\_cond\_wait}, pthread semaphores. 107 The complexity here is to support \at parking and unparking, timers, \io operations and all other \CFA features with minimal complexity. 108 Finally, idle sleep also includes a heuristic to determine the appropriate number of \procs to be in idle sleep an any given time. 109 This third challenge is however outside the scope of this thesis because developping a general heuristic is involved enough to justify its own work. 110 The \CFA scheduler simply follows the ``Race-to-Idle'\cit{https://doi.org/10.1137/1.9781611973099.100}' approach where a sleeping \proc is woken any time an \at becomes ready and \procs go to idle sleep anytime they run out of work. 111 112 113 \section{Tracking Sleepers} 114 Tracking which \procs are in idle sleep requires a data structure holding all the sleeping \procs, but more importantly it requires a concurrent \emph{handshake} so that no \at is stranded on a ready-queue with no active \proc. 115 The classic challenge is when a \at is made ready while a \proc is going to sleep, there is a race where the new \at may not see the sleeping \proc and the sleeping \proc may not see the ready \at. 116 117 Furthermore, the ``Race-to-Idle'' approach means that there is some 118 119 \section{Sleeping} 120 121 \subsection{Event FDs} 122 123 \subsection{Epoll} 124 125 \subsection{\texttt{io\_uring}} 126 127 \section{Reducing Latency} -
doc/theses/thierry_delisle_PhD/thesis/thesis.tex
rba897d21 r2e9b59b 202 202 203 203 \newcommand\io{\glsxtrshort{io}\xspace}% 204 \newcommand\at{\gls{at}\xspace}% 205 \newcommand\ats{\glspl{at}\xspace}% 206 \newcommand\proc{\gls{proc}\xspace}% 207 \newcommand\procs{\glspl{proc}\xspace}% 204 208 205 209 %======================================================================
Note:
See TracChangeset
for help on using the changeset viewer.