btrfs-progs: do sysfs detection of device discard capability

The detection of the discard status of a device is done by issuing a
real discard request but on an empty range. This works in most cases.
However there's a case of a VirtualBox driver that returns 'Operation
not supported' in that case, and then discard is skipped during mkfs.

The other tools like fstrim check the sysfs queue file
discard_granularity which is the recommended way. Do that as well.

Issue: #390
Signed-off-by: David Sterba <dsterba@suse.com>
This commit is contained in:
David Sterba 2021-09-27 18:22:38 +02:00
parent 6887a3192f
commit c50c448518

View file

@ -53,6 +53,25 @@ static int discard_range(int fd, u64 start, u64 len)
return 0;
}
static int discard_supported(const char *device)
{
int ret;
char buf[128] = {};
ret = device_get_queue_param(device, "discard_granularity", buf, sizeof(buf));
if (ret == 0) {
pr_verbose(3, "cannot read discard_granularity for %s\n", device);
return 0;
} else {
if (buf[0] == '0' && buf[1] == 0) {
pr_verbose(3, "%s: discard_granularity %s\n", device, buf);
return 0;
}
}
return 1;
}
/*
* Discard blocks in the given range in 1G chunks, the process is interruptible
*/
@ -242,7 +261,7 @@ int btrfs_prepare_device(int fd, const char *file, u64 *block_count_ret,
* is not necessary for the mkfs functionality but just an
* optimization.
*/
if (discard_range(fd, 0, 0) == 0) {
if (discard_supported(file)) {
if (opflags & PREP_DEVICE_VERBOSE)
printf("Performing full device TRIM %s (%s) ...\n",
file, pretty_size(block_count));