use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::{Cursor, Read, Seek, SeekFrom, Write};
// --- Constants ---
const BLOCK_SIZE: u64 = 4096;
const JOB_SIZE: u64 = 1024 * 1024; // 1MB Journal
const DISK_SIZE: u64 = 10 * 1024 * 1024; // 10MB Disk
const JOURNAL_START_BLOCK: u64 = 1;
// --- Disk Simulation ---
/// Simulates a raw block device (like /dev/sda)
#[derive(Clone)]
struct Disk {
raw: Vec<u8>,
}
impl Disk {
fn new(size: u64) -> Self {
Disk { raw: vec![0; size as usize] }
}
fn read_block(&self, block_idx: u64) -> Vec<u8> {
let start = (block_idx * BLOCK_SIZE) as usize;
let end = start + BLOCK_SIZE as usize;
self.raw[start..end].to_vec()
}
fn write_block(&mut self, block_idx: u64, data: &[u8]) {
let start = (block_idx * BLOCK_SIZE) as usize;
let end = start + BLOCK_SIZE as usize;
// Pad or truncate to block size
let mut chunk = data.to_vec();
chunk.resize(BLOCK_SIZE as usize, 0);
self.raw[start..end].copy_from_slice(&chunk);
}
}
// --- On-Disk Structures ---
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
struct SuperBlock {
magic: u32,
block_count: u64,
inode_count: u64,
free_block_ptr: u64, // Simplified allocator
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct Inode {
id: u64,
size: u64,
blocks: Vec<u64>, // Direct pointers (simplified Extents)
}
// --- Journal Structures ---
#[derive(Serialize, Deserialize, Debug, Clone)]
enum JournalOp {
WriteBlock { block_idx: u64, data: Vec<u8> },
UpdateInode { inode_idx: u64, inode: Inode },
UpdateSuperBlock { sb: SuperBlock },
}
/// Represents an atomic set of changes
#[derive(Serialize, Deserialize, Debug, Clone)]
struct Transaction {
id: u64,
ops: Vec<JournalOp>,
checksum: u32,
committed: bool,
}
// --- The Filesystem Engine ---
struct MiniExt4 {
disk: Disk,
superblock: SuperBlock,
next_tx_id: u64,
}
impl MiniExt4 {
/// Format the disk
fn mkfs(mut disk: Disk) -> Self {
let sb = SuperBlock {
magic: 0xEF53, // Ext4 magic number
block_count: DISK_SIZE / BLOCK_SIZE,
inode_count: 128,
free_block_ptr: 100, // Start data blocks at block 100
};
let mut fs = MiniExt4 {
disk,
superblock: sb,
next_tx_id: 1,
};
// Write SB to disk
fs.sync_superblock();
fs
}
/// Mount simulates an OS loading the FS. It checks the journal.
fn mount(mut disk: Disk) -> Self {
// 1. Read Superblock
let sb_data = disk.read_block(0);
let sb: SuperBlock = bincode::deserialize(&sb_data).expect("Corrupt SuperBlock");
let mut fs = MiniExt4 {
disk,
superblock: sb,
next_tx_id: 1,
};
// 2. RECOVERY: Replay Journal
fs.recover();
fs
}
fn sync_superblock(&mut self) {
let data = bincode::serialize(&self.superblock).unwrap();
self.disk.write_block(0, &data);
}
// --- Journaling Logic ---
/// The core of the journal: Write intent to log, then commit.
/// Returns the transaction ID if committed.
fn log_and_commit(&mut self, ops: Vec<JournalOp>) -> u64 {
let tx_id = self.next_tx_id;
self.next_tx_id += 1;
let tx = Transaction {
id: tx_id,
ops,
checksum: 0, // simplified
committed: true,
};
let tx_bytes = bincode::serialize(&tx).unwrap();
// In a real FS, this is a circular buffer.
// Here we simplify: Journal is at Block 1.
// We write the transaction to the Journal Area.
println!("[Journal] Writing Transaction #{} to journal area...", tx_id);
self.disk.write_block(JOURNAL_START_BLOCK, &tx_bytes);
// In real Ext4, we'd issue a write barrier/flush here.
tx_id
}
/// Checkpoint: Apply the changes from the journal to the actual file system locations.
/// In "Ordered" mode, data is written, then metadata. Here we do full journal replay.
fn checkpoint(&mut self, tx_id: u64) {
// Read the transaction back from the journal (simulating reliability)
let journal_data = self.disk.read_block(JOURNAL_START_BLOCK);
let tx: Transaction = match bincode::deserialize(&journal_data) {
Ok(t) => t,
Err(_) => return, // Empty or corrupt journal
};
// Only apply if IDs match and it's valid
if tx.id != tx_id { return; }
println!("[Checkpoint] Applying Transaction #{} to main store...", tx.id);
for op in tx.ops {
match op {
JournalOp::WriteBlock { block_idx, data } => {
self.disk.write_block(block_idx, &data);
}
JournalOp::UpdateInode { .. } => {
// Simplify: In our toy FS, inodes live in a simplified struct in memory
// In a real FS, we'd write to the Inode Table block.
println!(" -> Updated Inode metadata on disk");
}
JournalOp::UpdateSuperBlock { sb } => {
let data = bincode::serialize(&sb).unwrap();
self.disk.write_block(0, &data);
}
}
}
// Clear journal (mark as empty)
self.disk.write_block(JOURNAL_START_BLOCK, &[0; 4096]);
println!("[Checkpoint] Done. Journal cleared.\n");
}
/// Recovery runs on mount. It looks for a transaction in the journal
/// that was COMMITTED but not wiped (meaning Checkpoint failed/crashed).
fn recover(&mut self) {
println!("[Recovery] Scanning journal...");
let journal_data = self.disk.read_block(JOURNAL_START_BLOCK);
if let Ok(tx) = bincode::deserialize::<Transaction>(&journal_data) {
if tx.committed {
println!("[Recovery] FOUND CRASHED TRANSACTION #{}. Replaying...", tx.id);
// Replay Logic
for op in tx.ops {
match op {
JournalOp::WriteBlock { block_idx, data } => {
println!(" -> Replaying block write to index {}", block_idx);
self.disk.write_block(block_idx, &data);
}
JournalOp::UpdateSuperBlock { sb } => {
println!(" -> Replaying superblock update");
let data = bincode::serialize(&sb).unwrap();
self.disk.write_block(0, &data);
}
_ => {}
}
}
// Clear journal
self.disk.write_block(JOURNAL_START_BLOCK, &[0; 4096]);
println!("[Recovery] Replay complete. Filesystem consistent.");
}
} else {
println!("[Recovery] Journal clean.");
}
}
// --- User Operations ---
/// Simulates creating a file and writing data to it
fn write_file_atomic(&mut self, inode_id: u64, content: &[u8]) {
println!("--- Start Atomic Write (File ID: {}) ---", inode_id);
// 1. Allocate Block (Simplified)
let new_block_idx = self.superblock.free_block_ptr;
self.superblock.free_block_ptr += 1;
// 2. Create New Inode State
let new_inode = Inode {
id: inode_id,
size: content.len() as u64,
blocks: vec![new_block_idx],
};
// 3. Prepare Journal Operations (The "Transaction")
let ops = vec![
// Op: Write the actual data to the allocated block
JournalOp::WriteBlock {
block_idx: new_block_idx,
data: content.to_vec()
},
// Op: Update the inode to point to that block
JournalOp::UpdateInode {
inode_idx: inode_id,
inode: new_inode
},
// Op: Update superblock (allocator changed)
JournalOp::UpdateSuperBlock {
sb: self.superblock.clone()
},
];
// 4. Log to Journal (Persist Intent)
let tx_id = self.log_and_commit(ops);
// 5. CRASH SIMULATION POINT!
// If power is cut here, data is in Journal, but not in Main Disk locations.
// 6. Checkpoint (Apply Journal to Main Disk)
self.checkpoint(tx_id);
}
}
// --- Demonstration ---
fn main() {
// 1. Initialize a blank disk
let raw_disk = Disk::new(DISK_SIZE);
// 2. Format disk (mkfs)
let mut fs = MiniExt4::mkfs(raw_disk.clone());
// 3. Perform a healthy write and read it back
fs.write_file_atomic(1, b"Hello, World!");
let block_loc = 100; // Based on our simple allocator start
let data = fs.disk.read_block(block_loc);
println!("Read from Block {}: {:?}", block_loc, String::from_utf8_lossy(&data[0..13]));
println!("--------------------------------------------------");
println!("Starting Crash Simulation...");
// 4. Simulate a Power Outage
// We will manually write to the Journal, but prevent the Checkpoint.
let mut crashed_disk = fs.disk.clone(); // Clone state before new write
// Prepare a transaction
let content = b"Important Data!";
let alloc_block = 101;
let ops = vec![
JournalOp::WriteBlock { block_idx: alloc_block, data: content.to_vec() },
JournalOp::UpdateSuperBlock { sb: SuperBlock { free_block_ptr: 102, ..fs.superblock } }
];
let tx = Transaction { id: 99, ops, checksum: 0, committed: true };
let tx_bytes = bincode::serialize(&tx).unwrap();
// Manually write to Journal Area ONLY
println!("[System] Power failure during checkpointing...");
crashed_disk.write_block(JOURNAL_START_BLOCK, &tx_bytes);
// Verify main storage does NOT have the data yet
let check = crashed_disk.read_block(alloc_block);
println!("Disk state before recovery (Block {}): {:?}", alloc_block, &check[0..5]); // Should be empty
println!("--------------------------------------------------");
println!("Mounting Filesystem (triggering recovery)...");
// 5. Mount the "crashed" disk
let recovered_fs = MiniExt4::mount(crashed_disk);
// 6. Verify Data exists now
let check_rec = recovered_fs.disk.read_block(alloc_block);
println!("Disk state after recovery (Block {}): {:?}", alloc_block, String::from_utf8_lossy(&check_rec[0..15]));
}