How to Recover Files from a Corrupted UFS Filesystem on FreeBSD

How to Recover Files from a Corrupted UFS Filesystem on FreeBSD

Introduction

File system corruption can occur due to various reasons including power failures, hardware issues, improper shutdowns, or software bugs. When a UFS (Unix File System) filesystem becomes corrupted on a FreeBSD system, it can be a stressful situation, especially if the affected drive contains critical data. Fortunately, FreeBSD provides several built-in tools and techniques to recover files from a corrupted UFS filesystem.

This article provides a comprehensive guide on how to diagnose, repair, and recover files from a corrupted UFS filesystem on FreeBSD. We’ll cover everything from initial diagnosis to advanced recovery techniques, ensuring you have the best chance of salvaging your important data.

Understanding UFS Filesystem Corruption

Before diving into recovery procedures, it’s important to understand what filesystem corruption means in the context of UFS. The UFS filesystem, which has been the default in FreeBSD for many years, maintains several critical structures:

  • Superblock: Contains essential metadata about the filesystem
  • Cylinder groups: Organize the disk into manageable segments
  • Inodes: Store file metadata, including permissions and location information
  • Directory entries: Map filenames to their corresponding inodes

Corruption can affect any of these structures, resulting in various symptoms:

  • Inability to mount the filesystem
  • Read/write errors
  • Missing or inaccessible files
  • System crashes when accessing certain directories
  • Unexpected behavior during filesystem operations

Preliminary Steps Before Recovery

Before attempting any recovery, follow these important preliminary steps:

1. Stop Using the Affected Filesystem

The moment you suspect filesystem corruption, cease all operations on the affected drive. Continued use can worsen the damage and potentially overwrite recoverable data.

2. Create a Disk Image (If Possible)

If the hardware is still functional, consider creating a bit-by-bit copy of the affected disk using dd:

# Replace ada1 with your device name
dd if=/dev/ada1 of=/path/to/backup/disk.img bs=1M status=progress

Working with a copy ensures that recovery attempts don’t further damage the original data.

3. Document the Current State

Note any error messages, symptoms, and recent events that might have contributed to the corruption. This information can help diagnose the issue and determine the best recovery approach.

Basic Recovery Using fsck

FreeBSD’s fsck (File System Check) utility is the first line of defense against UFS corruption. It can detect and repair many common filesystem issues.

Running fsck in Read-Only Mode

Start with a non-destructive scan to assess the damage:

fsck -n /dev/devicename

This command will scan the filesystem and report issues without making any changes. Review the output to understand the extent of corruption.

Repairing the Filesystem

If fsck detects correctable errors, run it in repair mode:

fsck -y /dev/devicename

The -y flag automatically confirms all repair suggestions, which is generally safe for most corruption scenarios.

Handling Severe Corruption with Alternative Superblocks

If the primary superblock is corrupted, fsck can use backup superblocks. UFS maintains backup superblocks at various offsets, typically at:

  • 32
  • 8192
  • 16384
  • 24576
  • And additional offsets calculated as: (n × 8192)

To use an alternative superblock:

fsck -b 32 /dev/devicename

Try different backup superblock locations if the first attempt fails.

Mounting a Recovered Filesystem

After running fsck, attempt to mount the filesystem in read-only mode:

mount -o ro /dev/devicename /mnt

If successful, copy important files to a separate, healthy filesystem:

cp -R /mnt/important_data /path/to/backup/location

Advanced Recovery Techniques

When basic methods fail, several advanced techniques can be employed:

Using UFS Debug Tools

FreeBSD provides specialized debugging tools for UFS:

dumpfs /dev/devicename > dumpfs_output.txt

This command outputs detailed information about the filesystem structure, which can be valuable for manual recovery efforts or when seeking expert help.

Recovery with ffsinfo

The ffsinfo utility provides detailed information about UFS filesystems:

ffsinfo -g /dev/devicename

