A Write-Ahead Log (WAL) is a critical component in databases and storage systems to ensure durability, atomicity, and crash recovery. The information stored in a WAL typically includes:
1. Transaction Metadata
Transaction ID: Unique identifier for each transaction to track its lifecycle.
Timestamp/Log Sequence Number (LSN): A sequential identifier (e.g., LSN) to order operations and ensure replay consistency during recovery.
Transaction State: Flags indicating whether the transaction is in progress, committed, or aborted.
2. Data Modifications
Before-Image (Undo Data): The state of the data before the transaction modifies it. Used for rolling back uncommitted transactions (undo).
After-Image (Redo Data): The state of the data after the transaction modifies it. Used to reapply committed transactions during recovery (redo).
Operation Type: The type of operation (e.g., INSERT, UPDATE, DELETE, CHECKPOINT).
3. Log Entry Structure
Each log entry typically includes:
Header:
LSN or timestamp.
Transaction ID.
Page/block identifier (if the log operates at the granularity of disk pages).
Body:
Record type (e.g., BEGIN, COMMIT, ABORT, DATA).
Modified data (row-level or page-level changes).
Checksums for integrity validation.
4. Checkpoint Records
Periodic checkpoint markers to indicate a consistent state of the database. This reduces recovery time by limiting how far back the log must be replayed.
Checkpoints may include:
The current state of active transactions.
The position in the log up to which changes are guaranteed to be on disk.
5. Commit/Abort Markers
Commit Record: Written to the log when a transaction is committed, ensuring durability.
Abort Record: Written if a transaction is explicitly rolled back.
6. System State Changes
Database Configuration Changes: Adjustments to database settings (e.g., schema changes).
Page Allocations: Tracking new pages or blocks added to the database.
Append-Only: Log entries are written sequentially to avoid random I/O.
Durability: Log entries are flushed to stable storage (disk) before the transaction commits.
Atomicity: Uncommitted transactions are rolled back using undo data in the log.
Recovery: On restart, the database replays committed transactions (redo) and undoes uncommitted ones.
Use Cases
Crash Recovery: Rebuild the database state after a failure.
Replication: Stream logs to replicas for synchronization (e.g., in PostgreSQL, MySQL).
Point-in-Time Recovery: Restore the database to a specific moment using historical log entries.
Different databases (e.g., PostgreSQL, MySQL, Oracle) implement WAL with slight variations, but the core principles remain consistent.
User
How WAL is stored on disk?
Assistant
A Write-Ahead Log (WAL) is stored on disk in a structured, append-only manner to ensure durability, performance, and recoverability. Here’s a detailed breakdown of how WAL is typically organized and managed on disk:
1. Log File Segmentation
Append-Only Files:
WAL entries are written sequentially to log files (or segments) to avoid random disk I/O. New entries are added to the end of the current log file.
File Rotation:
When a log file reaches a size limit (e.g., 16 MB in PostgreSQL), a new file is created. This prevents individual files from growing too large and simplifies archival/cleanup.
Example: PostgreSQL uses files like 000000010000000000000001, 000000010000000000000002, etc., where the numeric suffix increments with each segment.
2. On-Disk Structure of Log Entries
Each WAL entry is structured to balance speed, integrity, and recoverability:
Header:
Log Sequence Number (LSN): A unique, monotonically increasing identifier (e.g., 0x000000010000000000000001 in PostgreSQL).
Transaction ID: Links the entry to a specific transaction.
Timestamp: Optional, for time-based recovery.
Checksum/CRC: Validates data integrity (e.g., CRC-32 in PostgreSQL).
Page/Block Identifier: If the log operates at the page/block level (e.g., Page 123).
3. Durability and Flushing
Write-Ahead Guarantee:
Log entries are flushed to diskbefore the corresponding transaction commits. This ensures that even if the system crashes, the log contains all changes needed for recovery.
User
I have a raw device, how can I make a file system on it (I want to bypass OS file system)
Assistant
To create a filesystem on a raw device without relying on the OS's built-in filesystem drivers, you need to manually define and write the filesystem metadata and structures to the device. This is typically done in custom or embedded systems where full control over storage is required. Here's a high-level guide:
1. Understand the Components of a Filesystem
A minimal filesystem requires these core components:
Superblock: Metadata about the filesystem (size, block size, inode count, etc.).
Block Allocation Map: Tracks free/used data blocks (e.g., bitmap or linked list).
Inode Table: Metadata for files/directories (permissions, timestamps, block pointers).
Data Blocks: The actual storage for file contents.
Directory Structure: Maps filenames to inodes.
2. Partition the Device (Optional)
If the device is a disk, create a partition table (e.g., MBR or GPT) to define a region for your filesystem. Use tools like fdisk, parted, or gdisk:
bash
sudo fdisk /dev/sdX # Replace with your device (e.g., /dev/sdb)
Create a single partition (e.g., /dev/sdX1).
3. Design the Filesystem Layout
Decide on parameters:
Block Size: Typically 512B, 1KB, or 4KB.
Total Blocks: (Device Size) / (Block Size).
Inode Size: Usually 128B–256B per inode.
Inode Count: Estimate based on expected files.
For example, a 1MB device with 512B blocks has 2048 blocks. Reserve the first block for the superblock.
4. Write the Superblock
The superblock is critical metadata. Define it as a struct (example in C-like pseudocode):
c
struct Superblock {
uint32 magic; // Identifier (e.g., 0xDEADBEAF)
uint32 block_size; // 512, 1024, etc.
uint32 total_blocks; // Total blocks in filesystem
uint32 inode_count; // Total inodes
uint32 inode_table_start; // Block number of inode table
// ... other fields (free blocks, root directory inode, etc.)
};
User
Where should we store the metadata?
Assistant
In a custom filesystem, metadata must be stored in consistent, well-defined locations so the system can locate and parse it. Here’s where to store key metadata components:
1. Superblock: The Root of Metadata
Location: The first block of the filesystem (offset 0).
This is a universal convention (used in ext2, ext3, etc.) to ensure the system can always find critical metadata.
Purpose:
Defines the filesystem’s layout (block size, total blocks, inode count).
Points to the location of other metadata (e.g., inode table, block bitmaps).
Example:
A superblock might store:
c
struct Superblock {
uint32 magic; // Identifier (e.g., 0xDEADBEAF)
uint32 block_size; // 512B, 1KB, etc.
uint32 total_blocks; // Total blocks in the filesystem
uint32 inode_count; // Total inodes
uint32 inode_table_start; // Block number of the inode table
uint32 block_bitmap_start; // Block number of the block allocation bitmap
// ... other fields (e.g., root directory inode number)
};
2. Inode Table: File/Directory Metadata
Location: A contiguous range of blocks reserved for inodes.
The starting block is defined in the superblock (e.g., inode_table_start = 1).
Structure:
Inodes are typically fixed-size (e.g., 128B–256B) and stored sequentially.
Example: If each inode is 128B and the table starts at block 1 (512B block size), inode #0 is at offset 1*512 + 0*128, inode #1 at 1*512 + 1*128, etc.
Purpose:
Each inode stores metadata for a file/directory (permissions, size, block pointers, timestamps).
3. Block Allocation Metadata (Bitmaps/Free Lists)
Location: A dedicated block (or blocks) for tracking free/used data blocks.
The starting block is defined in the superblock (e.g., block_bitmap_start = 2).
OS-Level Flushing:
Databases use system calls like fsync (Linux) or FlushFileBuffers (Windows) to bypass the OS cache and force writes to physical storage.
Example: PostgreSQL’s wal_buffers parameter controls how much WAL data is held in memory before flushing.
4. Checkpoints
Checkpoint Records:
Periodically, the database writes a checkpoint entry to the WAL. This marks a point where all prior changes are guaranteed to be on disk in the main data files (e.g., tables/indexes).
Purpose: Limits recovery time by allowing the system to start replay from the last checkpoint instead of the beginning of the log.
Content: Includes metadata like the LSN of the checkpoint and the transaction ID up to which changes are persisted.
5. Log File Management
Archiving:
Completed log segments are archived (e.g., for point-in-time recovery).
Example: PostgreSQL’s archive_command copies logs to a backup location.
Truncation/Recycling:
Once a log segment is no longer needed (after a checkpoint and backup), it is either:
Deleted (if backups exist).
Reused (WAL files are often preallocated and reused in a circular fashion).
6. Example: PostgreSQL WAL Storage
File Location:
WAL files are stored in pg_wal/ (or pg_xlog/ in older versions).
Path: /var/lib/postgresql/14/main/pg_wal/
File Naming:
Files are named with 24-digit hex numbers (e.g., 000000010000000000000001), where the first 8 digits represent the timeline ID.
Checkpoints:
Triggers log file rotation and updates the pg_control file to track the latest checkpoint LSN.
7. Key Optimizations
Batch Writes:
Log entries are grouped into blocks (e.g., 8 KB) to minimize I/O operations.
Shared Log Buffers:
In-memory buffers (e.g., wal_buffers in PostgreSQL) hold WAL entries before flushing to disk.
Parallelism:
High-end databases (e.g., Oracle) may split logs into multiple files for concurrent writes.
Visual Summary
code
Disk Structure:
├── pg_wal/ (PostgreSQL) or ib_logfile* (MySQL InnoDB)
│ ├── 000000010000000000000001 (Segment 1)
│ ├── 000000010000000000000002 (Segment 2)
│ └── ... (rotated as needed)
└── Checkpoint Record:
[LSN: 0x1234, TX_ID: 567, State: All changes up to LSN 0x1234 are on disk]
Performance: Avoids random writes to the main data files.
Scalability: Log segmentation and preallocation reduce filesystem overhead.
Different databases (PostgreSQL, MySQL, Oracle) implement WAL with slight variations, but the core principles of append-only storage, checksums, and checkpointing are universal.
Write it to the first block (offset 0):
bash
# Write a 512B superblock to /dev/sdX1
sudo dd if=superblock.bin of=/dev/sdX1 bs=512 count=1
5. Create the Inode Table
Design an inode structure (example):
c
struct Inode {
uint32 mode; // Permissions (e.g., 0x8000 for directory)
uint32 size; // File size in bytes
uint32 block_pointers[12]; // Direct block pointers
// ... indirect blocks, timestamps, etc.
};
Write inodes to reserved blocks (e.g., block 1 for the inode table).
6. Implement Block Allocation
Use a bitmap to track free/used blocks. For example:
A 2048-block filesystem needs a 2048-bit (256B) bitmap.
Store the bitmap in a known block (e.g., block 2).
Initialize the bitmap to mark reserved blocks (superblock, inode table) as used.
7. Define Root Directory
Create a root directory inode (e.g., inode #2).
Link filenames to inodes in the directory data block(s).
8. Write Data to the Device
Use dd or a custom tool to write data blocks. For example:
bash
# Write a file's data to block 5
echo "Hello World" | sudo dd of=/dev/sdX1 bs=512 seek=5 count=1
9. Custom Software to Interact with the Filesystem
Since the OS doesn’t recognize your filesystem, you’ll need to write code to:
Alternatives: If possible, use a lightweight existing filesystem (e.g., ext2, FAT) and disable the OS’s auto-mounting.
Let me know if you need help with a specific step!
Types:
Bitmap: A bit array where each bit represents a block (1 = used, 0 = free).
Example: For 2048 blocks, a 2048-bit (256B) bitmap stored in block 2.
Free List: A linked list of free blocks (less common, used in older filesystems).
Purpose:
Quickly find free blocks to allocate for new files.
4. Directory Entries: Filename-to-Inode Mapping
Location: Stored in data blocks allocated to directories.
Directories are treated as special files (with their own inodes) that contain directory entries.
Structure:
Each entry maps a filename to an inode number. For example:
c
struct DirectoryEntry {
uint32 inode_num; // Inode number of the file/directory
char filename[32]; // Null-terminated filename (e.g., "file.txt")
};
Organization:
Directories are hierarchical (e.g., the root directory is referenced by the superblock’s root_inode field).
5. Journaling Metadata (Optional)
If the filesystem supports journaling (for crash recovery):
Location: A dedicated journal area (e.g., a set of blocks).
The journal’s location is defined in the superblock.
Content:
Log entries for pending transactions (e.g., "about to write block 5").
Example Layout for a 1MB Filesystem (512B Blocks)
Block #
Content
0
Superblock
1
Inode Table (starts at block 1)
2
Block Allocation Bitmap
3–1023
Data Blocks (files/directories)
Key Takeaway
Metadata is stored in fixed, well-known locations (starting with the superblock) so the system can bootstrap and parse the filesystem. The superblock acts as the "map" to locate all other metadata. Consistency is critical—if the superblock is corrupted, the filesystem may become unreadable.