Sub topic 3
Contiguous allocation
This chapter assumes you know how disk blocks, pointers and the kernel's file-system calls work. You should also be comfortable converting between KB, MB and GB, and computing with powers of two.
Contiguous allocation
Contiguous allocation stores a file in consecutive disk blocks. The directory entry records only the starting block and the length. Reads are fast because the head moves little, but growing a file is hard, and free space becomes fragmented over time.
def contiguous_blocks(start, length):
return list(range(start, start + length))
print(contiguous_blocks(20, 5)) # [20, 21, 22, 23, 24]Linked allocation and FAT
Linked allocation lets each block hold a pointer to the next block of the file. Files grow easily, but random access requires following the chain from the start. The File Allocation Table (FAT) moves these pointers into one table on disk, so the chain can be read without touching every data block.
Indexed allocation and inodes
Indexed allocation places all block pointers for a file in an index structure. In Unix, that structure is the inode. It holds 12 direct pointers, plus single, double and triple indirect pointers.
With 4 KB blocks and 4-byte pointers, one index block holds 1024 pointers. The maximum file size is:
block = 4096
p = block // 4 # 1024 pointers per index block
blocks = 12 + p + p**2 + p**3 # direct, single, double, triple
print(blocks * block) # 4402345721856 bytes, about 4.004 TiBManaging free space
A bit vector uses one bit per block, where 0 means free. It is compact and finds a run of free blocks quickly. A linked list of free blocks uses no extra space when the disk is nearly full, but it is slower to search for contiguous runs.
Journaling and crash consistency
A crash can leave metadata half-updated. A journal fixes this by writing the planned changes to a log first, then a commit record, then applying the changes to their final locations. After a crash, the file system replays committed log entries and discards incomplete ones.
File protection and permissions
Unix stores nine permission bits per file: read, write and execute for the owner, the group and everyone else. The kernel checks these bits on each open and access call.
Exercise
Exercise
A file system uses 4 KB blocks and 4-byte pointers. An inode has 12 direct pointers and one single indirect pointer. What is the maximum file size in bytes?
Show answer
One index block holds 1024 pointers. Blocks reachable: 12 + 1024 = 1036. Size: 1036 × 4096 = 4,243,456 bytes.