btrfs-progs: tests: Add test for super block recovery
[platform/upstream/btrfs-progs.git] / tests / fsck-tests / 029-superblock-recovery / test.sh
1 #!/bin/bash
2 # Test that any superblock is correctly detected
3 # and fixed by btrfs rescue
4
5 source "$TOP/tests/common"
6
7 check_prereq btrfs
8 check_prereq mkfs.btrfs
9 check_prereq btrfs-select-super
10
11 setup_root_helper
12
13 rm -f dev1
14 run_check truncate -s 260G dev1
15 loop=$(run_check_stdout $SUDO_HELPER losetup --find --show dev1)
16
17 # Create the test file system.
18 run_check $SUDO_HELPER "$TOP"/mkfs.btrfs -f "$loop"
19
20 function check_corruption {
21         local sb_offset=$1
22         local source_sb=$2
23
24
25         # First we ensure we can mount it successfully
26         run_check $SUDO_HELPER mount $loop "$TEST_MNT"
27         run_check $SUDO_HELPER umount "$TEST_MNT"
28
29         # Now corrupt 1k of the superblock at sb_offset
30         run_check $SUDO_HELPER dd bs=1K count=1 seek=$(($sb_offset + 1)) if=/dev/zero of="$loop"
31
32         #if corrupting one of the sb copies, copy it over the initial superblock
33         if [ ! -z $source_sb ]; then
34                 local shift_val=$((16 << $source_sb * 12 ))
35                 run_check $SUDO_HELPER dd bs=1K count=4 seek=64 skip=$shift_val if="$loop" of="$loop"
36         fi
37
38         run_mustfail "Mounted fs with corrupted superblock" \
39                 $SUDO_HELPER mount $loop "$TEST_MNT"
40
41         # Now run btrfs rescue which should fix the superblock. It uses 2
42         # to signal success of recovery use mayfail to ignore that retval
43         # but still log the output of the command
44         run_mayfail $SUDO_HELPER "$TOP"/btrfs rescue super-recover -yv "$loop"
45         if [ $? != 2 ]; then
46                 _fail "couldn't rescue super"
47         fi
48
49         run_check $SUDO_HELPER mount $loop "$TEST_MNT"
50         run_check $SUDO_HELPER umount "$TEST_MNT"
51 }
52
53 _log "Corrupting first superblock"
54 check_corruption 64
55
56 _log "Corrupting second superblock"
57 check_corruption 65536 1
58
59 _log "Corrupting third superblock"
60 check_corruption 268435456 2
61
62 # Cleanup
63 run_check $SUDO_HELPER losetup -d "$loop"
64 rm -f dev1