Verify offline ext4 recovery with backup superblocks

Verify offline ext4 recovery with backup superblocks

When a directory used for batch processing suddenly fails to mount, repeatedly running repair commands can overwrite evidence needed for recovery. On a dedicated server holding build caches or collected data, a reliable workflow starts by distinguishing device failure from filesystem damage, then preserves a copy, and finally validates the repaired contents. This article reproduces primary ext4 superblock damage in a standalone file image. The entire exercise avoids writing to any production block device.

1. Distinguish checking, repair, and recovery

The superblock stores information such as filesystem size, block size, and filesystem features. Damage to the primary copy can prevent mounting, but finding a backup superblock does not establish that the directory tree and file contents are correct. e2fsck checks structural consistency. Trust in the contents still depends on hashes recorded beforehand, backups, or application-level validation.

Mbps dedicated servers provide two directly attached 1TB NVMe drives, without hardware RAID. The second drive does not automatically contain a copy of your data, and a backup superblock is not a file backup. If a device reports read errors or repeatedly disconnects, prioritize preserving readable data rather than repeatedly attempting repairs on the original drive.

All experiments that write data target only a newly created regular file image. For a production filesystem, stop all access and unmount it first. Handle a root filesystem in a separate recovery environment; do not apply these steps unchanged to a running system.

The following example uses Debian 12 and requires e2fsprogs, util-linux, coreutils, Python 3, and available loop devices. Run the commands in order within the same dedicated root Bash session. Keep at least 2GiB free in the exercise directory, and do not run the exercise on a busy data volume.

2. Create an image with a trusted content baseline

First, create a temporary directory accessible only to the current account. The image uses a fixed block size and block group size to make the backup superblocks easy to demonstrate. These parameters are part of the exercise setup, not formatting recommendations for production.

set -euo pipefail
umask 077
lab=$(mktemp -d /var/tmp/ext4-drill.XXXXXX)
image="$lab/ext4.img"
mkdir "$lab/mnt"
truncate -s 512M "$image"
mkfs.ext4 -F -b 4096 -g 32768 -m 0 "$image"
dumpe2fs "$image" > "$lab/layout.txt" 2> "$lab/layout.stderr"
grep 'Backup superblock' "$lab/layout.txt"
mount -o loop "$image" "$lab/mnt"
printf 'batch-result-v1\n' > "$lab/mnt/payload.bin"
(
  cd "$lab/mnt"
  sha256sum payload.bin
) > "$lab/payload.sha256"
sync
umount "$lab/mnt"
cp --sparse=always "$image" "$lab/baseline.img"

The hash manifest is stored outside the image so that filesystem damage cannot also destroy the reference used for verification. Copying the image only after unmounting gives this exercise a stable baseline. If unmounting reports that the filesystem is busy, first leave the mount directory and investigate open files. Do not force an unmount to continue the exercise.

Record the actual layout instead of guessing backup locations

In this example, the output should include a backup superblock at block 32768. Confirm this value in the layout file you just saved. If it is absent, stop before proceeding and review the formatting output. A production filesystem may have a different block size, different features, and different backup locations; do not reuse this number without verification.

Using mke2fs -n to infer an existing filesystem's layout also has a prerequisite: the creation parameters must match. An estimate based on default parameters is not a record of how the filesystem was originally formatted. Above all, never omit -n when running the creation command against the original device.

3. Inject primary superblock damage and preserve the evidence

The primary ext4 superblock starts at byte offset 1024. The two bytes at offset 56 within it hold the magic number. The following command overwrites only those two bytes in the exercise image. It neither modifies a partition table nor simulates an underlying hardware failure.

python3 - "$image" <<'PY'
import os
import sys

with open(sys.argv[1], "r+b", buffering=0) as stream:
    stream.seek(1024 + 56)
    stream.write(b"\x00\x00")
    os.fsync(stream.fileno())
PY
cp --sparse=always "$image" "$lab/damaged.img"
set +e
e2fsck -fn "$image" > "$lab/check-before.txt" 2>&1
check_rc=$?
set -e
printf 'check_exit=%s\n' "$check_rc"
cat "$lab/check-before.txt"

