blk-iocost: add BPF struct_ops cost model support
Subsystems (8)
v9 cover blk-iocost: add BPF struct_ops cost model support
From: Tao Cui <[email protected]>
This is v9 of the RFC. A BPF program can now take over the cost model of one device: attaching an iocost_model_ops struct_ops creates the ioc if needed and switches the device to the model, io.cost.model selects between the attached and the builtin model, and detaching or device removal restores the builtin one. The attachment, the cgroup callback pairing and the removal paths are serialized with what blkg creation and destruction actually use.
Why a pluggable model at all
----------------------------
When iocost landed in 2019, its commit message already promised that "a later patch will also allow using bpf progs for cost models", and the code has carried the split for it ever since: calc_vtime_cost() is a dispatcher whose only implementation is calc_vtime_cost_builtin(). Seven years later the builtin linear model is still the only one. This series fills that slot: builtin algorithms remain the default while new ones can be prototyped in BPF.
The measured problems
---------------------
The builtin model prices each IO with a binary sequential/random base picked by a single per-cgroup cursor and a 16MB seek threshold, plus a per-page cost. On a virtio-blk device with the HDD autop profile, a 4k IO costs ~24us when judged sequential and ~2.7ms when judged random, a 112x spread, so a wrong judgement becomes a wrong price. Three classes of mispricing, all measured:
1. Heuristic rigidity. Two legitimate sequential readers in one cgroup (a database with multiple tablespaces, a threaded backup) ping-pong the single cursor and are all priced random: a measured 89x overcharge collapses throughput under the same weight. Random IO within a hot window smaller than the 16MB threshold is priced sequential: measured 107x undercharge, an accounting escape for hotspot workloads. No setting of the six builtin parameters seems able to fix this: telling the streams apart requires per-IO state tracking, which looks like logic rather than coefficients.
2. Device nonlinearity. SLC-cache phases, SMR band placement and shared controllers (multiple NVMe namespaces multiplexing one device) make the real cost of an identical IO vary by an order of magnitude over time or across namespaces. A static 6-parameter linear model has no way to express that.
3. Unpriced operations. Flush and zone append fall through to a cost of zero and bypass throttling entirely, and the same pattern extends to device quirks the builtin model was never taught.
Mispricing feeds directly into the control loop: vtime budgets, surplus donation and the vrate feedback all consume the model's output, so a wrong model can skew the whole controller.
How
---
Attachment follows the hid_bpf_ops model: the target device is set in the dev member of the struct_ops from userspace before load; the device is looked up with blkdev_get_no_open() and disk_live() is checked under rq_qos_mutex, like blkg_conf_open_bdev(). Attaching creates the ioc if needed, like an io.cost.model write does, and switches the model under the same freeze and quiesce those writes go through; enabling stays with io.cost.qos and wbt stays with it too. When the disk goes away, the model is ejected completely.
Attachment is independent of the model selection and of the controller state: while a model is attached, "model" selects between it and the builtin model - "model=bpf" switches to the attached model, "model=linear" switches back to the builtin model, and neither detaches the struct_ops; only detaching removes the model, after which "model=bpf" fails. "ctrl" keeps describing the builtin coefficients, which are kept while the BPF model is in use and take effect again when switched back. Enabling and disabling the controller, and with it the wbt handover, remains with io.cost.qos.
A bound model in use owns pricing for every charged IO on the
device: it is called from the bio charging path and prices every operation including flushes. The completion-time request sizing which feeds the latency met/missed accounting uses the transfer cost coefficients the struct_ops carries (vtime per page for reads and writes), so the builtin latency tracking and vrate adjustment follow the model's pricing while it is in use; extending the model to the QoS side itself is left for a later interface.
The cgroup callbacks are bound to the iocg policy lifetime and pair
up: iocg_init() is delivered to every cgroup which already has a blkg on the device when the model is attached, and to each one appearing afterwards; iocg_free() is delivered to the cgroups which still exist when the model is detached. The existing iocgs are walked over q->blkg_list under q->blkcg_mutex, the same walk the blkcg policy teardown uses; cgroups without a blkg on the device yet are not missed, as their callbacks are delivered at blkg creation and destruction.
u64 calc_cost(struct bio *bio, u64 model_flags)
The model reads whatever it needs from the bio itself: the operation flags (the operation must be extracted with a mask, and the REQ_* flag bits, including PREFLUSH/FUA, are part of it), the size, the start sector and the issuing cgroup through bio->bi_blkg. model_flags carries iocost-specific metadata which is not a property of the bio, such as whether the cost calculation is for a merged request; the return value is vtime, clamped to 1 second of device time per IO. Per-cgroup state can be stored in BPF_MAP_TYPE_CGRP_STORAGE keyed by the cgroup of bi_blkg; it follows the cgroup lifetime. Sleepable models are rejected at verification, since calc_cost() runs under RCU read lock.
Patch overview:
1/4: the BPF struct_ops cost model support: Kconfig, ops
definition, per-device attachment, unified dispatch and verifier checks
2/4: selftests with two example models (the full builtin linear
HDD formula at double cost, and a multi-stream sequentiality model) plus a runner and the selftest kernel config entries
3/4: add an iocost_ioc_tick tracepoint emitting the per-period
controller state, so model quality can be evaluated without drgn (existing events are state-change driven and silent in steady state)
4/4: document the attachment in cgroup-v2.rst
Does it work
------------
Mechanism, verified functionally on a virtio-blk device (HDD profile, sequential-read workload from a 1%-weight cgroup, builtin vs the 2x example model):
- per-IO charge: 2882us -> 5722us, a factor of 1.985x; the completed IO count halves and total cost.usage is conserved, i.e. the model output drives both charging and budgeting
- attachment: model=bpf readback while in use (ctrl keeps describing the builtin coefficients), EBUSY for a second model on the same device, a second device attaches an independent model, "model=linear"/"model=bpf" switch between the attached model and the builtin without detaching, detaching removes the model and "model=bpf" fails afterwards
- edge cases: writing an unknown device fails and nothing is applied; the selftest runner checks the write error and errno of every step, including the restoration
Workload-shape verification (same setup, 4k IOs at weight 1000, builtin vs the 2x example model):
- flush-heavy workload (read/write/fsync alternating): priced 1.99x the builtin, i.e. flushes no longer reset the cursor and misjudge the following IO as random
- non-page-multiple IO (6 KiB): priced ~2x, matching the builtin's truncating page count
- first IO from a high LBA (past 16 MiB): priced 2.01x, i.e. a fresh cgroup's zero cursor no longer misjudges the first IO as random
Payoff, demonstrated with the multi-stream example model (2/4) on the same setup, 4k IOs at weight 1000, builtin vs the model:
- two sequential readers in one cgroup: priced 1961us/op by builtin (both judged random by the single cursor) and 23us/op by the model (each stream keeps its own slot); the completed IO count rises by two orders of magnitude
- random IO inside an 8M window: priced 24us/op by builtin (undercharge, an accounting escape) and 2607us/op by the model
- single-stream sequential and whole-disk random pricing are unchanged, so the model fixes both directions of mispricing without introducing a new one
Non-interference, measured on enterprise NVMe: no measurable overhead when the BPF model is not attached.
Changes in v9:
- the attach holds rq_qos_mutex from the disk_live() check through the unfreeze, like an io.cost.model write does, instead of releasing it between creating the ioc and switching the model; the queue reference, the second q_to_ioc() and the lockless traversal it needed are gone
- the attachment is published, cleared and the blkg list is walked under blkcg_mutex and queue_lock: blkg creation runs ioc_pd_init() and adds to q->blkg_list under queue_lock only, so the previous blkcg_mutex-only serialization could double-deliver iocg_init() or deliver iocg_free() without iocg_init(). The init walk now goes parents first, like blkcg_activate_policy()
- the device removal ejection reads ops->bdev before clearing ops->q:
once q is NULL .unreg returns without a lock and the map can be freed, so touching ops afterwards was a use-after-free window. The ejection moved to an ioc_bpf_eject() helper
- .unreg only detaches when the closing link is the one which owns the attachment, so a map re-attached to a new device through a newer link is not torn down by an old link; the v8 ops->q re-entry guard at .reg is gone, a second attach of an attached map now fails with -EBUSY like any other model would
- the ioc->attached and ioc->model pointers are unconditional and blk_get_queue_rcu() is declared in block/blk.h without an export, which drops the local prototypes and the remaining #ifdefs
- the unused struct_ops .init name lookup, the bdev/q cases in .init_member (the core already rejects nonzero non-function members it does not claim) and the unused write_cost_model() buffers are gone; the -EOPNOTSUPP selftest paths call test__skip()
- the selftest writes the dev member through the skeleton's typed struct_ops access instead of assuming it is the first member, and the maps are ".struct_ops.link" so closing the fd detaches; the example model's seek judgement is gated on a non-zero IO size so a dataless flush is priced sequentially, and write_cost_model() returns the negated errno ASSERT_ERR() expects
- the tick tracepoint's running field reports the active iocg list instead of ioc->running, which has not transitioned to IOC_IDLE at the emit point, so the final tick reads active=0 running=0
- the attach and detach take the queue freeze before rq_qos_mutex, like ioc_qos_write() does; taking the mutex around the freeze instead formed a lockdep cycle with the io.cost.qos write path, and .unreg's link recheck moved under the mutex inside ioc_bpf_detach()
- the io.cost.model documentation states that detaching restores the builtin model and that ctrl only accepts "auto" and "user" and never selects the model, says attaching rather than loading binds the model, and that removing the device removes the model as well, with the struct_ops link still having to be closed afterwards
Tao Cui (4):
blk-iocost: add BPF struct_ops cost model support selftests/bpf: add iocost cost model test
blk-iocost: add iocost_ioc_tick tracepoint for per-period device
summary
docs: cgroup-v2: document the iocost BPF cost model attachment
RFC PATCH v9 1/4 blk-iocost: add BPF struct_ops cost model support
iocost prices IO with a linear model derived from a handful of device parameters. The model is reasonable for common device classes, but the real cost of an IO depends on device internals the linear formula cannot capture (write amplification, GC, compression, cache behavior), and the right formula is device specific. This lets a BPF program take over pricing for a device, so the formula can be adapted to the device and updated without rebuilding the kernel.
An iocost_model_ops struct_ops is attached to one device: the target device is set in the dev member from userspace before load and .reg attaches the model to it, creating the ioc if needed, like an io.cost.model write does, and switching the device to the model under the same queue freeze and quiesce those writes go through. io.cost.model selects between the attached model and the builtin one:
"model=bpf" switches to the attached model, "model=linear" back to the builtin coefficients; neither detaches the struct_ops, and only .unreg or device removal does. Enabling and disabling the controller stays with io.cost.qos.
While the BPF model is the one in use, it prices every charged IO:calc_cost() is called from the IO submission path with RCU read lock held, receives the bio itself and returns the cost in vtime units, clamped to one second of device time per IO. IOs which are never charged, root cgroup IOs and IOs while the controller is disabled, do not reach it. The struct_ops also carries the transfer cost coefficients, vtime per page for reads and writes, which the builtin latency tracking and vrate adjustment use for the completion-time request sizing, so the whole controller follows the model's pricing.
The cgroup callbacks are bound to the iocg policy lifetime, one (cgroup, device) pair per invocation: iocg_init() is delivered on attach to every cgroup which already has a blkg on the device and to each one appearing afterwards, iocg_free() on detach to every cgroup still existing then, and at policy deactivation time for the rest, so init and free always pair up. The attach and detach paths walk the blkg list under blkcg_mutex and queue_lock, which is what blkg creation and destruction synchronize on; device removal only clears the attachment, as the policy deactivation which precedes it has already delivered the remaining iocg_free() calls.
Device removal ejects the model completely, and .unreg only detaches when the link which owns the attachment is closed, so a map re-attached to a new device through a newer link is not torn down by an old one.
--- block/Kconfig | 10 + block/Makefile | 1 + block/blk-core.c | 16 ++ block/blk-iocost-bpf.c | 182 +++++++++++++++++ block/blk-iocost.c | 390 ++++++++++++++++++++++++++++++++++++- block/blk.h | 1 + include/linux/blk-iocost.h | 120 ++++++++++++ 7 files changed, 712 insertions(+), 8 deletions(-) create mode 100644 block/blk-iocost-bpf.c create mode 100644 include/linux/blk-iocost.h
block/Kconfig +10 -0
@@ -231,4 +231,14 @@ config BLK_ERROR_INJECTION source "block/Kconfig.iosched" +config BLK_CGROUP_IOCOST_BPF + bool "Enable BPF pluggable cost model support for the cost IO controller" + depends on BLK_CGROUP_IOCOST && BPF_SYSCALL && BPF_JIT && DEBUG_INFO_BTF + help + Enabling this option registers the "iocost_model_ops" BPF + struct_ops type, which allows a BPF program to fully replace + the builtin linear cost model on the device it is attached + to. The struct_ops is attached per device, following the + hid_bpf_ops model. + endif # BLOCK
block/Makefile +1 -0
@@ -39,3 +39,4 @@ obj-$(CONFIG_BLK_INLINE_ENCRYPTION) += blk-crypto.o blk-crypto-profile.o \ blk-crypto-sysfs.o obj-$(CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK) += blk-crypto-fallback.o obj-$(CONFIG_BLOCK_HOLDER_DEPRECATED) += holder.o +obj-$(CONFIG_BLK_CGROUP_IOCOST_BPF) += blk-iocost-bpf.o
block/blk-core.c +16 -0
@@ -536,6 +536,22 @@ bool blk_get_queue(struct request_queue *q) }EXPORT_SYMBOL (blk_get_queue); +/** +* blk_get_queue_rcu - get a queue reference regardless of the dying flag +* @q: the request_queue to reference +* +* Unlike blk_get_queue(), this succeeds on a dying queue, so a caller +* which holds the queue only through RCU (e.g. a detach path which +* read the pointer locklessly) can still take a reference and touch +* the queue under its own lifetime. The caller must hold +* rcu_read_lock() so the memory is valid. Fails only when the +* refcount already dropped to zero. +*/ +bool blk_get_queue_rcu (struct request_queue *q) +{ +return refcount_inc_not_zero (&q->refs); +} +#ifdef CONFIG_FAIL_MAKE_REQUEST static DECLARE_FAULT_ATTR (fail_make_request);
block/blk-iocost-bpf.c new file +182 -0
182 lines not on this page · raw message
block/blk-iocost.c +382 -8
502 lines not on this page · raw message
block/blk.h +1 -0
@@ -112,6 +112,7 @@ static inline void blk_wait_io(struct completion *done) }struct block_device *blkdev_get_no_open (dev_t dev,bool autoload); +bool blk_get_queue_rcu (struct request_queue *q);void blkdev_put_no_open (struct block_device *bdev); bool bvec_try_merge_hw_page(struct request_queue *q, struct bio_vec *bv,
include/linux/blk-iocost.h new file +120 -0
120 lines not on this page · raw message
Signature · 1 line
2.43.0
RFC PATCH v9 2/4 selftests/bpf: add iocost cost model test
In reply to Tao CuiAdd two example iocost cost models and tests which attach them to one device, given as major:minor in $IOCOST_TEST_DEV.
The first model implements the builtin linear HDD formula at double cost. The second implements the multi-stream sequentiality
detection: it keeps a per-cgroup
table of stream slots instead of the single builtin cursor, so concurrent sequential streams in one cgroup are priced sequentially. Both set the target device through the struct_ops member before load, and attaching the struct_ops binds the model to the device; the maps are declared ".struct_ops.link" so that a test dying in between does not leave the model attached.
The test verifies the model=bpf readback while attached, that ctrl=bpf is rejected, that a second model on the same device fails with -EBUSY, that model=linear and model=bpf switch between the attached and builtin models without detaching, and that detaching restores the builtin model.
--- tools/testing/selftests/bpf/config | 2 + .../selftests/bpf/prog_tests/iocost_model.c | 233 ++++++++++++++++++ .../selftests/bpf/progs/iocost_model.c | 139 +++++++++++ tools/testing/selftests/bpf/progs/iocost_ms.c | 159 ++++++++++++ 4 files changed, 533 insertions(+) create mode 100644 tools/testing/selftests/bpf/prog_tests/iocost_model.c create mode 100644 tools/testing/selftests/bpf/progs/iocost_model.c create mode 100644 tools/testing/selftests/bpf/progs/iocost_ms.c
tools/testing/selftests/bpf/config +2 -0
@@ -140,3 +140,5 @@ CONFIG_SMC_HS_CTRL_BPF=y CONFIG_DIBS=y CONFIG_DIBS_LO=y CONFIG_PM_WAKELOCKS=y +CONFIG_BLK_CGROUP_IOCOST=y +CONFIG_BLK_CGROUP_IOCOST_BPF=y
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +233 -0
233 lines not on this page · raw message
tools/testing/selftests/bpf/progs/iocost_model.c new file +139 -0
139 lines not on this page · raw message
tools/testing/selftests/bpf/progs/iocost_ms.c new file +159 -0
159 lines not on this page · raw message
Signature · 1 line
2.43.0
RFC PATCH v9 3/4 blk-iocost: add iocost_ioc_tick tracepoint for per-period device summary
In reply to Tao CuiAdd iocost_ioc_tick, emitted once per period from ioc_timer_fn() with the overall controller state: period_us, vrate, busy_level, active iocg count, usage percentage and whether the controller still has active iocgs. It reads the values the period ran in:
the event is emitted before the vrate adjustment and the period transition, so each tick reports the completed period. ioc->running has not transitioned to IOC_IDLE at the emit point, so the running field reports the active iocg list instead.
It fires every period the controller is running, including steady states, plus one final tick before the controller goes idle, which reads active=0 running=0, making the transition to dormancy (e.g. a device saturated entirely by uncharged IO) directly visible.
--- block/blk-iocost.c | 14 +++++++++++ include/trace/events/iocost.h | 45 +++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+)
block/blk-iocost.c +14 -0
@@ -2276,6 +2276,7 @@ static void ioc_timer_fn(struct timer_list *timer)struct ioc_now now;LIST_HEAD (surpluses);int nr_debtors, nr_shortages =0 , nr_lagging =0 ; +int nr_active =0 ;u64 usage_us_sum =0 ;u32 ppm_rthr;u32 ppm_wthr;
@@ -2312,6 +2313,8 @@ static void ioc_timer_fn(struct timer_list *timer)u64 vdone, vtime, usage_us;u32 hw_active, hw_inuse; + nr_active++; +/* * Collect unused and wind vtime closer to vnow to prevent * iocgs from accumulating a large amount of budget.
@@ -2473,6 +2476,17 @@ static void ioc_timer_fn(struct timer_list *timer) ioc->busy_level =clamp (ioc->busy_level,-1000 ,1000 ); +/* +* Everything the tick reports is final here: busy_level was just +* computed, cur_period hasn't changed, nr_active and usage_us_sum +* are complete, and vrate and period_us still hold the values +* this period ran in. Emit before the refresh below so the +* event reads the completed period directly; ioc->running has +* not transitioned to IOC_IDLE yet, so the running field reports +* the active iocg list instead. +*/ +trace_iocost_ioc_tick (ioc, &now, nr_active, usage_us_sum); +ioc_adjust_base_vrate (ioc, rq_wait_pct, nr_lagging, nr_shortages, prev_busy_level, missed_ppm);
include/trace/events/iocost.h +45 -0
51 lines not on this page · raw message
Signature · 1 line
2.43.0
RFC PATCH v9 4/4 docs: cgroup-v2: document the iocost BPF cost model attachment
In reply to Tao CuiDocument the BPF cost model attachment in the io.cost.model section of the cgroup v2 documentation: attaching an iocost_model_ops struct_ops to a device by its major:minor, the model=bpf readback while attached (ctrl keeps describing the coefficients), that detaching restores the builtin model, and that ctrl= writes never select a model.
--- Documentation/admin-guide/cgroup-v2.rst | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+)
Documentation/admin-guide/cgroup-v2.rst +23 -0
@@ -2117,8 +2117,31 @@ IO Interface Files ===== ================================ ctrl "auto" or "user" model The cost model in use - "linear" + or "bpf" while the BPF model + is in use ===== ================================ + When CONFIG_BLK_CGROUP_IOCOST_BPF is enabled, a BPF cost model + can be bound to a device by attaching an "iocost_model_ops" + struct_ops carrying the whole disk's major:minor in its "dev" + member (a partition's major:minor is rejected). Attaching creates + the + controller if needed, like an io.cost.model write does, and + switches the device's pricing to the model; enabling and + disabling the controller stays with io.cost.qos. While a model + is attached, "model" selects between it and the builtin model: + "model=bpf" switches to the attached model and "model=linear" + switches back to the builtin model, and neither detaches the + struct_ops; only detaching removes the model, after which + "model=bpf" fails and the device prices with the builtin model + again. Device removal ejects the attached model as well, while + the struct_ops link remains until userspace destroys it. "ctrl" + accepts only "auto" and "user" and never + selects a model; it keeps describing the builtin coefficients, + which are kept while the BPF model is in use and take effect + again when switched back, and the automatic profile stepping + does not switch profiles while the BPF model is in use. + When "ctrl" is "auto", the kernel may change all parameters dynamically. When "ctrl" is set to "user" or any other parameters are written to, "ctrl" become "user" and the
Signature · 1 line
2.43.0
[email protected]
AI reviewThank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [Critical] bpf: UAF on ioc in ioc_bpf_detach due to lockless fetch before freeze - [Critical] bpf: UAF on…
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [Critical] bpf: UAF on ioc in ioc_bpf_detach due to lockless fetch before freeze
- [Critical] bpf: UAF on struct_ops map due to concurrent modification of ops->q
- [High] bpf: TOCTOU race in ioc_bpf_detach reading ops->q leads to UAF on queue
- [High] bpf: ioc_bpf_detach fails to verify ops->link causes cross-link teardown --
commit d8ef9c16531866711abee0afcce05f21400897b9
Author: Tao Cui <[email protected]>
Subject: blk-iocost: add BPF struct_ops cost model support
This patch adds BPF struct_ops support to blk-iocost, allowing BPF programs to provide custom IO pricing models. The struct_ops is attached per-device and replaces the built-in linear model for IO cost calculations.
Quoted 4 lines
block/blk-iocost.c +0
-0
[ ... ]
Quoted 24 lines
block/blk-iocost.c +20
-0@@ -2888,6 +2959,45 @@ static void ioc_rqos_queue_depth_changed(struct rq_qos *rqos)spin_unlock_irq (&ioc->lock); } +#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF +/* +* Eject the model on device removal. The caller holds rq_qos_mutex +* and blkcg_deactivate_policy() has already run, so every existing +* blkg got iocg_free() from ioc_pd_free() and no walk is needed. +* +* bdev is read into a local before ops->q is cleared: once q is +* NULL, .unreg returns without taking any lock and the map holding +* ops can be freed, so ops must not be touched afterwards. +*/ +static void ioc_bpf_eject (struct ioc *ioc) +{ +struct request_queue *q = ioc->rqos.disk->queue; +struct iocost_model_ops *ops; +struct block_device *bdev; + +spin_lock_irq (&q->queue_lock); +spin_lock (&ioc->lock); + ops = (struct iocost_model_ops *)rcu_dereference_protected ( + ioc->attached,lockdep_is_held (&ioc->lock));
block/blk-iocost.c static void ioc_rqos_queue_depth_changed(struct rq_qos *rqos) · line 2991
Quoted 10 lines
block/blk-iocost.c +10
-0+if (!ops) { +spin_unlock (&ioc->lock); +spin_unlock_irq (&q->queue_lock); +return ; + } + bdev = ops->bdev; +rcu_assign_pointer (ioc->attached,NULL ); +rcu_assign_pointer (ioc->model,NULL ); +spin_unlock (&ioc->lock); +WRITE_ONCE (ops->q,NULL );
[Severity: Critical]
Is it possible for this ejection to clear ops->q when the map has been re-attached to a different queue?
If a user attaches the same struct_ops map to multiple devices, ops->q gets overwritten. If the first device is then removed, ioc_bpf_eject() clears ops->q. This can cause subsequent unreg operations for other active links to fail to detach the map, resulting in a use-after-free when the map is freed but the surviving queues still use it.
Quoted 5 lines
block/blk-iocost.c +5
-0+WRITE_ONCE (ops->link,NULL ); +spin_unlock_irq (&q->queue_lock); + +blkdev_put_no_open (bdev); +}
[ ... ]
Quoted 4 lines
block/blk-iocost.c +4
-0+int ioc_bpf_attach (struct iocost_model_ops *ops,struct bpf_link *link) +{ +struct block_device *bdev; +struct request_queue *q;
[ ... ]
block/blk-iocost.c static int ioc_cost_model_show(struct seq_file *sf, void *v) · line 3724
Quoted 7 lines
block/blk-iocost.c +7
-0+rcu_assign_pointer (ioc->attached, ops); +rcu_assign_pointer (ioc->model, ops); +spin_unlock (&ioc->lock); + + ops->bdev = bdev; +WRITE_ONCE (ops->link, link); +WRITE_ONCE (ops->q, q);
[Severity: Critical]
Does this allow concurrent modification of the shared ops state?
ops->q is only protected by the target queue's queue_lock. If the same map is attached to multiple queues, this will clobber ops->q, setting up the ejection bug mentioned above.
Quoted 6 lines
block/blk-iocost.c +6
-0+ +/* pair iocg_init() with the cgroups which already exist */ +ioc_bpf_walk_iocgs (ioc, ops, true); + +spin_unlock_irq (&q->queue_lock); +mutex_unlock (&q->blkcg_mutex);
[ ... ]
block/blk-iocost.c static int ioc_cost_model_show(struct seq_file *sf, void *v) · line 3750
Quoted 9 lines
block/blk-iocost.c +9
-0+/* +* Detach a model: switch back to the builtin model when the attached +* model is in use, clear the attachment, and deliver iocg_free() to +* the cgroups which still exist, under the same freeze and quiesce as +* the attach. The caller has already checked ops->q. +*/ +void ioc_bpf_detach (struct iocost_model_ops *ops,struct bpf_link *link) +{ +struct request_queue *q =READ_ONCE (ops->q);
[Severity: High]
Does re-reading ops->q here introduce a TOCTOU race?
In bpf_iocost_unreg(), a queue reference is correctly secured using blk_get_queue_rcu(q). However, the queue is re-read here. If a concurrent attach overwrites ops->q before this read, the code will operate on a different, unreferenced queue. This can lead to a use-after-free when calling blk_mq_freeze_queue() if the new queue is concurrently destroyed.
block/blk-iocost.c static int ioc_cost_model_show(struct seq_file *sf, void *v) · line 3757
Quoted 7 lines
block/blk-iocost.c +7
-0+struct block_device *bdev; +struct ioc *ioc; +unsigned int memflags; + +if (!q) +return ; + ioc =q_to_ioc (q);
[Severity: Critical]
Can this lockless fetch of ioc lead to a use-after-free?
The ioc pointer is fetched here without securing an independent reference. When the function blocks on blk_mq_freeze_queue(q) directly below, a concurrent device hot-unplug (e.g. del_gendisk) can run rq_qos_exit() and free the ioc struct.
When this thread resumes, the later spin_lock(&ioc->lock) would dereference the freed ioc pointer.
Quoted 11 lines
block/blk-iocost.c +11
-0+if (!ioc) +return ; + + bdev = ops->bdev; + +/* +* the freeze is taken before rq_qos_mutex like in the attach; +* the link is re-checked under the mutex below, as the ejection +* or a newer attachment may have won the race meanwhile +*/ + memflags =blk_mq_freeze_queue (q);
block/blk-iocost.c static int ioc_cost_model_show(struct seq_file *sf, void *v) · line 3778
Quoted 10 lines
block/blk-iocost.c +10
-0+blk_mq_quiesce_queue (q); + +mutex_lock (&q->rq_qos_mutex); + +mutex_lock (&q->blkcg_mutex); +spin_lock_irq (&q->queue_lock); + +spin_lock (&ioc->lock); +if (rcu_dereference_protected (ioc->attached, +lockdep_is_held (&ioc->lock)) != ops) {
[Severity: High]
Is there a missing check to verify the link argument here?
ioc_bpf_detach() is passed a link pointer but never validates it against READ_ONCE(ops->link). If the same map was attached to another queue via a new link, closing the old link could cause this function to mistakenly tear down the new link's attachment, leaving the intended link orphaned.
Quoted 9 lines
block/blk-iocost.c +9
-0+/* the ejection or a newer link won; nothing to detach */ +spin_unlock (&ioc->lock); +spin_unlock_irq (&q->queue_lock); +mutex_unlock (&q->blkcg_mutex); +mutex_unlock (&q->rq_qos_mutex); +blk_mq_unquiesce_queue (q); +blk_mq_unfreeze_queue (q, memflags); +return ; + }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
[email protected]
AI reviewTL;DR: Possible behaviour issue in blk-iocost BPF model: a blkg whose radix_tree_insert() fails may get iocg_init() without iocg_free(), or the reverse, if attach/detach races, contradicting the…
Quoted 1 line
blk-iocost: add BPF
struct_opscost model support
TL;DR: Possible behaviour issue in blk-iocost BPF model: a blkg whose radix_tree_insert() fails may get iocg_init() without iocg_free(), or the reverse, if attach/detach races, contradicting the documented pairing. No kernel harm.
Quoted 4 lines
block/blk-iocost.c +0
-0
[ ... ]
Quoted 22 lines
block/blk-iocost.c +12
-0@@ -3048,6 +3163,18 @@ static void ioc_pd_init(struct blkg_policy_data *pd)spin_lock_irqsave (&ioc->lock, flags);weight_updated (iocg, &now);spin_unlock_irqrestore (&ioc->lock, flags); + +/* +* the attached model is RCU-protected: a concurrent detach +* publishes NULL and the struct_ops image survives it by a +* grace period, so the callback is safe inside the read-side +* critical section +*/ +rcu_read_lock (); + model =ioc_attached_or_null (ioc); +if (model && model->iocg_init) + model->iocg_init (blkg->blkcg, ioc->rqos.disk->queue); +rcu_read_unlock (); }static void iocg_release (struct rcu_head *rcu)@@ -3066,8 +3193,15 @@ static void ioc_pd_free(struct blkg_policy_data *pd)struct blkcg_gq *blkg =pd_to_blkg (pd);struct ioc *ioc = iocg->ioc;
block/blk-iocost.c static void ioc_pd_free(struct blkg_policy_data *pd) · line 3204
Quoted 10 lines
block/blk-iocost.c +7
-0unsigned long flags; +const struct iocost_model_ops *model;if (ioc) { +rcu_read_lock (); + model =ioc_attached_or_null (ioc); +if (model && model->iocg_free) + model->iocg_free (blkg->blkcg, ioc->rqos.disk->queue); +rcu_read_unlock (); +
The commit message says:
"... iocg_init() is delivered on attach to every cgroup which already has a blkg on the device and to each one appearing afterwards, iocg_free() on detach to every cgroup still existing then, and at policy deactivation time for the rest, so init and free always pair up."
Does that pairing hold for a blkg that never reaches q->blkg_list?
blkg_create() calls the policy's pd_init_fn (ioc_pd_init(), which delivers iocg_init() when a model is attached) before the radix_tree_insert(), and only adds the blkg to q->blkg_list if that insert succeeds:
blkg_create() {
...
pol->pd_init_fn(blkg->pd[i]);
...
ret = radix_tree_insert(&blkcg->blkg_tree, disk->queue->id, blkg);
if (likely(!ret)) {
...
list_add(&blkg->q_node, &disk->queue->blkg_list);
...
/* @blkg failed fully initialized, use the usual release path */
percpu_ref_kill(&blkg->refcnt);
return ERR_PTR(ret);
}The insert is into a GFP_NOWAIT radix tree, and on the bio association path (blkg_tryget_closest() -> blkg_lookup_create() -> blkg_create()) there is no preload, so it can fail with -ENOMEM. That blkg is then released through blkg_release() -> call_rcu() -> blkg_free_workfn() -> ioc_pd_free().
If ioc_bpf_detach() runs after that ioc_pd_init() but before that ioc_pd_free(), ioc_bpf_walk_iocgs() does not find the blkg on q->blkg_list, and ioc_pd_free() then sees ioc->attached as NULL. iocg_init() has been delivered and iocg_free() never is.
The reverse looks possible too. If ioc_bpf_attach() runs in that window, ioc_pd_init() ran with no model, the attach walk misses the blkg, and ioc_pd_free() then delivers an iocg_free() with no matching iocg_init().
Can a BPF model that keeps per-cgroup state in iocg_init()/iocg_free() see these unpaired callbacks? Nothing in the kernel itself is harmed, but the commit message and the comment above struct iocost_model_ops say the callbacks always pair up.
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/37087498848
Quoted 5 lines · 于 2026年10月3日 GMT+08:00 09:52:07,[email protected] 写道:
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [Critical] bpf: UAF on ioc inioc_bpf_detachdue to lockless fetch before freeze
- [Critical] bpf: UAF onstruct_opsmap due to concurrent modification ofops->q
- [High] bpf: TOCTOU race inioc_bpf_detachreadingops->qleads to UAF on queue
- [High] bpf:ioc_bpf_detachfails to verifyops->linkcauses cross-link teardown
Thank you for catching these issues.
I've noted all the reported UAF and TOCTOU races and am working on fixes.
Quoted 180 lines
--
commit
d8ef9c16531866711abee0afcce05f21400897b9
Author: Tao Cui <[email protected]>
Subject: blk-iocost: add BPFstruct_opscost model supportThis patch adds BPF
struct_opssupport to blk-iocost, allowing BPF programs to provide custom IO pricing models. Thestruct_opsis attached per-device and replaces the built-in linear model for IO cost calculations.Quoted 4 lines
block/blk-iocost.c +0
-0[ ... ]
Quoted 24 lines
block/blk-iocost.c +20
-0@@ -2888,6 +2959,45 @@ static void ioc_rqos_queue_depth_changed(struct rq_qos *rqos)spin_unlock_irq (&ioc->lock); } +#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF +/* +* Eject the model on device removal. The caller holds rq_qos_mutex +* and blkcg_deactivate_policy() has already run, so every existing +* blkg got iocg_free() from ioc_pd_free() and no walk is needed. +* +* bdev is read into a local before ops->q is cleared: once q is +* NULL, .unreg returns without taking any lock and the map holding +* ops can be freed, so ops must not be touched afterwards. +*/ +static void ioc_bpf_eject (struct ioc *ioc) +{ +struct request_queue *q = ioc->rqos.disk->queue; +struct iocost_model_ops *ops; +struct block_device *bdev; + +spin_lock_irq (&q->queue_lock); +spin_lock (&ioc->lock); + ops = (struct iocost_model_ops *)rcu_dereference_protected ( + ioc->attached,lockdep_is_held (&ioc->lock));block/blk-iocost.c static void ioc_rqos_queue_depth_changed(struct rq_qos *rqos) · line 2991
Quoted 10 lines
block/blk-iocost.c +10
-0+if (!ops) { +spin_unlock (&ioc->lock); +spin_unlock_irq (&q->queue_lock); +return ; + } + bdev = ops->bdev; +rcu_assign_pointer (ioc->attached,NULL ); +rcu_assign_pointer (ioc->model,NULL ); +spin_unlock (&ioc->lock); +WRITE_ONCE (ops->q,NULL );[Severity: Critical]
Is it possible for this ejection to clearops->qwhen the map has been re-attached to a different queue?If a user attaches the same
struct_opsmap to multiple devices,ops->qgets overwritten. If the first device is then removed,ioc_bpf_eject()clearsops->q. This can cause subsequent unreg operations for other active links to fail to detach the map, resulting in a use-after-free when the map is freed but the surviving queues still use it.Quoted 5 lines
block/blk-iocost.c +5
-0+WRITE_ONCE (ops->link,NULL ); +spin_unlock_irq (&q->queue_lock); + +blkdev_put_no_open (bdev); +}[ ... ]
Quoted 4 lines
block/blk-iocost.c +4
-0+int ioc_bpf_attach (struct iocost_model_ops *ops,struct bpf_link *link) +{ +struct block_device *bdev; +struct request_queue *q;[ ... ]
block/blk-iocost.c static int ioc_cost_model_show(struct seq_file *sf, void *v) · line 3724
Quoted 7 lines
block/blk-iocost.c +7
-0+rcu_assign_pointer (ioc->attached, ops); +rcu_assign_pointer (ioc->model, ops); +spin_unlock (&ioc->lock); + + ops->bdev = bdev; +WRITE_ONCE (ops->link, link); +WRITE_ONCE (ops->q, q);[Severity: Critical]
Does this allow concurrent modification of the shared ops state?
ops->qis only protected by the target queue'squeue_lock. If the same map is attached to multiple queues, this will clobberops->q, setting up the ejection bug mentioned above.Quoted 6 lines
block/blk-iocost.c +6
-0+ +/* pair iocg_init() with the cgroups which already exist */ +ioc_bpf_walk_iocgs (ioc, ops, true); + +spin_unlock_irq (&q->queue_lock); +mutex_unlock (&q->blkcg_mutex);[ ... ]
block/blk-iocost.c static int ioc_cost_model_show(struct seq_file *sf, void *v) · line 3750
Quoted 9 lines
block/blk-iocost.c +9
-0+/* +* Detach a model: switch back to the builtin model when the attached +* model is in use, clear the attachment, and deliver iocg_free() to +* the cgroups which still exist, under the same freeze and quiesce as +* the attach. The caller has already checked ops->q. +*/ +void ioc_bpf_detach (struct iocost_model_ops *ops,struct bpf_link *link) +{ +struct request_queue *q =READ_ONCE (ops->q);[Severity: High]
Does re-readingops->qhere introduce a TOCTOU race?In
bpf_iocost_unreg(), a queue reference is correctly secured usingblk_get_queue_rcu(q). However, the queue is re-read here. If a concurrent attach overwritesops->qbefore this read, the code will operate on a different, unreferenced queue. This can lead to a use-after-free when callingblk_mq_freeze_queue()if the new queue is concurrently destroyed.block/blk-iocost.c static int ioc_cost_model_show(struct seq_file *sf, void *v) · line 3757
Quoted 7 lines
block/blk-iocost.c +7
-0+struct block_device *bdev; +struct ioc *ioc; +unsigned int memflags; + +if (!q) +return ; + ioc =q_to_ioc (q);[Severity: Critical]
Can this lockless fetch of ioc lead to a use-after-free?The ioc pointer is fetched here without securing an independent reference. When the function blocks on
blk_mq_freeze_queue(q)directly below, a concurrent device hot-unplug (e.g.del_gendisk) can runrq_qos_exit()and free the ioc struct.When this thread resumes, the later
spin_lock(&ioc->lock)would dereference the freed ioc pointer.Quoted 11 lines
block/blk-iocost.c +11
-0+if (!ioc) +return ; + + bdev = ops->bdev; + +/* +* the freeze is taken before rq_qos_mutex like in the attach; +* the link is re-checked under the mutex below, as the ejection +* or a newer attachment may have won the race meanwhile +*/ + memflags =blk_mq_freeze_queue (q);block/blk-iocost.c static int ioc_cost_model_show(struct seq_file *sf, void *v) · line 3778
Quoted 10 lines
block/blk-iocost.c +10
-0+blk_mq_quiesce_queue (q); + +mutex_lock (&q->rq_qos_mutex); + +mutex_lock (&q->blkcg_mutex); +spin_lock_irq (&q->queue_lock); + +spin_lock (&ioc->lock); +if (rcu_dereference_protected (ioc->attached, +lockdep_is_held (&ioc->lock)) != ops) {[Severity: High]
Is there a missing check to verify the link argument here?
ioc_bpf_detach()is passed a link pointer but never validates it againstREAD_ONCE(ops->link). If the same map was attached to another queue via a new link, closing the old link could cause this function to mistakenly tear down the new link's attachment, leaving the intended link orphaned.Quoted 9 lines
block/blk-iocost.c +9
-0+/* the ejection or a newer link won; nothing to detach */ +spin_unlock (&ioc->lock); +spin_unlock_irq (&q->queue_lock); +mutex_unlock (&q->blkcg_mutex); +mutex_unlock (&q->rq_qos_mutex); +blk_mq_unquiesce_queue (q); +blk_mq_unfreeze_queue (q, memflags); +return ; + }