Re: [PATCH] treewide: Replace kmalloc with kmalloc_obj for non-scalar types

From: Kees Cook

Date: Mon Feb 23 2026 - 17:25:50 EST


On Mon, Feb 23, 2026 at 08:05:10AM -0800, Guenter Roeck wrote:
> On Fri, Feb 20, 2026 at 11:49:23PM -0800, Kees Cook wrote:
> > This is the result of running the Coccinelle script from
> > scripts/coccinelle/api/kmalloc_objs.cocci. The script is designed to
> > avoid scalar types (which need careful case-by-case checking), and
> > instead replace kmalloc-family calls that allocate struct or union
> > object instances:
> >
> > Single allocations: kmalloc(sizeof(TYPE), ...)
> > are replaced with: kmalloc_obj(TYPE, ...)
> >
> > Array allocations: kmalloc_array(COUNT, sizeof(TYPE), ...)
> > are replaced with: kmalloc_objs(TYPE, COUNT, ...)
> >
> > Flex array allocations: kmalloc(struct_size(PTR, FAM, COUNT), ...)
> > are replaced with: kmalloc_flex(*PTR, FAM, COUNT, ...)
> >
> > (where TYPE may also be *VAR)
> >
> > The resulting allocations no longer return "void *", instead returning
> > "TYPE *".
> >
> > Signed-off-by: Kees Cook <kees@xxxxxxxxxx>
> > ---
> > diff --git a/arch/um/drivers/ubd_kern.c b/arch/um/drivers/ubd_kern.c
> > index 37455e74d314..42f392e6add3 100644
> > --- a/arch/um/drivers/ubd_kern.c
> > +++ b/arch/um/drivers/ubd_kern.c
> > @@ -1069,20 +1069,16 @@ static int __init ubd_init(void)
> > if (register_blkdev(UBD_MAJOR, "ubd"))
> > return -1;
> >
> > - irq_req_buffer = kmalloc_array(UBD_REQ_BUFFER_SIZE,
> > - sizeof(struct io_thread_req *),
> > - GFP_KERNEL
> > - );
> > + irq_req_buffer = kmalloc_objs(struct io_thread_req *,
> > + UBD_REQ_BUFFER_SIZE, GFP_KERNEL);
> > irq_remainder = 0;
> >
> > if (irq_req_buffer == NULL) {
> > printk(KERN_ERR "Failed to initialize ubd buffering\n");
> > return -ENOMEM;
> > }
> > - io_req_buffer = kmalloc_array(UBD_REQ_BUFFER_SIZE,
> > - sizeof(struct io_thread_req *),
> > - GFP_KERNEL
> > - );
> > + io_req_buffer = kmalloc_objs(struct io_thread_req *,
> > + UBD_REQ_BUFFER_SIZE, GFP_KERNEL);
>
> Building um:defconfig ... failed
> --------------
> Error log:
> arch/um/drivers/ubd_kern.c: In function 'ubd_init':
> arch/um/drivers/ubd_kern.c:1072:24: error: assignment to 'struct io_thread_req * (*)[]' from incompatible pointer type 'struct io_thread_req **' [-Wincompatible-pointer-types]
> 1072 | irq_req_buffer = kmalloc_objs(struct io_thread_req *,
> | ^
> arch/um/drivers/ubd_kern.c:1080:23: error: assignment to 'struct io_thread_req * (*)[]' from incompatible pointer type 'struct io_thread_req **' [-Wincompatible-pointer-types]
> 1080 | io_req_buffer = kmalloc_objs(struct io_thread_req *,
>
> Guenter

Proposed solution sent now:
https://lore.kernel.org/all/20260223214341.work.846-kees@xxxxxxxxxx/

--
Kees Cook