All of lore.kernel.org
 help / color / mirror / Atom feed
From: sashiko-bot@kernel.org
To: "Tao Cui" <cui.tao@linux.dev>
Cc: bpf@vger.kernel.org, tj@kernel.org, hannes@cmpxchg.org, mkoutny@suse.com
Subject: Re: [PATCH v15 1/4] blk-iocost: add BPF struct_ops cost model support
Date: Thu, 03 Dec 2026 15:46:25 +0000	[thread overview]
Message-ID: <sashiko-outbox-248144@kernel.org> (raw)
In-Reply-To: <20261203150338.2625598-2-cui.tao@linux.dev>

Thank you for your contribution! Sashiko AI review found 12 potential
issues to consider:
- [High] blk-iocost: ioc_bpf_reg() drops bdev before unlocking mutex and
  unfreezing q
- [High] blk-iocost: missing single-attach guard on ops->bdev causes
  leak and UAF
- [High] blk-iocost: ioc_rqos_done_bio() clamp breaks wraparound and
  races with resets
- [Medium] blk-iocost: iocg_model_switch_reset() collapses non-debtor
  inuse via last_inuse
- [Medium] blk-iocost: ioc_cost_model_write() resets before freeze and
  model update
- [Medium] blk-iocost: unvalidated ops->name and ignored uops->bdev in
  ioc_bpf_init_member()
- [Medium] blk-iocost: kzalloc() failure in ioc_rqos_exit() skips BPF
  link detach
- [Medium] blk-iocost: ioc_cost_model_prfill() still prints ctrl= for
  BPF models
- [Medium] blk-iocost: ioc_bpf_reg() freezes queue before waiter reset
  and checks
- [Low] blk-iocost: commit message inaccurately claims -EOPNOTSUPP on
  model removal
- [Low] blk-iocost: sparse __rcu mismatches and redundant ifdef in
  prfill/detach
- [Low] blk-iocost: commit message claims bogus -EOPNOTSUPP rejection on
  removal
It also noticed 1 related pre-existing issue this patch does not
introduce:
- [High] blk-iocost: torn 64-bit reads of ioc->params in
  calc_vtime_cost_builtin() [4]
--

commit 8a71f60b071c249d3ca5b8b9aaa88e3dcad5402e
Author: Tao Cui <cuitao@kylinos.cn>

blk-iocost: add BPF struct_ops cost model support

This commit adds BPF struct_ops support (iocost_model_ops) so a BPF
program can price IOs for a block device under blk-iocost and switch
between the attached BPF model and the builtin linear model via
io.cost.model.

> and the model steps down when
> the struct_ops link is deleted or the device is removed, at
> which point the device reverts to the builtin model; a device
> with no attached model rejects removal with -EOPNOTSUPP.

[Severity: Low]
Is the last clause accurate?  Both ioc_rqos_exit() and ioc_bpf_unreg()
return void, and writing "model=bpf" to io.cost.model without an
attached model returns -EINVAL rather than -EOPNOTSUPP.  -EOPNOTSUPP is
only returned by ioc_bpf_reg() for non-link registration, partitions,
or non-mq queues, and by ioc_cost_model_write() for non-mq queues.

> diff --git a/block/blk-iocost.c b/block/blk-iocost.c
> index 0ffe34bd95b73..49622bf69fe35 100644
> --- a/block/blk-iocost.c
> +++ b/block/blk-iocost.c

[ ... ]

