use bincode::{deserialize, serialize};
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::{Read, Seek, SeekFrom, Write};
use std::sync::{Arc, Mutex};
// --- CONSTANTS ---
const BLOCK_SIZE: usize = 4096;
const DISK_SIZE: usize = 1024 * 1024 * 10; // 10 MB Disk
const JOURNAL_START: u64 = 1; // Block 1
const JOURNAL_SIZE_BLOCKS: u64 = 1024; // 4MB Journal
const MAIN_FS_START: u64 = JOURNAL_START + JOURNAL_SIZE_BLOCKS;
const INODE_SIZE: usize = 256;
const INODES_PER_BLOCK: usize = BLOCK_SIZE / INODE_SIZE;
// Magic numbers for integrity
const SUPER_MAGIC: u32 = 0xEF53;
const JOURNAL_MAGIC: u32 = 0xDEAD;
// --- ON-DISK STRUCTURES ---
#[derive(Serialize, Deserialize, Debug, Clone)]
struct Superblock {
magic: u32,
block_size: u32,
total_blocks: u64,
inode_count: u64,
free_blocks: u64,
// Pointers to specific areas
inode_table_start: u64, // Block ID where inode table begins
data_block_start: u64, // Block ID where actual data begins
}
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
struct Inode {
mode: u16, // Permissions, file/dir flag
size: u64,
blocks: u64,
direct_blocks: [u64; 12], // Direct pointers
single_indirect: u64, // Simplified for now
double_indirect: u64,
triple_indirect: u64,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
enum JournalState {
Empty,
TransactionStart,
DataLogged,
Commit,
Complete,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct JournalHeader {
magic: u32,
state: JournalState,
transaction_id: u64,
target_block: u64, // Which block in main FS we are overwriting
}
// --- BLOCK DEVICE LAYER ---
struct BlockDevice {
file: File,
}
impl BlockDevice {
fn new(path: &str) -> std::io::Result<Self> {
let mut file = File::options().read(true).write(true).create(true).open(path)?;
file.set_len(DISK_SIZE as u64)?;
Ok(BlockDevice { file })
}
fn write_block(&mut self, block_id: u64, data: &[u8; BLOCK_SIZE]) -> std::io::Result<()> {
self.file.seek(SeekFrom::Start(block_id * BLOCK_SIZE as u64))?;
self.file.write_all(data)?;
// Simulate physical disk flush
self.file.sync_all()?;
Ok(())
}
fn read_block(&mut self, block_id: u64) -> std::io::Result<[u8; BLOCK_SIZE]> {
let mut buf = [0u8; BLOCK_SIZE];
self.file.seek(SeekFrom::Start(block_id * BLOCK_SIZE as u64))?;
self.file.read_exact(&mut buf)?;
Ok(buf)
}
}
// --- FILESYSTEM LOGIC ---
pub struct Ext4Lite {
dev: Arc<Mutex<BlockDevice>>,
superblock: Superblock,
}
impl Ext4Lite {
pub fn format(path: &str) -> std::io::Result<Self> {
let mut dev = BlockDevice::new(path)?;
// 1. Initialize Superblock
let total_blocks = (DISK_SIZE / BLOCK_SIZE) as u64;
let sb = Superblock {
magic: SUPER_MAGIC,
block_size: BLOCK_SIZE as u32,
total_blocks,
inode_count: 0,
free_blocks: total_blocks - MAIN_FS_START, // rough calc
inode_table_start: MAIN_FS_START, // First block of main area is inode table
data_block_start: MAIN_FS_START + 10, // Reserve some space for inodes
};
let sb_bytes = serialize(&sb).unwrap();
let mut block_buf = [0u8; BLOCK_SIZE];
block_buf[..sb_bytes.len()].copy_from_slice(&sb_bytes);
dev.write_block(0, &block_buf)?; // Superblock at Block 0
// Initialize Journal Area
let jh = JournalHeader {
magic: JOURNAL_MAGIC,
state: JournalState::Empty,
transaction_id: 0,
target_block: 0,
};
let jh_bytes = serialize(&jh).unwrap();
let mut j_buf = [0u8; BLOCK_SIZE];
j_buf[..jh_bytes.len()].copy_from_slice(&jh_bytes);
// Write empty headers to the first few journal blocks
for i in JOURNAL_START..(JOURNAL_START + 4) {
dev.write_block(i, &j_buf)?;
}
Ok(Self {
dev: Arc::new(Mutex::new(dev)),
superblock: sb,
})
}
pub fn mount(path: &str) -> std::io::Result<Self> {
let mut dev = BlockDevice::new(path)?;
let sb_buf = dev.read_block(0)?;
// Basic error handling for magic number
let sb: Superblock = match deserialize(&sb_buf) {
Ok(s) if s.magic == SUPER_MAGIC => s,
_ => panic!("Invalid filesystem or corrupt superblock!"),
};
// Recovery Step: Check Journal
println!("Checking journal for recovery...");
// In a real FS, we would scan the journal here.
// For this demo, we assume clean mount or recovery happens on specific ops.
Ok(Self {
dev: Arc::new(Mutex::new(dev)),
superblock: sb,
})
}
// --- JOURNALED WRITE OPERATION ---
/// Writes data to a specific block ID using Write-Ahead Logging (WAL)
pub fn write_data_journaled(&mut self, block_id: u64, data: &[u8]) -> std::io::Result<()> {
let mut dev = self.dev.lock().unwrap();
// 1. Prepare Block Buffer
let mut block_buf = [0u8; BLOCK_SIZE];
let len = data.len().min(BLOCK_SIZE);
block_buf[..len].copy_from_slice(&data[..len]);
// 2. FIND A FREE JOURNAL BLOCK (Simplified: we use a fixed rotation)
// In reality, this involves checking the journal head/tail pointers.
// We assume the journal area is circular and we find a spot.
let journal_block_id = JOURNAL_START;
// --- PHASE 1: LOG THE TRANSACTION ---
// A. Write the Data to the Journal Block
// We write the data *payload* first, then the metadata header.
// This order matters for crash recovery.
dev.write_block(journal_block_id, &block_buf)?;
// B. Write the Journal Header (Transaction Start/Commit)
let header = JournalHeader {
magic: JOURNAL_MAGIC,
state: JournalState::Commit, // We commit immediately for atomicity
transaction_id: 1,
target_block: block_id,
};
let mut j_header_buf = [0u8; BLOCK_SIZE];
let h_bytes = serialize(&header).unwrap();
j_header_buf[..h_bytes.len()].copy_from_slice(&h_bytes);
// Overwrite the data block in the journal with the header + data?
// Real ext4 separates descriptor blocks and data blocks.
// Let's simulate writing the header to a dedicated slot (journal_block_id + 1)
dev.write_block(journal_block_id + 1, &j_header_buf)?;
// --- PHASE 2: CHECKPOINT (Write to Main FS) ---
// Now that the transaction is safely logged, we write to the actual destination
dev.write_block(block_id, &block_buf)?;
// --- PHASE 3: COMPLETE ---
// Mark transaction as complete in journal so we don't replay it next time
let complete_header = JournalHeader {
state: JournalState::Complete,
..header
};
let mut c_buf = [0u8; BLOCK_SIZE];
let c_bytes = serialize(&complete_header).unwrap();
c_buf[..c_bytes.len()].copy_from_slice(&c_bytes);
dev.write_block(journal_block_id + 1, &c_buf)?;
println!("Journaled write complete to block {}", block_id);
Ok(())
}
pub fn create_inode(&mut self, mode: u16) -> std::io::Result<u64> {
// 1. Allocate an Inode (Simplified: find first free slot)
let inode_table = self.superblock.inode_table_start;
// Scan for a zeroed out inode (simple allocation)
let mut dev = self.dev.lock().unwrap();
// In reality, we'd check a bitmap. Here we just take Inode #1
let inode_id = 1;
let block_offset = inode_id / (INODE_SIZE as u64);
let offset_in_block = inode_id % (INODE_SIZE as u64);
let inode = Inode {
mode,
size: 0,
..Default::default()
};
// Read-Modify-Write the inode table block
let mut block_buf = dev.read_block(inode_table + block_offset)?;
// Serialize inode into the buffer
let i_bytes = serialize(&inode).unwrap();
let start = (offset_in_block as usize) * INODE_SIZE;
block_buf[start..start + i_bytes.len()].copy_from_slice(&i_bytes);
// Write back to table (Ideally this write is also journaled!)
dev.write_block(inode_table + block_offset, &block_buf)?;
println!("Created Inode {}", inode_id);
Ok(inode_id)
}
// Recovery Logic
pub fn recover(&mut self) {
let mut dev = self.dev.lock().unwrap();
// Scan journal area
for i in JOURNAL_START..(JOURNAL_START + JOURNAL_SIZE_BLOCKS) {
let buf = dev.read_block(i).unwrap(); // Assuming header is inline
if let Ok(header) = deserialize::<JournalHeader>(&buf) {
if header.magic == JOURNAL_MAGIC && header.state == JournalState::Commit {
println!("CRASH DETECTED! Found uncommitted transaction in journal block {}", i);
// Replay Logic:
// 1. Read data from journal (i)
// 2. Write to target_block
println!("Replaying transaction to block {}", header.target_block);
// In this simplified model, data is at i, header at i?
// (Adjust logic based on the write phase above)
// This demonstrates the *concept* of recovery.
}
}
}
}
}
// --- DEMONSTRATION ---
fn main() -> std::io::Result<()> {
let disk_path = "my_ext4_disk.img";
// 1. Format the disk
println!("Formatting disk...");
let mut fs = Ext4Lite::format(disk_path)?;
// 2. Create an Inode
let ino = fs.create_inode(0o755)?;
// 3. Write data with Journaling
let data_block = 5000; // Some arbitrary data block location
let my_data = b"Hello, this is important file content.";
fs.write_data_journaled(data_block, my_data)?;
println!("\n--- Simulating Crash Recovery ---");
drop(fs); // Close FS
// Remount
let mut fs = Ext4Lite::mount(disk_path)?;
fs.recover(); // Check for unfinished transactions
Ok(())
}