Operating Systems CMPSC 473
CPU/memory virtualization February 4, 11, 2021 – Lectures 6, 7 Instructor: Bhuvan Urgaonkar ACK: slides adapted from CSAPP text
Carnegie Mellon
Errata: Lecture 6
¢ Lecture 6 video recording has me making some mistakes § Confusing narration re. size of a block
§ Chunk instead of block in some places
§ Compilation error instead of a runtime error
¢ Look out for a red box like this in updated slides for Lecture 6
Carnegie Mellon
Error in recorded lecture: freeing without malloc will cause a runtime error NOT a compilation error – try for yourself!
Overview
¢ Memory management occurs at 2 different granularities
¢ OS virtual memory management
§ Virtual memory is procured from the OS at a relatively coarse
granularity (page)
¢ User-space dynamic memory allocation
§ Heap and stack management logic makes use of procured pages at
a finer granularity (word)
§ We will study this first for the heap – needed for project 2
Carnegie Mellon
Dynamic Memory Allocation
¢ Programmers use dynamic memory allocators (such as malloc) to acquire VM at run time.
§ For data structures whose size is only known at runtime.
¢ Dynamic memory allocators manage the heap.
Top of heap (brk ptr)
Carnegie Mellon
Application
Dynamic Memory Allocator
Heap
User stack
Heap (via malloc)
Uninitialized data (.bss)
Initialized data (.data)
Program text (.text)
0
Dynamic Memory Allocation
¢ Allocator maintains heap as collection of variable sized
blocks, which are either allocated or free ¢ Types of allocators
§ Explicit allocator: application allocates and frees space § E.g., malloc and free in C
§ Implicit allocator: application allocates, but does not free space § E.g. garbage collection in Java, ML, and Lisp
Carnegie Mellon
The malloc Package #include
void *malloc(size_t size)// see C notes on next slide
§ Successful:
§ Returns a pointer to a memory block of at least size bytes
aligned to an 8-byte (x86) or 16-byte (x86-64) boundary § If size == 0, returns NULL
§ Unsuccessful: returns NULL (0) and sets errno
void free(void *p)
§ Returns the block pointed at by p to pool of available memory § p must come from a previous call to malloc or realloc
Other functions
§ calloc: Version of malloc that initializes allocated block to zero. § realloc: Changes the size of a previously allocated block.
§ sbrk: Used internally by allocators to grow or shrink the heap
Carnegie Mellon
The malloc Package #include
void *malloc(size_t size)// see C notes on next slide
§ Successful:
§ Returns a pointer to a memory block of at least size bytes
aligned to an 8-byte (x86) or 16-byte (x86-64) boundary § If size == 0, returns NULL
§ Unsuccessful: returns NULL (0) and sets errno
Carnegie Mellon
void free(void *p)
§ Returns theEbrlorcok prointerdeatcboyrpdtoepdoolleocf atvuairlaeb:lefmremeoirny g
without malloc will cause a runtime error NOT a compilation
§ p must come from a previous call to malloc or realloc
Other functions
§ calloc: Version of malloc that initializes allocated block to zero.
error – try for yourself!
§ realloc: Changes the size of a previously allocated block.
§ sbrk: Used internally by allocators to grow or shrink the heap
Some C notes
¢ Void pointer § What?
§ No associated data type
§ Can’t dereference or do pointer arithmetic § Need to typecast before dereferencing
§ Why?
§ Need to return a dynamic data type, e.g., malloc
§ Need to implement an opaque object
§ Need to implement a generic function that will take different types of arguments determined at run-time
Carnegie Mellon
Some C notes ¢ What is size_t?
¢ What is errno?
§ IMP: thread safe
Carnegie Mellon
malloc Example
Carnegie Mellon
#include
void foo(int n) {
int i, *p;
/* Allocate a block of n ints */
p = (int *) malloc(n * sizeof(int)); if (p == NULL) {
perror(“malloc”);
exit(0); }
/* Initialize allocated block */
for (i=0; i
§ If blocks are aligned, some low-order address bits are always 0 from the left should be a 0 or a 1,
1 word
Size
a
Payload
Optional padding
Format of allocated and free blocks
a = 1: Allocated block a = 0: Free block
Size: block size
Payload: application data (allocated blocks only)
Detailed Implicit Free List Example
Unused
heap
Start of
8/0 16/1 32/0
16/1 0/1
Double-word aligned
Allocated blocks: shaded
Free blocks: unshaded
Headers: labeled with size in bytes/allocated bit
Caution – the recorded video makes mistakes about the size of each square. Each square should be 4 bytes NOT 8 bytes.
Carnegie Mellon
IMPL #3. Implicit List: Finding a Free Block
¢ Firstfit:
§ Search list from beginning, choose first free block that fits:
p = start;
while ((p < end) && \\ not passed end
((*p & 1) || \\ already allocated
(*p <= len))) \\ too small
p = p + (*p & -2); \\ goto next block (word addressed)
§ Can take linear time in total number of blocks (allocated and free) § In practice it can cause “splinters” at beginning of list
¢ Nextfit:
§ Like first fit, but search list starting where previous search finished
§ Should often be faster than first fit: avoids re-scanning unhelpful blocks § Some research suggests that fragmentation is worse
¢ Bestfit:
§ Search the list, choose the best free block: fits, with fewest bytes left over § Keeps fragments small—usually improves memory utilization
§ Will typically run slower than first fit
Carnegie Mellon
IMPL #4. Implicit List: Allocating in Free Block ¢ Allocating in a free block: splitting
§ Since allocated space might be smaller than free space, we might want to split the block
Carnegie Mellon
4
4
6
2
addblock(p, 4)
p
4
4
4
2
2
void addblock(ptr p, int len) { intnewsize=((len+1)>>1)<<1; int oldsize = *p & -2;
*p = newsize | 1;
if (newsize < oldsize)
//rounduptoeven // mask out low bit // set new length
// set length in remaining
// part of block
}
*(p+newsize) = oldsize - newsize;
IMPL #5. Implicit List: Freeing a Block
¢ Simplest implementation:
§ Need only clear the “allocated” flag
void free_block(ptr p) { *p = *p & -2 }
§ But can lead to “false fragmentation”
Carnegie Mellon
4
4
4
2
2
free(p)
Oops!
p
4
4
4
2
2
malloc(5)
There is enough free space, but the allocator won’t be able to find it
Implicit List: Coalescing
¢ Join (coalesce) with next/previous blocks, if they are free
§ Coalescing with next block free(p)
p
logically gone
Carnegie Mellon
4
4
4
2
2
4
4
6
2
2
void free_block(ptr p) {
*p = *p & -2;
// clear allocated flag
// find next block
// add to this block if
// not allocated
}
next = p + *p;
if ((*next & 1) == 0)
*p = *p + *next;
§ But how do we coalesce with previous block?
Implicit List: Bidirectional Coalescing
¢ Boundary tags [Knuth73]
§ Replicate size/allocated word at “bottom” (end) of free blocks
§ Allows us to traverse the “list” backwards, but requires extra space § Important and general technique!
44446 644
Header
Format of allocated and free blocks
Boundary tag (footer)
Size a
Payload and padding
Size a
a = 1: Allocated block a = 0: Free block
Size: Total block size
Payload: Application data (allocated blocks only)
Carnegie Mellon
Constant Time Coalescing
Case 1 Case 2 Case 3 Case 4
Carnegie Mellon
Allocated
Allocated
Allocated
Free
Free
Allocated
Free
Free
Block being freed
Constant Time Coalescing (Case 1)
Carnegie Mellon
m1
1
m1
1
n
1
n
1
m2
1
m2
1
m1
1
m1
1
n
0
n
0
m2
1
m2
1
Constant Time Coalescing (Case 2)
Carnegie Mellon
m1
1
m1
1
n
1
n
1
m2
0
m2
0
m1
1
m1
1
n+m2
0
n+m2
0
Constant Time Coalescing (Case 3)
Carnegie Mellon
m1
0
m1
0
n
1
n
1
m2
1
m2
1
n+m1
0
n+m1
0
m2
1
m2
1
Constant Time Coalescing (Case 4)
Carnegie Mellon
m1
0
m1
0
n
1
n
1
m2
0
m2
0
n+m1+m2
0
n+m1+m2
0
Disadvantages of Boundary Tags ¢ Internal fragmentation
¢ Can it be optimized?
§ Which blocks need the footer tag?
Carnegie Mellon
Summary of Key Allocator Policies
¢ Placement policy:
§ First-fit, next-fit, best-fit, etc.
§ Trades off lower throughput for less fragmentation
§ Interesting observation: segregated free lists (next lecture) approximate a best fit placement policy without having to search entire free list
¢ Splitting policy:
§ When do we go ahead and split free blocks?
§ How much internal fragmentation are we willing to tolerate?
¢ Coalescing policy:
§ Immediate coalescing: coalesce each time free is called
§ Deferred coalescing: try to improve performance of free by deferring coalescing until needed. Examples:
§ Coalesce as you scan the free list for malloc
§ Coalesce when the amount of external fragmentation reaches some threshold
Carnegie Mellon
Implicit Lists: Summary
¢ Implementation: very simple
¢ Allocate cost:
§ linear time worst case
¢ Free cost:
§ constant time worst case § even with coalescing
¢ Memory usage:
§ will depend on placement policy § First-fit, next-fit or best-fit
¢ Not used in practice for malloc/free because of linear- time allocation
§ used in many special purpose applications
¢ However, the concepts of splitting and boundary tag coalescing are general to all allocators
Carnegie Mellon
Keeping Track of Free Blocks
¢ Method 1: Implicit free list using length—links all blocks
Carnegie Mellon
5
4
6
2
¢ Method 2: Explicit free list among the free blocks using pointers
5
4
6
2
¢ Method 3: Segregated free list
§ Different free lists for different size classes
¢ Method 4: Blocks sorted by size
§ Can use a balanced tree (e.g. Red-Black tree) with pointers within each free block, and the length used as a key
Explicit Free Lists
Allocated (as before) Free
Carnegie Mellon
Size
a
Payload and padding
Size
a
Size
a
Next
Prev
Size
a
¢ Maintain list(s) of free blocks, not all blocks § The “next” free block could be anywhere
§ So we need to store forward/back pointers, not just sizes § Still need boundary tags for coalescing
§ Luckily we track only free blocks, so we can use payload area
Explicit Free Lists ¢ Logically:
ABC
¢ Physically: blocks can be in any order
Carnegie Mellon
Forward (next) links
AB
4
4
4
4
6
6
4
4
4
4
C
Back (prev) links
Allocating From Explicit Free Lists
conceptual graphic
Carnegie Mellon
Before
After
(with splitting)
= malloc(...)
Freeing With Explicit Free Lists
¢ Insertion policy: Where in the free list do you put a newly freed block?
¢ LIFO (last-in-first-out) policy
§ Insert freed block at the beginning of the free list
§ Pro: simple and constant time
§ Con: studies suggest fragmentation is worse than address ordered
¢ Address-ordered policy
§ Insert freed blocks so that free list blocks are always in address order: addr(prev) < addr(curr) < addr(next)
Carnegie Mellon
§ Con: requires search
ERROR – discussion in recorded video says
§ Pro: studies suggest fragmentation is lower than LIFO runtime is O(log n) when it should be O(n)
Freeing With a LIFO Policy (Case 1)
¢ Insert the freed block at the root of the list
conceptual graphic
Carnegie Mellon
Before
Root
free( )
After
Root
Freeing With a LIFO Policy (Case 2)
conceptual graphic
Carnegie Mellon
Before
Root
free( )
¢ Splice out successor block, coalesce both memory blocks and insert the new block at the root of the list
After
Root
Freeing With a LIFO Policy (Case 3)
conceptual graphic
Carnegie Mellon
Before
Root
free( )
¢ Splice out predecessor block, coalesce both memory blocks, and insert the new block at the root of the list
After
Root
Freeing With a LIFO Policy (Case 4)
conceptual graphic
Carnegie Mellon
Before
Root
free( )
¢ Splice out predecessor and successor blocks, coalesce all 3 memory blocks and insert the new block at the root of the list
After
Root
Explicit List Summary
¢ Comparison to implicit list:
§ Allocate is linear time in number of free blocks instead of all blocks
§ Much faster when most of the memory is full
§ Slightly more complicated allocate and free since needs to splice blocks
in and out of the list
§ Some extra space for the links (2 extra words needed for each block)
§ Does this increase internal fragmentation?
¢ Most common use of linked lists is in conjunction with
segregated free lists
§ Keep multiple linked lists of different size classes, or possibly for different types of objects
Carnegie Mellon
Keeping Track of Free Blocks
¢ Method 1: Implicit list using length—links all blocks
¢ Method 2: Explicit list among the free blocks using pointers
Carnegie Mellon
5
4
6
2
5
4
6
2
¢ Method 3: Segregated free list
§ Different free lists for different size classes
¢ Method 4: Blocks sorted by size
§ Can use a balanced tree (e.g. Red-Black tree) with pointers within each free block, and the length used as a key
Segregated List (Seglist) Allocators ¢ Each size class of blocks has its own free list
1-2 3 4
5-8 9-inf
¢ Often have separate classes for each small size
¢ For larger sizes: One class for each two-power size
Carnegie Mellon
Seglist Allocator
¢ Given an array of free lists, each one for some size class
¢ To allocate a block of size n:
§ Search appropriate free list for block of size m > n § If an appropriate block is found:
§ Split block and place fragment on appropriate list (optional) § If no block is found, try next larger class
§ Repeat until block is found
¢ If no block is found:
§ Request additional heap memory from OS (using sbrk()) § Allocate block of n bytes from this new memory
§ Place remainder as a single free block in largest size class.
Carnegie Mellon
Seglist Allocator (cont.) ¢ To free a block:
§ Coalesce and place on appropriate list
¢ Advantages of seglist allocators § Higher throughput
§ log time for power-of-two size classes § Better memory utilization
§ First-fit search of segregated free list approximates a best-fit search of entire heap.
§ Extreme case: Giving each block its own size class is equivalent to best-fit.
Carnegie Mellon
Memory-Related Perils and Pitfalls
¢ Dereferencing bad pointers
¢ Reading uninitialized memory
¢ Overwriting memory
¢ Referencing nonexistent variables ¢ Freeing blocks multiple times
¢ Referencing freed blocks
¢ Failing to free blocks
Carnegie Mellon
C operators
Operators Associativity
Carnegie Mellon
() [] -> .
! ~ ++ — + – * &(type)sizeof */%
+-
<< >>
< <= > >=
== !=
&
^
|
&&
||
?:
= += -= *= /= %= &= ^= != <<= >>=
,
left to right righttoleft left to right left to right left to right left to right left to right left to right left to right left to right left to right left to right right to left right to left left to right
¢ ->, (), and [] have high precedence, with * and & just below ¢ Unary +, -, and * have higher precedence than binary forms
Source: K&R page 53
C Pointer Declarations: Test Yourself!
int *p
int *p[13]
int *(p[13])
int **p
int (*p)[13]
int *f()
int (*f)()
int (*(*f())[13])()
int (*(*x[3])())[5]
p is a pointer to int
p is an array[13] of pointer to int p is an array[13] of pointer to int p is a pointer to a pointer to an int
p is a pointer to an array[13] of int
f is a function returning a pointer to int
f is a pointer to a function returning int
f is a function returning ptr to an array[13] of pointers to functions returning int
x is an array[3] of pointers to functions returning pointers to array[5] of ints
Carnegie Mellon
Source: K&R Sec 5.12
Dereferencing Bad Pointers ¢ Theclassicscanfbug
Carnegie Mellon
int val;
…
scanf(“%d”, val);
Reading Uninitialized Memory
¢ Assuming that heap data is initialized to zero
Carnegie Mellon
/* return y = Ax */
int *matvec(int **A, int *x) {
int *y = malloc(N*sizeof(int));
int i, j;
for (i=0; i
free(x);
y = malloc(M*sizeof(int));
free(x);
Referencing Freed Blocks ¢ Evil!
Carnegie Mellon
x = malloc(N*sizeof(int));
free(x); …
y = malloc(M*sizeof(int));
for (i=0; i
head->next = NULL;
…
free(head);
return;
}
Dealing With Memory Bugs
¢ Debugger:gdb
§ Good for finding bad pointer dereferences § Hard to detect the other memory bugs
¢ Data structure consistency checker
§ Runs silently, prints message only on error § Use as a probe to zero in on error
¢ Binary translator: valgrind
§ Powerful debugging and analysis technique
§ Rewrites text section of executable object file § Checks each individual reference at runtime
§ Bad pointers, overwrites, refs outside of allocated block
¢ glibc malloc contains checking code § setenv MALLOC_CHECK_ 3
Carnegie Mellon