> @@ -2599,7 +2725,7 @@ static u64 adjust_inuse_and_calc_cost(struct ioc_gq *iocg, u64 vtime,
>  }
>  
>  static void calc_vtime_cost_builtin(struct bio *bio, struct ioc_gq *iocg,
> -				    bool is_merge, u64 *costp)
> +				    u64 calc_flags, u64 *costp)
>  {
>  	struct ioc *ioc = iocg->ioc;
>  	u64 coef_seqio, coef_randio, coef_page;

[Severity: High]
This problem wasn't introduced by this patch, but on 32-bit
architectures can calc_vtime_cost_builtin() and
calc_size_vtime_cost_builtin() suffer torn 64-bit reads of
ioc->params.lcoefs[] [4]?

Both functions read the u64 coefficients locklessly while a concurrent
io.cost.model write updates them.  On 32-bit systems that split u64
loads into two 32-bit reads, combining halves from old and new values
can produce a huge corrupted cost and stall cgroup I/O.

[ ... ]

> @@ -2923,8 +3139,24 @@ static void ioc_rqos_done_bio(struct rq_qos *rqos, struct bio *bio)
>  {
>  	struct ioc_gq *iocg = blkg_to_iocg(bio->bi_blkg);
>  
> -	if (iocg && bio->bi_iocost_cost)
> -		atomic64_add(bio->bi_iocost_cost, &iocg->done_vtime);
> +	if (iocg && bio->bi_iocost_cost) {
> +		/*
> +		 * A model switch reset re-anchors vtime and done_vtime
> +		 * while bios priced by the old model are still in flight.
> +		 * Their completion would pay the stale cost into done_vtime
> +		 * and can push it past vtime, breaking the (vtime -
> +		 * done_vtime) invariant the accounting relies on until new
> +		 * IO advances vtime again. Clamp the payoff to vtime; the
> +		 * excess is priced by a model that no longer exists and is
> +		 * what the reset drops.
> +		 */
> +		u64 vtime = atomic64_read(&iocg->vtime);
> +		u64 vdone = atomic64_read(&iocg->done_vtime);
> +
> +		atomic64_add(min(bio->bi_iocost_cost,
> +				 vtime - min(vtime, vdone)),
> +			     &iocg->done_vtime);
> +	}
>  }

[Severity: High]
Does this clamp break wraparound and race with
iocg_model_switch_reset()?

Every vtime shift in blk-iocost (including iocg_model_switch_reset())
adds the same delta to both iocg->vtime and iocg->done_vtime, so an
unconditional atomic64_add() already preserves (vtime - done_vtime) mod
2^64 and cannot push done_vtime past vtime.

With unsigned min(vtime, vdone), when vtarget = now.vnow -
ioc->margins.target wraps below 0 near boot (or on 64-bit wraparound),
done_vtime sits near U64_MAX while committed bios advance vtime past 0.
min(vtime, vdone) then returns vtime, making the clamp 0 and dropping
every completion payoff so iocg_is_idle() never returns true and the
cgroup can never deactivate.

It also races with iocg_model_switch_reset() while the queue is
unfrozen:

CPU0                              CPU1
iocg_model_switch_reset()
  atomic64_add(vtarget - vtime,
               &iocg->vtime)
                                  ioc_rqos_done_bio()
                                    reads vtime < vdone
                                    adds 0  <-- payoff dropped
  atomic64_add(vtarget - vtime,
               &iocg->done_vtime)

Two concurrent completions can also observe the same headroom and push
done_vtime past vtime (underflowing vtime - vdone in ioc_timer_fn()),
and the two extra atomic64_read() calls add cacheline traffic to every
bio completion even without BPF.  Dropping the clamp fixes all of
these.

[ ... ]

> @@ -2980,10 +3212,105 @@ static void ioc_rqos_queue_depth_changed(struct rq_qos *rqos)

[ ... ]

> +	if (ioc->attached_link) {
> +		struct bpf_link *link = bpf_link_inc_not_zero(ioc->attached_link);
> +		struct ioc_bpf_detach *d;
> +
> +		/* the closing link detaches through its own path */
> +		if (!IS_ERR_OR_NULL(link)) {
> +			d = kzalloc(sizeof(*d), GFP_NOIO);
> +			if (d) {
> +				d->link = link;
> +				INIT_WORK(&d->work, ioc_bpf_detach_workfn);
> +				queue_work(system_wq, &d->work);
> +			} else {
> +				/*
> +				 * allocation failed: the eject is deferred
> +				 * to the link's close path, which drops
> +				 * the references through .unreg
> +				 */
> +				bpf_link_put(link);
> +			}
> +		}
> +	}

[Severity: Medium]
If kzalloc() fails here, does skipping link->ops->detach() leave a
pinned or polled link stuck indefinitely?

Userspace waiting on poll() for EPOLLHUP or keeping the link pinned in
bpffs will never observe device removal, and ops->bdev will keep the
deleted gendisk and request_queue pinned until the link is manually
destroyed.  Pre-allocating struct ioc_bpf_detach in ioc_bpf_reg() would
make teardown infallible.

[ ... ]

> @@ -3535,14 +3862,37 @@ static u64 ioc_cost_model_prfill(struct seq_file *sf,
>  		return 0;
>  
>  	spin_lock_irq(&ioc->lock);
> -	seq_printf(sf, "%s ctrl=%s model=linear "
> +	seq_printf(sf, "%s ctrl=%s ", dname,
> +		   ioc->user_cost_model ? "user" : "auto");

[Severity: Medium]
As reported by Tejun Heo on RFC v14 [1], should ctrl= be omitted when a
BPF model is selected?  Printing it unconditionally emits "<dev>
ctrl=auto model=bpf name=<name>", which contradicts the documented
format showing only model=bpf and name=.

> +#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
> +	{
> +		const struct iocost_model_ops __rcu *ops;
> +
> +		rcu_read_lock();
> +		ops = rcu_dereference(ioc->bpf_model);
> +		if (ops)
> +			seq_printf(sf, "model=bpf name=%.*s\n",
> +				   (int)sizeof(ops->name), ops->name);
> +		else
> +			seq_printf(sf, "model=linear "

[Severity: Low]
As reported by Tejun Heo on RFC v7 [2], can this use ioc_bpf_model(ioc)
directly instead of the #ifdef block and duplicated linear
seq_printf()?  Declaring local ops as __rcu and dereferencing ops->name
also triggers sparse address-space and noderef warnings; similarly,
ioc_detach_model() compares ioc->bpf_model == ops directly without
rcu_access_pointer() or ioc_bpf_model().

[ ... ]

> @@ -3573,15 +3923,68 @@ static const match_table_t i_lcoef_tokens = {

[ ... ]

> +		/*
> +		 * The payoff paths normally restore inuse when the debt
> +		 * drains; restore it here since the state is dropped
> +		 * wholesale.
> +		 */
> +		propagate_weights(iocg, iocg->active,
> +				  iocg->last_inuse ?: iocg->weight, true, &now);

[Severity: Medium]
Does this collapse inuse to 1 for healthy, debt-free cgroups that
previously paid off debt?

When iocg_pay_debt() restores normal weight after debt drains,
__propagate_weights() saves the pre-update inuse (1) into
iocg->last_inuse.  Unconditionally passing iocg->last_inuse here drops
a non-debtor's inuse back to 1 and starves its I/O share; restoring
from last_inuse should only run when abs_vdebt was non-zero.

[ ... ]

> @@ -3632,35 +4034,72 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,

[ ... ]

> +	/*
> +	 * Reset before freezing: the waiters queued with the old prices
> +	 * are released here, so freezing the queue below no longer waits
> +	 * on them.
> +	 */
> +	if (switch_model) {
> +		spin_lock_irq(&ioc->lock);
> +		iocg_model_switch_reset(ioc);
> +		spin_unlock_irq(&ioc->lock);
> +	}
> +
> +	memflags = blk_mq_freeze_queue(q);
> +	blk_mq_quiesce_queue(q);
> +
> +	spin_lock_irq(&ioc->lock);
>  	if (user) {
>  		memcpy(ioc->params.i_lcoefs, u, sizeof(u));
>  		ioc->user_cost_model = true;
>  	} else {
>  		ioc->user_cost_model = false;
>  	}
> +	if (!(switch_model && old_model))
> +		ioc_bpf_model_set(ioc, model);
>  	ioc_refresh_params(ioc, true);
>  	spin_unlock_irq(&ioc->lock);

[Severity: Medium]
Can old-model debt, delays, and waiters re-accumulate between
iocg_model_switch_reset() and blk_mq_freeze_queue(q)?

On a linear-to-bpf switch, ioc->bpf_model is still NULL during that
gap, so concurrent bio submissions and merges keep pricing under the
linear model, can re-queue waiters (stalling the queue freeze), and
leave linear-priced abs_vdebt and delay intact after the BPF model is
installed.  The same window applies when switching from bpf to linear
with new coefficients before ioc->params.i_lcoefs is updated.  Running
iocg_model_switch_reset() again under ioc->lock after freezing and
updating the model would close this gap.

[ ... ]

> @@ -3703,6 +4142,205 @@ static struct blkcg_policy blkcg_policy_iocost = {

[ ... ]

> +	/* the order of ioc_qos_write() */
> +	memflags = blk_mq_freeze_queue(q);
> +	mutex_lock(&q->rq_qos_mutex);
> +
> +	ret = -ENODEV;
> +	if (!disk_live(bdev->bd_disk))
> +		goto out;
> +
> +	ioc = q_to_ioc(q);
> +	if (!ioc) {
> +		ret = blk_iocost_init(bdev->bd_disk);
> +		if (ret)
> +			goto out;
> +		ioc = q_to_ioc(q);
> +	}
> +
> +	if (ioc->attached) {
> +		ret = -EBUSY;
> +		goto out;
> +	}

[Severity: Medium]
Does freezing the queue here stall both the disk and global BPF
struct_ops operations on old-model waiters?

bpf_struct_ops_link_create() holds the kernel-wide update_mutex across
st_ops->reg(), and bio submitters sleeping on iocg->waitq in
ioc_rqos_throttle() hold q->q_usage_counter.  Calling
blk_mq_freeze_queue(q) before checking disk_live() or ioc->attached and
before releasing waiters via iocg_model_switch_reset() forces the
freeze (and all unrelated struct_ops operations) to wait until
throttled cgroups drain their old-model debt.  Taking q->rq_qos_mutex
first and only freezing when !ioc needs one-time blk_iocost_init()
would avoid this.

[ ... ]

> +	ops->bdev = bdev;
> +	ret = 0;
> +	goto done;

[Severity: High]
As reported by bot+bpf-ci@kernel.org on RFC v7 [3], does overwriting
ops->bdev without guarding against multiple links on the same
struct_ops map leak bdev references and cause a use-after-free?

BPF_F_LINK struct_ops maps remain in BPF_STRUCT_OPS_STATE_READY after
link creation, so userspace can create multiple links sharing the same
kvalue.data (ops).  When a removed disk's dev_t is reused before
ioc_bpf_detach_workfn() runs .unreg():

CPU0 (link1 / disk1)              CPU1 (link2 / disk2, same dev_t)
del_gendisk(disk1)
  ioc_rqos_exit()
    queue_work(detach_workfn)
                                  ioc_bpf_reg(ops, link2)
                                    ioc2->attached = ops
                                    ops->bdev = bdev2  <-- leaks bdev1
ioc_bpf_unreg(ops, link1)
  bdev = ops->bdev (bdev2)
  ioc2->attached_link != link1
  ops->bdev = NULL
  blkdev_put_no_open(bdev2)
                                  ioc_bpf_unreg(ops, link2)
                                    if (!bdev) return  <-- skips detach
                                  frees ops & link2
                                  I/O on disk2 -> ops->calc_cost()
                                    <-- use-after-free

Because bpf_struct_ops_map_link_dealloc() also calls .unreg() without
update_mutex, concurrent link1 close and link2 registration on
different queues race directly on ops->bdev.

> +out:
> +	blkdev_put_no_open(bdev);
> +done:
> +	mutex_unlock(&q->rq_qos_mutex);
> +	blk_mq_unfreeze_queue(q, memflags);
> +	return ret;
> +}

[Severity: High]
Can jumping to out: cause a use-after-free on q by dropping bdev before
unlocking q->rq_qos_mutex and unfreezing the queue?

When a concurrent del_gendisk() and put_disk() trigger the !disk_live()
check, ioc_bpf_reg() can hold the final reference to bdev.
blkdev_put_no_open(bdev) then synchronously runs put_device() ->
disk_release() -> blk_put_queue() -> blk_free_queue(q), which calls
blk_mq_release(q), unregisters the still-held freeze lockdep keys, and
schedules RCU freeing of q while ioc_bpf_reg() is in sleepable context
before mutex_unlock() and blk_mq_unfreeze_queue() touch q.  Unlocking
and unfreezing should happen before blkdev_put_no_open(bdev).

[ ... ]

> +	case offsetof(struct iocost_model_ops, name):
> +		memcpy(ops->name, uops->name, sizeof(ops->name));
> +		return 1;
> +	case offsetof(struct iocost_model_ops, bdev):
> +		/* kernel-owned; the BPF program cannot set it */
> +		ops->bdev = NULL;
> +		return 1;

[Severity: Medium]
Should ops->name be validated before copying it into the key=value
io.cost.model output?

Raw memcpy() allows spaces, newlines, '=', control characters, or an
empty string to be printed verbatim by ioc_cost_model_prfill(),
breaking userspace parsers; other struct_ops users use
bpf_obj_name_cpy() and reject empty names.  Also, returning 1 for bdev
bypasses bpf_struct_ops's non-zero check and silently ignores non-NULL
userspace pointers instead of returning 0 to reject them with -EINVAL.

[1] https://lore.kernel.org/r/e7400e9857d370843a5e9f099ca470fb@kernel.org
[2] https://lore.kernel.org/r/4412563645504aa9a87d3cafd544c97c@kernel.org
[3] https://lore.kernel.org/r/708eecd95cb24c85757f7f217915bfbb2bbd855b8f963a4cc32aa61ad6031034@mail.kernel.org
[4] https://sashiko.dev/#/bug/linux-4c7e36ef-fced-4307-b8b1-5e5dd7a97a5f

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261203150338.2625598-1-cui.tao@linux.dev?part=1

  parent reply	other threads:[~2026-12-03 15:46 UTC|newest]

Thread overview: 13+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-03 15:03 [PATCH v15 0/4] blk-iocost: BPF struct_ops cost model Tao Cui
2026-12-03 15:03 ` [PATCH v15 1/4] blk-iocost: add BPF struct_ops cost model support Tao Cui
2026-12-03 15:44   ` bot+bpf-ci
2026-12-04  9:27     ` Tao Cui
2026-12-03 15:46   ` sashiko-bot [this message]
2026-12-04  9:33     ` Tao Cui
2026-12-03 15:03 ` [PATCH v15 2/4] blk-iocost: add iocost_ioc_tick tracepoint for per-period device summary Tao Cui
2026-12-03 15:03 ` [PATCH v15 3/4] selftests/bpf: add iocost cost model test Tao Cui
2026-12-03 15:32   ` sashiko-bot
2026-12-03 15:33   ` bot+bpf-ci
2026-12-03 15:03 ` [PATCH v15 4/4] docs: cgroup-v2: document the iocost BPF cost model attachment Tao Cui
2026-12-03 15:19   ` sashiko-bot
2026-12-04  9:06 ` [PATCH v15 0/4] blk-iocost: BPF struct_ops cost model Tao Cui

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=sashiko-outbox-248144@kernel.org \
    --to=sashiko-bot@kernel.org \
    --cc=bpf@vger.kernel.org \
    --cc=cui.tao@linux.dev \
    --cc=hannes@cmpxchg.org \
    --cc=mkoutny@suse.com \
    --cc=sashiko-reviews@lists.linux.dev \
    --cc=tj@kernel.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.