[PATCH] sched, cpumask: don't leak impossible cpus via for_each_cpu_wrap().

From: Neel Natu
Date: Tue Aug 02 2022 - 17:41:15 EST


The value of 'nr_cpumask_bits' is dependent on CONFIG_CPUMASK_OFFSTACK.
This in turn can change the set of cpus visited by for_each_cpu_wrap()
with a mask that has bits set in the range [nr_cpu_ids, NR_CPUS).

Specifically on !CONFIG_CPUMASK_OFFSTACK kernels the API can iterate
over cpus outside the 'cpu_possible_mask'.

Fix this to make its behavior match for_each_cpu() which always limits
the iteration to the range [0, nr_cpu_ids).

Signed-off-by: Neel Natu <neelnatu@xxxxxxxxxx>
---
include/linux/cpumask.h | 2 +-
lib/cpumask.c | 4 ++--
2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/include/linux/cpumask.h b/include/linux/cpumask.h
index fe29ac7cc469..2a308cfc43da 100644
--- a/include/linux/cpumask.h
+++ b/include/linux/cpumask.h
@@ -303,7 +303,7 @@ extern int cpumask_next_wrap(int n, const struct cpumask *mask, int start, bool
*/
#define for_each_cpu_wrap(cpu, mask, start) \
for ((cpu) = cpumask_next_wrap((start)-1, (mask), (start), false); \
- (cpu) < nr_cpumask_bits; \
+ (cpu) < nr_cpu_ids; \
(cpu) = cpumask_next_wrap((cpu), (mask), (start), true))

/**
diff --git a/lib/cpumask.c b/lib/cpumask.c
index a971a82d2f43..d47937fb49eb 100644
--- a/lib/cpumask.c
+++ b/lib/cpumask.c
@@ -82,9 +82,9 @@ int cpumask_next_wrap(int n, const struct cpumask *mask, int start, bool wrap)
next = cpumask_next(n, mask);

if (wrap && n < start && next >= start) {
- return nr_cpumask_bits;
+ return nr_cpu_ids;

- } else if (next >= nr_cpumask_bits) {
+ } else if (next >= nr_cpu_ids) {
wrap = true;
n = -1;
goto again;
--
2.37.1.455.g008518b4e5-goog