]> www.infradead.org Git - users/sagi/nvme-cli.git/commitdiff
nvme: Introduce nvme_realloc function
authorBrandon Paupore <brandon.paupore@wdc.com>
Fri, 22 Sep 2023 19:55:32 +0000 (14:55 -0500)
committerDaniel Wagner <wagi@monom.org>
Mon, 25 Sep 2023 08:57:34 +0000 (10:57 +0200)
This attempts to preserve the functionality of realloc while also
ensuring the final memory is aligned.

Signed-off-by: Brandon Paupore <brandon.paupore@wdc.com>
nvme.c

diff --git a/nvme.c b/nvme.c
index 0085ae7553dc7fd948654ca5213d7184c4a716bb..1e4422e0f6efd66d83d8e80b90bf26172a60913d 100644 (file)
--- a/nvme.c
+++ b/nvme.c
@@ -69,6 +69,7 @@
 #include "fabrics.h"
 #define CREATE_CMD
 #include "nvme-builtin.h"
+#include "malloc.h"
 
 struct feat_cfg {
        enum nvme_features_id feature_id;
@@ -198,6 +199,20 @@ static void *nvme_alloc(size_t len)
        return p;
 }
 
+void *nvme_realloc(void *p, size_t len)
+{
+       size_t old_len = malloc_usable_size(p);
+
+       void *result = nvme_alloc(len);
+
+       if (p) {
+               memcpy(result, p, min(old_len, len));
+               free(p);
+       }
+
+       return result;
+}
+
 static void *__nvme_alloc_huge(size_t len, bool *huge)
 {
        void *p;
@@ -249,6 +264,21 @@ void *nvme_alloc_huge(size_t len, bool *huge)
 }
 #endif
 
+void *nvme_realloc_huge(void *p, size_t len, bool *huge)
+{
+       size_t old_len = malloc_usable_size(p);
+       bool was_huge = *huge;
+
+       void *result = nvme_alloc_huge(len, huge);
+
+       if (p) {
+               memcpy(result, p, min(old_len, len));
+               nvme_free_huge(p, was_huge);
+       }
+
+       return result;
+}
+
 const char *nvme_strerror(int errnum)
 {
        if (errnum >= ENVME_CONNECT_RESOLVE)