How do I recover files from ext4 with "discarded blocks" and rewritten superblock
Solution 1:
The resizing procedure you found seems very strange: blindly creating a new superblock on top of the old one is risky even if everything else about the filesystem remains the same, but seems incredibly unlikely to actually work if the filesystem's dimensions have changed – the new superblock will be expecting to find inodes and block groups at a completely different location; what it thinks is the "/" inode is probably some garbage data miles away from the real inode.
(Even the manual page notes about -S
that "This is an extreme measure to be taken only in the very unlikely case that all [superblocks] are corrupted" and "there is no guarantee that any data will be salvageable".)
The correct procedure would've been to use the resize2fs
program, which has been included in the same package as mkfs.ext4 and fsck.ext4 for more than two decades; it resizes and relocates the filesystem structures as necessary.
At this point, however, do not try to resize2fs a damaged filesystem or do anything else to it – instead run testdisk
on it to scrape as many files as it can still find. Testdisk works pretty much like the program that you tried to write, only deals with more formats (not just zip).
However, if you have enough disk space to make an image of the damaged filesystem, you could try resizing the partition back to exactly its original size and using mkfs -S once more. (Do it on an image – after making the backup image!) This could actually end up with a superblock that has the same parameters as the original one, and hopefully point at the original data structures if those haven't been damaged yet.