loop/001: verify all partitions are removed

loop/001 does not test whether all partitions are removed successfully
during loop device partition scanning. As a result, the regression
introduced by 0da03cab87e6 ("loop: Fix deadlock when calling
blkdev_reread_part()") can not be detected.

The regression will generate below message in dmesg:

[  464.414043] __loop_clr_fd: partition scan of loop0 failed (rc=-22)

and leave orphan partitions like below:

- /dev/loop0p1
- /sys/block/loop0/loop0p1

This patch verifies all partitions are removed by checking if there is
/sys/block/loopX/loopXpY left. The expected number of partitions left is 0.

Signed-off-by: Dongli Zhang <dongli.zhang@oracle.com>
[Omar: check devices and sysfs for both before and after]
Signed-off-by: Omar Sandoval <osandov@fb.com>
diff --git a/tests/loop/001 b/tests/loop/001
index 47f760a..db225f9 100755
--- a/tests/loop/001
+++ b/tests/loop/001
@@ -3,7 +3,8 @@
 # Copyright (C) 2017 Omar Sandoval
 #
 # Test loop device partition scanning. Regression test for commit e02898b42380
-# ("loop: fix LO_FLAGS_PARTSCAN hang").
+# ("loop: fix LO_FLAGS_PARTSCAN hang") and commit 758a58d0bc67 ("loop: set
+# GENHD_FL_NO_PART_SCAN after blkdev_reread_part()").
 
 . tests/loop/rc
 
@@ -14,6 +15,15 @@
 	_have_program parted
 }
 
+find_loop_partition_devices() {
+	lsblk -lno NAME | sed -n "s/^${1}p//p" | sort
+}
+
+find_loop_partition_sysfs() {
+	find "$sysfs/" -mindepth 1 -maxdepth 1 -name "$1"'p*' -printf '%f\n' |
+		sed -n "s/^${1}p//p" | sort
+}
+
 test() {
 	echo "Running ${TEST_NAME}"
 
@@ -23,10 +33,25 @@
 		mkpart primary 0% 50% \
 		mkpart primary 50% 100%
 
+	local loop_device name sysfs
 	loop_device="$(losetup -P -f --show "$TMPDIR/img")"
-	lsblk -ln "$loop_device" | wc -l
+	udevadm settle
+	name="$(basename "$loop_device")"
+	sysfs="/sys/block/$name"
+
+	echo "Partition devices"
+	find_loop_partition_devices "$name"
+	echo "Partition sysfs nodes"
+	find_loop_partition_sysfs "$name"
 
 	losetup -d "$loop_device"
+	udevadm settle
+
+	echo "Partition devices after detach"
+	find_loop_partition_devices "$name"
+	echo "Partition sysfs nodes after detach"
+	find_loop_partition_sysfs "$name"
+
 	rm "$TMPDIR/img"
 	echo "Test complete"
 }
diff --git a/tests/loop/001.out b/tests/loop/001.out
index 75979f0..2c65264 100644
--- a/tests/loop/001.out
+++ b/tests/loop/001.out
@@ -1,3 +1,10 @@
 Running loop/001
-3
+Partition devices
+1
+2
+Partition sysfs nodes
+1
+2
+Partition devices after detach
+Partition sysfs nodes after detach
 Test complete