On Mon Jan 5, 2026 at 9:56 AM UTC, David Gow wrote:
On Wed, 24 Dec 2025 at 00:18, Brendan Jackman jackmanb@google.com wrote:
lib/kunit/user_alloc.c currently uses kthread_use_mm() without a corresponding kthread_unuse_mm(). This is a bug, but fixing it in KUnit makes writing tests that use mms more difficult, because of KUnit's resource/try-catch model.
Therefore, introduce a new operation that does what kunit_attach_mm() wants, namely an unbalanced call with cleanup deferred to kthread_exit().
This is actually just the same as kthread_use_mm() but without taking a reference on the mm_struct.
While adding this, clarify the reference returned by mm_alloc(), since that is what kthread_take_mm() is gonna be paired with, in practice.
Signed-off-by: Brendan Jackman jackmanb@google.com
This makes some sense to me from the KUnit side, though it'd probably be nicer to have a way of actually triggering kunit_unuse_mm() at the right spot. I'm not sure if we'll want to have tests spawn additional threads sharing the same mm in the future, too, which this shouldn't make impossible, particularly if we have a requirement that those threads don't outlast the original test thread.
Otherwise, Is there a reason we can't mmdrop() from another kthread instead of trying to kthread_unuse_mm()? I wouldn't be surprised (it doesn't _seem_ right), but seems to work here.
No I think this works and it's actually how I originally wrote the patch.
However I think it's very messy, it depends very heavily on the implementation of kthread_use_mm(), i.e. it is saying "I assume that everything in kthread_use_mm() gets undone by kthread_exit(), except that there's exactly one mmdrop() missing". This seems like a natural conclusion when you've just spent half an hour staring at kthread.c and drawing up a stupid little ASCII diagram to try and drill this godforsaken refcount API into your head... But once you step away from this patchset I think it would look completely bonkers. Here I'm looking for a way to actually solve this with a proper API.
On the other hand, I'm now adding a weird special kthread API just to solve this one little problem in KUnit, which people might reasonably object to.
So yeah I probably should have laid out some other options in the cover letter. The ones I can obviously see are:
1. The current proposal.
2. Just call mmdrop() from the other kthread and spray comments everywhere to try and make it make sense.
3. Find a way to call kthread_unuse_mm() before the kthread dies, with some sort of magic in the kunit_try_catch logic. But presumably to make that all work with faulting tests etc is gonna mean more special APIs, probably worse than kthread_take_mm(). (I did not explore this very carefully so it's possible this is easier than I guess).