Re: [PATCH v2 2/3] sched_ext: Track bits[] storage size in struct scx_cmask

From: Andrea Righi

Date: Mon May 18 2026 - 18:14:01 EST


Hi Tejun,

On Sun, May 17, 2026 at 09:29:30AM -1000, Tejun Heo wrote:
> scx_cmask carries @base and @nr_cids but not the bits[] allocation size, so
> helpers reshaping the active range have no way to check it fits and later
> kfuncs taking caller-provided storage can't validate it.
>
> Add @alloc_words (u64 word count) annotated with __counted_by, and split the
> bit-range API into three helpers:
>
> - SCX_CMASK_DEFINE() / __SCX_CMASK_DEFINE() define an on-stack cmask, the
> latter taking an explicit capacity for oversized storage.
> SCX_CMASK_DEFINE_SHARD() is a thin wrapper that always reserves
> SCX_CID_SHARD_MAX_CPUS bits of storage.
>
> - scx_cmask_init() / __scx_cmask_init() initialize a cmask, with the same
> tight-vs-explicit split.
>
> - scx_cmask_reframe() reshapes the active range without resizing storage.
>
> The BPF mirror (cmask_init / __cmask_init / cmask_reframe) gets the same
> shape.
>
> Add scx_cmask_clear() and scx_cmask_fill() to zero and set the
> active-range bits respectively. scx_cpumask_to_cmask() uses
> scx_cmask_clear(); scx_cmask_init() would otherwise re-write @alloc_words
> on every call.
>
> A later patch uses @alloc_words in scx_cmask_ref_shard() to refuse output
> storage that can't hold the requested shard.
>
> v2: Init per-CPU scx_set_cmask_scratch (was zero-init, emitted empty
> cmasks). Add nr_cids/alloc_cids check in BPF __cmask_init().
> (sashiko AI)
>
> Signed-off-by: Tejun Heo <tj@xxxxxxxxxx>
> ---

...

> +/**
> + * scx_cmask_reframe - Reshape @m's active range without resizing storage
> + * @m: cmask to reframe
> + * @base: new active range base
> + * @nr_cids: new active range length, must fit within @m->alloc_words
> + *
> + * Body bits within the new range become garbage - only the head and tail
> + * words are zeroed to keep the padding invariant.
> + */
> +static inline void scx_cmask_reframe(struct scx_cmask *m, u32 base, u32 nr_cids)
> +{
> + if (WARN_ON_ONCE(SCX_CMASK_NR_WORDS(nr_cids) > m->alloc_words))
> + return;

Considering that:

#define SCX_CMASK_NR_WORDS(nr_cids) (((nr_cids) + 63) / 64 + 1)

If we pass nr_cids == UINT_MAX here, we have:

CMASK_NR_WORDS(UINT_MAX) = (UINT_MAX + 63)/64 + 1 = 62/64 + 1 = 1 (wraps)

Should we simply reject if it's greater than a certain reasonable upper bound?

Thanks,
-Andrea

> +
> + if (nr_cids) {
> + u32 last_word = ((base & 63) + nr_cids - 1) / 64;
> +
> + m->bits[0] = 0;
> + m->bits[last_word] = 0;
> + }
> +
> m->base = base;
> m->nr_cids = nr_cids;
> - memset(m->bits, 0, SCX_CMASK_NR_WORDS(nr_cids) * sizeof(u64));
> }