[PATCH] iio: buffer: kfifo: reject lengths exceeding the kmalloc limit

From: YuanZhe Liu

Date: Fri Nov 20 2026 - 08:23:57 EST


__iio_allocate_kfifo() rejects lengths that would overflow an unsigned
int after kfifo rounds them up to the next power of two, but the byte
size handed to __kfifo_alloc() can still be beyond what kmalloc() can
serve.

The kfifo buffer is allocated with kmalloc(), which is limited to
KMALLOC_MAX_SIZE. A larger request has an allocation order above
MAX_PAGE_ORDER, so the page allocator's order sanity check fires and
enabling the buffer ends with a WARNING instead of a clean error.

The buffer length is set through buffer/length, which accepts any value
up to UINT_MAX. With the voltage and timestamp scan channels enabled,
a length of 262349 makes the rounded up size exceed KMALLOC_MAX_SIZE
and triggers the warning on buffer/enable.

Also reject lengths whose rounded up size does not fit into
KMALLOC_MAX_SIZE, so that enabling the buffer fails with -EINVAL.

Co-developed-by: Bin Yu <byu@xxxxxxxxxxxxx>
Signed-off-by: Bin Yu <byu@xxxxxxxxxxxxx>
Co-developed-by: Cheng Wen <wencheng@xxxxxxxxxxxxx>
Signed-off-by: Cheng Wen <wencheng@xxxxxxxxxxxxx>
Signed-off-by: YuanZhe Liu <25031212351@xxxxxxxxxxxxxxxxx>
---
drivers/iio/buffer/kfifo_buf.c | 9 +++++++++
1 file changed, 9 insertions(+)

diff --git a/drivers/iio/buffer/kfifo_buf.c b/drivers/iio/buffer/kfifo_buf.c
index b67ea6468226..2069d7ca4409 100644
--- a/drivers/iio/buffer/kfifo_buf.c
+++ b/drivers/iio/buffer/kfifo_buf.c
@@ -35,6 +35,15 @@ static inline int __iio_allocate_kfifo(struct iio_kfifo *buf,
if (roundup_pow_of_two(length) > UINT_MAX / bytes_per_datum)
return -EINVAL;

+ /*
+ * The kfifo memory is allocated with kmalloc(), so the size must also
+ * fit into the largest allocation kmalloc() can serve. Larger
+ * requests need an order above MAX_PAGE_ORDER and are refused by the
+ * page allocator with a warning.
+ */
+ if (roundup_pow_of_two(length) > KMALLOC_MAX_SIZE / bytes_per_datum)
+ return -EINVAL;
+
return __kfifo_alloc((struct __kfifo *)&buf->kf, length,
bytes_per_datum, GFP_KERNEL);
}
--
2.34.1