The user is asking for a C file system that supports journaling and crash recovery, but I think they might want a simplified educational example—a "toy" implementation, perhaps as a file-backed block device. I need to ensure I scope it appropriately since they didn’t specify the environment or space. I’ll provide a concise code example while keeping my explanations modest. It seems like I should clarify constraints, but I'll infer what they might be asking for.Designing a minimal filesystem
I'm thinking about how to design a simplified filesystem with structures like Superblock, Inode, DirectoryEntry, JournalHeader, and JournalEntry. For the implementation, I’ll need functions to initialize the filesystem image, mount, unmount, create, write, and read files, along with a journaling system for both metadata and data. Since I can’t create a complete filesystem within the time constraints, I'll aim for a minimal, compilable code example. The journaling mechanism includes a write-ahead log for transactions that starts with a BEGIN record, followed by UPDATE records, and ends with a COMMIT record.Implementing journal replay and recovery
I’m planning the journal replay process for mounting the filesystem. I’ll scan the journal and track transactions, doing writes for those with a COMMIT and ignoring others. To keep things simple, I might use a static journal region of fixed size. The user wants a crash recovery demonstration, so I need to ensure flush writes with fsync for proper ordering, though I won't implement that directly. Instead, I’ll provide a single C file that defines constants, implements types like SuperBlock and Inode, and uses a simple single-level directory without permissions. The "disk" will be represented as an array of bytes in memory, which may also be saved to a file.Designing a simplified in-memory filesystem
I’m thinking it might be easier to present a single C program that initializes an in-memory "disk" and demonstrates journaling, though it won't persist across runs. However, for meaningful crash recovery, I'll need to implement reading and writing to a backing file so the log can persist. I’ll design the disk layout, starting with a Superblock, followed by a journal region, and then the inode table and data blocks.
I can simplify this to one root directory containing up to N files, where directory entries map filenames to inode indices. I’ll also include journaling for both data and metadata. The user wants a filesystem written in C, so I'll provide a short introduction and code with comments to clarify things.Designing journal and structure for filesystem
I’m considering how to present a simplified user-space filesystem with journaling and crash recovery in C. We’ll define some key parameters, like BLOCK_SIZE and MAX_BLOCKS. The disk image should be treated as "fs.img" based on the size of these blocks. The journal will have its entries allocated to fit one block each, containing a header with various details.
I need to decide how to structure the JournalRecord, taking care that the size makes sense without conflicting with the block size. It might be simpler to treat it as a record-based structure rather than forcing alignment with disk blocks. The journaling will focus on logging metadata operations rather than complete data blocks. For clarity, I might define the journal region size and allocate slots for journal records sequentially, allowing us to handle essential operations like creating files or updating metadata efficiently.Outlining metadata journaling design
I’m planning to create a metadata journaling system for a filesystem, where only metadata updates go through journaling. This means file content writes won’t be journaled, which keeps things simpler. Journal entries will log necessary writes with a defined structure.
I’ll set up core functions for operations like opening the disk, formatting the filesystem, starting journal transactions, logging writes, and committing those transactions. The superblock and data structures will include details like offsets and counts, ensuring an organized layout that fits within a predetermined file size. I aim to clarify the relationship between the inodes, directory entries, and the journaling process. Simplification will be key for usability and understanding.Implementing simple journaling and recovery
In the superblock, I'll track offsets and counts for dynamic data usage. At the formatting stage, I’ll ensure the superblock is properly initialized, while clearing out bitmaps and journal. The fs_recover() function will read the superblock and journal entries, helping to manage transaction status.
I’ll adopt a straightforward journaling logic that documents metadata updates without relying on immediate disk writes. I'll implement transactional logging with operations documented until committed. In case of a crash, recovery will focus on reapplying committed changes while ignoring incomplete operations, ensuring a basic level of consistency in the filesystem. This will keep the design intuitive, focusing on simplicity over full ACID compliance.Managing journaling and recovery processes
I need to log records before applying data to the main disk and ensure the commit record is written before we call fsync. In the event of a crash after a commit but before applying changes, recovery will allow these changes to take effect. I’ll manage 'updated ranges per transaction' by keeping track of modifications in memory.
To streamline this, I’ll keep a global static cache of the filesystem's metadata, reading it into memory on mount or recovery. For each operation, modifications will be tracked until a commit is called, ensuring the integrity of the data during recovery. I must also ensure that we do not begin applying data writes until the commit record is confirmed on disk.Improving redo logging algorithm
I’m thinking about a better algorithm for redo logging. The first step is to create log records for each modification and append them to the journal, which right now only exists in the OS cache. After that, I’ll append a COMMIT record and flush the journal to disk to ensure it’s durable.
If a crash happens before flushing completes, we analyze the state during recovery as uncommitted changes. If the crash occurs after the journal is flushed but before the actual data is applied, I’ll retry all modifications to maintain consistency. This approach should help manage where to resume after recovery and avoid reusing invalid journal entries.Developing journal management
I’m thinking about how to manage journal records for a file system. While I could run into older entries beyond overwritten ones, I can ensure that scanning stops at the first invalid record. When the log gets full, I won't be able to commit more.
During recovery, I’ll scan the journal and map transaction IDs to their modifications. A two-pass approach seems beneficial: the first pass identifies committed transactions, and the second applies data records. I’ll also consider managing modifications directly within FS functions to streamline the process.Designing journaling API
I'm working on designing a journaling API for a file system. I’ve set up a structure to manage transactions, including an ID and range for modifications. The tx_begin function initiates a transaction, and the tx_add_range function records changes.
While handling data logging, I must ensure that I capture current values during commits without risking aliasing. The proposed method allows for snapshots of data, avoiding copying. I’m planning to keep it simple with static sizes for data structures, ensuring sufficient overall filesystem size for both metadata and journaling needs.Setting up the filesystem
I’m creating a disk image for the filesystem, ensuring that its size meets the total size requirement and planning a 4MB journal region. I've defined parameters for the number of journal records, ensuring they fit within the overall size of the filesystem.
As I prepare to format the filesystem, I’m calculating various offsets for structures like the superblock and bitmaps. I’m also making sure to initialize everything properly and set the necessary fields in the superblock, ensuring everything aligns correctly in memory during operations. Using utility functions, I’ll also implement inode and block allocation while maintaining journaling.Implementing filesystem operations
I need to set up the fs_create function to create files. I'll start a transaction and check that the file length doesn’t exceed the block size, as my system only supports single-block files. If a file with the same name exists in the root directory, I'll return an error.
Next, I’ll find a free directory entry, allocate an inode and a block, and write the provided data to the disk. The journaling aspect is important, as I’ll log modifications to both the file data and directory entries.
For reading files, I’ll ensure pread retrieves the right data using offsets. Implementing crash recovery is also key, simulating crashes and allowing re-run for recovery. I'll sketch out the main program to demonstrate these features and ensure consistency while interacting with the disk.Designing journaling features
I'm setting JOURNAL_RECORD_COUNT to 4096, allowing for about 2048 transactions maximum since each transaction uses at least 2-3 records. I'll define MAX_TXIDS as 4096 to keep track of committed transactions. The first step in recovery involves reading journal records. If a record doesn't match expected magic numbers or types, I’ll break out.
During recovery, I’ll ensure I only apply committed transactions while avoiding duplicates. Optional journal clearing might be considered, but it can lead to unnecessary repetition of operations, so it may be unnecessary.
To maintain recovery consistency, the design includes utilizing either applied logs for the last known state or, alternatively, applying all committed transactions from the log during recovery. This approach allows for the accurate reconstruction of the filesystem's latest state without needing to clear previous logs. This method should keep everything in sync as long as I manage the logs carefully.Implementing journaling features
I don’t need a persistent superblock.journal_head since I can compute the next head by finding the first invalid record. On commit, I just require the head pointer, and I can set journal_next_index from there after scanning. I’ll maintain a global journal_next_index, starting at 0.
For transaction commitments, I must ensure I don’t exceed the journal record capacity. If not enough space exists, I’ll return an error. I'll structure transactions to use defined ranges, ensuring smooth reading and writing while keeping features minimal for demonstration.Designing journaling system
It's clear that we typically don't change much. So, I'll allocate and load the metadata arrays while ensuring next_txid is assigned uniquely from the highest ID logged. This prevents confusion in recovery due to duplicate transaction IDs.
In fs_recover, I’ll parse journal records to compute necessary details like committed_txid, highest_txid, and max_idx, and apply modifications in the correct sequence. I must also emphasize ensuring the journal's integrity while writing records, particularly focusing on the magic field to identify valid records accurately.
Now I’ll prepare to summarize the design and present the code.Implementing tinyfs structure
I'm developing a minimal journaling filesystem demo in user space, focusing on features like a single flat directory and journaling capabilities for crash recovery.
First, I'll define the on-disk structure, including a Superblock with essential metadata. Using malloc, I'll allocate space for various elements like the inode bitmap, data blocks, and journal records. Error handling functions will also be set up for robustness.
Next, I'll implement functions for formatting the filesystem and initializing from disk, ensuring that recovery processes efficiently manage transactions while maintaining data integrity.Developing fs_load and journaling functions
I'm moving on to implementing the fs_load_metadata function, which will allocate memory for the inode bitmap and read it from the disk. I also need to ensure I handle different bits of metadata effectively while managing dynamic memory.
Next, I’ll set up my journaling structure. I'll define important global constants and functions related to transactions, like fs_alloc_block for allocating blocks. Additionally, I’ll include a function for finding directory entries.
Now, I’ll write some C code with minimal explanations but ample comments, ensuring that everything is clear without unnecessary mistakes. Let's begin crafting this final message, focusing on providing the complete code. Below is a self‑contained, minimal journaling filesystem implemented in C as a user‑space program using a file as the “disk” image.
It is not production‑quality, but it demonstrates:
A concrete on‑disk layout with superblock, bitmaps, inodes, directory entries, data blocks, and a journal region.
Write‑ahead redo logging for metadata and data.
Crash recovery by replaying committed transactions from the journal.
Features/limitations:
Flat namespace: only a single root directory (no subdirectories).
Each file stores up to one 4 KiB block.
Simple redo log journaling (no rollbacks, no checksums).
Journal stored inside the same image file.
No permissions, timestamps, etc.
Compile:
sh
cc -Wall -O2 -o tinyfs tinyfs.c
Usage:
sh
# Create and format a new filesystem image
./tinyfs img.fs format
# Create a file "foo" with contents "hello world"
./tinyfs img.fs create foo "hello world"
# List all files
./tinyfs img.fs ls
# Read file
./tinyfs img.fs read foo
# Explicit crash recovery (normally done automatically at mount)
./tinyfs img.fs recover
c
This is a compact but complete starting point. If you want, I can:
Extend it to support multi-block files and a free block bitmap with bit‑level packing.
Add delete/overwrite operations with journaling.
Integrate with FUSE so it can be mounted as a real filesystem on Linux.
/*
* tinyfs.c - Minimal journaling filesystem demo in user space.
*
* Build:
* cc -Wall -O2 -o tinyfs tinyfs.c
*
* Usage:
* ./tinyfs img.fs format
* ./tinyfs img.fs create <name> "<data>"
* ./tinyfs img.fs read <name>
* ./tinyfs img.fs ls
* ./tinyfs img.fs recover
*
* This is an educational example only.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
/* Basic filesystem layout parameters */
#define FS_TOTAL_SIZE (16ULL * 1024 * 1024) /* 16 MiB image */
#define FS_MAGIC 0x544E5946U /* "TNYF" */
#define FS_VERSION 1
#define BLOCK_SIZE 4096 /* 4 KiB blocks */
#define INODE_COUNT 128
#define DATA_BLOCK_COUNT 1024 /* 1024 * 4KiB = 4 MiB data */
#define ROOT_DIR_ENTRIES 128
/* Journal */
#define JOURNAL_RECORD_SIZE 256
#define JOURNAL_RECORD_COUNT 4096 /* 4096 * 256 = 1 MiB journal */
#define JOURNAL_MAGIC 0x4A524E4CU /* "JRNL" */
#define JRNL_MAX_PAYLOAD 224 /* fits inside 256-byte record */
#define FS_MAX_NAME 64
/* ---- On-disk structures ---- */
#pragma pack(push, 1)
typedef struct {
uint32_t magic;
uint32_t version;
uint32_t block_size;
uint32_t inode_count;
uint32_t data_block_count;
uint32_t root_dir_entries;
uint64_t fs_size;
uint64_t free_inode_bitmap_offset;
uint64_t free_block_bitmap_offset;
uint64_t inode_table_offset;
uint64_t root_dir_offset;
uint64_t journal_offset;
uint32_t journal_record_count;
uint64_t data_region_offset;
} Superblock;
typedef struct {
uint32_t used; /* 0 = free, 1 = used */
uint32_t size; /* bytes of file data */
uint32_t direct_block; /* index into data blocks (0..DATA_BLOCK_COUNT-1), or 0xFFFFFFFF for none */
} Inode;
typedef struct {
uint32_t used; /* 0 = free, 1 = used */
uint32_t inode_index; /* index in inode table */
char name[FS_MAX_NAME];
} DirEntry;
typedef enum {
JRNL_TYPE_DATA = 1,
JRNL_TYPE_COMMIT = 2
} JournalType;
typedef struct {
uint32_t magic; /* JOURNAL_MAGIC */
uint32_t type; /* JournalType */
uint32_t txid; /* transaction id */
uint32_t payload_size; /* bytes used in payload for DATA; 0 for COMMIT */
uint64_t disk_offset; /* where DATA applies in the image; 0 for COMMIT */
uint8_t payload[JRNL_MAX_PAYLOAD];
uint8_t _pad[8]; /* pad to 256 bytes total */
} JournalRecord;
#pragma pack(pop)
/* ---- In-memory FS state ---- */
typedef struct {
int fd;
Superblock sb;
uint8_t *inode_bitmap;
uint8_t *block_bitmap;
Inode *inode_table;
DirEntry *root_dir;
uint32_t next_txid; /* next transaction id to allocate */
uint32_t journal_next_index; /* index of next free journal record */
} Fs;
/* ---- Utilities ---- */
static void die(const char *msg)
{
perror(msg);
exit(EXIT_FAILURE);
}
static void die_msg(const char *msg)
{
fprintf(stderr, "Fatal: %s\n", msg);
exit(EXIT_FAILURE);
}
/* Safe pread/pwrite wrappers */
static void read_exact(int fd, void *buf, size_t len, off_t off)
{
uint8_t *p = buf;
size_t left = len;
while (left > 0) {
ssize_t r = pread(fd, p, left, off);
if (r < 0) die("pread");
if (r == 0) die_msg("short read");
left -= (size_t)r;
p += r;
off += r;
}
}
static void write_exact(int fd, const void *buf, size_t len, off_t off)
{
const uint8_t *p = buf;
size_t left = len;
while (left > 0) {
ssize_t w = pwrite(fd, p, left, off);
if (w < 0) die("pwrite");
if (w == 0) die_msg("short write");
left -= (size_t)w;
p += w;
off += w;
}
}
/* ---- Filesystem formatting ---- */
static void fs_format(const char *path)
{
int fd = open(path, O_CREAT | O_TRUNC | O_RDWR, 0644);
if (fd < 0) die("open format");
if (ftruncate(fd, FS_TOTAL_SIZE) != 0)
die("ftruncate");
Superblock sb;
memset(&sb, 0, sizeof(sb));
sb.magic = FS_MAGIC;
sb.version = FS_VERSION;
sb.block_size = BLOCK_SIZE;
sb.inode_count = INODE_COUNT;
sb.data_block_count = DATA_BLOCK_COUNT;
sb.root_dir_entries = ROOT_DIR_ENTRIES;
sb.fs_size = FS_TOTAL_SIZE;
uint64_t offset = sizeof(Superblock);
sb.free_inode_bitmap_offset = offset;
offset += sb.inode_count; /* 1 byte per inode */
sb.free_block_bitmap_offset = offset;
offset += sb.data_block_count; /* 1 byte per block */
sb.inode_table_offset = offset;
offset += sb.inode_count * sizeof(Inode);
sb.root_dir_offset = offset;
offset += sb.root_dir_entries * sizeof(DirEntry);
sb.journal_offset = offset;
sb.journal_record_count = JOURNAL_RECORD_COUNT;
offset += (uint64_t)JOURNAL_RECORD_COUNT * JOURNAL_RECORD_SIZE;
/* Align data region to block size */
if (offset % BLOCK_SIZE != 0)
offset += BLOCK_SIZE - (offset % BLOCK_SIZE);
sb.data_region_offset = offset;
uint64_t data_end = sb.data_region_offset +
(uint64_t)sb.data_block_count * BLOCK_SIZE;
if (data_end > FS_TOTAL_SIZE) {
close(fd);
die_msg("layout does not fit in FS_TOTAL_SIZE");
}
/* Write superblock */
write_exact(fd, &sb, sizeof(sb), 0);
/* Zero metadata and journal regions (image is already zeroed by ftruncate on most systems,
but we do it explicitly for clarity). */
size_t meta_journal_size = (size_t)(sb.data_region_offset - sizeof(Superblock));
void *zero = calloc(1, meta_journal_size);
if (!zero) die("calloc");
write_exact(fd, zero, meta_journal_size, sizeof(Superblock));
free(zero);
/* Data region can remain implicit zeros */
if (fsync(fd) != 0) die("fsync");
close(fd);
printf("Formatted filesystem '%s'\n", path);
}
/* ---- Journal recovery ---- */
#define MAX_TXIDS 4096
static int txid_in_set(uint32_t *arr, size_t count, uint32_t id)
{
for (size_t i = 0; i < count; i++) {
if (arr[i] == id) return 1;
}
return 0;
}
/* Scan the journal, redo all committed transactions, and set
* fs->journal_next_index and fs->next_txid. */
static void fs_recover(Fs *fs)
{
Superblock *sb = &fs->sb;
uint64_t joff = sb->journal_offset;
uint32_t max_rec = sb->journal_record_count;
uint32_t committed[MAX_TXIDS];
size_t committed_count = 0;
uint32_t highest_txid = 0;
uint32_t max_idx = 0;
JournalRecord rec;
/* Pass 1: collect committed txids and highest txid,
and find end of valid journal. */
for (uint32_t i = 0; i < max_rec; i++) {
off_t pos = (off_t)(joff + (uint64_t)i * JOURNAL_RECORD_SIZE);
ssize_t r = pread(fs->fd, &rec, sizeof(rec), pos);
if (r <= 0) break;
if ((size_t)r < sizeof(rec)) break;
if (rec.magic != JOURNAL_MAGIC) {
break; /* end of log */
}
max_idx = i + 1;
if (rec.txid > highest_txid)
highest_txid = rec.txid;
if (rec.type == JRNL_TYPE_COMMIT) {
if (!txid_in_set(committed, committed_count, rec.txid)) {
if (committed_count < MAX_TXIDS) {
committed[committed_count++] = rec.txid;
}
}
}
}
/* Pass 2: replay DATA records for committed txids */
for (uint32_t i = 0; i < max_idx; i++) {
off_t pos = (off_t)(joff + (uint64_t)i * JOURNAL_RECORD_SIZE);
ssize_t r = pread(fs->fd, &rec, sizeof(rec), pos);
if (r <= 0) break;
if ((size_t)r < sizeof(rec)) break;
if (rec.magic != JOURNAL_MAGIC) break;
if (rec.type == JRNL_TYPE_DATA &&
txid_in_set(committed, committed_count, rec.txid)) {
if (rec.payload_size > 0 &&
rec.payload_size <= JRNL_MAX_PAYLOAD) {
write_exact(fs->fd, rec.payload, rec.payload_size,
(off_t)rec.disk_offset);
}
}
}
if (fsync(fs->fd) != 0)
die("fsync after recovery");
fs->journal_next_index = max_idx;
fs->next_txid = (highest_txid == 0) ? 1 : (highest_txid + 1);
/* For demonstration */
if (max_idx > 0) {
fprintf(stderr,
"Recovery: journal records=%u, committed tx=%zu, next_txid=%u\n",
max_idx, committed_count, fs->next_txid);
}
}
/* ---- Mount / load metadata ---- */
static void fs_mount(Fs *fs, const char *path)
{
memset(fs, 0, sizeof(*fs));
fs->fd = open(path, O_RDWR);
if (fs->fd < 0)
die("open image");
read_exact(fs->fd, &fs->sb, sizeof(fs->sb), 0);
if (fs->sb.magic != FS_MAGIC) {
close(fs->fd);
die_msg("not a tinyfs filesystem (bad magic)");
}
if (fs->sb.version != FS_VERSION) {
close(fs->fd);
die_msg("unsupported filesystem version");
}
/* Recover journal before loading metadata */
fs_recover(fs);
/* Load metadata into memory */
fs->inode_bitmap = malloc(fs->sb.inode_count);
fs->block_bitmap = malloc(fs->sb.data_block_count);
fs->inode_table = calloc(fs->sb.inode_count, sizeof(Inode));
fs->root_dir = calloc(fs->sb.root_dir_entries, sizeof(DirEntry));
if (!fs->inode_bitmap || !fs->block_bitmap ||
!fs->inode_table || !fs->root_dir) {
die("malloc metadata");
}
read_exact(fs->fd, fs->inode_bitmap,
fs->sb.inode_count, (off_t)fs->sb.free_inode_bitmap_offset);
read_exact(fs->fd, fs->block_bitmap,
fs->sb.data_block_count, (off_t)fs->sb.free_block_bitmap_offset);
read_exact(fs->fd, fs->inode_table,
fs->sb.inode_count * sizeof(Inode),
(off_t)fs->sb.inode_table_offset);
read_exact(fs->fd, fs->root_dir,
fs->sb.root_dir_entries * sizeof(DirEntry),
(off_t)fs->sb.root_dir_offset);
if (fs->next_txid == 0)
fs->next_txid = 1;
}
static void fs_unmount(Fs *fs)
{
if (!fs) return;
if (fs->inode_bitmap) {
free(fs->inode_bitmap);
fs->inode_bitmap = NULL;
}
if (fs->block_bitmap) {
free(fs->block_bitmap);
fs->block_bitmap = NULL;
}
if (fs->inode_table) {
free(fs->inode_table);
fs->inode_table = NULL;
}
if (fs->root_dir) {
free(fs->root_dir);
fs->root_dir = NULL;
}
if (fs->fd >= 0) {
close(fs->fd);
fs->fd = -1;
}
}
/* ---- Transaction (in-memory) ---- */
#define TX_MAX_RANGES 16
typedef struct {
uint64_t disk_offset;
uint32_t length;
uint8_t *buffer;
int own_buffer; /* if 1, free after commit */
} TxRange;
typedef struct {
uint32_t txid;
int range_count;
TxRange ranges[TX_MAX_RANGES];
} Tx;
static void tx_init(Fs *fs, Tx *tx)
{
memset(tx, 0, sizeof(*tx));
tx->txid = fs->next_txid++;
if (tx->txid == 0) /* handle wrap around */
tx->txid = 1;
}
static void tx_add_range(Tx *tx,
uint64_t disk_offset,
uint8_t *buffer,
uint32_t length,
int own_buffer)
{
if (tx->range_count >= TX_MAX_RANGES)
die_msg("too many modified ranges in one transaction");
TxRange *r = &tx->ranges[tx->range_count++];
r->disk_offset = disk_offset;
r->length = length;
r->buffer = buffer;
r->own_buffer = own_buffer;
}
/* Append a single journal record at given journal index */
static void journal_write_record(Fs *fs, uint32_t index, const JournalRecord *rec)
{
uint64_t off = fs->sb.journal_offset +
(uint64_t)index * JOURNAL_RECORD_SIZE;
write_exact(fs->fd, rec, sizeof(*rec), (off_t)off);
}
/* Commit a transaction:
* - append DATA records for all modified ranges
* - append COMMIT record
* - fsync (journal)
* - apply ranges to main region
* - fsync (data)
*/
static void tx_commit(Fs *fs, Tx *tx)
{
if (tx->range_count == 0)
return; /* nothing to do */
/* Compute how many journal records we need */
uint32_t needed = 1; /* COMMIT */
for (int i = 0; i < tx->range_count; i++) {
uint32_t len = tx->ranges[i].length;
uint32_t n = (len + JRNL_MAX_PAYLOAD - 1) / JRNL_MAX_PAYLOAD;
needed += n;
}
if (fs->journal_next_index + needed > fs->sb.journal_record_count) {
die_msg("journal full, cannot commit transaction");
}
uint32_t base_index = fs->journal_next_index;
uint32_t idx = base_index;
/* DATA records */
for (int i = 0; i < tx->range_count; i++) {
TxRange *r = &tx->ranges[i];
uint32_t remaining = r->length;
uint64_t offset = r->disk_offset;
uint8_t *ptr = r->buffer;
while (remaining > 0) {
uint32_t chunk = remaining;
if (chunk > JRNL_MAX_PAYLOAD)
chunk = JRNL_MAX_PAYLOAD;
JournalRecord rec;
memset(&rec, 0, sizeof(rec));
rec.magic = JOURNAL_MAGIC;
rec.type = JRNL_TYPE_DATA;
rec.txid = tx->txid;
rec.payload_size = chunk;
rec.disk_offset = offset;
memcpy(rec.payload, ptr, chunk);
journal_write_record(fs, idx++, &rec);
remaining -= chunk;
ptr += chunk;
offset += chunk;
}
}
/* COMMIT record */
{
JournalRecord rec;
memset(&rec, 0, sizeof(rec));
rec.magic = JOURNAL_MAGIC;
rec.type = JRNL_TYPE_COMMIT;
rec.txid = tx->txid;
rec.payload_size = 0;
rec.disk_offset = 0;
journal_write_record(fs, idx++, &rec);
}
fs->journal_next_index = idx;
/* Ensure journal hit disk before data writes (WAL) */
if (fsync(fs->fd) != 0)
die("fsync journal");
/* Apply modifications to main area */
for (int i = 0; i < tx->range_count; i++) {
TxRange *r = &tx->ranges[i];
write_exact(fs->fd, r->buffer, r->length, (off_t)r->disk_offset);
}
if (fsync(fs->fd) != 0)
die("fsync data");
/* Free any owned buffers */
for (int i = 0; i < tx->range_count; i++) {
if (tx->ranges[i].own_buffer && tx->ranges[i].buffer) {
free(tx->ranges[i].buffer);
tx->ranges[i].buffer = NULL;
}
}
}
/* ---- Allocators & directory helpers ---- */
static int alloc_inode(Fs *fs, Tx *tx)
{
for (uint32_t i = 0; i < fs->sb.inode_count; i++) {
if (fs->inode_bitmap[i] == 0) {
fs->inode_bitmap[i] = 1;
/* initialize inode in memory */
Inode *ino = &fs->inode_table[i];
ino->used = 1;
ino->size = 0;
ino->direct_block = 0xFFFFFFFFU;
/* Mark bitmap byte dirty */
uint64_t bmp_off = fs->sb.free_inode_bitmap_offset + i;
tx_add_range(tx, bmp_off, &fs->inode_bitmap[i], 1, 0);
/* Mark inode struct dirty */
uint64_t ino_off = fs->sb.inode_table_offset +
(uint64_t)i * sizeof(Inode);
tx_add_range(tx, ino_off, (uint8_t*)ino, sizeof(Inode), 0);
return (int)i;
}
}
return -1; /* no free inode */
}
static int alloc_block(Fs *fs, Tx *tx)
{
for (uint32_t i = 0; i < fs->sb.data_block_count; i++) {
if (fs->block_bitmap[i] == 0) {
fs->block_bitmap[i] = 1;
uint64_t bmp_off = fs->sb.free_block_bitmap_offset + i;
tx_add_range(tx, bmp_off, &fs->block_bitmap[i], 1, 0);
return (int)i;
}
}
return -1;
}
static int find_dir_entry(Fs *fs, const char *name)
{
for (uint32_t i = 0; i < fs->sb.root_dir_entries; i++) {
if (fs->root_dir[i].used &&
strncmp(fs->root_dir[i].name, name, FS_MAX_NAME) == 0) {
return (int)i;
}
}
return -1;
}
static int find_free_dir_entry(Fs *fs)
{
for (uint32_t i = 0; i < fs->sb.root_dir_entries; i++) {
if (!fs->root_dir[i].used)
return (int)i;
}
return -1;
}
/* ---- High-level operations ---- */
static void cmd_ls(Fs *fs)
{
printf("Files:\n");
for (uint32_t i = 0; i < fs->sb.root_dir_entries; i++) {
DirEntry *de = &fs->root_dir[i];
if (de->used) {
Inode *ino = &fs->inode_table[de->inode_index];
printf(" %s (size=%u)\n", de->name, ino->size);
}
}
}
static void cmd_read(Fs *fs, const char *name)
{
int de_idx = find_dir_entry(fs, name);
if (de_idx < 0) {
fprintf(stderr, "No such file: %s\n", name);
return;
}
DirEntry *de = &fs->root_dir[de_idx];
Inode *ino = &fs->inode_table[de->inode_index];
if (!ino->used || ino->direct_block == 0xFFFFFFFFU) {
fprintf(stderr, "File has no data block\n");
return;
}
if (ino->size > BLOCK_SIZE) {
fprintf(stderr, "File too large for demo (size=%u)\n", ino->size);
return;
}
uint64_t data_off = fs->sb.data_region_offset +
(uint64_t)ino->direct_block * BLOCK_SIZE;
uint8_t *buf = malloc(ino->size + 1);
if (!buf) die("malloc read buf");
read_exact(fs->fd, buf, ino->size, (off_t)data_off);
buf[ino->size] = '\0';
printf("%s\n", buf);
free(buf);
}
/* Create a file with given name and data (single block max) */
static void cmd_create(Fs *fs, const char *name, const char *data)
{
if (strlen(name) >= FS_MAX_NAME) {
fprintf(stderr, "Name too long (max %d)\n", FS_MAX_NAME - 1);
return;
}
if (find_dir_entry(fs, name) >= 0) {
fprintf(stderr, "File already exists: %s\n", name);
return;
}
size_t len = strlen(data);
if (len > BLOCK_SIZE) {
fprintf(stderr, "Data too large for one-block demo (%zu bytes)\n", len);
return;
}
Tx tx;
tx_init(fs, &tx);
int ino_idx = alloc_inode(fs, &tx);
if (ino_idx < 0) {
fprintf(stderr, "No free inodes\n");
return;
}
Inode *ino = &fs->inode_table[ino_idx];
int blk_idx = alloc_block(fs, &tx);
if (blk_idx < 0) {
fprintf(stderr, "No free data blocks\n");
return;
}
ino->direct_block = (uint32_t)blk_idx;
ino->size = (uint32_t)len;
/* Mark inode dirty again (size, direct_block changed) */
uint64_t ino_off = fs->sb.inode_table_offset +
(uint64_t)ino_idx * sizeof(Inode);
tx_add_range(&tx, ino_off, (uint8_t*)ino, sizeof(Inode), 0);
int de_idx = find_free_dir_entry(fs);
if (de_idx < 0) {
fprintf(stderr, "No free directory entries\n");
return;
}
DirEntry *de = &fs->root_dir[de_idx];
de->used = 1;
de->inode_index = (uint32_t)ino_idx;
memset(de->name, 0, FS_MAX_NAME);
strncpy(de->name, name, FS_MAX_NAME - 1);
uint64_t de_off = fs->sb.root_dir_offset +
(uint64_t)de_idx * sizeof(DirEntry);
tx_add_range(&tx, de_off, (uint8_t*)de, sizeof(DirEntry), 0);
/* File data: store in a temporary buffer owned by the transaction */
uint8_t *block_buf = malloc(len);
if (!block_buf) die("malloc data block");
memcpy(block_buf, data, len);
uint64_t data_off = fs->sb.data_region_offset +
(uint64_t)blk_idx * BLOCK_SIZE;
tx_add_range(&tx, data_off, block_buf, (uint32_t)len, 1);
tx_commit(fs, &tx);
printf("Created file '%s' (%zu bytes)\n", name, len);
}
/* Expose recovery as a command */
static void cmd_recover_only(const char *path)
{
Fs fs;
fs_mount(&fs, path);
/* fs_recover already called in fs_mount */
fs_unmount(&fs);
printf("Recovery completed on '%s'\n", path);
}
/* ---- Main ---- */
static void usage(const char *prog)
{
fprintf(stderr,
"Usage:\n"
" %s <image> format\n"
" %s <image> create <name> <data>\n"
" %s <image> read <name>\n"
" %s <image> ls\n"
" %s <image> recover\n",
prog, prog, prog, prog, prog);
}
int main(int argc, char **argv)
{
if (argc < 3) {
usage(argv[0]);
return EXIT_FAILURE;
}
const char *img = argv[1];
const char *cmd = argv[2];
if (strcmp(cmd, "format") == 0) {
if (argc != 3) {
usage(argv[0]);
return EXIT_FAILURE;
}
fs_format(img);
return EXIT_SUCCESS;
}
if (strcmp(cmd, "recover") == 0) {
if (argc != 3) {
usage(argv[0]);
return EXIT_FAILURE;
}
cmd_recover_only(img);
return EXIT_SUCCESS;
}
Fs fs;
fs_mount(&fs, img);
if (strcmp(cmd, "ls") == 0) {
if (argc != 3) {
usage(argv[0]);
fs_unmount(&fs);
return EXIT_FAILURE;
}
cmd_ls(&fs);
} else if (strcmp(cmd, "read") == 0) {
if (argc != 4) {
usage(argv[0]);
fs_unmount(&fs);
return EXIT_FAILURE;
}
cmd_read(&fs, argv[3]);
} else if (strcmp(cmd, "create") == 0) {
if (argc != 5) {
usage(argv[0]);
fs_unmount(&fs);
return EXIT_FAILURE;
}
cmd_create(&fs, argv[3], argv[4]);
} else {
usage(argv[0]);
fs_unmount(&fs);
return EXIT_FAILURE;
}
fs_unmount(&fs);
return EXIT_SUCCESS;
}