The -n option checks without making changes and answers no to repair prompts; -f forces a full check. The tool may automatically try backup superblocks, so the fact that it does not exit immediately is not evidence that the primary superblock is intact. Read the log to see how the filesystem was identified and whether a backup was used.

The damaged copy and clean baseline serve different purposes: the former preserves the failure state, while the latter provides a control for the exercise. In production, also record device identifiers, the filesystem UUID, kernel errors, and the original check output. Restrict access to images containing business data; do not casually send them as ordinary support-ticket attachments.

4. Repair with a backup superblock and retain the exit code

Confirm again that the image is not mounted and check the recorded layout before running the repair with an explicit backup block and block size. Automatic approval here is only for a disposable exercise copy. For production repairs, preserve an image first, then review the proposed changes rather than accepting everything by default.

set +e
e2fsck -f -y -b 32768 -B 4096 "$image" \
  > "$lab/repair.txt" 2>&1
repair_rc=$?
set -e
cat "$lab/repair.txt"
printf 'repair_exit=%s\n' "$repair_rc"
case "$repair_rc" in
  0|1) ;;
  *) exit "$repair_rc" ;;
esac
e2fsck -fn "$image" > "$lab/check-after.txt" 2>&1
cat "$lab/check-after.txt"

The e2fsck exit code is a bitmask: 0 means no errors, 1 means errors were corrected, 2 means a reboot is required, 4 means errors remain uncorrected, and 8 means an operational error occurred. This exercise continues only after 0 or 1. Stop and investigate any other result; do not let the script proceed to mounting after a failed repair.

Do not judge success using an unhandled e2fsck ... | tee ... pipeline. A pipeline can affect which exit code is captured. Here, output is redirected to a file and the command status is saved immediately afterward, preventing log output from masking a repair failure. The post-repair check-only run must return 0; otherwise, do not proceed.

5. Read data without writing and validate the contents

Begin recovery with read-only access rather than immediately resuming writes. Even when mounted read-only, ext4 may attempt journal replay; noload prevents that replay. The filesystem in this example has already passed an offline check. This option keeps the image unchanged during validation.

mount -o loop,ro,noload "$image" "$lab/mnt"
findmnt -no SOURCE,FSTYPE,OPTIONS --target "$lab/mnt"
(
  cd "$lab/mnt"
  sha256sum -c "$lab/payload.sha256"
)
cat "$lab/mnt/payload.bin"
umount "$lab/mnt"
printf 'evidence_dir=%s\n' "$lab"

Validation must satisfy all three conditions: the mount options show read-only access, the hash check succeeds, and the file contents match expectations. Being able to list a directory or seeing the same file size is no substitute for content verification. Real workloads also require checks such as record counts, whether artifacts can be unpacked, or a database's own consistency checks.

ro,noload is not a general workaround for damage. An unrepaired, dirty filesystem may expose an inconsistent view of the data. If mounting fails, do not keep changing parameters to force read access. If structural recovery succeeds but the hash does not match, preserve the image and move to backup restoration or further forensic analysis.

After the exercise, retain the layout, pre- and post-repair logs, exit codes, and hash results. Clean up the exercise directory only after confirming that nothing remains mounted. A successful recovery exercise is not merely one that produces a “repair complete” message. It must establish what changed, why the contents can be trusted, and which data still cannot be verified.

Frequently asked questions

Can e2fsck run against an ext4 filesystem mounted read-write?

No. Stop services accessing the filesystem and unmount it first. A root filesystem requires a separate recovery environment. Even a check-only run can produce unreliable results while the filesystem is mounted.

Does successful repair using a backup superblock prove file integrity?

No. e2fsck primarily checks filesystem structures. Extract files read-only, compare them with previously saved hashes, and run application-level checks. Without a trusted baseline, integrity cannot be claimed.

AMD EPYC 7543P Dedicated Server

From $471.8/month

Configure an Mbps Dedicated Server View Mbps rental pricing

Clear paths to configuration and access

Rental pricing lists the hardware and options, while the connection guide explains SSH and RDP access after delivery.