From: Chris Mason Installing a mempolicy with MPOL_F_RELATIVE_NODES can trigger a division by zero when racing with memory offlining. I managed to reproduce this in a small VM with excessive set_mempolicy() calls while offlining memory: Oops: divide error: 0000 [#1] SMP RIP: 0010:bitmap_fold+0x43/0x60 Call Trace: ? mpol_relative_nodemask+0x26/0x40 ? mpol_set_nodemask+0x43/0x90 ? do_set_mempolicy+0x5e/0xe0 ? __x64_sys_set_mempolicy+0x6c/0x80 mpol_set_nodemask() intersects current->mems_allowed with N_MEMORY, and mpol_relative_nodemask() folds the user's nodemask modulo the weight of the result. If memory offlining just cleared the task's only allowed node in N_MEMORY, but cpuset did not update mems_allowed yet, the intersection is empty and nodes_fold() divides by zero. do_mbind() and mpol_shared_policy_init() call mpol_set_nodemask() as well. Let's fix it by failing with -EINVAL early if there is no allowed node with memory, just like ->create() would later fail for an empty nodemask. The same division by zero was originally reported by syzkaller for mpol_rebind_mm() [1]. The discussion of Yury's fix attempt [2] also identified this path in mpol_set_nodemask() [3], but only the rebind path got fixed, by commit b983c5642638 ("cgroup/cpuset: rebind mm mempolicy to effective_mems, not mems_allowed"). This has low urgency, as it is extremely unlikely to hit in practice. Fixes: 8fe23e057172 ("mm: clear node in N_HIGH_MEMORY and stop kswapd when all memory is offlined") Cc: stable@vger.kernel.org Reported-by: David Hildenbrand (Arm) Closes: https://lore.kernel.org/all/fe33c767-ea11-43e2-8732-f752c9c1205c@kernel.org/ [3] Link: https://lore.kernel.org/all/CA+0ovCgxbZkXa+OU8w3s84R3KNPNxxRfmsNR-udh+afQBbGNmw@mail.gmail.com/ [1] Link: https://lore.kernel.org/all/20260528190337.878027-1-ynorov@nvidia.com/ [2] Signed-off-by: Chris Mason [ david: update description and comment; add reproduction details ] Signed-off-by: David Hildenbrand (Arm) --- mm/mempolicy.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/mm/mempolicy.c b/mm/mempolicy.c index 1f68a463b3bc7..746fd0a137515 100644 --- a/mm/mempolicy.c +++ b/mm/mempolicy.c @@ -491,9 +491,13 @@ static int mpol_set_nodemask(struct mempolicy *pol, if (!pol || pol->mode == MPOL_LOCAL) return 0; - /* Check N_MEMORY */ - nodes_and(nsc->mask1, - cpuset_current_mems_allowed, node_states[N_MEMORY]); + /* + * If we just offlined the last memory on a node, it might be gone from + * N_MEMORY before cpuset updates mems_allowed. Just fail in that case. + */ + if (!nodes_and(nsc->mask1, + cpuset_current_mems_allowed, node_states[N_MEMORY])) + return -EINVAL; VM_BUG_ON(!nodes); -- 2.56.1