Re: [PATCH 1/3] lib/maple_tree: fix potential NULL dereference in mas_pop_node()
From: Josh Law
Date: Fri Mar 13 2026 - 12:14:09 EST
13 Mar 2026 09:05:37 Pedro Falcato <pfalcato@xxxxxxx>:
> On Fri, Mar 13, 2026 at 07:17:17AM +0000, Josh Law wrote:
>> 12 Mar 2026 23:22:48 Pedro Falcato <pfalcato@xxxxxxx>:
>>
>>> On Thu, Mar 12, 2026 at 01:45:31PM -0700, Andrew Morton wrote:
>>>> On Thu, 12 Mar 2026 18:40:53 +0000 Josh Law <hlcj1234567@xxxxxxxxx> wrote:
>>>>
>>>>> If kmem_cache_alloc_from_sheaf() returns NULL (possible under
>>>>> GFP_NOWAIT pressure), mas_pop_node() falls through to the out label
>>>>> and dereferences the NULL pointer in memset(ret, 0, sizeof(*ret)).
>>>>
>>>> This is such a glaring bug that I wonder if we're missing something.
>>>
>>> According to my local copy of lib/maple_tree.c:
>>>
>>> mas_pop_node() - Get a previously allocated maple node from the maple state.
>>>
>>> Note the "previously" :) kmem_cache_alloc_from_sheaf() can only fail if you
>>> run out of objects in the sheaf.
>>>
>>> So yeah, this "bug" looks bogus.
>>>
>>> --
>>> Pedro
>>
>> Hi Pedro,
>>
>> I see the comment regarding 'previously allocated' nodes. However,
>> mas_pop_node() explicitly calls kmem_cache_alloc_from_sheaf() with
>> GFP_NOWAIT. If there is any path—even an unexpected one—where the
>> sheaf is exhausted or the allocator fails, the code immediately
>> performs a memset on the NULL pointer.
>
> And? This does not happen, simply. If it does, your maple tree is hosed
> and, really, you're not recovering from it.
>
>>
>> Even if this is a 'should never happen' scenario, returning NULL is
>> safer than a kernel panic. As Andrew noted, the current structure
>> allows a fall-through directly into a dereference. My patch ensures
>> we handle that edge case safely.
>
> ... and now because none of the mas_pop_node() callers ever checks for NULL
> (why would they, they preallocated those same nodes before), you safely
> dereference NULL away from mas_pop_node!.
>
> --
> Pedro
Hi Pedro,
I see your point regarding the invariants of the sheaf. If the
pre-allocation logic is guaranteed, then a NULL return here implies
a fundamental corruption of the maple state.
My concern was primarily the 'fall-through' structure which makes the
dereference look accidental rather than intentional. However, if
the callers aren't prepared to handle a NULL return anyway, simply
returning NULL doesn't solve the underlying panic.
I'll take this as a lesson in understanding function invariants
before jumping to defensive checks. Thanks for the technical
explanation.
V/R
Josh law