From: Darrick J. Wong Date: Tue, 3 Mar 2026 18:47:29 +0000 (-0800) Subject: libxfs: port various kernel apis from 7.0 X-Git-Tag: v7.0.0~98 X-Git-Url: http://git-server-git.apps.pok.os.sepia.ceph.com/?a=commitdiff_plain;h=1b8bca4e0bd192588be341f591f8d450d490f4e5;p=xfsprogs-dev.git libxfs: port various kernel apis from 7.0 Port more kernel APIs from Linux as of 7.0. Signed-off-by: "Darrick J. Wong" Reviewed-by: Christoph Hellwig --- diff --git a/include/kmem.h b/include/kmem.h index 66f8b1fb..2c276e92 100644 --- a/include/kmem.h +++ b/include/kmem.h @@ -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);