[Ocfs2-tools-devel] [PATCH] discard unused blocks before mkfs

Larry Chen lchen at suse.com
Fri Feb 23 20:14:03 PST 2018


From: Larry <lchen at suse.com>

When using a SSD as a block device, if unused SSD blocks could
be discarded in advance, performance will be improved.

This patch uses ioctl interface to release unused blocks on SSD
layer.

Signed-off-by: Larry Chen <lchen at suse.com>
---
 mkfs.ocfs2/mkfs.c | 44 ++++++++++++++++++++++++++++++++++++++++++++
 mkfs.ocfs2/mkfs.h |  9 +++++++++
 2 files changed, 53 insertions(+)

diff --git a/mkfs.ocfs2/mkfs.c b/mkfs.ocfs2/mkfs.c
index 354b2ee5..e9c8a9fb 100644
--- a/mkfs.ocfs2/mkfs.c
+++ b/mkfs.ocfs2/mkfs.c
@@ -543,6 +543,48 @@ static void finish_normal_format(State *s)
 	ocfs2_close(fs);
 }
 
+static errcode_t _discard_blocks(State *s, uint64_t block,
+		uint64_t count)
+{
+	int ret;
+	uint64_t range[2];
+
+	range[0] = (uint64_t)(block) << s->blocksize_bits;
+	range[1] = (uint64_t)(count) << s->blocksize_bits;
+
+	ret = ioctl(s->fd, BLKDISCARD, &range);
+	if (ret < 0) {
+		if (errno == EOPNOTSUPP && !s->quiet)
+			printf("block discard not supported...skip\n");
+		return errno;
+	}
+	return 0;
+}
+
+static int discard_blocks(State *s)
+{
+	uint64_t blocks = s->volume_size_in_blocks;
+	uint64_t count = DISCARD_STEP_MB;
+	uint64_t cur = 0;
+	int retval = 0;
+
+	count *= (1024 * 1024);
+	count >>= s->blocksize_bits;
+
+	while (cur < blocks) {
+		if (cur + count > blocks)
+			count = blocks - cur;
+
+		retval = _discard_blocks(s, cur, count);
+		if (retval)
+			break;
+		cur += count;
+	}
+
+	return retval;
+}
+
+
 int
 main(int argc, char **argv)
 {
@@ -615,6 +657,8 @@ main(int argc, char **argv)
 		return 0;
 	}
 
+	discard_blocks(s);
+ 
 	clear_both_ends(s);
 
 	init_record(s, &superblock_rec, SFI_OTHER, S_IFREG | 0644);
diff --git a/mkfs.ocfs2/mkfs.h b/mkfs.ocfs2/mkfs.h
index f9ba4dcf..ac9709f3 100644
--- a/mkfs.ocfs2/mkfs.h
+++ b/mkfs.ocfs2/mkfs.h
@@ -41,6 +41,7 @@
 #include <inttypes.h>
 #include <ctype.h>
 #include <assert.h>
+#include <sys/ioctl.h>
 
 #include <uuid/uuid.h>
 
@@ -92,6 +93,14 @@
 
 #define MAX_EXTALLOC_RESERVE_PERCENT	5
 
+#define DISCARD_STEP_MB         2048
+
+#if defined(__linux__) && !defined(BLKDISCARD)
+#define BLKDISCARD		_IO(0x12,119)
+#endif
+
+
+
 enum {
 	SFI_JOURNAL,
 	SFI_CLUSTER,
-- 
2.13.6




More information about the Ocfs2-tools-devel mailing list