Sub topic 13
Contiguous Allocation
Working model
This chapter assumes you know binary units, disk blocks, system calls, and the difference between user mode and kernel mode.
In contiguous allocation, a file occupies consecutive disk blocks. The file system stores only two essential values in its directory entry:
- The starting block.
- The number of blocks allocated.
If a file starts at block 120 and uses 8 blocks, it occupies blocks 120 through 127. To find the block containing byte offset x, the file system computes:
physical block = start + floor(x / block_size)
This simple layout supports both sequential and direct access.
Allocation and access
When creating a file, the file system must find a run of free blocks large enough for the entire file. A possible directory entry is:
| Field | Value |
|---|---|
| Starting block | 120 |
| Length in blocks | 4 |
The physical location of block i in the file is 120 + i. Because the blocks are adjacent, a disk head can read the file with little extra movement. Direct access is also efficient because the address calculation is constant time.
def physical_block(start, byte_offset, block_size):
if byte_offset < 0:
raise ValueError("offset cannot be negative")
return start + byte_offset // block_size
start = 120
block_size = 4096
for offset in (0, 4095, 4096, 12000):
print(offset, physical_block(start, offset, block_size))For a 4-KiB block size, byte offset 4096 belongs to the second file block, so its physical block is 121.
Fragmentation and file growth
The main weakness is external fragmentation. This occurs when free space is split into small gaps. The total free space may be sufficient, but no single gap may hold a new file.
File growth is also difficult. If the block immediately after a file is occupied, the file cannot expand in place. The system may need to copy the file to a larger consecutive run, which costs time and temporarily requires extra space.
A file's final block can contain unused bytes. This is internal fragmentation caused by block-sized allocation, but it is usually much smaller than the external fragmentation problem.
Compaction moves allocated files together to create larger free runs. It can reduce external fragmentation, but it requires substantial copying and changes physical locations. Extents provide a practical compromise: a file uses several contiguous runs instead of one, reducing the need for a single very large gap.
Numerical check
If a file needs 18 blocks and the largest free run has 16 blocks, allocation fails even when the disk has more than 18 free blocks overall.
Exercise
A file starts at block 500, has 12 blocks, and each block is 1 KiB. Which physical block contains byte offset 7168?
Show answer
Block 507, because floor(7168 / 1024) = 7 and 500 + 7 = 507.