[PATCH] mkfs: add discard support

Christoph Hellwig
2009-10-06T18:46:33Z

Call the BLKDISCARD ioctl to mark the whole disk as unused before creating
a new filesystem. This will allow SSDs, Arrays with thin provisioning support
and virtual machines to make smarter allocation decisions.

Signed-off-by: Christoph Hellwig <hch@lst.de>

Index: xfsprogs-dev/mkfs/xfs_mkfs.c
===================================================================
--- xfsprogs-dev.orig/mkfs/xfs_mkfs.c 2009-10-06 18:02:34.000000000 +0000
+++ xfsprogs-dev/mkfs/xfs_mkfs.c 2009-10-06 18:03:55.000000000 +0000
@@ -605,6 +605,29 @@ done:
free(buf);
}

+#ifdef __linux__
+
+#ifndef BLKDISCARD
+#define BLKDISCARD _IO(0x12,119)
+#endif
+
+static void
+discard_blocks(dev_t dev, __uint64_t nsectors)
+{
+ int fd = libxfs_device_to_fd(dev);
+ __uint64_t range[2] = { 0, nsectors << 9 };
+
+ /*
+ * We intentionally ignore errors from the discard ioctl. It is
+ * not nessecary for the mkfs functionality but just an optimization.
+ */
+ if (fd > 0)
+ ioctl(fd, BLKDISCARD, &range);
+}
+#else
+#define discard_blocks(dev, nsectors)
+#endif
+
int
main(
int argc,
@@ -1645,6 +1668,12 @@ main(
}
}

+ discard_blocks(xi.ddev, xi.dsize);
+ if (xi.rtdev)
+ discard_blocks(xi.rtdev, xi.rtsize);
+ if (xi.logdev && xi.logdev != xi.ddev)
+ discard_blocks(xi.logdev, xi.logBBsize);
+
if (!liflag && !ldflag)
loginternal = xi.logdev == 0;
if (xi.logname)