use serde::{Deserialize, Serialize};
use std::fs::{File, OpenOptions};
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::Path;
use std::sync::{Arc, Mutex};
type Error = Box<dyn std::error::Error + Send + Sync>;
type Result<T> = std::result::Result<T, Error>;
const BLOCK_SIZE: usize = 4096;
const INODE_SLOT_SIZE: usize = 256;
const INODES_PER_BLOCK: usize = BLOCK_SIZE / INODE_SLOT_SIZE;
const FS_MAGIC: u32 = 0xF5F5_E4T4;
const JOURNAL_MAGIC: u32 = 0x4A4E_4C30; // "JNL0"
const MAX_TX_RECORDS: usize = 64; // max metadata blocks per transaction
const JOURNAL_BLOCKS: u64 = 128; // fixed journal size for demo
// In a real FS you'd pull these from the platform or config
const DEFAULT_TOTAL_INODES: u64 = 128;
// Very simple inode type (ext4-inspired but much smaller)
#[derive(Serialize, Deserialize, Debug, Clone)]
struct Inode {
mode: u16, // POSIX mode bits, + file type
uid: u32,
gid: u32,
size: u64,
links: u32,
atime: u64,
mtime: u64,
ctime: u64,
direct: [u64; 12], // direct data block pointers
// For brevity, no indirect blocks, no extents.
}
impl Inode {
fn new_file(mode: u16, uid: u32, gid: u32) -> Self {
Self {
mode,
uid,
gid,
size: 0,
links: 1,
atime: 0,
mtime: 0,
ctime: 0,
direct: [0; 12],
}
}
fn new_dir(mode: u16, uid: u32, gid: u32) -> Self {
let mut inode = Self::new_file(mode, uid, gid);
inode.links = 2; // "." and parent (for root, parent == self)
inode
}
}
// Superblock contains overall layout + bitmaps.
#[derive(Serialize, Deserialize, Debug, Clone)]
struct Superblock {
magic: u32,
block_size: u32,
total_blocks: u64,
total_inodes: u64,
free_blocks: u64,
free_inodes: u64,
inode_table_start: u64,
inode_table_blocks: u64,
first_data_block: u64,
journal_start: u64,
journal_blocks: u64,
root_inode: u64,
// simple bitmaps (true = used)
inode_bitmap: Vec<bool>,
block_bitmap: Vec<bool>,
}
// Each directory is stored as a file containing serialized DirEntries.
#[derive(Serialize, Deserialize, Debug, Clone)]
struct DirEntry {
inode: u64,
name: String,
}
// ---------------------------------------------------------------------------
// BlockDevice abstraction (file-backed)
// ---------------------------------------------------------------------------
trait BlockDevice: Send + Sync {
fn block_size(&self) -> usize {
BLOCK_SIZE
}
fn num_blocks(&self) -> Result<u64>;
fn read_block(&self, block_id: u64, buf: &mut [u8]) -> Result<()>;
fn write_block(&self, block_id: u64, buf: &[u8]) -> Result<()>;
fn flush(&self) -> Result<()>;
}
struct FileDisk {
file: Mutex<File>,
blocks: u64,
}
impl FileDisk {
fn open(path: &Path, blocks: Option<u64>) -> Result<Self> {
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(path)?;
let actual_len = file.metadata()?.len();
let mut file = file;
let blocks = if let Some(b) = blocks {
file.set_len(b * BLOCK_SIZE as u64)?;
b
} else if actual_len == 0 {
return Err("File exists but has zero length; specify blocks".into());
} else {
actual_len / BLOCK_SIZE as u64
};
Ok(Self {
file: Mutex::new(file),
blocks,
})
}
}
impl BlockDevice for FileDisk {
fn num_blocks(&self) -> Result<u64> {
Ok(self.blocks)
}
fn read_block(&self, block_id: u64, buf: &mut [u8]) -> Result<()> {
if buf.len() != BLOCK_SIZE {
return Err("buffer size != BLOCK_SIZE".into());
}
if block_id >= self.blocks {
return Err("read_block: block out of range".into());
}
let mut f = self.file.lock().unwrap();
f.seek(SeekFrom::Start(block_id * BLOCK_SIZE as u64))?;
f.read_exact(buf)?;
Ok(())
}
fn write_block(&self, block_id: u64, buf: &[u8]) -> Result<()> {
if buf.len() != BLOCK_SIZE {
return Err("buffer size != BLOCK_SIZE".into());
}
if block_id >= self.blocks {
return Err("write_block: block out of range".into());
}
let mut f = self.file.lock().unwrap();
f.seek(SeekFrom::Start(block_id * BLOCK_SIZE as u64))?;
f.write_all(buf)?;
Ok(())
}
fn flush(&self) -> Result<()> {
let mut f = self.file.lock().unwrap();
f.sync_all()?;
Ok(())
}
}
// ---------------------------------------------------------------------------
// Journaling
//
// Simple physical metadata journal stored at the end of the device.
// Only metadata blocks are logged (superblock, inode blocks, directory blocks).
// Data blocks are written directly to their home locations and flushed
// before committing metadata (like ext4's ordered mode).
// ---------------------------------------------------------------------------
#[derive(Serialize, Deserialize, Debug, Clone)]
struct JournalHeader {
magic: u32,
start_block: u64, // first transaction block
end_block: u64, // next free after last transaction
last_seq: u64,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct JournalTxHeader {
seq: u64,
num_records: u32,
block_ids: Vec<u64>, // len == num_records, <= MAX_TX_RECORDS
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct JournalTxCommit {
seq: u64,
}
struct Transaction {
seq: u64,
// in-memory buffer of changed metadata blocks:
records: Vec<(u64, [u8; BLOCK_SIZE])>, // (block_id, block_data)
}
struct Journal {
dev: Arc<dyn BlockDevice>,
header_block: u64, // block index of JournalHeader
area_start: u64, // first tx block
area_end: u64, // last block in journal area + 1
header: JournalHeader,
}
impl Journal {
fn open(dev: Arc<dyn BlockDevice>, journal_start: u64, journal_blocks: u64) -> Result<Self> {
let header_block = journal_start;
let area_start = journal_start + 1;
let area_end = journal_start + journal_blocks;
let mut buf = vec![0u8; BLOCK_SIZE];
dev.read_block(header_block, &mut buf)?;
let header: JournalHeader = match bincode::deserialize(&buf) {
Ok(h) if h.magic == JOURNAL_MAGIC => h,
_ => {
// Initialize fresh journal
JournalHeader {
magic: JOURNAL_MAGIC,
start_block: area_start,
end_block: area_start,
last_seq: 0,
}
}
};
let mut j = Self {
dev,
header_block,
area_start,
area_end,
header,
};
j.replay()?; // ensure FS is consistent
Ok(j)
}
fn begin_tx(&mut self) -> Transaction {
Transaction {
seq: self.header.last_seq + 1,
records: Vec::new(),
}
}
fn log_block(&mut self, tx: &mut Transaction, block_id: u64, data: &[u8]) -> Result<()> {
if data.len() != BLOCK_SIZE {
return Err("log_block: data len != BLOCK_SIZE".into());
}
if tx.records.len() >= MAX_TX_RECORDS {
return Err("transaction too large".into());
}
// coalesce multiple changes to same block
if let Some((_, ref mut existing)) =
tx.records.iter_mut().find(|(bid, _)| *bid == block_id)
{
existing.copy_from_slice(data);
} else {
let mut buf = [0u8; BLOCK_SIZE];
buf.copy_from_slice(data);
tx.records.push((block_id, buf));
}
Ok(())
}
fn commit(&mut self, tx: Transaction) -> Result<()> {
if tx.records.is_empty() {
// Nothing to do
self.header.last_seq = tx.seq;
self.write_header()?;
return Ok(());
}
let num_records = tx.records.len() as u32;
let needed_blocks = 1 + num_records as u64 + 1; // header + records + commit
if self.header.end_block + needed_blocks > self.area_end {
// For simplicity: wrap or ignore old log is not implemented;
// we just reset the journal when full. Production FS would do better.
self.header.start_block = self.area_start;
self.header.end_block = self.area_start;
}
let tx_start = self.header.end_block;
// 1. Write TX header
let header = JournalTxHeader {
seq: tx.seq,
num_records,
block_ids: tx.records.iter().map(|(bid, _)| *bid).collect(),
};
let mut buf = vec![0u8; BLOCK_SIZE];
let encoded = bincode::serialize(&header)?;
if encoded.len() > BLOCK_SIZE {
return Err("JournalTxHeader too large".into());
}
buf[..encoded.len()].copy_from_slice(&encoded);
self.dev.write_block(tx_start, &buf)?;
// 2. Write data blocks for each record
for (i, (_, block_data)) in tx.records.iter().enumerate() {
let jblock = tx_start + 1 + i as u64;
self.dev.write_block(jblock, block_data)?;
}
// 3. Write commit block
let commit = JournalTxCommit { seq: tx.seq };
let mut cbuf = vec![0u8; BLOCK_SIZE];
let cencoded = bincode::serialize(&commit)?;
if cencoded.len() > BLOCK_SIZE {
return Err("JournalTxCommit too large".into());
}
cbuf[..cencoded.len()].copy_from_slice(&cencoded);
let commit_block = tx_start + 1 + num_records as u64;
self.dev.write_block(commit_block, &cbuf)?;
// 4. Flush journal
self.dev.flush()?;
// 5. Apply changes to home locations
for (block_id, block_data) in &tx.records {
self.dev.write_block(*block_id, block_data)?;
}
self.dev.flush()?;
// 6. Advance journal header
self.header.last_seq = tx.seq;
self.header.end_block = commit_block + 1;
self.write_header()?;
Ok(())
}
fn write_header(&self) -> Result<()> {
let mut buf = vec![0u8; BLOCK_SIZE];
let encoded = bincode::serialize(&self.header)?;
if encoded.len() > BLOCK_SIZE {
return Err("JournalHeader too large".into());
}
buf[..encoded.len()].copy_from_slice(&encoded);
self.dev.write_block(self.header_block, &buf)?;
self.dev.flush()?;
Ok(())
}
fn replay(&mut self) -> Result<()> {
let mut pos = self.header.start_block;
while pos < self.header.end_block {
// Read tx header
let mut hbuf = vec![0u8; BLOCK_SIZE];
self.dev.read_block(pos, &mut hbuf)?;
let header: JournalTxHeader = match bincode::deserialize(&hbuf) {
Ok(h) => h,
Err(_) => break, // corrupted; stop
};
if header.num_records == 0 || header.block_ids.len() != header.num_records as usize {
break; // malformed
}
// Read commit
let commit_block = pos + 1 + header.num_records as u64;
if commit_block >= self.area_end {
break;
}
let mut cbuf = vec![0u8; BLOCK_SIZE];
self.dev.read_block(commit_block, &mut cbuf)?;
let commit: JournalTxCommit = match bincode::deserialize(&cbuf) {
Ok(c) => c,
Err(_) => break,
};
if commit.seq != header.seq {
break; // partial / corrupted
}
// Fully committed tx: replay it
for (i, block_id) in header.block_ids.iter().enumerate() {
let jblock = pos + 1 + i as u64;
let mut data = vec![0u8; BLOCK_SIZE];
self.dev.read_block(jblock, &mut data)?;
self.dev.write_block(*block_id, &data)?;
}
self.dev.flush()?;
pos = commit_block + 1;
}
// Reset journal (we've applied everything)
self.header.start_block = self.area_start;
self.header.end_block = self.area_start;
self.write_header()?;
Ok(())
}
}
// ---------------------------------------------------------------------------
// Filesystem core
// ---------------------------------------------------------------------------
struct FileSystem {
dev: Arc<dyn BlockDevice>,
journal: Journal,
sb: Superblock,
}
impl FileSystem {
// Format a new filesystem on the device
fn format_new(dev: Arc<dyn BlockDevice>) -> Result<()> {
let total_blocks = dev.num_blocks()?;
if total_blocks < 1024 {
return Err("device too small (need >=1024 blocks)".into());
}
let total_inodes = DEFAULT_TOTAL_INODES;
let inode_table_blocks = ((total_inodes + INODES_PER_BLOCK as u64 - 1)
/ INODES_PER_BLOCK as u64) as u64;
let journal_start = total_blocks - JOURNAL_BLOCKS;
let first_data_block = 1 + inode_table_blocks;
if first_data_block >= journal_start {
return Err("not enough room for data + journal".into());
}
// Superblock
let mut inode_bitmap = vec![false; total_inodes as usize + 1]; // inode 0 unused
let mut block_bitmap = vec![false; total_blocks as usize];
// Reserve metadata blocks as "used"
block_bitmap[0] = true; // superblock
for b in 0..inode_table_blocks {
block_bitmap[1 + b as usize] = true;
}
for b in journal_start..total_blocks {
block_bitmap[b as usize] = true;
}
// Root inode = 1
inode_bitmap[1] = true;
let free_inodes = total_inodes - 1;
let data_blocks =
(journal_start - first_data_block) as u64; // data area excludes journal & metadata
let free_blocks = data_blocks;
let sb = Superblock {
magic: FS_MAGIC,
block_size: BLOCK_SIZE as u32,
total_blocks,
total_inodes,
free_blocks,
free_inodes,
inode_table_start: 1,
inode_table_blocks,
first_data_block,
journal_start,
journal_blocks: JOURNAL_BLOCKS,
root_inode: 1,
inode_bitmap,
block_bitmap,
};
// Zero all blocks
let zero = vec![0u8; BLOCK_SIZE];
for b in 0..total_blocks {
dev.write_block(b, &zero)?;
}
// Write superblock
Self::write_superblock_raw(&*dev, &sb)?;
// Write root inode (empty directory)
let root_inode = Inode::new_dir(0o40755, 0, 0);
Self::write_inode_raw(&*dev, &sb, 1, &root_inode)?;
// Initialize empty journal header
let jhdr = JournalHeader {
magic: JOURNAL_MAGIC,
start_block: journal_start + 1,
end_block: journal_start + 1,
last_seq: 0,
};
let mut jbuf = vec![0u8; BLOCK_SIZE];
let encoded = bincode::serialize(&jhdr)?;
jbuf[..encoded.len()].copy_from_slice(&encoded);
dev.write_block(journal_start, &jbuf)?;
dev.flush()?;
Ok(())
}
fn mount(dev: Arc<dyn BlockDevice>) -> Result<Self> {
let sb = Self::read_superblock_raw(&*dev)?;
if sb.magic != FS_MAGIC {
return Err("bad filesystem magic; not formatted or wrong FS".into());
}
let journal = Journal::open(
Arc::clone(&dev),
sb.journal_start,
sb.journal_blocks,
)?;
Ok(Self { dev, journal, sb })
}
// -------- Raw (non-journaled) superblock/inode IO, used by format/mount -----
fn write_superblock_raw(dev: &dyn BlockDevice, sb: &Superblock) -> Result<()> {
let mut buf = vec![0u8; BLOCK_SIZE];
let encoded = bincode::serialize(sb)?;
if encoded.len() > BLOCK_SIZE {
return Err("Superblock too large".into());
}
buf[..encoded.len()].copy_from_slice(&encoded);
dev.write_block(0, &buf)?;
dev.flush()?;
Ok(())
}
fn read_superblock_raw(dev: &dyn BlockDevice) -> Result<Superblock> {
let mut buf = vec![0u8; BLOCK_SIZE];
dev.read_block(0, &mut buf)?;
let sb: Superblock = bincode::deserialize(&buf)?;
Ok(sb)
}
// Inode index -> (block, offset within block)
fn inode_location(sb: &Superblock, inode_id: u64) -> (u64, usize) {
assert!(inode_id > 0);
let index = inode_id as usize - 1;
let block_offset = index / INODES_PER_BLOCK;
let slot_offset = index % INODES_PER_BLOCK;
let block_id = sb.inode_table_start + block_offset as u64;
let byte_offset = slot_offset * INODE_SLOT_SIZE;
(block_id, byte_offset)
}
fn read_inode_raw(dev: &dyn BlockDevice, sb: &Superblock, inode_id: u64) -> Result<Inode> {
let (block_id, offset) = Self::inode_location(sb, inode_id);
let mut buf = vec![0u8; BLOCK_SIZE];
dev.read_block(block_id, &mut buf)?;
let slot = &buf[offset..offset + INODE_SLOT_SIZE];
// find first 0 byte from end? For simplicity, just try full slot.
let inode: Inode = bincode::deserialize(slot)?;
Ok(inode)
}
fn write_inode_raw(
dev: &dyn BlockDevice,
sb: &Superblock,
inode_id: u64,
inode: &Inode,
) -> Result<()> {
let (block_id, offset) = Self::inode_location(sb, inode_id);
let mut buf = vec![0u8; BLOCK_SIZE];
dev.read_block(block_id, &mut buf)?;
let encoded = bincode::serialize(inode)?;
if encoded.len() > INODE_SLOT_SIZE {
return Err("Inode too large for INODE_SLOT_SIZE".into());
}
let slot = &mut buf[offset..offset + INODE_SLOT_SIZE];
slot.fill(0);
slot[..encoded.len()].copy_from_slice(&encoded);
dev.write_block(block_id, &buf)?;
dev.flush()?;
Ok(())
}
// ----- Journaled variants used during normal operation -----
fn flush_superblock(&mut self, tx: &mut Transaction) -> Result<()> {
let mut buf = vec![0u8; BLOCK_SIZE];
let encoded = bincode::serialize(&self.sb)?;
if encoded.len() > BLOCK_SIZE {
return Err("Superblock too large".into());
}
buf[..encoded.len()].copy_from_slice(&encoded);
self.journal.log_block(tx, 0, &buf)
}
fn read_inode(&self, inode_id: u64) -> Result<Inode> {
Self::read_inode_raw(&*self.dev, &self.sb, inode_id)
}
fn write_inode(&mut self, tx: &mut Transaction, inode_id: u64, inode: &Inode) -> Result<()> {
let (block_id, offset) = Self::inode_location(&self.sb, inode_id);
let mut buf = vec![0u8; BLOCK_SIZE];
self.dev.read_block(block_id, &mut buf)?;
let encoded = bincode::serialize(inode)?;
if encoded.len() > INODE_SLOT_SIZE {
return Err("Inode too large".into());
}
let slot = &mut buf[offset..offset + INODE_SLOT_SIZE];
slot.fill(0);
slot[..encoded.len()].copy_from_slice(&encoded);
self.journal.log_block(tx, block_id, &buf)
}
// ----- Block/inode allocation -----
fn alloc_inode(&mut self) -> Result<u64> {
for (i, used) in self.sb.inode_bitmap.iter_mut().enumerate().skip(1) {
if !*used {
*used = true;
self.sb.free_inodes -= 1;
return Ok(i as u64);
}
}
Err("no free inodes".into())
}
fn alloc_block(&mut self) -> Result<u64> {
for (i, used) in self.sb.block_bitmap.iter_mut().enumerate() {
let b = i as u64;
if b < self.sb.first_data_block || b >= self.sb.journal_start {
continue;
}
if !*used {
*used = true;
self.sb.free_blocks -= 1;
return Ok(b);
}
}
Err("no free blocks".into())
}
// ----- Directory helpers -----
fn read_dir(&self, inode_id: u64) -> Result<Vec<DirEntry>> {
let inode = self.read_inode(inode_id)?;
if inode.size == 0 {
return Ok(Vec::new());
}
// Only handle small dirs in first direct block for demo
let data_block = inode.direct[0];
if data_block == 0 {
return Ok(Vec::new());
}
let mut buf = vec![0u8; BLOCK_SIZE];
self.dev.read_block(data_block, &mut buf)?;
let entries: Vec<DirEntry> = bincode::deserialize(&buf)?;
Ok(entries)
}
fn write_dir(
&mut self,
tx: &mut Transaction,
inode_id: u64,
mut entries: Vec<DirEntry>,
) -> Result<()> {
let mut inode = self.read_inode(inode_id)?;
let block_id = if inode.direct[0] == 0 {
let b = self.alloc_block()?;
inode.direct[0] = b;
b
} else {
inode.direct[0]
};
// Serialize dir entries
let mut buf = vec![0u8; BLOCK_SIZE];
let encoded = bincode::serialize(&entries)?;
if encoded.len() > BLOCK_SIZE {
return Err("directory too large for one block (demo limit)".into());
}
buf[..encoded.len()].copy_from_slice(&encoded);
inode.size = encoded.len() as u64;
self.journal.log_block(tx, block_id, &buf)?;
self.write_inode(tx, inode_id, &inode)?;
Ok(())
}
fn lookup(&self, dir_inode: u64, name: &str) -> Result<Option<u64>> {
for e in self.read_dir(dir_inode)? {
if e.name == name {
return Ok(Some(e.inode));
}
}
Ok(None)
}
// ----- File API (very small subset) -----
fn create_file(&mut self, parent: u64, name: &str, mode: u16) -> Result<u64> {
let mut tx = self.journal.begin_tx();
let new_ino = self.alloc_inode()?;
let inode = Inode::new_file(0o100000 | mode, 0, 0); // regular file
self.write_inode(&mut tx, new_ino, &inode)?;
// add to parent dir
let mut dir = self.read_dir(parent)?;
dir.push(DirEntry {
inode: new_ino,
name: name.to_string(),
});
self.write_dir(&mut tx, parent, dir)?;
// persist superblock (bitmap changes)
self.flush_superblock(&mut tx)?;
self.journal.commit(tx)?;
Ok(new_ino)
}
// Sequential write from offset 0 only, small files only
fn write_file(&mut self, inode_id: u64, data: &[u8]) -> Result<()> {
let mut inode = self.read_inode(inode_id)?;
let mut tx = self.journal.begin_tx();
let needed_blocks =
((data.len() + BLOCK_SIZE - 1) / BLOCK_SIZE).min(inode.direct.len());
let mut written = 0usize;
// 1. Allocate blocks & write data directly
for i in 0..needed_blocks {
let block_id = if inode.direct[i] == 0 {
let b = self.alloc_block()?;
inode.direct[i] = b;
b
} else {
inode.direct[i]
};
let start = i * BLOCK_SIZE;
let end = (start + BLOCK_SIZE).min(data.len());
let mut buf = vec![0u8; BLOCK_SIZE];
buf[..end - start].copy_from_slice(&data[start..end]);
self.dev.write_block(block_id, &buf)?;
written = end;
}
self.dev.flush()?; // ensure data blocks are on disk
// 2. Update inode metadata via journal
inode.size = written as u64;
self.write_inode(&mut tx, inode_id, &inode)?;
// 3. Superblock (block bitmap may have changed)
self.flush_superblock(&mut tx)?;
self.journal.commit(tx)?;
Ok(())
}
fn read_file(&self, inode_id: u64) -> Result<Vec<u8>> {
let inode = self.read_inode(inode_id)?;
let mut result = Vec::with_capacity(inode.size as usize);
let mut remaining = inode.size as usize;
for &b in &inode.direct {
if b == 0 || remaining == 0 {
break;
}
let mut buf = vec![0u8; BLOCK_SIZE];
self.dev.read_block(b, &mut buf)?;
let to_take = remaining.min(BLOCK_SIZE);
result.extend_from_slice(&buf[..to_take]);
remaining -= to_take;
}
result.truncate(inode.size as usize);
Ok(result)
}
}
// ---------------------------------------------------------------------------
// Demo main
// ---------------------------------------------------------------------------
fn main() -> Result<()> {
let path = Path::new("fs.img");
let blocks = 8192u64; // 8192 * 4KiB = 32 MiB image
if !path.exists() {
println!("Formatting new filesystem...");
let dev = Arc::new(FileDisk::open(path, Some(blocks))?);
FileSystem::format_new(Arc::clone(&dev))?;
println!("Formatted.");
}
let dev = Arc::new(FileDisk::open(path, None)?);
let mut fs = FileSystem::mount(Arc::clone(&dev))?;
// Create a file under root and write some data
let root = fs.sb.root_inode;
let test_inode = match fs.lookup(root, "hello.txt")? {
Some(ino) => ino,
None => {
println!("Creating /hello.txt ...");
fs.create_file(root, "hello.txt", 0o644)?
}
};
let content = b"Hello from mini ext4-like filesystem with journaling!";
fs.write_file(test_inode, content)?;
let read_back = fs.read_file(test_inode)?;
println!(
"Read from /hello.txt: {}",
String::from_utf8_lossy(&read_back)
);
Ok(())
}