Linux XFS Corruption: Safe Repair Guide Without Data Loss
When a Linux kernel throws an XFS filesystem error, the operating system immediately acts to defend data consistency. Storage drivers encounter sudden I/O aborts, kernel panics populate /var/log/messages, or the kernel abruptly forces a mount into read-only mode with messages like XFS: Metadata corruption detected at xfs_inode_buf_verify or XFS: I/O Error detected. Shutting down filesystem.
Because XFS is an enterprise-grade 64-bit journaling filesystem designed for high parallel throughput across independent Allocation Groups (AGs), corruption in metadata B-trees or stale journal records requires precise handling. Running aggressive repair commands blindly—particularly passing -L without a sector-level clone—can permanently strip out uncommitted file allocations.
This guide details a production-tested disaster recovery runbook. You will learn how to isolate corrupted block devices, extract diagnostic metadata clones with xfs_metadump, perform dry-run assessments with xfs_repair -n, safely clear dirty transaction logs, and mount degraded filesystems cleanly.
If your host suffered a broader partition table collapse or damaged partition headers before the filesystem layer, cross-reference our diagnostic walkthrough on recovering Linux corrupted superblock and partition headers.
Anatomy of XFS Corruption: Allocation Groups and Journal State
Unlike ext4 which maintains centralized block allocation bitmaps, XFS divides each storage device into independent Allocation Groups (AGs), typically between 4 and 128 depending on drive geometry.
Figure 1: Safe non-destructive recovery workflow: isolation, metadata dump, dry-run replay, and controlled repair.
Each Allocation Group contains its own:
- Primary Superblock: Sector 0 of the AG holding filesystem geometry.
- Free Space B-trees (
bnoandcnt): Tracking available block counts and block offsets. - Inode B-trees (
inobtandfinobt): Tracking allocated and free inode numbers. - Reverse Mapping B-trees (
rmapbt): Used in modern XFS (kernel ≥ 4.8) for physical-to-logical block tracing.
In addition to AG metadata, XFS maintains a dedicated write-ahead journal (log). In 90% of sudden power outages or SAN disconnects, the filesystem is not physically destroyed; rather, the transaction log contains uncommitted metadata operations that failed to sync to disk before power dropped.
When Linux re-mounts an XFS volume, it automatically reads the journal and replays pending log records into the AG B-trees. Corruption occurs when a physical hardware sector inside the log becomes unreadable, when underlying storage controllers flush cache out-of-order, or when kernel memory faults write garbage into an allocation pointer.
Diagnostic Matrix: Identifying XFS Failure Modes
Before unmounting or running repair binaries, capture the active failure signature from the kernel ring buffer.
| Kernel Error Pattern | Root Cause | Safety Tier | First Step |
|---|---|---|---|
XFS: Metadata corruption detected at ... | Damaged B-tree pointer or invalid magic number | High Risk | Unmount device; freeze write queues |
XFS: Log checkpoint failed (err -5) | Storage disconnect / underlying I/O error | Critical | Check dmesg, physical cables, and SMART |
Structure needs cleaning (errno 117) | Filesystem flagged dirty; mount refused | Moderate | Dry-run xfs_repair -n |
Filesystem has duplicate UUID | Cloning LVM volume or raw snapshot onto same host | Safe | Mount with -o nouuid |
XFS: Mounting read-only | Defensive kernel shutdown after write fault | High Risk | Inspect dmesg -T |
Execute these commands to extract the specific failing device and allocation group:
dmesg -T | grep -E -i "xfs|corrupt|error|allocation" | tail -n 25
Identify the exact mount point and block device:
findmnt -t xfs
lsblk -o NAME,FSTYPE,SIZE,MOUNTPOINT,UUID
The Non-Destructive Recovery Protocol
Follow these sequential steps in strict order. Skipping directly to write repairs is the primary cause of unrecoverable data loss in enterprise outages.
+-------------------------------------------------------------+
| THE SAFE XFS REPAIR PIPELINE |
| |
| [Failing Storage] |
| | |
| v |
| Phase 1: Emergency Unmount & Write-Locking |
| | |
| v |
| Phase 2: Metadata Extraction (xfs_metadump) |
| | |
| v |
| Phase 3: Dry-Run Assessment (xfs_repair -n) |
| | |
| v |
| Phase 4: Read-Only Dirty Log Mount (-o ro,norecovery) |
| | |
| v |
| Phase 5: Definitive xfs_repair (with or without -L) |
+-------------------------------------------------------------+
Phase 1: Immediate Isolation and Write-Locking
If the filesystem is mounted read-write or in degraded read-only mode, immediately sever active processes to prevent cascade corruption.
Step 1: Terminate Accessing Processes
Identify and kill processes holding open file handles on the target mount (e.g., /mnt/data):
fuser -km /mnt/data
# or using lsof
lsof +D /mnt/data
Step 2: Unmount the Block Device
Unmount the volume cleanly:
umount /mnt/data
If the kernel refuses to release the filesystem due to stuck I/O operations, use lazy unmount as a temporary fallback, but avoid running repairs until the block layer is completely idle:
umount -l /mnt/data
Phase 2: Metadata Capture via xfs_metadump
Before running any utility that alters on-disk bits, extract an XFS metadata dump. xfs_metadump copies all superblocks, B-trees, directory indexes, and inode attributes to a single compact file while omitting file contents. A 10TB storage volume often yields a metadata dump under 2GB.
This file allows you to replicate the corruption in a non-destructive testing environment (such as a loopback device) or share it with storage vendors without exposing sensitive business data.
# -a: capture all superblocks, -o: disable obfuscation (preserves directory names)
xfs_metadump -a -o /dev/mapper/vg_data-lv_storage /backup/vg_data_meta.dump
Compress the dump immediately:
pigz -c /backup/vg_data_meta.dump > /backup/vg_data_meta.dump.gz
Safety Warning: If you have adequate backup storage, create a full raw block copy with
ddrescuebefore performing physical writes:ddrescue -b 4096 -v /dev/mapper/vg_data-lv_storage /backup/raw_disk.img /backup/ddrescue.log
Phase 3: Non-Destructive Dry-Run (xfs_repair -n)
The -n flag directs xfs_repair to scan the filesystem geometry, check allocation B-trees, evaluate inode maps, and print errors without writing a single bit to disk.
xfs_repair -n /dev/mapper/vg_data-lv_storage
Analyze the terminal output:
- Phase 1 (Superblock Verification): Checks primary and secondary superblocks.
- Phase 2 (Log Check): Scans the internal or external log. Look for:
ERROR: The filesystem has valuable metadata changes in a log which needs to be replayed. - Phase 3 (Inode Scan): Validates directory structures and root inodes.
- Phase 4-7 (Allocation & Free Space B-trees): Verifies block reference consistency.
If xfs_repair -n terminates with clean return codes or reports that only the dirty log needs replay, proceed to Phase 4.
Phase 4: Mounting with ro,norecovery for Data Extraction
If xfs_repair indicates that critical log records are unplayed, do not wipe the log yet. Instead, attempt to mount the filesystem in read-only mode while explicitly suppressing journal replay.
This allows you to verify file availability and copy vital databases or configuration files to safety before any destructive repair operations.
mkdir -p /mnt/recovery_target
mount -o ro,norecovery /dev/mapper/vg_data-lv_storage /mnt/recovery_target
Verify whether your files are readable:
ls -la /mnt/recovery_target
rsync -avP --dry-run /mnt/recovery_target/critical_app /backup/emergency_restore/
If the mount succeeds, pull your high-priority data off the disk immediately:
rsync -aHAXxv /mnt/recovery_target/critical_app/ /backup/emergency_restore/
Once data is secured, unmount the recovery mount:
umount /mnt/recovery_target
Phase 5: Executing Definitive xfs_repair
Now perform the actual filesystem repair.
Scenario A: Standard Repair (No Log Zeroing)
Run xfs_repair without -L:
xfs_repair /dev/mapper/vg_data-lv_storage
If the repair tool reports:
Phase 2 - using internal log
- zero log...
- scan filesystem freespace and inode maps...
Phase 7 - verify and correct link counts...
done
The repair succeeded cleanly. Re-mount the device read-write:
mount /dev/mapper/vg_data-lv_storage /mnt/data
touch /mnt/data/.health_check && rm /mnt/data/.health_check
Scenario B: The -L Flag (Force Log Zeroing)
If the log contains corrupted sectors that the kernel cannot replay, xfs_repair exits with:
The filesystem has valuable metadata changes in a log which needs to be replayed. Mount the filesystem to replay the log, and unmount it before re-running xfs_repair. If you are unable to mount the filesystem, then use the -L option to destroy the log and attempt a repair.
+-------------------------------------------------------+
| CAUTION: WHAT THE -L (LOG ZEROING) FLAG ACTUALLY DOES |
| |
| 1. Erases all pending write-ahead transactions |
| 2. Any file written within the last 5-30 seconds |
| prior to the crash will lose its metadata |
| 3. Incomplete directory links are dumped into |
| /lost+found/ |
| 4. Superblocks and AG headers are forcibly synced |
+-------------------------------------------------------+
If mounting with mount -o ro or standard mount fails to replay the log, and you have completed the metadata dump in Phase 2, execute the forced repair:
xfs_repair -L /dev/mapper/vg_data-lv_storage
Review the output carefully:
- Note the quantity of cleared inodes.
- Check if directories were unlinked and moved to
lost+found.
Once completed, mount the repaired filesystem:
mount /dev/mapper/vg_data-lv_storage /mnt/data
Check the lost+found directory:
ls -la /mnt/data/lost+found
Use file command to identify raw recovered inodes:
file /mnt/data/lost+found/*
Verifying Repaired XFS Volumes: Health Checklist
Confirm that the storage pool and filesystem are stable before returning the host to production service:
- Test Inode Creation and Block Allocation:
dd if=/dev/urandom of=/mnt/data/test_write.img bs=1M count=100 status=progress sync rm /mnt/data/test_write.img - Review Disk Free Space & Inode Ratios:
df -hT /mnt/data df -i /mnt/data - Verify Superblock Integrity Across Allocation Groups:
Use
xfs_dbin read-only mode to verify geometry across secondary superblocks:xfs_db -r -c "sb 0" -c "p" /dev/mapper/vg_data-lv_storage | grep -E "blocklog|inopblock|agcount" xfs_db -r -c "sb 1" -c "p" /dev/mapper/vg_data-lv_storage | grep -E "blocklog|inopblock|agcount" - Check Underlying Physical Drive Health:
Filesystem corruption is frequently an early warning of physical drive or SAN controller failure. Run:
smartctl -H /dev/sdX smartctl -l error /dev/sdX
Related Runbooks
Implementation Checklist
- Replicate the steps in a controlled lab before production changes.
- Document configs, versions, and rollback steps.
- Set monitoring + alerts for the components you changed.
- Review access permissions and least-privilege policies.
Official References
Need a Hand?
If you want this implemented safely in production, I can help with assessment, execution, and hardening.
Contact MeDeploy on Cloud Infrastructure with $200 Free Credit
Spin up high-performance SSD cloud Droplets, managed Kubernetes, and databases in seconds. Test your containers and production workloads with $200 in free credits.
Transparency: We independently test and operate all recommended infrastructure. If you use our partner links, you receive free promotional credits and support our testing lab at zero extra cost to you.
Weekly Production DevOps Runbooks
Join 1,000+ infrastructure engineers receiving real-world Linux troubleshooting, Proxmox clustering setups, and Docker optimization runbooks every Tuesday. Zero spam, unsubscribe anytime.
About the Author
Kamandanu Wijaya
IT Infrastructure & Network Administrator
Infrastructure & network administrator with 15+ years of enterprise experience, focused on stability, security, and automation.
Certifications: Google IT Support, Cisco Networking Academy, DevOps.
Proxmox Backup Server: Fix Full Disk and Garbage Collection
Next →Docker Compose Secrets: Production Hardening Guide
Need IT Solutions?
DoWithSudo is ready to help setup servers, VPS, and your security systems.
Contact Us