Re: [PATCH v4] rust: alloc: add per-task memalloc scope abstractions
From: Gary Guo
Date: Wed Nov 25 2026 - 14:28:00 EST
On Wed Nov 25, 2026 at 7:10 PM GMT, Andreas Hindborg wrote:
> Add an abstraction for the per-task allocation policies exposed by
> the kernel through paired save/restore helpers in `linux/sched/mm.h`:
> `memalloc_noio`, `memalloc_nofs`, `memalloc_noreclaim` and
> `memalloc_pin`. Each pair wraps `memalloc_flags_save` and
> `memalloc_flags_restore`. The save call sets bits in `current->flags`
> and returns the bits it added, which the restore call clears again. The
> pairing assumes strict LIFO nesting; restoring out of order corrupts
> the per-task state.
>
> Expose each policy as a variant of the `ScopeFlag` enum, with
> `ScopeFlags` as the corresponding set type, both generated by
> `impl_flags!`. Add `alloc_scope`, which applies a set of policies, runs
> a closure and restores the previous policies before returning. The save
> and restore operations are not exposed on their own, so safe code
> cannot leave a scope open or restore out of order.
>
> Signed-off-by: Andreas Hindborg <a.hindborg@xxxxxxxxxx>
Reviewed-by: Gary Guo <gary@xxxxxxxxxxx>
> ---
> Changes in v4:
> - Replace the `ScopeKind` trait and its tag types with an `alloc_scope()`
> function taking `ScopeFlags` built with `impl_flags!` (Gary).
> - Replace the per-policy C helpers with a single `memalloc_flags_save()`
> and `memalloc_flags_restore()` helper pair.
> - Do not expose a safe/restore functions public (Sashiko).
> - Mark `alloc_scope()` as `#[inline]` (Sashiko).
> - Link to v3: https://msgid.link/20261109-gfp-noio-v3-1-a573e7be9c44@xxxxxxxxxx
>
> Changes in v3:
> - Rebase on v7.4-rc1.
> - Replace the pinned `Scope` guard and `memalloc_scope!` macro with a
> closure-based `ScopeKind::with` entry point (Alice, Gary).
> - Make the doctests compile and run under KUnit instead of `ignore`.
> - Document that `NoReclaim` has no effect in hard interrupt context.
> - Link to v2: https://msgid.link/20260605-gfp-noio-v2-1-cfa2e236c2a3@xxxxxxxxxx
>
> Changes in v2:
> - Rewrite the patch to use scoped allocation flags instead of exposing
> a `GFP_NOIO` flag constant.
> - Link to v1: https://lore.kernel.org/r/20260128-gfp-noio-v1-1-9a808fc49b44@xxxxxxxxxx
> ---
> rust/bindings/bindings_helper.h | 1 +
> rust/helpers/mm.c | 10 +++
> rust/kernel/alloc.rs | 1 +
> rust/kernel/alloc/scoped.rs | 134 ++++++++++++++++++++++++++++++++++++++++
> 4 files changed, 146 insertions(+)