Considering filesystem implementation
The user is asking for an ext4-like filesystem with journaling in Rust, but that’s a huge task—way beyond just writing code. I need to focus on something more manageable, like creating a design, skeleton, or partial implementation. I should also highlight its complexity while providing an outline and some example Rust code about journaling. Since the user didn’t specify details, I'll keep my response general and admit I can't produce a full, production-ready filesystem.Outlining filesystem design
I need to clarify assumptions first. Then, I should outline the architecture including disk layout, journaling model, and other key components. I can provide Rust modules like BlockDevice, Journal, Inode, and FileSystem with necessary operations. I might mention helpful crates like memmap2 and tokio::fs, but I should warn against using unstable ones. Since the user didn’t specify FUSE but it’s common in user-space implementations, I’ll approach this as an educational, simplified ext4-like filesystem, mentioning that some parts might be omitted for brevity.Deciding on filesystem delivery
I need to decide how to present this project. I could deliver a reasonably detailed skeleton with partial implementations and guide the user to complete it, including some journaling logic. I'll outline: first, the scope and constraints focused on a simplified ext4-like filesystem that isn’t for production. Then, I want to cover key concepts of ext4 structure and journaling, like write-ahead logging with transaction logs, commit records, and replay mechanisms.Drafting Rust code components
I'm outlining some Rust code for a simplified filesystem. It starts with defining a BlockDevice trait for reading and writing blocks. Then, I’ll create a FileBackedBlockDev struct as a specific implementation. For on-disk layout, I'll use #[repr(C)] and bytemuck or zerocopy for serialization. I'll define a Superblock and an inode struct.
The journaling component includes both on-disk and in-memory structures, like a Journal struct. Finally, I'll structure the filesystem core and its methods, focusing on essential operations while noting that some complexities like directory indexing will need to be simplified or omitted.Designing journal transaction handling
At the transaction (TX) start, I’ll initialize used_blocks to zero and leverage it as I log blocks. Once we commit, I need a mechanism to ensure superblock updates persist for reliable validations. I can encode a magic number and commit flag within log blocks to validate logs without referencing the superblock. This means scanning log areas for TxBegin entries and looking for corresponding commits.
I’ll proceed to zero the entire journal region at the start of a transaction to avoid stray data. The journal operations will involve beginning a transaction, logging blocks, and committing with a structured algorithm that allows room for handling crashes effectively. My recovery design will ensure I capture adequate information, maintaining data integrity while simplifying the header management process.Managing crash scenarios in journaling
I’m laying out how to handle potential crashes during journaling. If a crash happens before the commit header is written, we simply ignore any data blocks, ensuring journaling keeps the FS safe from inconsistencies.
However, if we crash after marking the header as committed but before fully flushing data blocks, there’s a risk of having incomplete data. So, I’ll ensure that the commit record is the last stable piece. This means writing all data blocks first, then updating the header to indicate a complete transaction.
Next, I’ll design recovery protocols to handle various scenarios, ensuring we maintain consistency and avoid anomalies in the file system, simplifying the need for a specific commit flag.Designing the journaling layout
I'm structuring the journal layout for transactions, defining blocks for data and a header block. The header will provide important values like record count and target LBAs. On mount, I’ll read from the journal's end backwards to locate the header, which helps identify the number of data blocks.
When committing, I’ll write the data blocks first, then the header, ensuring it's the last logical action. During recovery, if the header indicates a valid transaction, I'll apply the logs back to the file system. This approach simplifies the management of crashes and ensures data integrity.Implementing minimal filesystem features
I'm planning to create a simplified filesystem with basic metadata. The structure will include an inode table starting block and a limited inode count, allowing for only a small number of files. I’ll focus on a root directory without subdirectories, using a simple HashMap<String, u32> for file path mapping.
The implementation will include functions for creating inodes, writing, and reading inode data. Journaling will be a core part, and each operation will involve logging changes and handling transactions efficiently, ensuring that metadata and data modifications are correctly managed. This keeps the overall design straightforward while still functional.Designing journaling and block allocation
I'm planning to implement a minimal journaling filesystem where, during a commit, we create a header that includes a magic number and record count. For replaying logs, I will check the magic number and ensure the record count is valid.
Next, I'm focusing on block devices, ensuring they support random access while handling data correctly. My filesystem layout will be simple, resembling ext4 without its complexity, and I'll define constants for block sizes, superblock structures, and allocation strategies. The superblock will track essential metadata, including total blocks and free block counts, while block allocation will handle bitmap modifications with journaling to ensure consistency.Planning a minimal journaling filesystem
I'm deciding on how to balance time and quality for the user's request to write an ext4-like filesystem with journaling in Rust. I'll provide a complete code sample for the journaling block layer, but keep the filesystem operations skeletal. I need to set clear expectations that this is a simplified illustrative example, not production-ready.
To structure my code, I'll create a Cargo.toml file without extra dependencies and provide a main.rs that includes essential modules. The design will feature basic block device functions, a superblock structure, and journaling mechanisms. Additionally, I'll simplify inode management with a focus on clarity instead of complete functionality, allowing room for user adaptation. The constants and layout will be systematically defined, ensuring I stay aligned with user expectations while avoiding unnecessary complexity.Designing the filesystem layout
I need to ensure I define both the block bitmap and the inode table properly. I'm establishing constants like BLOCK_BITMAP_BLOCKS and INODE_TABLE_BLOCKS. The layout will consist of various logical block addresses for the superblock, bitmap, and inode table.
For the superblock representation, I'll avoid unsafe transmutations and instead create structured encode/decode functions to prevent undefined behavior. The inode structure will hold necessary information, and I'll implement functions to read and write inodes while managing transactions through a journaling mechanism. It’s important to ensure that all modifications are logged and that the filesystem operates efficiently while balancing complexity with clarity.Integrating journaling and superblock management
I need to prevent duplicates when writing to the same block during a transaction. So, I’ll implement a function to log any updates to the superblock. This will store the superblock’s final version, ensuring it’s done only once per operation to avoid confusion.
When mounting the filesystem, I will ensure that the journal is replayed if needed while calculating the starting location of the journal based on the total blocks. For file operations, I'm defining a block device structure with proper alignment and ensuring all read/write actions are safe and efficient.
The mkfs function will establish the filesystem layout accurately by writing the superblock first and zeroing out necessary structures. At mounting, I’ll confirm the integrity of the superblock and track inodes accurately, while keeping the implementation straightforward yet robust.Designing a file system structure
I'm working on implementing the write_file function, which will restrict file sizes to a maximum of 12 blocks. I’ll allocate new blocks based on data length, ensuring that if there's leftover space in the last block, I fill it with zeros.
Next, the read_file function will fetch data from the blocks without requiring journaling. For journaling, methods will ensure data safety during operations. My FileSystem struct will use Arc for shared access, while the Journal will manage transaction records efficiently. I’ll define synchronizing methods to ensure consistency.Building File System Modules
I'm working on implementing the FileBlockDevice, ensuring it uses Mutex<File> while handling lifetimes correctly.
Firstly, I’ll define utility functions for reading and writing little-endian data types, like read_u32_le and write_u32_le, for use in modules like Superblock and Journal.
Next, I’ll set constants for block sizes and offsets, then create a function to compute the layout based on total blocks, ensuring the structure meets criteria for data allocation.
The Superblock will be implemented to handle reading and writing in designated offsets, verifying integrity through magic numbers.
Finally, I'll develop the Journal's replay mechanism to handle applying transactions safely.Implementing Inode Operations and Filesystem Structure
I’m defining the Inode structure, including fields for mode, link count, size, and direct blocks. I need to add functions to convert the Inode to and from bytes, ensuring proper offsets while keeping the size manageable.
Next, I’ll set up a FileSystem structure, incorporating the device, superblock, journal, and next inode fields. In the open method, I’ll read the superblock from the device and prepare to initialize the filesystem.
I also need to implement the mkfs function for formatting the filesystem and correctly writing the superblock and initial structures. I'll ensure bitmap management is in place while paying attention to the allocation of data blocks and reflecting updates accurately in the log.Finalizing Filesystem Implementation
I need to ensure that the free_block_count doesn't underflow while managing the filesystem. For reading and writing inodes, I’ll set up methods to read from and write to the inode table, confirming that the right blocks are accessed.
In write_file_inner, I'll check the data length restrictions and handle existing blocks carefully. I must log any changes when allocating blocks to maintain consistency. Integrating journal commits will be critical for durability.
I also plan to implement main functionality, ensuring I create or open the disk image correctly and call necessary initialization functions while keeping everything organized and clear.Describing Toy Filesystem Design
This project involves creating a toy ext4-like filesystem with journaling semantics. It's important to note that this is not a fully-functional ext4, as it lacks features like concurrency and crash safety. Additionally, we're omitting several ext4 features, such as block groups and extents. Integrating with the Linux kernel or FUSE would also require more code than we're including here.
Next, I'll outline the main components before presenting the code. This will include FileBlockDevice, layout computations, and necessary constants for structuring the filesystem properly. Implementing something truly “ext4” is a multi-person-year effort, tightly coupled to the Linux VFS and block layer. What I can give you here is:
- A toy, ext4-inspired filesystem implemented in safe Rust
- Backed by a file-as-disk
- With a real write-ahead journal that replays after crashes
- With inodes, a free-block bitmap, and simple files with direct blocks
- No directories, no permissions, no extents, no block groups, etc.
You can extend this into FUSE or a kernel module later; for now it’s a self-contained library + demo.
Below is a single main.rs you can drop into a new cargo project.
Cargo.toml (minimal)
[package]
name = "toy_ext4_journal"
version = "0.1.0"
edition = "2021"
[dependencies]
src/main.rs
use std::{
fs::{File, OpenOptions},
io::{self, Read, Seek, SeekFrom, Write},
path::Path,
sync::{Arc, Mutex},
};
// ===================== Constants & basic helpers =====================
const BLOCK_SIZE: usize = 4096;
const SUPERBLOCK_LBA: u64 = 1;
const BLOCK_BITMAP_LBA: u64 = 2;
const BLOCK_BITMAP_BLOCKS: u64 = 1;
const INODE_TABLE_LBA: u64 = BLOCK_BITMAP_LBA + BLOCK_BITMAP_BLOCKS; // 3
const INODE_TABLE_BLOCKS: u64 = 32;
const INODE_SIZE: usize = 128;
const JOURNAL_BLOCKS: u64 = 1024;
const SUPERBLOCK_MAGIC: u32 = 0x4558_5434; // "EXT4"
const JOURNAL_MAGIC: u32 = 0x4a4e_4c31; // "JNL1"
const MIN_BLOCKS: u64 = INODE_TABLE_LBA + INODE_TABLE_BLOCKS + 1 + JOURNAL_BLOCKS;
fn read_u16_le(buf: &[u8], off: usize) -> u16 {
let mut b = [0u8; 2];
b.copy_from_slice(&buf[off..off + 2]);
u16::from_le_bytes(b)
}
fn read_u32_le(buf: &[u8], off: usize) -> u32 {
let mut b = [0u8; 4];
b.copy_from_slice(&buf[off..off + 4]);
u32::from_le_bytes(b)
}
fn read_u64_le(buf: &[u8], off: usize) -> u64 {
let mut b = [0u8; 8];
b.copy_from_slice(&buf[off..off + 8]);
u64::from_le_bytes(b)
}
fn write_u16_le(buf: &mut [u8], off: usize, v: u16) {
buf[off..off + 2].copy_from_slice(&v.to_le_bytes());
}
fn write_u32_le(buf: &mut [u8], off: usize, v: u32) {
buf[off..off + 4].copy_from_slice(&v.to_le_bytes());
}
fn write_u64_le(buf: &mut [u8], off: usize, v: u64) {
buf[off..off + 8].copy_from_slice(&v.to_le_bytes());
}
// ===================== Block device abstraction =====================
struct FileBlockDevice {
file: Mutex<File>,
block_size: usize,
total_blocks: u64,
}
impl FileBlockDevice {
fn create(path: &Path, size_bytes: u64) -> io::Result<Self> {
if size_bytes % BLOCK_SIZE as u64 != 0 {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"size_bytes must be multiple of BLOCK_SIZE",
));
}
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(true)
.open(path)?;
file.set_len(size_bytes)?;
Ok(Self::from_file(file, size_bytes))
}
fn open(path: &Path) -> io::Result<Self> {
let file = OpenOptions::new().read(true).write(true).open(path)?;
let size_bytes = file.metadata()?.len();
if size_bytes % BLOCK_SIZE as u64 != 0 {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"backing file size not a multiple of BLOCK_SIZE",
));
}
Ok(Self::from_file(file, size_bytes))
}
fn from_file(file: File, size_bytes: u64) -> Self {
let total_blocks = size_bytes / BLOCK_SIZE as u64;
Self {
file: Mutex::new(file),
block_size: BLOCK_SIZE,
total_blocks,
}
}
fn total_blocks(&self) -> u64 {
self.total_blocks
}
fn read_block(&self, lba: u64, buf: &mut [u8]) -> io::Result<()> {
if buf.len() != self.block_size {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"buffer size != block_size",
));
}
if lba >= self.total_blocks {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"LBA out of range",
));
}
let mut f = self.file.lock().unwrap();
f.seek(SeekFrom::Start(lba * self.block_size as u64))?;
f.read_exact(buf)?;
Ok(())
}
fn write_block(&self, lba: u64, buf: &[u8]) -> io::Result<()> {
if buf.len() != self.block_size {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"buffer size != block_size",
));
}
if lba >= self.total_blocks {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"LBA out of range",
));
}
let mut f = self.file.lock().unwrap();
f.seek(SeekFrom::Start(lba * self.block_size as u64))?;
f.write_all(buf)?;
Ok(())
}
fn sync(&self) -> io::Result<()> {
let f = self.file.lock().unwrap();
f.sync_all()
}
}
// ===================== On-disk layout helper =====================
#[derive(Debug, Clone, Copy)]
struct Layout {
inode_table_start: u64,
data_start: u64,
data_blocks: u64,
journal_start: u64,
journal_blocks: u64,
}
fn compute_layout(total_blocks: u64) -> io::Result<Layout> {
if total_blocks < MIN_BLOCKS {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"device too small for toy filesystem",
));
}
let inode_table_start = INODE_TABLE_LBA;
let data_start = INODE_TABLE_LBA + INODE_TABLE_BLOCKS;
let journal_start = total_blocks - JOURNAL_BLOCKS;
let data_blocks = journal_start - data_start;
if data_blocks == 0 {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"no space for data blocks",
));
}
let max_data_blocks = (BLOCK_SIZE as u64) * 8; // 1 bitmap block
if data_blocks > max_data_blocks {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"filesystem too large for single block bitmap",
));
}
Ok(Layout {
inode_table_start,
data_start,
data_blocks,
journal_start,
journal_blocks: JOURNAL_BLOCKS,
})
}
// ===================== Superblock =====================
#[derive(Debug, Clone)]
struct Superblock {
magic: u32,
block_size: u32,
total_blocks: u64,
inode_count: u32,
free_block_count: u32,
inode_table_start: u64,
data_start: u64,
data_block_count: u64,
journal_start: u64,
journal_block_count: u64,
}
impl Superblock {
fn new(total_blocks: u64, layout: Layout) -> Self {
let inode_count = (INODE_TABLE_BLOCKS * BLOCK_SIZE as u64 / INODE_SIZE as u64) as u32;
Self {
magic: SUPERBLOCK_MAGIC,
block_size: BLOCK_SIZE as u32,
total_blocks,
inode_count,
free_block_count: layout.data_blocks as u32,
inode_table_start: layout.inode_table_start,
data_start: layout.data_start,
data_block_count: layout.data_blocks,
journal_start: layout.journal_start,
journal_block_count: layout.journal_blocks,
}
}
fn to_bytes(&self) -> [u8; BLOCK_SIZE] {
let mut buf = [0u8; BLOCK_SIZE];
write_u32_le(&mut buf, 0, self.magic);
write_u32_le(&mut buf, 4, self.block_size);
write_u64_le(&mut buf, 8, self.total_blocks);
write_u32_le(&mut buf, 16, self.inode_count);
write_u32_le(&mut buf, 20, self.free_block_count);
write_u64_le(&mut buf, 24, self.inode_table_start);
write_u64_le(&mut buf, 32, self.data_start);
write_u64_le(&mut buf, 40, self.data_block_count);
write_u64_le(&mut buf, 48, self.journal_start);
write_u64_le(&mut buf, 56, self.journal_block_count);
buf
}
fn from_bytes(buf: &[u8]) -> io::Result<Self> {
let magic = read_u32_le(buf, 0);
if magic != SUPERBLOCK_MAGIC {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"bad superblock magic",
));
}
let block_size = read_u32_le(buf, 4);
if block_size as usize != BLOCK_SIZE {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"block_size mismatch",
));
}
Ok(Self {
magic,
block_size,
total_blocks: read_u64_le(buf, 8),
inode_count: read_u32_le(buf, 16),
free_block_count: read_u32_le(buf, 20),
inode_table_start: read_u64_le(buf, 24),
data_start: read_u64_le(buf, 32),
data_block_count: read_u64_le(buf, 40),
journal_start: read_u64_le(buf, 48),
journal_block_count: read_u64_le(buf, 56),
})
}
}
// ===================== Journal (very simplified) =====================
#[derive(Debug, Clone)]
struct PendingBlock {
lba: u64,
data: Vec<u8>,
}
impl PendingBlock {
fn new(lba: u64, data: Vec<u8>) -> Self {
Self { lba, data }
}
}
/// Very simple journal: supports one transaction at a time.
/// Layout in journal region:
/// block 0: header [magic, count, reserved, array of target LBAs]
/// blocks 1..count: raw block images
struct Journal {
dev: Arc<FileBlockDevice>,
start_lba: u64,
block_count: u64,
block_size: usize,
}
impl Journal {
fn new(dev: Arc<FileBlockDevice>, start_lba: u64, block_count: u64) -> Self {
Self {
dev,
start_lba,
block_count,
block_size: BLOCK_SIZE,
}
}
fn max_records(&self) -> usize {
// header: magic (4) + count (4) + reserved(8) = 16 bytes
(self.block_size - 16) / 8
}
fn replay_if_needed(&self) -> io::Result<()> {
let mut hdr = vec![0u8; self.block_size];
self.dev.read_block(self.start_lba, &mut hdr)?;
let magic = read_u32_le(&hdr, 0);
if magic != JOURNAL_MAGIC {
// No committed transaction
return Ok(());
}
let count = read_u32_le(&hdr, 4) as usize;
if count == 0 {
return Ok(());
}
if count > self.max_records() || (count as u64) + 1 > self.block_count {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"journal header corrupted",
));
}
let mut buf = vec![0u8; self.block_size];
for i in 0..count {
let target_lba = read_u64_le(&hdr, 16 + i * 8);
let journal_lba = self.start_lba + 1 + i as u64;
self.dev.read_block(journal_lba, &mut buf)?;
self.dev.write_block(target_lba, &buf)?;
}
self.dev.sync()?;
// Clear header to mark journal empty
let zero = vec![0u8; self.block_size];
self.dev.write_block(self.start_lba, &zero)?;
self.dev.sync()?;
Ok(())
}
fn commit(&self, records: &[PendingBlock]) -> io::Result<()> {
if records.is_empty() {
return Ok(());
}
if records.len() > self.max_records() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"too many blocks in one transaction",
));
}
if records.len() as u64 + 1 > self.block_count {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"journal region too small for transaction",
));
}
// 1) Write journal data blocks
for (i, rec) in records.iter().enumerate() {
if rec.data.len() != self.block_size {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"record block size mismatch",
));
}
let j_lba = self.start_lba + 1 + i as u64;
self.dev.write_block(j_lba, &rec.data)?;
}
self.dev.sync()?;
// 2) Write header (commit record)
let mut hdr = vec![0u8; self.block_size];
write_u32_le(&mut hdr, 0, JOURNAL_MAGIC);
write_u32_le(&mut hdr, 4, records.len() as u32);
// bytes 8..16 reserved
for (i, rec) in records.iter().enumerate() {
write_u64_le(&mut hdr, 16 + i * 8, rec.lba);
}
self.dev.write_block(self.start_lba, &hdr)?;
self.dev.sync()?;
// 3) Apply to main filesystem
for rec in records {
self.dev.write_block(rec.lba, &rec.data)?;
}
self.dev.sync()?;
// 4) Clear header (journal now empty)
let zero = vec![0u8; self.block_size];
self.dev.write_block(self.start_lba, &zero)?;
self.dev.sync()?;
Ok(())
}
}
// ===================== Inodes =====================
#[derive(Debug, Clone)]
struct Inode {
mode: u16,
links_count: u16,
size: u64,
direct_blocks: [u64; 12],
}
impl Inode {
const MODE_FILE: u16 = 0x8000;
fn empty_file() -> Self {
Self {
mode: Self::MODE_FILE,
links_count: 0,
size: 0,
direct_blocks: [0; 12],
}
}
fn to_bytes(&self) -> [u8; INODE_SIZE] {
let mut buf = [0u8; INODE_SIZE];
write_u16_le(&mut buf, 0, self.mode);
write_u16_le(&mut buf, 2, self.links_count);
write_u64_le(&mut buf, 8, self.size);
for (i, blk) in self.direct_blocks.iter().enumerate() {
write_u64_le(&mut buf, 16 + i * 8, *blk);
}
buf
}
fn from_bytes(buf: &[u8]) -> Self {
let mode = read_u16_le(buf, 0);
let links = read_u16_le(buf, 2);
let size = read_u64_le(buf, 8);
let mut direct_blocks = [0u64; 12];
for i in 0..12 {
direct_blocks[i] = read_u64_le(buf, 16 + i * 8);
}
Self {
mode,
links_count: links,
size,
direct_blocks,
}
}
}
// ===================== Filesystem core =====================
struct FileSystem {
dev: Arc<FileBlockDevice>,
superblock: Superblock,
journal: Journal,
next_inode: u32, // very naive inode allocator
}
impl FileSystem {
fn mkfs(dev: &Arc<FileBlockDevice>) -> io::Result<()> {
let total_blocks = dev.total_blocks();
let layout = compute_layout(total_blocks)?;
let sb = Superblock::new(total_blocks, layout);
// Write superblock
let sb_bytes = sb.to_bytes();
dev.write_block(SUPERBLOCK_LBA, &sb_bytes)?;
// Zero block bitmap
let zero = vec![0u8; BLOCK_SIZE];
for i in 0..BLOCK_BITMAP_BLOCKS {
dev.write_block(BLOCK_BITMAP_LBA + i, &zero)?;
}
// Zero inode table
for i in 0..INODE_TABLE_BLOCKS {
dev.write_block(layout.inode_table_start + i, &zero)?;
}
// Zero data region and journal header (optional: data region lazily zeroed)
// Here we only ensure journal is cleared:
for i in 0..layout.journal_blocks {
dev.write_block(layout.journal_start + i, &zero)?;
}
dev.sync()?;
Ok(())
}
fn open(dev: Arc<FileBlockDevice>) -> io::Result<Self> {
let total_blocks = dev.total_blocks();
let layout = compute_layout(total_blocks)?;
let journal = Journal::new(dev.clone(), layout.journal_start, layout.journal_blocks);
// Replay any committed-but-uncheckpointed transaction
journal.replay_if_needed()?;
// Now load superblock
let mut sb_buf = vec![0u8; BLOCK_SIZE];
dev.read_block(SUPERBLOCK_LBA, &mut sb_buf)?;
let sb = Superblock::from_bytes(&sb_buf)?;
Ok(Self {
dev,
superblock: sb,
journal,
next_inode: 1,
})
}
fn transaction<F, T>(&mut self, f: F) -> io::Result<T>
where
F: FnOnce(&mut FileSystem, &mut Vec<PendingBlock>) -> io::Result<T>,
{
let mut records = Vec::new();
let result = f(self, &mut records)?;
self.journal.commit(&records)?;
Ok(result)
}
fn log_superblock(&self, log: &mut Vec<PendingBlock>) {
let sb_bytes = self.superblock.to_bytes();
log.push(PendingBlock::new(SUPERBLOCK_LBA, sb_bytes.to_vec()));
}
fn alloc_data_block(&mut self, log: &mut Vec<PendingBlock>) -> io::Result<u64> {
if self.superblock.free_block_count == 0 {
return Err(io::Error::new(
io::ErrorKind::Other,
"out of data blocks",
));
}
let mut bm = vec![0u8; BLOCK_SIZE];
self.dev.read_block(BLOCK_BITMAP_LBA, &mut bm)?;
let mut found_index: Option<u64> = None;
for i in 0..self.superblock.data_block_count {
let byte_index = (i / 8) as usize;
let bit_mask = 1u8 << (i % 8);
if (bm[byte_index] & bit_mask) == 0 {
bm[byte_index] |= bit_mask;
found_index = Some(i);
break;
}
}
let idx = found_index.ok_or_else(|| {
io::Error::new(io::ErrorKind::Other, "bitmap full but free_block_count > 0")
})?;
let lba = self.superblock.data_start + idx;
// Log updated bitmap
log.push(PendingBlock::new(BLOCK_BITMAP_LBA, bm));
// Update and log superblock
self.superblock.free_block_count -= 1;
self.log_superblock(log);
Ok(lba)
}
fn read_inode(&self, ino: u32) -> io::Result<Inode> {
if ino == 0 || ino as u64 > self.superblock.inode_count as u64 {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "bad inode number"));
}
let index = (ino - 1) as usize;
let inodes_per_block = BLOCK_SIZE / INODE_SIZE;
let block_index = index / inodes_per_block;
let offset = (index % inodes_per_block) * INODE_SIZE;
let inode_lba = self.superblock.inode_table_start + block_index as u64;
let mut buf = vec![0u8; BLOCK_SIZE];
self.dev.read_block(inode_lba, &mut buf)?;
let inode_bytes = &buf[offset..offset + INODE_SIZE];
Ok(Inode::from_bytes(inode_bytes))
}
fn write_inode(
&self,
ino: u32,
inode: &Inode,
log: &mut Vec<PendingBlock>,
) -> io::Result<()> {
if ino == 0 || ino as u64 > self.superblock.inode_count as u64 {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "bad inode number"));
}
let index = (ino - 1) as usize;
let inodes_per_block = BLOCK_SIZE / INODE_SIZE;
let block_index = index / inodes_per_block;
let offset = (index % inodes_per_block) * INODE_SIZE;
let inode_lba = self.superblock.inode_table_start + block_index as u64;
let mut buf = vec![0u8; BLOCK_SIZE];
self.dev.read_block(inode_lba, &mut buf)?;
let raw = inode.to_bytes();
buf[offset..offset + INODE_SIZE].copy_from_slice(&raw);
log.push(PendingBlock::new(inode_lba, buf));
Ok(())
}
fn create_inode(&mut self, log: &mut Vec<PendingBlock>) -> io::Result<u32> {
if self.next_inode as u64 > self.superblock.inode_count as u64 {
return Err(io::Error::new(
io::ErrorKind::Other,
"out of inodes (naive allocator)",
));
}
let ino = self.next_inode;
self.next_inode += 1;
let mut inode = Inode::empty_file();
inode.links_count = 1;
self.write_inode(ino, &inode, log)?;
Ok(ino)
}
fn write_file_inner(
&mut self,
ino: u32,
data: &[u8],
log: &mut Vec<PendingBlock>,
) -> io::Result<()> {
let mut inode = self.read_inode(ino)?;
let max_blocks = inode.direct_blocks.len();
let needed_blocks = (data.len() + BLOCK_SIZE - 1) / BLOCK_SIZE;
if needed_blocks > max_blocks {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"file too large for direct blocks",
));
}
let mut remaining = data.len();
let mut offset = 0;
for i in 0..needed_blocks {
let lba = if inode.direct_blocks[i] == 0 {
let new_lba = self.alloc_data_block(log)?;
inode.direct_blocks[i] = new_lba;
new_lba
} else {
inode.direct_blocks[i]
};
let mut buf = vec![0u8; BLOCK_SIZE];
let to_copy = remaining.min(BLOCK_SIZE);
buf[..to_copy].copy_from_slice(&data[offset..offset + to_copy]);
// rest is zero
log.push(PendingBlock::new(lba, buf));
remaining -= to_copy;
offset += to_copy;
}
inode.size = data.len() as u64;
if inode.links_count == 0 {
inode.links_count = 1;
}
self.write_inode(ino, &inode, log)?;
Ok(())
}
fn read_file(&self, ino: u32) -> io::Result<Vec<u8>> {
let inode = self.read_inode(ino)?;
let mut buf = Vec::with_capacity(inode.size as usize);
let mut remaining = inode.size as usize;
for &lba in &inode.direct_blocks {
if remaining == 0 {
break;
}
if lba == 0 {
break;
}
let mut blk = vec![0u8; BLOCK_SIZE];
self.dev.read_block(lba, &mut blk)?;
let to_copy = remaining.min(BLOCK_SIZE);
buf.extend_from_slice(&blk[..to_copy]);
remaining -= to_copy;
}
buf.truncate(inode.size as usize);
Ok(buf)
}
}
// ===================== Demo main =====================
fn main() -> io::Result<()> {
let path = Path::new("disk.img");
let size_bytes = 16 * 1024 * 1024; // 16 MiB
let dev = if path.exists() {
Arc::new(FileBlockDevice::open(path)?)
} else {
let dev = Arc::new(FileBlockDevice::create(path, size_bytes)?);
FileSystem::mkfs(&dev)?;
dev
};
let mut fs = FileSystem::open(dev.clone())?;
// Create a file and write some data in a single transaction
let ino = fs.transaction(|fs, log| {
let ino = fs.create_inode(log)?;
fs.write_file_inner(ino, b"Hello from a toy ext4-like journaled FS\n", log)?;
Ok(ino)
})?;
// Read it back (no journaling needed for reads)
let data = fs.read_file(ino)?;
print!("{}", String::from_utf8_lossy(&data));
Ok(())
}
What this gives you
- A file-backed block device (
FileBlockDevice)
- A fixed on-disk layout:
- Block 0: unused
- Block 1: superblock
- Block 2: 1 block bitmap (for data blocks)
- Blocks 3–34: inode table (1024 inodes at 128 bytes each)
- Blocks 35..(N - 1025): data blocks
- Last 1024 blocks: journal region
- A write-ahead journal:
- For each transaction, it writes:
- All new block images into the journal area
- A header block with magic, count, and target LBAs
- Then applies those blocks to the main filesystem
- Then clears the header
- On mount, if the header is present, it replays the recorded blocks and clears the header.
- A miniature inode-based filesystem:
- Fixed-size inodes, with 12 direct block pointers
- Single global bitmap for data blocks
- You can create inodes and write/read file contents by inode number
Notably missing (by design)
- Directories, filenames, links
- Permissions, timestamps, ownership
- Extents, block groups, resizing, journaling modes, checksums, barriers, etc.
- Any integration with Linux VFS or FUSE
This is intentionally stripped down so that the journaling logic and ext4-like on-disk structures are clear and hackable. You can:
- Add a directory inode (e.g. inode 1 as root) storing
{name, ino} pairs.
- Wrap this in a FUSE filesystem (using
fuse3 or fuser crates).
- Extend journaling to support multiple transactions, ring buffer, checksums, etc.
If you want, I can next:
- Add a minimal directory layer on top (supporting
/foo names), or
- Show how to map this onto a FUSE interface so you can
mount it and use it from the shell.