]> www.infradead.org Git - users/sagi/nvme-cli.git/commitdiff
nvme: introduce alloc helper with alignment support
authorDaniel Wagner <dwagner@suse.de>
Thu, 14 Sep 2023 08:53:20 +0000 (10:53 +0200)
committerDaniel Wagner <wagi@monom.org>
Wed, 20 Sep 2023 10:04:25 +0000 (12:04 +0200)
The kernel supports since v5.2 direct mapped DMA buffers to userspace.
Up to this point a bounce buffer was involved. Because the buffers are
now directly accessed by the device, the rules of alignment also apply
for the payloads.

Introduce a helper to allocate all correctly buffers aligned.

Furthermore, ensure that the buffer is a multiple of 4k, because there
are devices on the market which will always transfer a multiple of 4k,
even if we ask for less, e.g 512 bytes. This avoid stack smashes.

Signed-off-by: Daniel Wagner <dwagner@suse.de>
nvme.c

diff --git a/nvme.c b/nvme.c
index 354c6dad89bd30671a5e69bc78a52262061f9901..e26666b04dc02612341df49628ebe2cf27169111 100644 (file)
--- a/nvme.c
+++ b/nvme.c
@@ -183,7 +183,20 @@ static const char space[51] = {[0 ... 49] = ' ', '\0'};
 
 static void *mmap_registers(nvme_root_t r, struct nvme_dev *dev);
 
-static void *__nvme_alloc(size_t len, bool *huge)
+#define ROUND_UP(N, S) ((((N) + (S) - 1) / (S)) * (S))
+
+static void *nvme_alloc(size_t len)
+{
+       size_t _len = ROUND_UP(len, 0x1000);
+       void *p;
+
+       if (posix_memalign((void *)&p, getpagesize(), _len))
+               return NULL;
+
+       memset(p, 0, _len);
+       return p;
+}
+
 static void *__nvme_alloc_huge(size_t len, bool *huge)
 {
        void *p;