Re: [PATCH v3 2/4] mm: huge_memory: refactor anon_enabled_store() with change_anon_orders()

From: Andrew Morton

Date: Sun Mar 08 2026 - 17:05:39 EST


On Sat, 07 Mar 2026 08:08:06 -0800 Breno Leitao <leitao@xxxxxxxxxx> wrote:

> Consolidate the repeated spin_lock/set_bit/clear_bit pattern in
> anon_enabled_store() into a new change_anon_orders() helper that
> loops over an orders[] array, setting the bit for the selected mode
> and clearing the others.
>
> Introduce enum anon_enabled_mode and anon_enabled_mode_strings[]
> for the per-order anon THP setting.
>
> Use sysfs_match_string() with the anon_enabled_mode_strings[] table
> to replace the if/else chain of sysfs_streq() calls.
>
> The helper uses test_and_set_bit()/test_and_clear_bit() to track
> whether the state actually changed, so start_stop_khugepaged() is
> only called when needed. When the mode is unchanged,
> set_recommended_min_free_kbytes() is called directly to preserve
> the watermark recalculation behavior of the original code.
>
> ...

Somme nitlets, feel free to ignore:

> --- a/mm/huge_memory.c
> +++ b/mm/huge_memory.c
> @@ -316,6 +316,20 @@ static ssize_t enabled_show(struct kobject *kobj,
> return sysfs_emit(buf, "%s\n", output);
> }
>
> +enum anon_enabled_mode {
> + ANON_ENABLED_ALWAYS,
> + ANON_ENABLED_MADVISE,
> + ANON_ENABLED_INHERIT,
> + ANON_ENABLED_NEVER,
> +};

If we're feeling fancy we could use

ANON_ENABLED_ALWAYS = 0,
...

here, just to make it clear that we iterate over the enum values with
an integer and we *require* those values.

> +static bool change_anon_orders(int order, enum anon_enabled_mode mode)
> +{
> + static unsigned long *orders[] = {
> + &huge_anon_orders_always,
> + &huge_anon_orders_madvise,
> + &huge_anon_orders_inherit,
> + };
> + bool changed = false;
> + int i;

enum anon_enabled_mode m;

might be clearer here?

> +
> + spin_lock(&huge_anon_orders_lock);
> + for (i = 0; i < ARRAY_SIZE(orders); i++) {
> + if (i == mode)
> + changed |= !test_and_set_bit(order, orders[i]);
> + else
> + changed |= test_and_clear_bit(order, orders[i]);
> + }
> + spin_unlock(&huge_anon_orders_lock);
> +
> + return changed;
> +}