Sub topic 16
Managing Free Space
Assume you know binary arithmetic, blocks, pointers, and basic file-system allocation. Free-space management records which disk blocks are available for new files and for file growth. The main goals are fast allocation, low memory use, and easy recovery after a crash.
Bit vectors
A bit vector, or bitmap, uses one bit for each disk block. A common convention is:
0means the block is free.1means the block is allocated.
For a disk with \(N\) blocks, the bitmap needs \(N\) bits, or \(N/8\) bytes. A bitmap makes it easy to find one free block and to find a run of consecutive free blocks. However, scanning a very large bitmap can take time.
For example, if blocks 0, 1, and 4 are allocated and blocks 2 and 3 are free, the bitmap begins as:
| Block | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| Status | 1 | 1 | 0 | 0 | 1 |
The bitmap also supports contiguous allocation well because the system can search for a sequence of zero bits.
def find_run(bitmap, length):
"""Return the first run of free blocks, or None."""
start = 0
while start <= len(bitmap) - length:
if all(bit == 0 for bit in bitmap[start:start + length]):
return start
start += 1
return None
bitmap = [1, 1, 0, 0, 0, 1, 0]
print(find_run(bitmap, 3)) # 2Linked free lists
A linked free list stores the address of one free block in another free block. Each node points to the next free block. This method uses little extra space when free blocks are scattered, but finding a long consecutive run is difficult. Traversing many pointers also requires extra disk accesses unless the list is cached.
A variation stores ranges rather than individual blocks. One list entry can record a starting block and the number of consecutive free blocks. This reduces list size when free space appears in large runs.
Grouping and counting
Grouping stores the addresses of several free blocks inside one free block. The final entry points to another group of addresses. This allows the system to discover many free blocks with fewer accesses.
Counting stores each free extent as a pair:
- Starting block
- Number of consecutive free blocks
Counting is efficient when allocation and deletion create large contiguous extents. It is less efficient when free space becomes highly fragmented. Fragmentation means that free space exists, but is divided into many small pieces.
Choosing a method
The allocation strategy should match the file system's workload.
Exercise
Exercise
A disk has 8192 blocks. How many bytes are needed for a bitmap with one bit per block?
Show answer
The bitmap needs 8192 bits, which is 8192 / 8 = 1024 bytes.