This displays cylinder group information, which can be useful in advanced recovery scenarios.

Using debugfs for Manual Recovery

For granular control over recovery, FreeBSD offers debugfs. While not user-friendly, it allows direct access to filesystem structures:

debugfs -w /dev/devicename

This opens an interactive session where you can execute commands to examine and potentially recover files. Common commands include:

  • ls: List directory contents
  • cd: Change directories
  • stat: Display inode information
  • cat: Output file contents
  • cp: Copy a file from the filesystem to a recovery location

Data Carving with Photorec

When filesystem structures are too damaged for traditional recovery, data carving tools like Photorec (part of the TestDisk suite) can recover files based on their signatures rather than filesystem metadata:

# Install TestDisk package
pkg install testdisk

# Run Photorec
photorec /dev/devicename

Photorec can recover many common file types even when the filesystem structure is severely damaged.

Salvaging Individual Files

Sometimes you may need to recover specific critical files rather than the entire filesystem.

Using grep to Find File Fragments

If you know unique content within a file, you can search for it directly on the device:

grep -a "unique string" /dev/devicename > found_fragments.txt

Recovery Using File Signatures

Many file types begin with specific byte sequences (magic numbers). Tools like foremost can scan a device for these signatures:

# Install foremost
pkg install foremost

# Run recovery
foremost -i /dev/devicename -o /path/to/recovery/directory

Specialized Scenarios

Recovering from a Failed Drive

If the drive is failing, prioritize creating an image of the entire device using dd_rescue or ddrescue, which are designed to work with failing media:

# Install gddrescue
pkg install gddrescue

# Create an image with best effort for bad sectors
ddrescue /dev/devicename disk_image.img ddrescue.log

Once you have an image, perform recovery operations on the image rather than the failing device.

Recovering from Snapshot Backups

If you’ve enabled UFS snapshots, you might be able to recover files from a previous snapshot:

# List available snapshots
ls /.snap

# Access files from a snapshot
cp /.snap/daily.0/path/to/file /recovery/location

Recovering Encrypted Filesystems

For GELI-encrypted UFS filesystems, you’ll need to attach the encrypted device before recovery:

geli attach /dev/devicename
fsck -y /dev/devicename.eli
mount -o ro /dev/devicename.eli /mnt

Prevention Strategies

After successful recovery, implement these strategies to prevent future data loss:

  1. Regular Backups: Maintain up-to-date backups using tools like dump, rsync, or ZFS snapshots
  2. Enable Journaling: Use soft-updates journaling (SU+J) for new UFS filesystems
  3. UPS Protection: Use an uninterruptible power supply to prevent corruption from power failures
  4. Regular Filesystem Checks: Schedule periodic fsck runs during system maintenance
  5. Consider ZFS: For critical data, consider migrating to ZFS, which offers advanced data protection features
  6. Monitor SMART Statistics: Use smartctl to monitor drive health and replace drives showing signs of failure

When to Seek Professional Help

If your recovery attempts are unsuccessful and the data is valuable, consider professional data recovery services. Signs that professional help may be needed include:

  • Physical drive damage (clicking or other unusual noises)
  • Multiple failed recovery attempts
  • Critical business or personal data at stake
  • Complex RAID or encrypted filesystem setups

Conclusion

Recovering files from a corrupted UFS filesystem on FreeBSD requires a methodical approach. Start with the least invasive methods like fsck before progressing to more advanced techniques. Throughout the recovery process, prioritize creating backups and avoid actions that might cause further damage.

While FreeBSD provides robust tools for filesystem recovery, the best defense against data loss remains a comprehensive backup strategy. Regular backups, combined with filesystem monitoring and proper shutdown procedures, can significantly reduce the risk of permanent data loss due to filesystem corruption.

By following the techniques outlined in this guide, you’ll be well-equipped to handle UFS filesystem corruption and maximize your chances of successful data recovery.