Write a log-structured file system in C where all writes append sequentially to the end of the disk for write performance. Implement a cleaner garbage collector thread that compacts old segments in the background.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Implementing log-structured filesystem simulation in C with cleaner
The code models a memory-based log-structured file system with append-only writes, an inode table mapping file blocks, and a concurrent cleaner thread that compacts segments by relocating live blocks and freeing segments with high invalid ratios; it includes basic synchronization and a demonstration main function.
c
/*
* Simple in-memory simulation of a log-structured file system in C.
* All writes append sequentially to the end of the disk (log).
* A background cleaner thread compacts segments by copying live blocks.
*
* Compile with: gcc -pthread -o lfs lfs.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <stdbool.h>
#define BLOCK_SIZE 256 /* bytes */
#define SEGMENT_SIZE 8 /* blocks per segment */
#define NUM_SEGMENTS 16 /* number of segments on the "disk" */
#define MAX_FILES 16 /* number of supported files */
#define MAX_BLOCKS_PER_FILE 64 /* max blocks per file */
#define CLEANER_SLEEP_USEC 50000 /* cleaner sleep when no work (50ms) */
#define INVALID -1
typedef struct {
int file_id;
int file_block; /* index within the file */
bool live; /* whether this block is still referenced */
char data[BLOCK_SIZE];
} Block;
typedef struct {
Block blocks[SEGMENT_SIZE];
int used; /* number of blocks written in this segment */
bool cleaning; /* marked for cleaning */
} Segment;
typedef struct {
int file_id;
int size_blocks;
int segment_idx[MAX_BLOCKS_PER_FILE];
int block_idx[MAX_BLOCKS_PER_FILE];
} Inode;
typedef struct {
Segment segments[NUM_SEGMENTS];
Inode inodes[MAX_FILES];
int current_segment;
int current_block;
pthread_mutex_t lock;
pthread_cond_t space_available;
pthread_t cleaner_thread;
bool stop_cleaner;
} FileSystem;
static FileSystem fs;
/* Forward declarations */
void* cleaner_thread_func(void *arg);
/* Initialize file system */
void fs_init() {
memset(&fs, 0, sizeof(fs));
for (int i = 0; i < MAX_FILES; ++i) {
fs.inodes[i].file_id = INVALID;
for (int j = 0; j < MAX_BLOCKS_PER_FILE; ++j) {
fs.inodes[i].segment_idx[j] = INVALID;
fs.inodes[i].block_idx[j] = INVALID;
}
}
for (int s = 0; s < NUM_SEGMENTS; ++s) {
fs.segments[s].used = 0;
fs.segments[s].cleaning = false;
for (int b = 0; b < SEGMENT_SIZE; ++b) {
fs.segments[s].blocks[b].live = false;
fs.segments[s].blocks[b].file_id = INVALID;
fs.segments[s].blocks[b].file_block = INVALID;
}
}
fs.current_segment = 0;
fs.current_block = 0;
pthread_mutex_init(&fs.lock, NULL);
pthread_cond_init(&fs.space_available, NULL);
fs.stop_cleaner = false;
pthread_create(&fs.cleaner_thread, NULL, cleaner_thread_func, NULL);
}
/* Destroy FS and stop cleaner */
void fs_destroy() {
pthread_mutex_lock(&fs.lock);
fs.stop_cleaner = true;
pthread_cond_signal(&fs.space_available);
pthread_mutex_unlock(&fs.lock);
pthread_join(fs.cleaner_thread, NULL);
pthread_mutex_destroy(&fs.lock);
pthread_cond_destroy(&fs.space_available);
}
/* Find or create inode for file_id */
static Inode* get_inode(int file_id) {
Inode *free_slot = NULL;
for (int i = 0; i < MAX_FILES; ++i) {
if (fs.inodes[i].file_id == file_id)
return &fs.inodes[i];
if (fs.inodes[i].file_id == INVALID && free_slot == NULL)
free_slot = &fs.inodes[i];
}
if (free_slot) {
free_slot->file_id = file_id;
free_slot->size_blocks = 0;
return free_slot;
}
return NULL;
}
/* Append a block to the log; returns segment and block index, or -1 on failure. */
static int append_block(int file_id, int file_block, const char *data, int *out_seg, int *out_idx) {
while (1) {
if (fs.current_segment >= NUM_SEGMENTS)
fs.current_segment = 0;
Segment *seg = &fs.segments[fs.current_segment];
/* Skip segments being cleaned or full */
if (seg->cleaning || seg->used >= SEGMENT_SIZE) {
fs.current_segment++;
fs.current_block = 0;
continue;
}
int bidx = fs.current_block;
if (bidx >= SEGMENT_SIZE) {
fs.current_segment++;
fs.current_block = 0;
continue;
}
/* We found space */
Block *blk = &seg->blocks[bidx];
blk->file_id = file_id;
blk->file_block = file_block;
blk->live = true;
memcpy(blk->data, data, BLOCK_SIZE);
seg->used++;
*out_seg = fs.current_segment;
*out_idx = bidx;
/* Advance pointer */
fs.current_block++;
if (fs.current_block >= SEGMENT_SIZE) {
fs.current_segment++;
fs.current_block = 0;
}
return 0;
}
return -1;
}
/* Invalidate an existing block */
static void invalidate_block(int seg_idx, int blk_idx) {
if (seg_idx < 0 || seg_idx >= NUM_SEGMENTS) return;
if (blk_idx < 0 || blk_idx >= SEGMENT_SIZE) return;
Block *blk = &fs.segments[seg_idx].blocks[blk_idx];
blk->live = false;
}
/* Write a block of data to a file at file_block index */
int fs_write(int file_id, int file_block, const char *data) {
pthread_mutex_lock(&fs.lock);
Inode *inode = get_inode(file_id);
if (!inode || file_block >= MAX_BLOCKS_PER_FILE) {
pthread_mutex_unlock(&fs.lock);
return -1;
}
/* Invalidate old location if any */
int old_seg = inode->segment_idx[file_block];
int old_idx = inode->block_idx[file_block];
if (old_seg != INVALID && old_idx != INVALID) {
invalidate_block(old_seg, old_idx);
}
int seg_idx, blk_idx;
/* Wait for space if necessary */
while (append_block(file_id, file_block, data, &seg_idx, &blk_idx) != 0) {
pthread_cond_wait(&fs.space_available, &fs.lock);
}
inode->segment_idx[file_block] = seg_idx;
inode->block_idx[file_block] = blk_idx;
if (file_block >= inode->size_blocks)
inode->size_blocks = file_block + 1;
pthread_mutex_unlock(&fs.lock);
return 0;
}
/* Read a block of data from a file */
int fs_read(int file_id, int file_block, char *out_data) {
pthread_mutex_lock(&fs.lock);
Inode *inode = get_inode(file_id);
if (!inode || file_block >= inode->size_blocks) {
pthread_mutex_unlock(&fs.lock);
return -1;
}
int seg_idx = inode->segment_idx[file_block];
int blk_idx = inode->block_idx[file_block];
if (seg_idx == INVALID || blk_idx == INVALID) {
pthread_mutex_unlock(&fs.lock);
return -1;
}
Block *blk = &fs.segments[seg_idx].blocks[blk_idx];
memcpy(out_data, blk->data, BLOCK_SIZE);
pthread_mutex_unlock(&fs.lock);
return 0;
}
/* Compute utilization ratio for a segment */
static float segment_utilization(int seg_idx) {
Segment *seg = &fs.segments[seg_idx];
if (seg->used == 0)
return 0.0f;
int live_count = 0;
for (int b = 0; b < SEGMENT_SIZE; ++b) {
if (seg->blocks[b].live)
live_count++;
}
return (float)live_count / SEGMENT_SIZE;
}
/* Mark a segment for cleaning if good candidate */
static int choose_segment_for_cleaning() {
float worst_util = 1.1f;
int worst_idx = -1;
for (int i = 0; i < NUM_SEGMENTS; ++i) {
if (i == fs.current_segment)
continue; /* skip currently writing segment */
Segment *seg = &fs.segments[i];
if (seg->used == 0 || seg->cleaning)
continue;
float util = segment_utilization(i);
/* choose lowest utilization */
if (util < worst_util) {
worst_util = util;
worst_idx = i;
}
}
/* threshold: clean only if less than 0.5 utilization */
if (worst_idx != -1 && worst_util < 0.5f)
return worst_idx;
return -1;
}
/* Cleaner: copy live blocks to new segments, free old segments */
void* cleaner_thread_func(void *arg) {
(void)arg;
while (1) {
pthread_mutex_lock(&fs.lock);
if (fs.stop_cleaner) {
pthread_mutex_unlock(&fs.lock);
break;
}
int seg_idx = choose_segment_for_cleaning();
if (seg_idx == -1) {
pthread_mutex_unlock(&fs.lock);
usleep(CLEANER_SLEEP_USEC);
continue;
}
Segment *seg = &fs.segments[seg_idx];
seg->cleaning = true;
/* Copy live blocks */
for (int b = 0; b < SEGMENT_SIZE; ++b) {
Block *blk = &seg->blocks[b];
if (!blk->live)
continue;
/* append to log */
int new_seg, new_idx;
append_block(blk->file_id, blk->file_block, blk->data, &new_seg, &new_idx);
/* update inode mapping */
Inode *inode = get_inode(blk->file_id);
if (inode && inode->segment_idx[blk->file_block] == seg_idx &&
inode->block_idx[blk->file_block] == b) {
inode->segment_idx[blk->file_block] = new_seg;
inode->block_idx[blk->file_block] = new_idx;
}
/* invalidate old block */
blk->live = false;
}
/* Free segment */
seg->used = 0;
for (int b = 0; b < SEGMENT_SIZE; ++b) {
seg->blocks[b].file_id = INVALID;
seg->blocks[b].file_block = INVALID;
seg->blocks[b].live = false;
}
seg->cleaning = false;
pthread_cond_broadcast(&fs.space_available);
pthread_mutex_unlock(&fs.lock);
}
return NULL;
}
/* Debug print segments */
void fs_print_segments() {
pthread_mutex_lock(&fs.lock);
printf("Segments:\n");
for (int i = 0; i < NUM_SEGMENTS; ++i) {
Segment *seg = &fs.segments[i];
printf("Segment %2d: used=%d cleaning=%d live_blocks=", i, seg->used, seg->cleaning);
int live = 0;
for (int b = 0; b < SEGMENT_SIZE; ++b) {
if (seg->blocks[b].live)
live++;
}
printf("%d util=%.2f\n", live, segment_utilization(i));
}
pthread_mutex_unlock(&fs.lock);
}
/* Demo usage */
int main() {
fs_init();
char buf[BLOCK_SIZE];
memset(buf, 'A', sizeof(buf));
fs_write(1, 0, buf);
memset(buf, 'B', sizeof(buf));
fs_write(1, 1, buf);
memset(buf, 'C', sizeof(buf));
fs_write(2, 0, buf);
printf("Initial writes complete.\n");
fs_print_segments();
/* Overwrite a block to create garbage */
memset(buf, 'D', sizeof(buf));
fs_write(1, 0, buf);
printf("Overwritten block in file 1.\n");
fs_print_segments();
/* Let cleaner run for a bit */
sleep(1);
printf("After cleaner ran.\n");
fs_print_segments();
/* Read back */
char out[BLOCK_SIZE];
fs_read(1, 0, out);
printf("Read file1 block0 first byte: %c\n", out[0]);
fs_read(1, 1, out);
printf("Read file1 block1 first byte: %c\n", out[0]);
fs_read(2, 0, out);
printf("Read file2 block0 first byte: %c\n", out[0]);
fs_destroy();
return 0;
}