Subject: Re: [PATCH v2] net:qrtr: fix atomic idr allocation in qrtr_port_assign()

From: Du Cheng <[email-masked]>
Date: Sat, 27 Mar 2021 22:25:20 +0800

On Sat, Mar 27, 2021 at 03:12:14PM +0100, Greg Kroah-Hartman wrote:
> Adding the xarray maintainer...
> 
> On Sat, Mar 27, 2021 at 10:07:02PM +0800, Du Cheng wrote:
> > add idr_preload() and idr_preload_end() around idr_alloc_u32(GFP_ATOMIC)
> > due to internal use of per_cpu variables, which requires preemption
> > disabling/enabling.
> > 
> > reported as "BUG: "using smp_processor_id() in preemptible" by syzkaller
> > 
> > Reported-by: [email-masked]
> > Signed-off-by: Du Cheng <[email-masked]>
> > ---
> > changelog
> > v1: change to GFP_KERNEL for idr_alloc_u32() but might sleep
> > v2: revert to GFP_ATOMIC but add preemption disable/enable protection
> > 
> >  net/qrtr/qrtr.c | 6 ++++++
> >  1 file changed, 6 insertions(+)
> > 
> > diff --git a/net/qrtr/qrtr.c b/net/qrtr/qrtr.c
> > index edb6ac17ceca..6361f169490e 100644
> > --- a/net/qrtr/qrtr.c
> > +++ b/net/qrtr/qrtr.c
> > @@ -722,17 +722,23 @@ static int qrtr_port_assign(struct qrtr_sock *ipc, int *port)
> >  	mutex_lock(&qrtr_port_lock);
> >  	if (!*port) {
> >  		min_port = QRTR_MIN_EPH_SOCKET;
> > +		idr_preload(GFP_ATOMIC);
> >  		rc = idr_alloc_u32(&qrtr_ports, ipc, &min_port, QRTR_MAX_EPH_SOCKET, GFP_ATOMIC);
> > +		idr_preload_end();
> 
> This seems "odd" to me.  We are asking idr_alloc_u32() to abide by
> GFP_ATOMIC, so why do we need to "preload" it with the same type of
> allocation?
> 
> Is there something in the idr/radix/xarray code that can't really handle
> GFP_ATOMIC during a "normal" idr allocation that is causing this warning
> to be hit?  Why is this change the "correct" one?
> 
> thanks,
> 
> greg k-h

>From the comment above idr_preload() in lib/radix-tree.c:1460
/**
 * idr_preload - preload for idr_alloc()
 * @gfp_mask: allocation mask to use for preloading
 *
 * Preallocate memory to use for the next call to idr_alloc().  This function
 * returns with preemption disabled.  It will be enabled by idr_preload_end().
 */

idr_alloc is a very simple wrapper around idr_alloc_u32().

On top of radix_tree_node_alloc() which is called by idr_alloc_u32(), there is
this comment at line 244 in the same radix-tree.c
/*
 * This assumes that the caller has performed appropriate preallocation, and
 * that the caller has pinned this thread of control to the current CPU.
 */

Therefore the preload/preload_end are necessary, or at least should have
preemption disabled

Regards,
Du Cheng