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.
This is a great systems programming question asking for a log-structured file system (LFS) implementation in C. This is a complex topic, so I'll create a comprehensive implementation that includes:
Core Components:
Log structure with segments
Inode management
Directory structure
File metadata
Key Features:
Sequential writes to disk (append-only)
Garbage collection/segment cleaner
Concurrent access handling
Index management (inode map)
Segment summary blocks
Implementation Details:
Thread-safe operations
Garbage collector thread that runs in background
Segment selection policies
Live block identification
Segment compaction
Let me create a detailed, well-commented implementation:
I need to define the core data structures for tracking inodes, directory entries, and segment metadata. The inode structure stores file metadata including size, type, and version information for tracking updates. Directory entries map filenames to inode numbers, and segment summary blocks maintain information about which blocks are live versus dead for garbage collection decisions. _fs;
// Function declarations
LogFS* logfs_init(const char *disk_path);
void logfs_shutdown(LogFS *fs);
int logfs_create(LogFS *fs, const char *name);
int logfs_open(LogFS *fs, const char *name);
int logfs_write(LogFS *fs, int fd, const void *data, uint32_t size);
int logfs_read(LogFS *fs, int fd, void *data, uint32_t size);
int logfs_close(LogFS *fs, int fd);
int logfs_delete(LogFS *fs, const char *name);
void logfs_gc(LogFS *fs);
The metadata tracks write position, segment usage, and garbage collection thresholds with thread synchronization. The main filesystem structure holds the disk file, metadata, inode mappings, segment summaries, and a background garbage collection thread. A global instance provides access to the filesystem throughout the program.
Utility functions handle timestamped logging, millisecond timing, and bitmap operations for tracking live inodes. Disk I/O operations manage reading and writing data at specific offsets with error checking. If appending would exceed the garbage collection threshold, I signal the GC condition variable. Then I write the data to disk at the current offset, update the write position and statistics, unlock the mutex, and return the offset where the data was written.
For inode map management, I iterate through available entries to find an empty slot where I can store the inode number, disk offset, and version. If an entry for that inode already exists, I update its disk offset and version information instead of creating a duplicate.
When retrieving an inode, I search the map for a matching valid entry, then allocate memory and read the inode data from disk at the stored offset. If the disk read fails, I clean up the allocated memory and return null.
For persisting an inode, I increment its version, update the modification timestamp, and append it to the log. Then I create a corresponding map entry with the new offset and version, mark the inode as live in the bitmap, and return the log offset where it was written.
When initializing the file system, I allocate memory for the LogFS structure and open the disk file in read-write mode. I set up the metadata with initial values—write offset at zero, starting inode number at one, and garbage collection threshold at 80% capacity. I also initialize the synchronization primitives (mutex and condition variable) and zero out the inode map and segment summaries.
The garbage collection thread is enabled and configured to run. After logging the initialization parameters, the function returns successfully. When creating a new file, I acquire the metadata lock to atomically assign the next available inode number, then release the lock. I initialize a new inode structure with the assigned number, mark it as a regular file, and set its creation and modification timestamps to the current time.
I set the initial file size to zero, version to zero, and block count to zero, then copy the filename into the inode's name field and mark it as valid before persisting it to disk. The function logs the file creation and returns the inode number. For writing data to a file, I first validate that the requested size doesn't exceed the maximum file data capacity, then retrieve the inode. If the inode doesn't exist, I return an error. The write operation then appends a data block to the file.
The data gets written to the log and its offset is stored in the inode's block pointer array, provided we haven't exceeded the 64-block limit. After updating the inode's size and incrementing the block count, I save the changes and log the write operation. Reading a file involves fetching the inode and checking if it contains any blocks—if not, the file is empty. Otherwise, I retrieve the most recent data block using the offset stored in the block pointers array.
For deletion, I mark the inode as invalid by setting its valid flag to zero, write this tombstone record, and clear the inode from the live bitmap. The garbage collection phase then needs to identify which segments contain live data by iterating through active inodes and checking their block pointer references against each segment's address range. for (uint32_t i = 0; i < total_segments; i++) {
uint32_t segment_live_bytes = calculate_segment_live_bytes(i);
uint32_t segment_dead_bytes = SEGMENT_SIZE - segment_live_bytes;
I'm iterating through each segment to compute how many live bytes it contains, then calculating the dead space as the difference from the total segment size. I track these metrics in the segment summaries and use a greedy approach to pick the segment with the most dead bytes for collection. If no valid segment is found, I return an error; otherwise I set the output parameter and return success.
Now I need to handle segment compaction by relocating all live data. I'll scan through the live inodes bitmap and for each valid inode, check whether any of its data blocks fall within the target segment's address range. When I find an inode with data in that segment, I rewrite both the inode and its associated blocks to new locations.
For each block that needs relocation, I read the old data from disk, append it to the log at a fresh offset, and update the inode's block pointer accordingly. After processing all blocks for an inode, I save the updated inode with its new pointers. The function tracks how many bytes were successfully moved and calculates the freed space as the difference between the segment size and the live bytes recovered.
The garbage collection worker thread begins by waiting on a condition variable until the write offset exceeds the collection threshold. Once signaled, it acquires the necessary locks and initiates a garbage collection cycle, logging the current write offset and preparing to track how many segments get collected.
For each collection cycle, the thread attempts to compact up to three segments, selecting candidates based on their dead byte ratio. It skips any segment that still contains mostly live data (less than half dead bytes), then proceeds with compaction for viable candidates. After completing the compaction passes, it records timing metrics and logs the results including segment count and elapsed time.
The metadata gets updated with garbage collection statistics—incrementing the run counter and storing the current timestamp. The collection threshold resets to 80% disk capacity for the next cycle, protected by the metadata lock. A one-second sleep prevents the thread from consuming excessive CPU while waiting for the next trigger condition.
The garbage collector thread creation wraps pthread_create with error handling, returning -1 on failure. Stopping the thread sets the exit flag, signals the condition variable to wake it, and joins to wait for completion.
The statistics function displays disk usage as a fraction of total capacity, tracks write operations and bytes written in megabytes, counts garbage collection cycles and bytes reclaimed, and if a collection has run, shows how long ago it occurred. Closing the file system stops the background collector, closes the disk file handle, destroys all synchronization primitives, and frees the main structure.
For testing, I'm creating three files and writing distinct content to each—file1 gets a short message, file2 receives more data, and file3 holds minimal content. After writing, I'll read the data back to verify it matches what was stored.
Then I need to test larger sequential writes by creating a file and repeatedly writing 8KB blocks of data to it in a loop, checking that the filesystem handles the volume correctly.
For concurrent operations, I'm creating multiple files simultaneously and writing to each one to verify the system can manage parallel file access without corruption or conflicts.
After the concurrent write test completes, I need to initialize the file system with a disk image, start the garbage collection thread to handle space reclamation, then execute the three test suites with brief pauses between them to let the system stabilize. Once all tests finish, I'll print final statistics to see how the system performed overall.
Then I need to clean up by closing the file system and logging that testing is complete before returning.
Log-Structured File System in C
I'll create a complete LFS implementation with segment-based storage, inode mapping, and a background garbage collector.
c
Compilation and Usage
bash
# Compile with threading support
gcc -o lfs lfs.c -lpthread -Wall -Wextra -O2
# Run tests
./lfs
Key Features Demonstrated
Sequential Writes: All data appended to end of log (FIFO-like)
Inode Map: In-memory index for fast inode lookup
Segment-Based Storage: Logical disk divided into 1MB segments
Background GC Thread: Compacts segments when disk usage exceeds threshold
Live/Dead Tracking: Identifies garbage data for collection
Thread-Safe Operations: Mutexes protect shared state
Greedy Segment Selection: Prioritizes segments with most wasted space
Performance Characteristics
Write: O(1) - Sequential append
Read: O(log n) - Inode map lookup + disk seek
Delete: O(1) - Mark inode invalid
GC: Background, minimal impact on foreground I/O
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <stdint.h>
#include <assert.h>
#include <sys/time.h>
#include <errno.h>
#include <stdarg.h>
// ============================================================================
// CONFIGURATION
// ============================================================================
#define DISK_SIZE (100 * 1024 * 1024) // 100 MB virtual disk
#define SEGMENT_SIZE (1 * 1024 * 1024) // 1 MB segments
#define BLOCK_SIZE 4096
#define MAX_FILES 1000
#define MAX_SEGMENTS (DISK_SIZE / SEGMENT_SIZE)
#define MAX_FILENAME 256
#define MAX_FILE_BLOCKS 256
// Block and metadata types
#define BLOCK_TYPE_INODE 1
#define BLOCK_TYPE_DATA 2
#define BLOCK_TYPE_DELETE 3
#define BLOCK_TYPE_SUMMARY 4
// GC policies
#define GC_THRESHOLD_PERCENT 75
#define GC_COLLECTION_PERCENT 50
// ============================================================================
// DATA STRUCTURES
// ============================================================================
typedef struct {
uint32_t inode_num;
uint32_t size;
uint32_t version;
time_t created_time;
time_t modified_time;
char name[MAX_FILENAME];
uint64_t block_offsets[MAX_FILE_BLOCKS];
uint32_t block_count;
uint8_t valid;
uint8_t is_deleted;
} Inode;
typedef struct {
uint32_t inode_num;
uint64_t disk_offset;
uint32_t version;
uint8_t valid;
} InodeMapEntry;
typedef struct {
uint32_t segment_num;
uint64_t segment_start;
uint32_t live_bytes;
uint32_t dead_bytes;
uint32_t total_blocks;
time_t creation_time;
uint32_t live_inode_count;
} SegmentStats;
typedef struct {
uint64_t total_writes;
uint64_t total_writes_bytes;
uint64_t gc_runs;
uint64_t bytes_recovered;
uint64_t data_reads;
uint64_t data_writes;
time_t last_gc_time;
uint32_t gc_ms_last;
} FSStats;
typedef struct {
uint64_t write_offset;
uint32_t next_inode_num;
uint32_t gc_threshold;
pthread_mutex_t lock;
FSStats stats;
} LogMetadata;
typedef struct {
FILE *disk;
LogMetadata metadata;
InodeMapEntry inode_map[INODE_MAP_ENTRIES];
// GC state
pthread_t gc_thread;
pthread_mutex_t gc_lock;
pthread_cond_t gc_signal;
volatile int gc_running;
volatile int gc_should_exit;
volatile int gc_in_progress;
// Segment tracking
SegmentStats segment_stats[MAX_SEGMENTS];
uint32_t live_inode_bitmap[(MAX_FILES + 31) / 32];
} LogFS;
// Global instance
LogFS *g_fs = NULL;
// ============================================================================
// UTILITY FUNCTIONS
// ============================================================================
void log_msg(const char *format, ...) {
va_list args;
time_t now = time(NULL);
struct tm *tm_info = localtime(&now);
char time_str[20];
strftime(time_str, sizeof(time_str), "%H:%M:%S", tm_info);
printf("[%s] ", time_str);
va_start(args, format);
vprintf(format, args);
va_end(args);
printf("\n");
fflush(stdout);
}
uint64_t get_time_ms() {
struct timeval tv;
gettimeofday(&tv, NULL);
return (tv.tv_sec * 1000ULL) + (tv.tv_usec / 1000ULL);
}
// Bitmap operations
static inline void bitmap_set(uint32_t *bitmap, uint32_t bit) {
bitmap[bit / 32] |= (1U << (bit % 32));
}
static inline void bitmap_clear(uint32_t *bitmap, uint32_t bit) {
bitmap[bit / 32] &= ~(1U << (bit % 32));
}
static inline int bitmap_test(uint32_t *bitmap, uint32_t bit) {
return (bitmap[bit / 32] >> (bit % 32)) & 1;
}
static inline int bitmap_count_set(uint32_t *bitmap, uint32_t max_bits) {
int count = 0;
for (uint32_t i = 0; i < max_bits; i++) {
if (bitmap_test(bitmap, i)) count++;
}
return count;
}
// ============================================================================
// DISK I/O
// ============================================================================
int disk_write(uint64_t offset, const void *data, uint32_t size) {
if (offset + size > DISK_SIZE) {
log_msg("ERROR: Write exceeds disk size at offset 0x%lx, size %u",
offset, size);
return -1;
}
if (fseek(g_fs->disk, offset, SEEK_SET) != 0) {
perror("fseek");
return -1;
}
if (fwrite(data, 1, size, g_fs->disk) != size) {
perror("fwrite");
return -1;
}
g_fs->metadata.stats.data_writes++;
return 0;
}
int disk_read(uint64_t offset, void *data, uint32_t size) {
if (offset + size > DISK_SIZE) {
log_msg("ERROR: Read exceeds disk size at offset 0x%lx, size %u",
offset, size);
return -1;
}
if (fseek(g_fs->disk, offset, SEEK_SET) != 0) {
perror("fseek");
return -1;
}
if (fread(data, 1, size, g_fs->disk) != size) {
perror("fread");
return -1;
}
g_fs->metadata.stats.data_reads++;
return 0;
}
// Append to log (sequential writes)
uint64_t log_append(const void *data, uint32_t size) {
pthread_mutex_lock(&g_fs->metadata.lock);
uint64_t offset = g_fs->metadata.write_offset;
if (offset + size > DISK_SIZE) {
pthread_mutex_unlock(&g_fs->metadata.lock);
log_msg("ERROR: Disk full, cannot append %u bytes", size);
return UINT64_MAX;
}
disk_write(offset, data, size);
g_fs->metadata.write_offset += size;
g_fs->metadata.stats.total_writes++;
g_fs->metadata.stats.total_writes_bytes += size;
// Signal GC if threshold reached
uint64_t usage_percent = (g_fs->metadata.write_offset * 100) / DISK_SIZE;
if (usage_percent >= GC_THRESHOLD_PERCENT && !g_fs->gc_in_progress) {
pthread_cond_signal(&g_fs->gc_signal);
}
pthread_mutex_unlock(&g_fs->metadata.lock);
return offset;
}
// ============================================================================
// INODE MAP
// ============================================================================
int inode_map_update(uint32_t inode_num, uint64_t disk_offset, uint32_t version) {
// Find existing entry or empty slot
for (int i = 0; i < INODE_MAP_ENTRIES; i++) {
if (!g_fs->inode_map[i].valid ||
g_fs->inode_map[i].inode_num == inode_num) {
g_fs->inode_map[i].inode_num = inode_num;
g_fs->inode_map[i].disk_offset = disk_offset;
g_fs->inode_map[i].version = version;
g_fs->inode_map[i].valid = 1;
return 0;
}
}
return -1;
}
// Get inode from disk via inode map
Inode* inode_get(uint32_t inode_num) {
for (int i = 0; i < INODE_MAP_ENTRIES; i++) {
if (g_fs->inode_map[i].valid &&
g_fs->inode_map[i].inode_num == inode_num) {
Inode *inode = malloc(sizeof(Inode));
if (!inode) return NULL;
if (disk_read(g_fs->inode_map[i].disk_offset, inode,
sizeof(Inode)) != 0) {
free(inode);
return NULL;
}
return inode;
}
}
return NULL;
}
// Write inode to log
uint64_t inode_save(Inode *inode) {
inode->version++;
inode->modified_time = time(NULL);
uint64_t offset = log_append(inode, sizeof(Inode));
if (offset != UINT64_MAX) {
inode_map_update(inode->inode_num, offset, inode->version);
bitmap_set(g_fs->live_inode_bitmap, inode->inode_num);
}
return offset;
}
// ============================================================================
// FILE SYSTEM OPERATIONS
// ============================================================================
int lfs_init(const char *disk_path) {
g_fs = malloc(sizeof(LogFS));
if (!g_fs) return -1;
memset(g_fs, 0, sizeof(LogFS));
// Open disk file
g_fs->disk = fopen(disk_path, "wb+");
if (!g_fs->disk) {
perror("fopen");
free(g_fs);
return -1;
}
// Initialize metadata
g_fs->metadata.write_offset = 0;
g_fs->metadata.next_inode_num = 1;
g_fs->metadata.gc_threshold = (DISK_SIZE * GC_THRESHOLD_PERCENT) / 100;
pthread_mutex_init(&g_fs->metadata.lock, NULL);
pthread_mutex_init(&g_fs->gc_lock, NULL);
pthread_cond_init(&g_fs->gc_signal, NULL);
memset(g_fs->inode_map, 0, sizeof(g_fs->inode_map));
memset(g_fs->live_inode_bitmap, 0, sizeof(g_fs->live_inode_bitmap));
g_fs->gc_running = 1;
g_fs->gc_should_exit = 0;
g_fs->gc_in_progress = 0;
log_msg("LFS initialized: disk_size=%u MB, segment_size=%u MB, "
"gc_threshold=%u%%",
DISK_SIZE / (1024*1024),
SEGMENT_SIZE / (1024*1024),
GC_THRESHOLD_PERCENT);
return 0;
}
uint32_t lfs_create_file(const char *name) {
pthread_mutex_lock(&g_fs->metadata.lock);
uint32_t inode_num = g_fs->metadata.next_inode_num++;
pthread_mutex_unlock(&g_fs->metadata.lock);
Inode inode = {0};
inode.inode_num = inode_num;
inode.size = 0;
inode.version = 0;
inode.created_time = time(NULL);
inode.modified_time = inode.created_time;
inode.block_count = 0;
inode.valid = 1;
inode.is_deleted = 0;
strncpy(inode.name, name, MAX_FILENAME - 1);
uint64_t offset = inode_save(&inode);
if (offset != UINT64_MAX) {
log_msg("Created file: %s (inode=%u, offset=0x%lx)",
name, inode_num, offset);
}
return inode_num;
}
int lfs_write_file(uint32_t inode_num, const void *data, uint32_t size) {
if (size > SEGMENT_SIZE) {
log_msg("ERROR: Write size %u exceeds segment size", size);
return -1;
}
Inode *inode = inode_get(inode_num);
if (!inode) {
log_msg("ERROR: Inode %u not found", inode_num);
return -1;
}
// Append data block
uint64_t block_offset = log_append(data, size);
if (block_offset == UINT64_MAX) {
log_msg("ERROR: Failed to append data block");
free(inode);
return -1;
}
// Update inode with new block
if (inode->block_count < MAX_FILE_BLOCKS) {
inode->block_offsets[inode->block_count++] = block_offset;
inode->size = size;
inode_save(inode);
log_msg("Wrote %u bytes to inode %u (block %u at 0x%lx)",
size, inode_num, inode->block_count - 1, block_offset);
} else {
log_msg("ERROR: Inode %u has too many blocks", inode_num);
free(inode);
return -1;
}
free(inode);
return 0;
}
int lfs_read_file(uint32_t inode_num, void *buffer, uint32_t *size) {
Inode *inode = inode_get(inode_num);
if (!inode) {
log_msg("ERROR: Inode %u not found", inode_num);
return -1;
}
if (inode->is_deleted) {
log_msg("ERROR: Inode %u is deleted", inode_num);
free(inode);
return -1;
}
if (inode->block_count == 0) {
*size = 0;
free(inode);
return 0;
}
// Read most recent block
uint64_t block_offset = inode->block_offsets[inode->block_count - 1];
*size = inode->size;
if (disk_read(block_offset, buffer, inode->size) != 0) {
log_msg("ERROR: Failed to read block at 0x%lx", block_offset);
free(inode);
return -1;
}
log_msg("Read %u bytes from inode %u", *size, inode_num);
free(inode);
return 0;
}
int lfs_delete_file(uint32_t inode_num) {
Inode *inode = inode_get(inode_num);
if (!inode) {
log_msg("ERROR: Inode %u not found", inode_num);
return -1;
}
inode->is_deleted = 1;
inode->valid = 0;
inode_save(inode);
bitmap_clear(g_fs->live_inode_bitmap, inode_num);
log_msg("Deleted inode %u: %s", inode_num, inode->name);
free(inode);
return 0;
}
// ============================================================================
// GARBAGE COLLECTION
// ============================================================================
// Get segment number for offset
uint32_t get_segment_num(uint64_t offset) {
return offset / SEGMENT_SIZE;
}
// Calculate live bytes in segment from live inodes
void calculate_segment_stats(uint32_t segment_num) {
uint64_t seg_start = (uint64_t)segment_num * SEGMENT_SIZE;
uint64_t seg_end = seg_start + SEGMENT_SIZE;
uint32_t live_bytes = 0;
uint32_t live_inode_count = 0;
// Check all live inodes
for (int i = 0; i < MAX_FILES; i++) {
if (!bitmap_test(g_fs->live_inode_bitmap, i)) {
continue;
}
Inode *inode = inode_get(i);
if (!inode || !inode->valid) {
free(inode);
continue;
}
// Check if inode or its data blocks are in this segment
uint64_t inode_offset = 0;
for (int j = 0; j < INODE_MAP_ENTRIES; j++) {
if (g_fs->inode_map[j].valid &&
g_fs->inode_map[j].inode_num == i) {
inode_offset = g_fs->inode_map[j].disk_offset;
break;
}
}
int in_segment = 0;
// Check inode location
if (inode_offset >= seg_start && inode_offset < seg_end) {
live_bytes += sizeof(Inode);
in_segment = 1;
}
// Check block locations
for (uint32_t j = 0; j < inode->block_count; j++) {
uint64_t block_offset = inode->block_offsets[j];
if (block_offset >= seg_start && block_offset < seg_end) {
live_bytes += inode->size;
in_segment = 1;
}
}
if (in_segment) {
live_inode_count++;
}
free(inode);
}
g_fs->segment_stats[segment_num].segment_num = segment_num;
g_fs->segment_stats[segment_num].segment_start = seg_start;
g_fs->segment_stats[segment_num].live_bytes = live_bytes;
g_fs->segment_stats[segment_num].dead_bytes = SEGMENT_SIZE - live_bytes;
g_fs->segment_stats[segment_num].live_inode_count = live_inode_count;
}
// Select segment for compaction (greedy: max dead bytes)
int select_segment_for_gc() {
uint32_t max_dead = 0;
int best_segment = -1;
uint32_t num_segments = (g_fs->metadata.write_offset + SEGMENT_SIZE - 1) / SEGMENT_SIZE;
for (uint32_t i = 0; i < num_segments; i++) {
calculate_segment_stats(i);
uint32_t dead = g_fs->segment_stats[i].dead_bytes;
// Skip nearly-full segments and empty segments
if (dead > SEGMENT_SIZE / 4 && dead > max_dead) {
max_dead = dead;
best_segment = i;
}
}
return best_segment;
}
// Rewrite live data from segment
void compact_segment(uint32_t segment_num) {
uint64_t seg_start = (uint64_t)segment_num * SEGMENT_SIZE;
uint64_t seg_end = seg_start + SEGMENT_SIZE;
log_msg(" Compacting segment %u (0x%lx-0x%lx), "
"live=%u bytes, dead=%u bytes",
segment_num, seg_start, seg_end,
g_fs->segment_stats[segment_num].live_bytes,
g_fs->segment_stats[segment_num].dead_bytes);
// Find and rewrite all inodes touching this segment
for (int i = 0; i < MAX_FILES; i++) {
if (!bitmap_test(g_fs->live_inode_bitmap, i)) {
continue;
}
Inode *inode = inode_get(i);
if (!inode || !inode->valid) {
free(inode);
continue;
}
int needs_update = 0;
// Check and rewrite data blocks in this segment
for (uint32_t j = 0; j < inode->block_count; j++) {
uint64_t old_offset = inode->block_offsets[j];
if (old_offset >= seg_start && old_offset < seg_end) {
// Read old block
void *block_data = malloc(inode->size);
if (!block_data) continue;
if (disk_read(old_offset, block_data, inode->size) == 0) {
// Write to new location in log
uint64_t new_offset = log_append(block_data, inode->size);
if (new_offset != UINT64_MAX) {
inode->block_offsets[j] = new_offset;
needs_update = 1;
log_msg(" Rewritten data block: 0x%lx -> 0x%lx",
old_offset, new_offset);
}
}
free(block_data);
}
}
if (needs_update) {
inode_save(inode);
}
free(inode);
}
}
// GC thread function
void* gc_thread_worker(void *arg) {
log_msg("GC thread started");
while (!g_fs->gc_should_exit) {
pthread_mutex_lock(&g_fs->gc_lock);
// Wait for signal
while (!g_fs->gc_should_exit) {
uint64_t usage = (g_fs->metadata.write_offset * 100) / DISK_SIZE;
if (usage >= GC_THRESHOLD_PERCENT) {
break;
}
pthread_cond_wait(&g_fs->gc_signal, &g_fs->gc_lock);
}
if (g_fs->gc_should_exit) {
pthread_mutex_unlock(&g_fs->gc_lock);
break;
}
g_fs->gc_in_progress = 1;
pthread_mutex_unlock(&g_fs->gc_lock);
// Perform GC
uint64_t start_ms = get_time_ms();
uint64_t usage_before = g_fs->metadata.write_offset;
uint64_t bytes_freed = 0;
log_msg("GC cycle started (usage=%lu/%lu bytes, %.1f%%)",
g_fs->metadata.write_offset, DISK_SIZE,
(g_fs->metadata.write_offset * 100.0) / DISK_SIZE);
// Compact up to N segments
int segments_compacted = 0;
for (int i = 0; i < 5; i++) {
int seg = select_segment_for_gc();
if (seg < 0) break;
// Only compact if significantly wasted space
if (g_fs->segment_stats[seg].dead_bytes > SEGMENT_SIZE / 3) {
compact_segment(seg);
bytes_freed += g_fs->segment_stats[seg].dead_bytes;
segments_compacted++;
}
}
uint64_t elapsed_ms = get_time_ms() - start_ms;
log_msg("GC cycle completed: segments=%d, bytes_freed=%lu, "
"elapsed_ms=%lu",
segments_compacted, bytes_freed, elapsed_ms);
pthread_mutex_lock(&g_fs->metadata.lock);
g_fs->metadata.stats.gc_runs++;
g_fs->metadata.stats.bytes_recovered += bytes_freed;
g_fs->metadata.stats.last_gc_time = time(NULL);
g_fs->metadata.stats.gc_ms_last = elapsed_ms;
pthread_mutex_unlock(&g_fs->metadata.lock);
pthread_mutex_lock(&g_fs->gc_lock);
g_fs->gc_in_progress = 0;
pthread_mutex_unlock(&g_fs->gc_lock);
usleep(500000); // Sleep 500ms before next check
}
log_msg("GC thread exiting");
return NULL;
}
int gc_start() {
return pthread_create(&g_fs->gc_thread, NULL, gc_thread_worker, NULL);
}
void gc_stop() {
g_fs->gc_should_exit = 1;
pthread_cond_signal(&g_fs->gc_signal);
pthread_join(g_fs->gc_thread, NULL);
}
// ============================================================================
// DIAGNOSTICS
// ============================================================================
void lfs_print_stats() {
FSStats *stats = &g_fs->metadata.stats;
printf("\n");
printf("╔════════════════════════════════════════════════════════╗\n");
printf("║ Log-Structured File System Statistics ║\n");
printf("╠════════════════════════════════════════════════════════╣\n");
printf("║ Disk Usage: %6llu / %6u MB (%.1f%%) ║\n",
g_fs->metadata.write_offset / (1024*1024),
DISK_SIZE / (1024*1024),
(g_fs->metadata.write_offset * 100.0) / DISK_SIZE);
printf("║ Total Writes: %20llu writes ║\n",
stats->total_writes);
printf("║ Data Written: %6llu MB ║\n",
stats->total_writes_bytes / (1024*1024));
printf("║ GC Cycles: %20llu cycles ║\n",
stats->gc_runs);
printf("║ Bytes Recovered: %6llu MB ║\n",
stats->bytes_recovered / (1024*1024));
printf("║ Last GC Time: %20u ms ║\n",
stats->gc_ms_last);
printf("║ Disk Reads: %20llu ops ║\n",
stats->data_reads);
printf("║ Disk Writes: %20llu ops ║\n",
stats->data_writes);
printf("║ Live Inodes: %20u ║\n",
bitmap_count_set(g_fs->live_inode_bitmap, MAX_FILES));
printf("╚════════════════════════════════════════════════════════╝\n");
printf("\n");
}
void lfs_print_segments() {
printf("\n");
printf("╔════════════════════════════════════════════════════════╗\n");
printf("║ Segment Statistics ║\n");
printf("╠════════════════════════════════════════════════════════╣\n");
printf("║ Segment │ Live │ Dead │ Usage │ Inodes ║\n");
printf("╠════════════════════════════════════════════════════════╣\n");
uint32_t num_segments = (g_fs->metadata.write_offset + SEGMENT_SIZE - 1) / SEGMENT_SIZE;
for (uint32_t i = 0; i < num_segments && i < 10; i++) {
calculate_segment_stats(i);
double usage = (g_fs->segment_stats[i].live_bytes * 100.0) / SEGMENT_SIZE;
printf("║ %7u │ %6u B │ %6u B │ %5.1f%% │ %8u ║\n",
i,
g_fs->segment_stats[i].live_bytes,
g_fs->segment_stats[i].dead_bytes,
usage,
g_fs->segment_stats[i].live_inode_count);
}
if (num_segments > 10) {
printf("║ ... %u more segments ║\n",
num_segments - 10);
}
printf("╚════════════════════════════════════════════════════════╝\n");
printf("\n");
}
void lfs_close() {
if (!g_fs) return;
gc_stop();
if (g_fs->disk) {
fclose(g_fs->disk);
}
pthread_mutex_destroy(&g_fs->metadata.lock);
pthread_mutex_destroy(&g_fs->gc_lock);
pthread_cond_destroy(&g_fs->gc_signal);
free(g_fs);
g_fs = NULL;
}
// ============================================================================
// TESTS
// ============================================================================
void test_basic_io() {
log_msg("\n=== Test 1: Basic File I/O ===");
uint32_t file1 = lfs_create_file("config.txt");
uint32_t file2 = lfs_create_file("data.bin");
uint32_t file3 = lfs_create_file("readme.md");
char data1[] = "Configuration settings for the system";
char data2[] = "Binary data chunk";
char data3[] = "# Project Readme\n## Introduction\nThis is a test.";
lfs_write_file(file1, data1, strlen(data1));
lfs_write_file(file2, data2, strlen(data2));
lfs_write_file(file3, data3, strlen(data3));
char buffer[512];
uint32_t size;
lfs_read_file(file1, buffer, &size);
printf(" Read: %.*s\n", size, buffer);
lfs_read_file(file3, buffer, &size);
printf(" Read: %.*s\n", size, buffer);
}
void test_large_writes() {
log_msg("\n=== Test 2: Large Sequential Writes ===");
uint32_t file = lfs_create_file("large.dat");
char data[256 * 1024];
memset(data, 'X', sizeof(data));
for (int i = 0; i < 5; i++) {
lfs_write_file(file, data, sizeof(data));
log_msg(" Wrote chunk %d", i + 1);
usleep(100000);
}
}
void test_gc_pressure() {
log_msg("\n=== Test 3: GC Under Pressure ===");
uint32_t files[20];
for (int i = 0; i < 20; i++) {
char filename[32];
snprintf(filename, sizeof(filename), "file_%02d.dat", i);
files[i] = lfs_create_file(filename);
}
char data[64 * 1024];
memset(data, 'A' + (rand() % 26), sizeof(data));
// Write to files multiple times
for (int round = 0; round < 3; round++) {
for (int i = 0; i < 20; i++) {
lfs_write_file(files[i], data, sizeof(data));
}
log_msg(" Round %d completed", round + 1);
sleep(1);
}
// Delete half the files
for (int i = 0; i < 10; i++) {
lfs_delete_file(files[i]);
}
log_msg(" Deleted 10 files to trigger GC");
sleep(2); // Let GC run
}
void test_concurrent_access() {
log_msg("\n=== Test 4: Concurrent Operations ===");
uint32_t files[10];
for (int i = 0; i < 10; i++) {
char buf[32];
snprintf(buf, sizeof(buf), "concurrent_%d.dat", i);
files[i] = lfs_create_file(buf);
}
char data[8 * 1024];
memset(data, 'C', sizeof(data));
for (int i = 0; i < 10; i++) {
lfs_write_file(files[i], data, sizeof(data));
}
log_msg(" Concurrent writes completed");
}
int main() {
srand((unsigned)time(NULL));
log_msg("╔════════════════════════════════════════════════════════╗");
log_msg("║ Log-Structured File System with Garbage Collection ║");
log_msg("╚════════════════════════════════════════════════════════╝");
// Initialize
if (lfs_init("/tmp/lfs_test.img") != 0) {
fprintf(stderr, "Failed to initialize LFS\n");
return 1;
}
// Start GC thread
if (gc_start() != 0) {
fprintf(stderr, "Failed to start GC thread\n");
return 1;
}
// Run tests
test_basic_io();
sleep(1);
test_large_writes();
sleep(2);
test_gc_pressure();
sleep(2);
test_concurrent_access();
sleep(2);
// Print final statistics
lfs_print_stats();
lfs_print_segments();
// Cleanup
lfs_close();
log_msg("All tests completed successfully");
return 0;
}