]> git-server-git.apps.pok.os.sepia.ceph.com Git - xfsprogs-dev.git/commitdiff
libxfs: port various kernel apis from 7.0
authorDarrick J. Wong <djwong@kernel.org>
Tue, 3 Mar 2026 18:47:29 +0000 (10:47 -0800)
committerAndrey Albershteyn <aalbersh@kernel.org>
Wed, 8 Apr 2026 19:39:18 +0000 (21:39 +0200)
Port more kernel APIs from Linux as of 7.0.

Signed-off-by: "Darrick J. Wong" <djwong@kernel.org>
Reviewed-by: Christoph Hellwig <hch@lst.de>
include/kmem.h

index 66f8b1fbea8fdfecb3279b8520cdce22ed2b992a..2c276e929c4808e20781fecc90d9d7deab4a3bc8 100644 (file)
@@ -61,6 +61,56 @@ static inline void *kmalloc(size_t size, gfp_t flags)
 #define kzalloc(size, gfp)     kvmalloc((size), (gfp) | __GFP_ZERO)
 #define kvzalloc(size, gfp)    kzalloc((size), (gfp))
 
+/**
+ * kmalloc_array - allocate memory for an array.
+ * @n: number of elements.
+ * @size: element size.
+ * @flags: the type of memory to allocate (see kmalloc).
+ */
+static inline void *kmalloc_array(size_t n, size_t size, gfp_t flags)
+{
+       size_t bytes;
+
+       if (unlikely(check_mul_overflow(n, size, &bytes)))
+               return NULL;
+       return kmalloc(bytes, flags);
+}
+#define kcalloc(n, size, gfp)  kmalloc_array((n), (size), (gfp) | __GFP_ZERO)
+
+/**
+ * size_mul() - Calculate size_t multiplication with saturation at SIZE_MAX
+ * @factor1: first factor
+ * @factor2: second factor
+ *
+ * Returns: calculate @factor1 * @factor2, both promoted to size_t,
+ * with any overflow causing the return value to be SIZE_MAX. The
+ * lvalue must be size_t to avoid implicit type conversion.
+ */
+static inline size_t __must_check size_mul(size_t factor1, size_t factor2)
+{
+       size_t bytes;
+
+       if (check_mul_overflow(factor1, factor2, &bytes))
+               return SIZE_MAX;
+
+       return bytes;
+}
+
+#define __alloc_objs(KMALLOC, GFP, TYPE, COUNT)                                \
+({                                                                     \
+       const size_t __obj_size = size_mul(sizeof(TYPE), COUNT);        \
+       (TYPE *)KMALLOC(__obj_size, GFP);                               \
+})
+
+/* Helper macro to avoid gfp flags if they are the default one */
+#define __default_gfp(a,b,...) b
+#define default_gfp(...) __default_gfp(,##__VA_ARGS__,GFP_KERNEL)
+
+#define kzalloc_obj(P, ...) \
+       __alloc_objs(kzalloc, default_gfp(__VA_ARGS__), typeof(P), 1)
+#define kmalloc_obj(VAR_OR_TYPE, ...) \
+       __alloc_objs(kmalloc, default_gfp(__VA_ARGS__), typeof(VAR_OR_TYPE), 1)
+
 static inline void kfree(const void *ptr)
 {
        free((void *)ptr);