blk-iocost: BPF struct_ops cost model
Subsystems (8)
v12 cover blk-iocost: BPF struct_ops cost model
From: Tao Cui <[email protected]>
This series lets a BPF program take over the cost model of one device. The BPF model provides calc_cost() for charged IOs plus two transfer coefficients for the completion-time sizing, io.cost.model selects between the attached model and the builtin one, and enabling and disabling the controller stays with io.cost.qos.
The builtin model is a linear formula derived from a handful of device parameters, and the right formula is device specific. A BPF model can be adapted to the device and updated without rebuilding the kernel.
The series is based on next-20261030.
Patches:
1/4 blk-iocost: add BPF struct_ops cost model support 2/4 blk-iocost: add iocost_ioc_tick tracepoint for per-period
device summary
3/4 selftests/bpf: add iocost cost model test
4/4 docs: cgroup-v2: document the iocost BPF cost model attachment
Changes since v11:
- dropped the cgroup callbacks (the models build their state in calc_cost() anyway)
- dropped the queue freeze from detach
- folded everything into blk-iocost.c
- the selftest now uses cgroup_helpers: the tests create their own cgroups and remove them on exit; io.cost.qos/io.cost.model are root-only cgroupfs files and the test reverts them on its exit paths
Tested on next-20261030 (qemu x86_64): the selftests pass, and the 2x example model doubles the charged cost over the builtin on a rotational device (2.01x measured), returning to 1.00x after "model=linear".
RFC PATCH v12 1/4 blk-iocost: add BPF struct_ops cost model support
From: Tao Cui <[email protected]>
iocost prices IO with a linear model derived from a handful of device parameters. The real cost of an IO depends on device internals the formula cannot capture and the right formula is device specific. This lets a BPF program take over pricing for a device so that the model can be adapted to it without rebuilding the kernel.
Attaching an iocost_model_ops struct_ops binds the model to one
device: the target is set in the dev member from userspace and .reg creates the ioc if needed like an io.cost.model write and publishes the model with the queue frozen and rq_qos_mutex held like an io.cost.qos write. The attachment records the owning link in the ioc, so a second attach on the same device fails with -EBUSY, and device removal ejects the model. Detaching takes only rq_qos_mutex in a single critical section, and the map is freed after an RCU grace period so that a calc_cost() already running can finish. io.cost.model selects between the attached and builtin models without detaching the struct_ops; only .unreg or device removal detaches, and .unreg detaches only its own attachment so a reused dev_t cannot tear down a newer one. While a model is selected, the automatic profile stepping of ctrl=auto is suspended; it resumes when the model is switched off or detached.
While in use, the BPF model prices every charged IO: calc_cost() is called from the submission path with the bio and returns the cost in vtime units, clamped to VTIME_PER_SEC by the caller. The struct_ops also carries the transfer coefficients used by the completion-time request sizing, so latency tracking and vrate adjustment follow the model's pricing. Models without calc_cost or with zero or out-of-range transfer coefficients are rejected at registration.
The kernel keeps no per-cgroup state for the model; models which need per-cgroup data keep it in their own maps, created and freed with the cgroups. Without CONFIG_BLK_CGROUP_IOCOST_BPF the struct_ops is not built and the builtin model is the only choice.
--- block/Kconfig | 4 + block/blk-iocost.c | 260 ++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 259 insertions(+), 5 deletions(-)
block/Kconfig +4 -0
@@ -161,6 +161,10 @@ config BLK_CGROUP_IOCOST distributes IO capacity between different groups based on their share of the overall weight distribution. +config BLK_CGROUP_IOCOST_BPF + def_bool y + depends on BLK_CGROUP_IOCOST && BPF_SYSCALL && BPF_JIT && DEBUG_INFO_BTF + config BLK_CGROUP_IOPRIO bool "Cgroup I/O controller for assigning an I/O priority class" depends on BLK_CGROUP
block/blk-iocost.c +255 -5
366 lines not on this page · raw message
Signature · 1 line
2.53.0
RFC PATCH v12 2/4 blk-iocost: add iocost_ioc_tick tracepoint for per-period device summary
In reply to Tao CuiFrom: Tao Cui <[email protected]>
Add iocost_ioc_tick, emitted once per period from ioc_timer_fn() with the overall controller state: period_us, vrate, busy_level, active iocg count and usage percentage. busy_level, cur_period, nr_active and usage_us_sum are complete at the emission point. usage is wall time over wall time, summed over iocgs, and is not capped at 100. vrate and period_us reflect the current controller state, which an io.cost.qos write may have changed mid-period.
The event fires every period the controller is running, including steady states, plus one final tick before the controller goes idle, so the transition to dormancy is directly visible. The active iocg count is only gathered when the tracepoint is enabled.
--- MAINTAINERS | 1 + block/blk-iocost.c | 17 ++++++++++++++ include/trace/events/iocost.h | 43 +++++++++++++++++++++++++++++++++++ 3 files changed, 61 insertions(+)
MAINTAINERS +1 -0
@@ -6832,6 +6832,7 @@ F: block/blk-iocost.c F: block/blk-iolatency.c F: block/blk-throttle.c F: include/linux/blk-cgroup.h +F: include/trace/events/iocost.h CONTROL GROUP - CPUSET M: Waiman Long <[email protected]>
block/blk-iocost.c +17 -0
@@ -2349,6 +2349,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;
@@ -2546,6 +2547,22 @@ static void ioc_timer_fn(struct timer_list *timer) ioc->busy_level =clamp (ioc->busy_level,-1000 ,1000 ); +/* +* busy_level, cur_period, nr_active and usage_us_sum are complete +* here. usage is wall time over wall time, summed over iocgs, and +* is not capped at 100. vrate and period_us reflect the current +* controller state, which an io.cost.qos write may have changed +* mid-period. Emit before the refresh and the period transition. +*/ +if (trace_iocost_ioc_tick_enabled ()) { +struct ioc_gq *active_iocg; + +list_for_each_entry (active_iocg, &ioc->active_iocgs, + active_list) + nr_active++; + } +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 +43 -0
49 lines not on this page · raw message
Signature · 1 line
2.53.0
RFC PATCH v12 3/4 selftests/bpf: add iocost cost model test
In reply to Tao CuiFrom: Tao Cui <[email protected]>
Add two example iocost cost models and tests which attach them to a null_blk instance the tests create through configfs, so everything runs without external setup.
The first model implements the builtin linear HDD formula at double cost. The second implements 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 the maps are declared ".struct_ops.link" so that a test dying in between does not leave the model attached.
The tests verify 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. With the controller enabled through io.cost.qos, they also verify that IOs are priced through calc_cost() and that the iocost_ioc_tick tracepoint is seen from BPF. They also verify that device removal under the attached model ejects it, with a recreated device attachable again.
--- tools/testing/selftests/bpf/config | 2 + .../selftests/bpf/prog_tests/iocost_model.c | 748 ++++++++++++++++++ .../selftests/bpf/progs/iocost_model.c | 184 +++++ tools/testing/selftests/bpf/progs/iocost_ms.c | 187 +++++ 4 files changed, 1121 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
@@ -141,3 +141,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_DEV_NULL_BLK=y
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +748 -0
748 lines not on this page · raw message
tools/testing/selftests/bpf/progs/iocost_model.c new file +184 -0
184 lines not on this page · raw message
tools/testing/selftests/bpf/progs/iocost_ms.c new file +187 -0
187 lines not on this page · raw message
Signature · 1 line
2.53.0
RFC PATCH v12 4/4 docs: cgroup-v2: document the iocost BPF cost model attachment
In reply to Tao CuiFrom: Tao Cui <[email protected]>
Document 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), the builtin model coming back on detach, and ctrl writes never selecting a model.
--- Documentation/admin-guide/cgroup-v2.rst | 45 ++++++++++++++++++++----- 1 file changed, 37 insertions(+), 8 deletions(-)
Documentation/admin-guide/cgroup-v2.rst +37 -8
@@ -2056,8 +2056,9 @@ IO Interface Files currently implements "io.weight" proportional control. Lines are keyed by $MAJ:$MIN device numbers and not ordered. The line for a given device is populated on the first write for - the device on "io.cost.qos" or "io.cost.model". The following - nested keys are defined. + the device on "io.cost.qos" or "io.cost.model", or when a BPF + cost model is attached to it. The following nested keys are + defined. ====== ===================================== enable Weight-based control enable
@@ -2111,13 +2112,40 @@ IO Interface Files implements "io.weight" proportional control. Lines are keyed by $MAJ:$MIN device numbers and not ordered. The line for a given device is populated on the first write for the device on - "io.cost.qos" or "io.cost.model". The following nested keys - are defined. + "io.cost.qos" or "io.cost.model", or when a BPF cost model is + attached to it. The following nested keys are defined. - ===== ================================ + ===== ========================================== ctrl "auto" or "user" - model The cost model in use - "linear" - ===== ================================ + model The cost model in use - "linear" or "bpf" + ===== ========================================== + + When BPF cost model support is available, 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 as encoded by makedev(3) in its "dev" member (a + partition's major:minor is rejected). Attaching creates the + controller if needed, like + an io.cost.model write does, switches the device's pricing to + the model and populates the device's line in this file and in + "io.cost.qos" if it did not exist yet. Attaching fails with + -EBUSY if the device already has a model attached. The + attached model prices IOs only while the controller is + enabled through "io.cost.qos"; attaching does not enable it. + IOs issued directly by the root cgroup bypass the model. + + 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. + + 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 take effect + again when switched back. When "ctrl" is "auto", the kernel may change all parameters dynamically. When "ctrl" is set to "user" or any other
@@ -2125,7 +2153,8 @@ IO Interface Files automatic changes are disabled. When "model" is "linear", the following model parameters are - defined. + defined. They remain readable and writable while "model" is + "bpf". ============= ======================================== [r|w]bps The maximum sequential IO throughput
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [RFC PATCH v12 1/4] blk-iocost: add BPF struct_ops cost model support
In reply to Tao CuiThank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] blk-iocost: lock order inversion between queue freeze and rq_qos_mutex - [Medium] blk-iocost…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] blk-iocost: lock order inversion between queue freeze and rq_qos_mutex
- [Medium] blk-iocost: stale autop timestamps across model attach/detach
--
commit 145ca796c6aa0e9492a94bdce49377cc07f92750
Author: Tao Cui <[email protected]>
blk-iocost: add BPF struct_ops cost model support
This commit adds BPF struct_ops support (iocost_model_ops) to blk-iocost so a BPF program can calculate per-bio vtime costs and provide page transfer coefficients for a target block device. It also extends io.cost.model to switch between the linear and attached BPF cost models while suspending ctrl=auto profile stepping when a BPF model is active.
Quoted 4 lines
block/blk-iocost.c +0
-0
[ ... ]
Quoted 9 lines
block/blk-iocost.c +1
-1@@ -806,7 +844,7 @@ static int ioc_autop_idx(struct ioc *ioc, struct gendisk *disk)return AUTOP_SSD_DFL ;/* if user is overriding anything, maintain what was there */ -if (ioc->user_qos_params || ioc->user_cost_model) +if (ioc->user_qos_params || ioc->user_cost_model ||ioc_model (ioc))return idx;/* step up/down based on the vrate */
[ ... ]
Quoted 10 lines
block/blk-iocost.c +6
-0@@ -2908,10 +2968,33 @@ static void ioc_rqos_queue_depth_changed(struct rq_qos *rqos)spin_unlock_irq (&ioc->lock); } +/* Called by .unreg and by device removal, whichever is first. */ +static void ioc_detach_model (struct ioc *ioc) +{ +#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF +const struct iocost_model_ops *ops = ioc->attached; +
block/blk-iocost.c static void ioc_rqos_queue_depth_changed(struct rq_qos *rqos) · line 2986
Quoted 10 lines
block/blk-iocost.c +10
-0+lockdep_assert_held (&ioc->rqos.disk->queue->rq_qos_mutex); + +if (!ops) +return ; + +spin_lock_irq (&ioc->lock); +rcu_assign_pointer (ioc->model,NULL ); + ioc->attached =NULL ; + ioc->attached_link =NULL ; +spin_unlock_irq (&ioc->lock);
[Severity: Medium]
When ctrl=auto is active under the builtin linear model and vrate_pct crosses too_fast_vrate_pct or too_slow_vrate_pct in ioc_autop_idx(), the current timestamp is recorded in ioc->autop_too_fast_at or ioc->autop_too_slow_at, requiring AUTOP_CYCLE_NSEC (10 seconds) of sustained condition before stepping ioc->autop_idx.
When a BPF model is attached in ioc_bpf_reg() and later detached in ioc_detach_model(), ioc->model is updated without calling ioc_refresh_params(ioc, true) or clearing ioc->autop_too_fast_at and ioc->autop_too_slow_at, unlike ioc_cost_model_write() and ioc_qos_write():
block/blk-iocost.c:ioc_refresh_params_disk() {
...
idx = ioc_autop_idx(ioc, disk);
p = &autop[idx];
if (idx == ioc->autop_idx && !force)
return false;
...
ioc->autop_idx = idx;
ioc->autop_too_fast_at = 0;
ioc->autop_too_slow_at = 0;
...
}While the BPF model is active, ioc_autop_idx() returns idx early at the ioc_model(ioc) check before reaching the timestamp update and reset logic, and ioc_refresh_params_disk(ioc, false, disk) returns false early because idx == ioc->autop_idx, leaving any pre-attachment timestamp in ioc->autop_too_fast_at or ioc->autop_too_slow_at intact.
Once the BPF model is detached via ioc_bpf_unreg() -> ioc_detach_model(), on the first timer tick (ioc_timer_fn() -> ioc_refresh_params(ioc, false) -> ioc_autop_idx()), if vrate_pct is past the threshold,now_ns - ioc->autop_too_fast_at (or autop_too_slow_at) includes the entire time the BPF model was attached.
Could this cause ioc_autop_idx() to immediately exceed AUTOP_CYCLE_NSEC and step ioc->autop_idx (resetting vtime_rate) on the first tick after detach instead of waiting for a full AUTOP_CYCLE_NSEC cycle? Should ioc_bpf_reg() and ioc_detach_model() reset the autop timestamps or call ioc_refresh_params(ioc, true) under ioc->lock?
[ ... ]
Quoted 38 lines
block/blk-iocost.c +19
-1@@ -3559,7 +3644,11 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,continue ;case COST_MODEL :match_strlcpy (buf, &args[0 ],sizeof (buf)); -if (strcmp (buf,"linear" )) +if (!strcmp (buf,"linear" )) + model =NULL ; +else if (!strcmp (buf,"bpf" ) && ioc->attached) + model = ioc->attached; +else goto unlock;continue ; }@@ -3579,6 +3668,7 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input, }else { ioc->user_cost_model = false; } +rcu_assign_pointer (ioc->model, model);ioc_refresh_params (ioc, true); ret =0 ;@@ -3626,6 +3716,166 @@ static struct blkcg_policy blkcg_policy_iocost = { .pd_stat_fn = ioc_pd_stat, }; +#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF +static int ioc_bpf_reg (void *kdata,struct bpf_link *link) +{ +struct iocost_model_ops *ops = kdata; +struct block_device *bdev; +struct request_queue *q; +unsigned int memflags; +struct ioc *ioc; +int ret; + + bdev =blkdev_get_no_open (new_decode_dev (ops->dev), false); +if (!bdev) +return -ENODEV ;
block/blk-iocost.c static struct blkcg_policy blkcg_policy_iocost = { · line 3741
Quoted 10 lines
block/blk-iocost.c +10
-0+ + q =bdev_get_queue (bdev); +if (bdev_is_partition (bdev) || !queue_is_mq (q)) { +blkdev_put_no_open (bdev); +return -EOPNOTSUPP ; + } + +/* the order of ioc_qos_write() */ + memflags =blk_mq_freeze_queue (q); +mutex_lock (&q->rq_qos_mutex);
[Severity: High]
In ioc_bpf_reg(), blk_mq_freeze_queue(q) is called before acquiring q->rq_qos_mutex, which establishes the lock order:
q->io_lockdep_map -> q->q_lockdep_map -> q->rq_qos_mutex
However, in ioc_cost_model_write() (which is used to toggle between model=linear and model=bpf), blkg_conf_open_bdev(&ctx) acquires q->rq_qos_mutex first, and unlike ioc_qos_write(), ioc_cost_model_write() does not drop q->rq_qos_mutex before calling blk_iocost_init() and blk_mq_freeze_queue(q):
block/blk-iocost.c:ioc_cost_model_write() {
blkg_conf_init(&ctx, input);
ret = blkg_conf_open_bdev(&ctx); // locks q->rq_qos_mutex
if (ret)
return ret;
...
ioc = q_to_ioc(q);
if (!ioc) {
ret = blk_iocost_init(ctx.bdev->bd_disk);
if (ret)
goto close_bdev;
ioc = q_to_ioc(q);
}
memflags = blk_mq_freeze_queue(q); // locks q->io_lockdep_map -> q->q_lockdep_map
...
}This establishes the opposite lock order in ioc_cost_model_write():
q->rq_qos_mutex -> q->io_lockdep_map -> q->q_lockdep_map
In addition, paths that hold q->rq_qos_mutex without freezing the queue first (such as ioc_cost_model_write() -> blk_iocost_init() and ioc_weight_write() -> blkg_conf_prep()) perform GFP_KERNEL allocations under q->rq_qos_mutex without memalloc_noio_save(), which can enter fs_reclaim and wait on a frozen queue.
Can attaching a BPF model via ioc_bpf_reg() and writing to io.cost.model via ioc_cost_model_write() trigger a lockdep circular locking dependency splat or an ABBA deadlock between queue freeze and q->rq_qos_mutex? Should ioc_cost_model_write() release and re-acquire q->rq_qos_mutex around blk_mq_freeze_queue(q) the same way ioc_qos_write() does?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
[email protected]
AI reviewRe: [RFC PATCH v12 2/4] blk-iocost: add iocost_ioc_tick tracepoint for per-period device summary
In reply to Tao CuiTL;DR: In iocost_ioc_tick, the tracepoint call sits outside its enabled() check, so a probe attached in between may log a bogus active count of 0, which consumers could read as dormancy.
Quoted 1 line
blk-iocost: add
iocost_ioc_ticktracepoint for per-period device summary
TL;DR: In iocost_ioc_tick, the tracepoint call sits outside its enabled() check, so a probe attached in between may log a bogus active count of 0, which consumers could read as dormancy.
Quoted 3 lines
block/blk-iocost.c +0
-0
[ ... ]
Quoted 10 lines
block/blk-iocost.c +6
-0@@ -2478,6 +2479,22 @@ static void ioc_timer_fn(struct timer_list *timer) ioc->busy_level =clamp (ioc->busy_level,-1000 ,1000 ); +/* +* busy_level, cur_period, nr_active and usage_us_sum are complete +* here. usage is wall time over wall time, summed over iocgs, and +* is not capped at 100. vrate and period_us reflect the current +* controller state, which an io.cost.qos write may have changed +* mid-period. Emit before the refresh and the period transition.
block/blk-iocost.c static void ioc_timer_fn(struct timer_list *timer) · line 2497
Quoted 10 lines
block/blk-iocost.c +10
-0+*/ +if (trace_iocost_ioc_tick_enabled ()) { +struct ioc_gq *active_iocg; + +list_for_each_entry (active_iocg, &ioc->active_iocgs, + active_list) + nr_active++; + } +trace_iocost_ioc_tick (ioc, &now, nr_active, usage_us_sum); +
Can this record a bogus nr_active of 0?
trace_iocost_ioc_tick() is called outside the trace_iocost_ioc_tick_enabled() block, so the two static key tests are independent. If a probe is attached on another CPU between them, the first test sees the key disabled and skips the count, while the tracepoint itself then fires with nr_active still 0 even though ioc->active_iocgs is non-empty.
Documentation/trace/tracepoints.rst says the tracepoint call should always be within the block of the if (trace_<tracepoint>_enabled()) check to avoid this race.
Since the commit message describes active=0 as the marker for the transition to dormancy, a consumer could read this spurious record as that transition, alongside a non-zero usage value.
Would moving the trace_iocost_ioc_tick() call inside the enabled block work? Alternatively, nr_active could be counted in the existing list_for_each_entry() walk over ioc->active_iocgs earlier in ioc_timer_fn().
---
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/41646836440
[email protected]
AI reviewRe: [RFC PATCH v12 3/4] selftests/bpf: add iocost cost model test
In reply to Tao CuiTL;DR: Selftest cgroup names "iocost_pairing" and "iocost_ms" lack a leading '/', so the cgroups are likely created outside the work directory and not removed by cleanup_cgroup_environment()…
Quoted 1 line
selftests/bpf: add iocost cost model test
TL;DR: Selftest cgroup names "iocost_pairing" and "iocost_ms" lack a leading '/', so the cgroups are likely created outside the work directory and not removed by cleanup_cgroup_environment(), leaving empty cgroups on the host.
Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +0
-0
[ ... ]
Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +10
-0+/* +* cgroup_setup_and_join() creates the priced-IO cgroup with the +* available controllers enabled, so the cgroup has +* io.weight/io.stat and the iocg activates. +* cleanup_cgroup_environment() removes it from every exit path +* below. io.cost.qos and io.cost.model are root-only cgroupfs +* files: they are written at the hierarchy root and reverted on +* exit. +*/ + cg =cgroup_setup_and_join ("iocost_pairing" );
[ ... ]
tools/testing/selftests/bpf/prog_tests/iocost_model.c line 603
Quoted 1 line
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +1
-0+ cg =cgroup_setup_and_join ("iocost_ms" );
Will these cgroups actually be removed by cleanup_cgroup_environment()?
The name has no leading '/', and format_cgroup_path() in cgroup_helpers.c joins the pieces with no separator:
#define format_cgroup_path_pid(buf, path, pid) \
snprintf(buf, sizeof(buf), "%s%s%d%s", CGROUP_MOUNT_PATH, \
CGROUP_WORK_DIR, pid, path)So cgroup_setup_and_join("iocost_pairing") ends up doing mkdir on "/mnt/cgroup-test-work-dir<pid>iocost_pairing". That is a sibling of the work directory directly under the cgroup2 root, not a child of it. join_cgroup(), write_cgroup_file() and read_cgroup_file() build the same path, so the test itself works.
But __cleanup_cgroup_environment() only walks the work directory:
format_cgroup_path(cgroup_workdir, "");
join_cgroup_from_top(CGROUP_MOUNT_PATH);
nftw(cgroup_workdir, nftwfunc, WALK_FD_LIMIT, FTW_DEPTH | FTW_MOUNT);so the sibling directory is never visited. The empty cgroup remains on the host as /sys/fs/cgroup/cgroup-test-work-dir<pid>iocost_pairing, which also contradicts the comment above ("cleanup_cgroup_environment() removes it from every exit path below"). serial_test_iocost_model_streams() has the same problem with "iocost_ms", including the matching write_cgroup_file() and read_cost_usage() calls.
Other callers that use a fixed name pass a leading slash, for example "/skb_cgroup_test" and "/cgroup_iter_memcg_test". Would "/iocost_pairing" and "/iocost_ms" at every place they are passed put the cgroups under the work directory where the existing cleanup removes them?
---
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/41646836440
[email protected]
AI reviewRe: [RFC PATCH v12 3/4] selftests/bpf: add iocost cost model test
In reply to Tao CuiThank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [Medium] selftests/bpf: missing leading slash in cgroup paths in iocost_model tests - [Medium]…
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [Medium] selftests/bpf: missing leading slash in cgroup paths in iocost_model tests
- [Medium] selftests/bpf: iocost_bpf_supported() requires /proc/config.gz to run tests
- [Low] selftests/bpf: unpaired cleanup_cgroup_environment() in iocost_model
- [Low] selftests/bpf: missing rmdir() on error paths in nullb_create()
--
commit 853e704fa28b8b44bb71705b9e1a9ac55510a4dd
Author: Tao Cui <[email protected]>
selftests/bpf: add iocost cost model test
This commit adds two BPF iocost cost models (a doubled linear HDD model and a multi-stream sequentiality model) along with selftests that attach them to a configfs-created null_blk device and verify pricing, tracepoints, model switching, and device removal.
Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +0
-0@@ -0,0 +1,748 @@
[ ... ]
Quoted 23 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +23
-0+static int nullb_create (const char *name,char *dev,size_t dev_sz) +{ +char path[128 ]; +char p2[128 ]; +int err; + +snprintf (path,sizeof (path),"/sys/kernel/config/nullb/%s" , name); +if (mkdir (path,0755 )) { +if (errno !=EEXIST ) +return -errno; +/* +* a leftover instance from an earlier crashed run may +* still be powered: tear it down before reusing the +* name +*/ +snprintf (p2,sizeof (p2), +"/sys/kernel/config/nullb/%s/power" , name); +configfs_write (p2,"0" ); +if (rmdir (path) && errno !=ENOENT ) +return -errno; +if (mkdir (path,0755 ) && errno !=EEXIST ) +return -errno; + }
tools/testing/selftests/bpf/prog_tests/iocost_model.c line 95
Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +10
-0+ +snprintf (path,sizeof (path),"/sys/kernel/config/nullb/%s/size" , name); + err =configfs_write (path,"128" ); +if (err) +return err; + +snprintf (path,sizeof (path),"/sys/kernel/config/nullb/%s/power" , name); + err =configfs_write (path,"1" ); +if (err) +return err;
[Severity: Low]
As reported by Sashiko on RFC v11 [1], if configfs_write() fails when writing to size or power in nullb_create(), does this return early and leave the /sys/kernel/config/nullb/<name> directory and its underlying kernel nullb_device allocated?
In serial_test_iocost_model() and serial_test_iocost_model_streams(), the callers also return directly on nullb_create() failure without calling nullb_remove(IOCOST_NULLB). Should nullb_create() remove the instance directory on these error paths just like the read_file_token() failure path below?
Quoted 14 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +14
-0+ +snprintf (path,sizeof (path),"/sys/block/%s/dev" , name); + err =read_file_token (path, dev, dev_sz); +if (err) { +/* do not leave a powered instance behind */ +snprintf (path,sizeof (path), +"/sys/kernel/config/nullb/%s/power" , name); +configfs_write (path,"0" ); +snprintf (path,sizeof (path), +"/sys/kernel/config/nullb/%s" , name); +rmdir (path); + } +return err; +}
[ ... ]
Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +6
-0+static bool iocost_bpf_supported (void ) +{ +FILE *f; +char line[128 ]; +bool on = false; +
tools/testing/selftests/bpf/prog_tests/iocost_model.c line 151
Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +10
-0+ f =popen ("zcat /proc/config.gz 2>/dev/null" ,"r" ); +if (!f) +return false; +while (fgets (line,sizeof (line), f)) { +if (strstr (line,"CONFIG_BLK_CGROUP_IOCOST_BPF=y" )) + on = true; + } +pclose (f); +return on; +}
[Severity: Medium]
As reported by Tejun Heo on RFC v11 [2], won't iocost_bpf_supported() still return false and cause iocost_test_env() to skip all three tests whenever /proc/config.gz is not present on the system, even if the running kernel has CONFIG_BLK_CGROUP_IOCOST_BPF=y enabled?
When CONFIG_IKCONFIG_PROC is disabled, popen() still succeeds while zcat outputs nothing, so fgets() reads zero lines and on remains false. In RFC v11 it was noted that the any variable tracking whether any lines were read was set but never used; here any was removed rather than used to avoid skipping when /proc/config.gz is unavailable (or falling back to /boot/config-<release> or BTF probing).
[ ... ]
Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +6
-0+ cg =cgroup_setup_and_join ("iocost_pairing" ); +if (!ASSERT_GE (cg,0 ,"setup_cg" )) { +iocost_model__destroy (skel); +nullb_remove (IOCOST_NULLB ); +return ; + }
[ ... ]
Quoted 21 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +21
-0+ASSERT_OK (join_cgroup ("iocost_pairing" ),"join_pairing" ); +snprintf (qbuf,sizeof (qbuf),"%s 1000" , dev); +ASSERT_OK (write_cgroup_file ("iocost_pairing" ,"io.weight" , + qbuf),"weight_pairing" ); +snprintf (qbuf,sizeof (qbuf), +"%s enable=1 ctrl=user min=100.00 max=100.00" , dev); +ASSERT_OK (configfs_write ("/sys/fs/cgroup/io.cost.qos" , qbuf), +"qos_enable" ); + + devfd =open (path,O_RDONLY ); +if (!ASSERT_OK (devfd <0 ? -errno :0 ,"open_dev_priced" )) { +iocost_model__destroy (skel); +snprintf (qbuf,sizeof (qbuf),"%s enable=0" , dev); + (void )configfs_write ("/sys/fs/cgroup/io.cost.qos" , qbuf); +nullb_remove (IOCOST_NULLB ); +cleanup_cgroup_environment (); +return ; + } +ASSERT_OK (read_cost_usage ("iocost_pairing" , + dev, &u1),"cost_usage_pre" ); +for (i =0 ; i <500 ; i++)
tools/testing/selftests/bpf/prog_tests/iocost_model.c line 464
Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +10
-0+ (void )read (devfd, buf,sizeof (buf)); +close (devfd); +ASSERT_GT (skel->bss->calc_costs,0 ,"model_priced" ); +/* +* the usage stat is flushed by the iocost timer, give +* the current period a chance to end before reading +*/ +sleep (3 ); +ASSERT_OK (read_cost_usage ("iocost_pairing" , + dev, &u2),"cost_usage_post" );
[Severity: Medium]
Does passing "iocost_pairing" (and "iocost_ms" in serial_test_iocost_model_streams() below) without a leading slash to cgroup_setup_and_join(), join_cgroup(), write_cgroup_file(), and read_cost_usage()->read_cgroup_file() leak the test cgroups in the root cgroup hierarchy?
In tools/testing/selftests/bpf/cgroup_helpers.c, format_cgroup_path_pid() formats paths without inserting a slash before path:
#define format_cgroup_path_pid(buf, path, pid) \
snprintf(buf, sizeof(buf), "%s%s%d%s", CGROUP_MOUNT_PATH, \
CGROUP_WORK_DIR, pid, path)Without a leading slash, this creates /mnt/cgroup-test-work-dir<pid>iocost_pairing as a sibling of /mnt/cgroup-test-work-dir<pid> rather than a child inside it. When cleanup_cgroup_environment() runs, __cleanup_cgroup_environment() only runs nftw() on /mnt/cgroup-test-work-dir<pid>, leaving the sibling cgroup directories and their associated kernel cgroup, blkcg, and cgroup storage allocated after the test finishes. Should these relative cgroup paths be "/iocost_pairing" and "/iocost_ms"?
[ ... ]
Quoted 25 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +25
-0+ err =iocost_ms__load (skel); +if (!ASSERT_OK (err,"skel_load" )) { +cleanup_cgroup_environment (); +iocost_ms__destroy (skel); +nullb_remove (IOCOST_NULLB ); +return ; + } + + err =iocost_ms__attach (skel); +if (ASSERT_OK (err,"attach" )) { + err =readback_model (dev, model,sizeof (model)); +if (ASSERT_OK (err,"readback" )) +ASSERT_STREQ (model,"bpf" ,"model_bpf" ); + +/* +* drive IO through the model: enable the controller, price +* from a cgroup, and check the model actually charged them +*/ + cg =cgroup_setup_and_join ("iocost_ms" ); +if (!ASSERT_GE (cg,0 ,"setup_cg_ms" )) { +iocost_ms__destroy (skel); +nullb_remove (IOCOST_NULLB ); +cleanup_cgroup_environment (); +return ; + }
[ ... ]
tools/testing/selftests/bpf/prog_tests/iocost_model.c line 609
Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +6
-0+ } + +iocost_ms__destroy (skel); +nullb_remove (IOCOST_NULLB ); +cleanup_cgroup_environment (); +}
[Severity: Low]
In serial_test_iocost_model_streams(), cgroup_setup_and_join() is only called inside the if (ASSERT_OK(err, "attach")) block, and it already calls cleanup_cgroup_environment() internally if it fails.
If iocost_ms__load() fails, if iocost_ms__attach() fails, or if cgroup_setup_and_join() fails, won't calling cleanup_cgroup_environment() in those paths attempt to clean up an uninitialized or already-cleaned cgroup environment and log spurious errors for /mnt/cgroup.procs?
[1] https://lore.kernel.org/r/[email protected]
[2] https://lore.kernel.org/r/[email protected]
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
Re: [RFC PATCH v12 1/4] blk-iocost: add BPF struct_ops cost model support
In reply to Tao Cuiblock/blk-iocost.c static u64 ioc_weight_prfill(struct seq_file *sf, struct blkg_policy_data *pd, · line 3309
Quoted 6 lines · Tao Cui
block/blk-iocost.c +0
-1@@ -3223,7 +3306,6 @@ static u64 ioc_weight_prfill(struct seq_file *sf, struct blkg_policy_data *pd,return 0 ; } -static int ioc_weight_show (struct seq_file *sf,void *v)
Unrelated change. Tejun pointed at this hunk in v11.
Overall makes sense to me:
Re: [RFC PATCH v12 1/4] blk-iocost: add BPF struct_ops cost model support
Hello Alexei,
Quoted 10 lines · Alexei Starovoitov
block/blk-iocost.c static u64 ioc_weight_prfill(struct seq_file *sf, struct blkg_policy_data *pd, · line 3309
Quoted 6 lines · Tao Cui
block/blk-iocost.c +0
-1@@ -3223,7 +3306,6 @@ static u64 ioc_weight_prfill(struct seq_file *sf, struct blkg_policy_data *pd,return 0 ; } -static int ioc_weight_show (struct seq_file *sf,void *v)Unrelated change. Tejun pointed at this hunk in v11.
Right, Tejun already pointed this out in v11, but I missed it when preparing v12. I'll restore the blank line in the next revision.
Quoted 2 lines
Overall makes sense to me:
Thanks for reviewing and for the ack.
Tao
Re: [RFC PATCH v12 1/4] blk-iocost: add BPF struct_ops cost model support
In reply to [email protected]Hello,
Quoted 2 lines · 在 2026/11/3 21:51, [email protected] 写道:
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] blk-iocost: lock order inversion between queue freeze andrq_qos_mutex
This was discussed in the v10 round. The attach/detach order in this series matches ioc_qos_write(). The reverse order in ioc_cost_model_write() predates this series. Tejun's conclusion at the time was:
Quoted 4 lines
The attach and detach order matches
ioc_qos_write(). The reverse order inioc_cost_model_write()predates this series and is better fixed separately. An earlier attempt to convert it ran into blk_iocost_init()'s percpu allocation under the freeze.
https://lore.kernel.org/all/aV5OwAvw1sRF1IW1@fedora/
So I don't think this is a regression introduced by this series. The pre-existing ordering issue should be addressed separately.
Quoted 1 line
- [Medium] blk-iocost: stale autop timestamps across model attach/detach
Confirmed. While a model is attached, ioc_autop_idx() returns early, leaving the timestamps at their pre-attach values. As a result, the first evaluation after detach can exceed AUTOP_CYCLE_NSEC immediately.
I'll clear both timestamps in ioc_detach_model() so the cooldown restarts fresh on detach. The io.cost.model write path already resets them through its forced refresh when switching between models, so crossing evidence collected while a BPF model drives vrate won't affect builtin profile stepping.
Thanks,
Tao
Quoted 194 lines
--
commit
145ca796c6aa0e9492a94bdce49377cc07f92750
Author: Tao Cui <[email protected]>blk-iocost: add BPF
struct_opscost model supportThis commit adds BPF
struct_opssupport (iocost_model_ops) to blk-iocost so a BPF program can calculate per-bio vtime costs and provide page transfer coefficients for a target block device. It also extends io.cost.model to switch between the linear and attached BPF cost models while suspending ctrl=auto profile stepping when a BPF model is active.Quoted 4 lines
block/blk-iocost.c +0
-0[ ... ]
Quoted 9 lines
block/blk-iocost.c +1
-1@@ -806,7 +844,7 @@ static int ioc_autop_idx(struct ioc *ioc, struct gendisk *disk)return AUTOP_SSD_DFL ;/* if user is overriding anything, maintain what was there */ -if (ioc->user_qos_params || ioc->user_cost_model) +if (ioc->user_qos_params || ioc->user_cost_model ||ioc_model (ioc))return idx;/* step up/down based on the vrate */ [ ... ]
Quoted 10 lines
block/blk-iocost.c +6
-0@@ -2908,10 +2968,33 @@ static void ioc_rqos_queue_depth_changed(struct rq_qos *rqos)spin_unlock_irq (&ioc->lock); } +/* Called by .unreg and by device removal, whichever is first. */ +static void ioc_detach_model (struct ioc *ioc) +{ +#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF +const struct iocost_model_ops *ops = ioc->attached; +block/blk-iocost.c static void ioc_rqos_queue_depth_changed(struct rq_qos *rqos) · line 2986
Quoted 10 lines
block/blk-iocost.c +10
-0+lockdep_assert_held (&ioc->rqos.disk->queue->rq_qos_mutex); + +if (!ops) +return ; + +spin_lock_irq (&ioc->lock); +rcu_assign_pointer (ioc->model,NULL ); + ioc->attached =NULL ; + ioc->attached_link =NULL ; +spin_unlock_irq (&ioc->lock);[Severity: Medium]
When ctrl=auto is active under the builtin linear model andvrate_pctcrossestoo_fast_vrate_pctortoo_slow_vrate_pctinioc_autop_idx(), the current timestamp is recorded inioc->autop_too_fast_atorioc->autop_too_slow_at, requiringAUTOP_CYCLE_NSEC(10 seconds) of sustained condition before steppingioc->autop_idx.When a BPF model is attached in
ioc_bpf_reg()and later detached inioc_detach_model(),ioc->modelis updated without callingioc_refresh_params(ioc, true)or clearingioc->autop_too_fast_atandioc->autop_too_slow_at, unlikeioc_cost_model_write()andioc_qos_write():block/blk-iocost.c:ioc_refresh_params_disk() { ... idx = ioc_autop_idx(ioc, disk); p = &autop[idx]; if (idx == ioc->autop_idx && !force) return false; ... ioc->autop_idx = idx; ioc->autop_too_fast_at = 0; ioc->autop_too_slow_at = 0; ... }While the BPF model is active,
ioc_autop_idx()returns idx early at theioc_model(ioc)check before reaching the timestamp update and reset logic, andioc_refresh_params_disk(ioc, false, disk)returns false early because idx ==ioc->autop_idx, leaving any pre-attachment timestamp inioc->autop_too_fast_atorioc->autop_too_slow_atintact.Once the BPF model is detached via
ioc_bpf_unreg()->ioc_detach_model(), on the first timer tick (ioc_timer_fn()->ioc_refresh_params(ioc, false)->ioc_autop_idx()), ifvrate_pctis past the threshold,now_ns-ioc->autop_too_fast_at(orautop_too_slow_at) includes the entire time the BPF model was attached.Could this cause
ioc_autop_idx()to immediately exceedAUTOP_CYCLE_NSECand stepioc->autop_idx(resettingvtime_rate) on the first tick after detach instead of waiting for a fullAUTOP_CYCLE_NSECcycle? Shouldioc_bpf_reg()andioc_detach_model()reset the autop timestamps or callioc_refresh_params(ioc, true)underioc->lock?[ ... ]
Quoted 38 lines
block/blk-iocost.c +19
-1@@ -3559,7 +3644,11 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,continue ;case COST_MODEL :match_strlcpy (buf, &args[0 ],sizeof (buf)); -if (strcmp (buf,"linear" )) +if (!strcmp (buf,"linear" )) + model =NULL ; +else if (!strcmp (buf,"bpf" ) && ioc->attached) + model = ioc->attached; +else goto unlock;continue ; }@@ -3579,6 +3668,7 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input, }else { ioc->user_cost_model = false; } +rcu_assign_pointer (ioc->model, model);ioc_refresh_params (ioc, true); ret =0 ;@@ -3626,6 +3716,166 @@ static struct blkcg_policy blkcg_policy_iocost = { .pd_stat_fn = ioc_pd_stat, }; +#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF +static int ioc_bpf_reg (void *kdata,struct bpf_link *link) +{ +struct iocost_model_ops *ops = kdata; +struct block_device *bdev; +struct request_queue *q; +unsigned int memflags; +struct ioc *ioc; +int ret; + + bdev =blkdev_get_no_open (new_decode_dev (ops->dev), false); +if (!bdev) +return -ENODEV ;block/blk-iocost.c static struct blkcg_policy blkcg_policy_iocost = { · line 3741
Quoted 10 lines
block/blk-iocost.c +10
-0+ + q =bdev_get_queue (bdev); +if (bdev_is_partition (bdev) || !queue_is_mq (q)) { +blkdev_put_no_open (bdev); +return -EOPNOTSUPP ; + } + +/* the order of ioc_qos_write() */ + memflags =blk_mq_freeze_queue (q); +mutex_lock (&q->rq_qos_mutex);[Severity: High]
Inioc_bpf_reg(),blk_mq_freeze_queue(q)is called before acquiringq->rq_qos_mutex, which establishes the lock order:
q->io_lockdep_map->q->q_lockdep_map->q->rq_qos_mutexHowever, in
ioc_cost_model_write()(which is used to toggle between model=linear and model=bpf),blkg_conf_open_bdev(&ctx)acquiresq->rq_qos_mutexfirst, and unlikeioc_qos_write(),ioc_cost_model_write()does not dropq->rq_qos_mutexbefore callingblk_iocost_init()andblk_mq_freeze_queue(q):block/blk-iocost.c:ioc_cost_model_write() { blkg_conf_init(&ctx, input); ret = blkg_conf_open_bdev(&ctx); // locks q->rq_qos_mutex if (ret) return ret; ... ioc = q_to_ioc(q); if (!ioc) { ret = blk_iocost_init(ctx.bdev->bd_disk); if (ret) goto close_bdev; ioc = q_to_ioc(q); } memflags = blk_mq_freeze_queue(q); // locks q->io_lockdep_map -> q->q_lockdep_map ... }This establishes the opposite lock order in
ioc_cost_model_write():
q->rq_qos_mutex->q->io_lockdep_map->q->q_lockdep_mapIn addition, paths that hold
q->rq_qos_mutexwithout freezing the queue first (such asioc_cost_model_write()->blk_iocost_init()andioc_weight_write()->blkg_conf_prep()) performGFP_KERNELallocations underq->rq_qos_mutexwithoutmemalloc_noio_save(), which can enterfs_reclaimand wait on a frozen queue.Can attaching a BPF model via
ioc_bpf_reg()and writing to io.cost.model viaioc_cost_model_write()trigger a lockdep circular locking dependency splat or an ABBA deadlock between queue freeze andq->rq_qos_mutex? Shouldioc_cost_model_write()release and re-acquireq->rq_qos_mutexaroundblk_mq_freeze_queue(q)the same wayioc_qos_write()does?
Re: [RFC PATCH v12 2/4] blk-iocost: add iocost_ioc_tick tracepoint for per-period device summary
In reply to [email protected]Hello,
Quoted 5 lines · 在 2026/11/3 22:07, [email protected] 写道:
Quoted 1 line
blk-iocost: add
iocost_ioc_ticktracepoint for per-period device summaryTL;DR: In
iocost_ioc_tick, the tracepoint call sits outside itsenabled()check, so a probe attached in between may log a bogus active count of 0, which consumers could read as dormancy.
Confirmed. nr_active is only consumed by this tracepoint, so there is no reason for trace_iocost_ioc_tick() to sit outside the trace_iocost_ioc_tick_enabled() block. The split was simply an oversight when the active count was made conditional on the tracepoint being enabled.
Quoted 36 lines
Quoted 4 lines
block/blk-iocost.c +0
-0[ ... ]
Quoted 10 lines
block/blk-iocost.c +6
-0@@ -2478,6 +2479,22 @@ static void ioc_timer_fn(struct timer_list *timer) ioc->busy_level =clamp (ioc->busy_level,-1000 ,1000 ); +/* +* busy_level, cur_period, nr_active and usage_us_sum are complete +* here. usage is wall time over wall time, summed over iocgs, and +* is not capped at 100. vrate and period_us reflect the current +* controller state, which an io.cost.qos write may have changed +* mid-period. Emit before the refresh and the period transition. block/blk-iocost.c static void ioc_timer_fn(struct timer_list *timer) · line 2497
Quoted 10 lines
block/blk-iocost.c +10
-0+*/ +if (trace_iocost_ioc_tick_enabled ()) { +struct ioc_gq *active_iocg; + +list_for_each_entry (active_iocg, &ioc->active_iocgs, + active_list) + nr_active++; + } +trace_iocost_ioc_tick (ioc, &now, nr_active, usage_us_sum); +Can this record a bogus
nr_activeof 0?
trace_iocost_ioc_tick()is called outside thetrace_iocost_ioc_tick_enabled()block, so the two static key tests are independent. If a probe is attached on another CPU between them, the first test sees the key disabled and skips the count, while the tracepoint itself then fires withnr_activestill 0 even thoughioc->active_iocgsis non-empty.
Quoted 3 lines
Documentation/trace/tracepoints.rstsays the tracepoint call should always be within the block of the if (trace_<tracepoint>_enabled()) check to avoid this race.
I'll move trace_iocost_ioc_tick() inside the enabled() block in the next posting.
Thanks,
Tao
Quoted 16 lines
Since the commit message describes active=0 as the marker for the transition to dormancy, a consumer could read this spurious record as that transition, alongside a non-zero usage value.
Would moving the
trace_iocost_ioc_tick()call inside the enabled block work? Alternatively,nr_activecould be counted in the existinglist_for_each_entry()walk overioc->active_iocgsearlier inioc_timer_fn().---
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.mdCI run summary: https://github.com/kernel-patches/bpf/actions/runs/41646836440
Re: [RFC PATCH v12 3/4] selftests/bpf: add iocost cost model test
In reply to [email protected]Hello,
Quoted 6 lines · 在 2026/11/3 22:07, [email protected] 写道:
Quoted 1 line
selftests/bpf: add iocost cost model test
TL;DR: Selftest cgroup names "
iocost_pairing" and "iocost_ms" lack a leading '/', so the cgroups are likely created outside the work directory and not removed bycleanup_cgroup_environment(), leaving empty cgroups on the host.
Confirmed. The missing leading '/' places both cgroups alongside the per-test work directory instead of inside it, so cleanup_cgroup_environment() never visits them. The test itself still works because every helper builds the same path.
I'll switch every use to "/iocost_pairing" and "/iocost_ms", so the cgroups live under the work directory and are removed by the existing cleanup.
Thanks,
Tao
Quoted 59 lines
Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +0
-0[ ... ]
Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +10
-0+/* +* cgroup_setup_and_join() creates the priced-IO cgroup with the +* available controllers enabled, so the cgroup has +* io.weight/io.stat and the iocg activates. +* cleanup_cgroup_environment() removes it from every exit path +* below. io.cost.qos and io.cost.model are root-only cgroupfs +* files: they are written at the hierarchy root and reverted on +* exit. +*/ + cg =cgroup_setup_and_join ("iocost_pairing" );[ ... ]
tools/testing/selftests/bpf/prog_tests/iocost_model.c line 603
Quoted 1 line
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +1
-0+ cg =cgroup_setup_and_join ("iocost_ms" );Will these cgroups actually be removed by
cleanup_cgroup_environment()?The name has no leading '/', and
format_cgroup_path()incgroup_helpers.cjoins the pieces with no separator:#define format_cgroup_path_pid(buf, path, pid) \ snprintf(buf, sizeof(buf), "%s%s%d%s", CGROUP_MOUNT_PATH, \ CGROUP_WORK_DIR, pid, path)So
cgroup_setup_and_join("iocost_pairing")ends up doing mkdir on "/mnt/cgroup-test-work-dir<pid>iocost_pairing". That is a sibling of the work directory directly under the cgroup2 root, not a child of it.join_cgroup(),write_cgroup_file()andread_cgroup_file()build the same path, so the test itself works.But
__cleanup_cgroup_environment()only walks the work directory:format_cgroup_path(cgroup_workdir, ""); join_cgroup_from_top(CGROUP_MOUNT_PATH); nftw(cgroup_workdir, nftwfunc, WALK_FD_LIMIT, FTW_DEPTH | FTW_MOUNT);so the sibling directory is never visited. The empty cgroup remains on the host as /sys/fs/cgroup/cgroup-test-work-dir<pid>iocost_pairing, which also contradicts the comment above ("
cleanup_cgroup_environment()removes it from every exit path below").serial_test_iocost_model_streams()has the same problem with "iocost_ms", including the matchingwrite_cgroup_file()andread_cost_usage()calls.Other callers that use a fixed name pass a leading slash, for example "/skb_cgroup_test" and "/cgroup_iter_memcg_test". Would "/iocost_pairing" and "/iocost_ms" at every place they are passed put the cgroups under the work directory where the existing cleanup removes them?
---
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.mdCI run summary: https://github.com/kernel-patches/bpf/actions/runs/41646836440
Re: [RFC PATCH v12 3/4] selftests/bpf: add iocost cost model test
In reply to [email protected]Hello,
Quoted 2 lines · 在 2026/11/3 22:16, [email protected] 写道:
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [Medium] selftests/bpf: missing leading slash in cgroup paths iniocost_modeltests
Confirmed, and the test host did accumulate leftovers named cgroup-test-work-dir<pid>iocost_pairing. Will pass "/iocost_pairing" and "/iocost_ms" so the cgroups are created inside the per-pid work directory and nftw() in __cleanup_cgroup_environment() removes them.
Quoted 1 line
- [Medium] selftests/bpf:
iocost_bpf_supported()requires/proc/config.gzto run tests
You're right. This was already pointed out in the v11 review. I removed the unused any variable in v12 without fixing the underlying issue.
I'll make the probe distinguish an unavailable kernel config from CONFIG_BLK_CGROUP_IOCOST_BPF=n instead of treating both as unsupported.
Quoted 1 line
- [Low] selftests/bpf: unpaired
cleanup_cgroup_environment()iniocost_model
Right — in serial_test_iocost_model_streams() the environment is set up after attach, so the skel_load and attach failure paths call cleanup before anything was created. Will drop cleanup from those two paths and keep it only where the setup has run.
Quoted 1 line
- [Low] selftests/bpf: missing
rmdir()on error paths innullb_create()
Confirmed. If either the size or power write fails, nullb_create() returns without removing the instance directory, leaving the configfs instance behind.
I'll mirror the read_file_token() failure path: power the instance off and remove the directory before returning.
Thanks,
Tao
Quoted 230 lines
--
commit
853e704fa28b8b44bb71705b9e1a9ac55510a4dd
Author: Tao Cui <[email protected]>selftests/bpf: add iocost cost model test
This commit adds two BPF iocost cost models (a doubled linear HDD model and a multi-stream sequentiality model) along with selftests that attach them to a configfs-created
null_blkdevice and verify pricing, tracepoints, model switching, and device removal.Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +0
-0@@ -0,0 +1,748 @@[ ... ]
Quoted 23 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +23
-0+static int nullb_create (const char *name,char *dev,size_t dev_sz) +{ +char path[128 ]; +char p2[128 ]; +int err; + +snprintf (path,sizeof (path),"/sys/kernel/config/nullb/%s" , name); +if (mkdir (path,0755 )) { +if (errno !=EEXIST ) +return -errno; +/* +* a leftover instance from an earlier crashed run may +* still be powered: tear it down before reusing the +* name +*/ +snprintf (p2,sizeof (p2), +"/sys/kernel/config/nullb/%s/power" , name); +configfs_write (p2,"0" ); +if (rmdir (path) && errno !=ENOENT ) +return -errno; +if (mkdir (path,0755 ) && errno !=EEXIST ) +return -errno; + }tools/testing/selftests/bpf/prog_tests/iocost_model.c line 95
Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +10
-0+ +snprintf (path,sizeof (path),"/sys/kernel/config/nullb/%s/size" , name); + err =configfs_write (path,"128" ); +if (err) +return err; + +snprintf (path,sizeof (path),"/sys/kernel/config/nullb/%s/power" , name); + err =configfs_write (path,"1" ); +if (err) +return err;[Severity: Low]
As reported by Sashiko on RFC v11 [1], ifconfigfs_write()fails when writing to size or power innullb_create(), does this return early and leave the /sys/kernel/config/nullb/<name> directory and its underlying kernelnullb_deviceallocated?In
serial_test_iocost_model()andserial_test_iocost_model_streams(), the callers also return directly onnullb_create()failure without callingnullb_remove(IOCOST_NULLB). Shouldnullb_create()remove the instance directory on these error paths just like theread_file_token()failure path below?Quoted 14 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +14
-0+ +snprintf (path,sizeof (path),"/sys/block/%s/dev" , name); + err =read_file_token (path, dev, dev_sz); +if (err) { +/* do not leave a powered instance behind */ +snprintf (path,sizeof (path), +"/sys/kernel/config/nullb/%s/power" , name); +configfs_write (path,"0" ); +snprintf (path,sizeof (path), +"/sys/kernel/config/nullb/%s" , name); +rmdir (path); + } +return err; +}[ ... ]
Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +6
-0+static bool iocost_bpf_supported (void ) +{ +FILE *f; +char line[128 ]; +bool on = false; +tools/testing/selftests/bpf/prog_tests/iocost_model.c line 151
Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +10
-0+ f =popen ("zcat /proc/config.gz 2>/dev/null" ,"r" ); +if (!f) +return false; +while (fgets (line,sizeof (line), f)) { +if (strstr (line,"CONFIG_BLK_CGROUP_IOCOST_BPF=y" )) + on = true; + } +pclose (f); +return on; +}[Severity: Medium]
As reported by Tejun Heo on RFC v11 [2], won'tiocost_bpf_supported()still return false and causeiocost_test_env()to skip all three tests whenever/proc/config.gzis not present on the system, even if the running kernel hasCONFIG_BLK_CGROUP_IOCOST_BPF=yenabled?When
CONFIG_IKCONFIG_PROCis disabled,popen()still succeeds while zcat outputs nothing, sofgets()reads zero lines and on remains false. In RFC v11 it was noted that the any variable tracking whether any lines were read was set but never used; here any was removed rather than used to avoid skipping when/proc/config.gzis unavailable (or falling back to /boot/config-<release> or BTF probing).[ ... ]
Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +6
-0+ cg =cgroup_setup_and_join ("iocost_pairing" ); +if (!ASSERT_GE (cg,0 ,"setup_cg" )) { +iocost_model__destroy (skel); +nullb_remove (IOCOST_NULLB ); +return ; + }[ ... ]
Quoted 21 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +21
-0+ASSERT_OK (join_cgroup ("iocost_pairing" ),"join_pairing" ); +snprintf (qbuf,sizeof (qbuf),"%s 1000" , dev); +ASSERT_OK (write_cgroup_file ("iocost_pairing" ,"io.weight" , + qbuf),"weight_pairing" ); +snprintf (qbuf,sizeof (qbuf), +"%s enable=1 ctrl=user min=100.00 max=100.00" , dev); +ASSERT_OK (configfs_write ("/sys/fs/cgroup/io.cost.qos" , qbuf), +"qos_enable" ); + + devfd =open (path,O_RDONLY ); +if (!ASSERT_OK (devfd <0 ? -errno :0 ,"open_dev_priced" )) { +iocost_model__destroy (skel); +snprintf (qbuf,sizeof (qbuf),"%s enable=0" , dev); + (void )configfs_write ("/sys/fs/cgroup/io.cost.qos" , qbuf); +nullb_remove (IOCOST_NULLB ); +cleanup_cgroup_environment (); +return ; + } +ASSERT_OK (read_cost_usage ("iocost_pairing" , + dev, &u1),"cost_usage_pre" ); +for (i =0 ; i <500 ; i++)tools/testing/selftests/bpf/prog_tests/iocost_model.c line 464
Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +10
-0+ (void )read (devfd, buf,sizeof (buf)); +close (devfd); +ASSERT_GT (skel->bss->calc_costs,0 ,"model_priced" ); +/* +* the usage stat is flushed by the iocost timer, give +* the current period a chance to end before reading +*/ +sleep (3 ); +ASSERT_OK (read_cost_usage ("iocost_pairing" , + dev, &u2),"cost_usage_post" );[Severity: Medium]
Does passing "iocost_pairing" (and "iocost_ms" inserial_test_iocost_model_streams()below) without a leading slash tocgroup_setup_and_join(),join_cgroup(),write_cgroup_file(), and read_cost_usage()->read_cgroup_file() leak the test cgroups in the root cgroup hierarchy?In
tools/testing/selftests/bpf/cgroup_helpers.c,format_cgroup_path_pid()formats paths without inserting a slash before path:#define format_cgroup_path_pid(buf, path, pid) \ snprintf(buf, sizeof(buf), "%s%s%d%s", CGROUP_MOUNT_PATH, \ CGROUP_WORK_DIR, pid, path)Without a leading slash, this creates /mnt/cgroup-test-work-dir<pid>iocost_pairing as a sibling of /mnt/cgroup-test-work-dir<pid> rather than a child inside it. When
cleanup_cgroup_environment()runs,__cleanup_cgroup_environment()only runsnftw()on /mnt/cgroup-test-work-dir<pid>, leaving the sibling cgroup directories and their associated kernel cgroup, blkcg, and cgroup storage allocated after the test finishes. Should these relative cgroup paths be "/iocost_pairing" and "/iocost_ms"?[ ... ]
Quoted 25 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +25
-0+ err =iocost_ms__load (skel); +if (!ASSERT_OK (err,"skel_load" )) { +cleanup_cgroup_environment (); +iocost_ms__destroy (skel); +nullb_remove (IOCOST_NULLB ); +return ; + } + + err =iocost_ms__attach (skel); +if (ASSERT_OK (err,"attach" )) { + err =readback_model (dev, model,sizeof (model)); +if (ASSERT_OK (err,"readback" )) +ASSERT_STREQ (model,"bpf" ,"model_bpf" ); + +/* +* drive IO through the model: enable the controller, price +* from a cgroup, and check the model actually charged them +*/ + cg =cgroup_setup_and_join ("iocost_ms" ); +if (!ASSERT_GE (cg,0 ,"setup_cg_ms" )) { +iocost_ms__destroy (skel); +nullb_remove (IOCOST_NULLB ); +cleanup_cgroup_environment (); +return ; + }[ ... ]
tools/testing/selftests/bpf/prog_tests/iocost_model.c line 609
Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +6
-0+ } + +iocost_ms__destroy (skel); +nullb_remove (IOCOST_NULLB ); +cleanup_cgroup_environment (); +}[Severity: Low]
Inserial_test_iocost_model_streams(),cgroup_setup_and_join()is only called inside the if (ASSERT_OK(err, "attach")) block, and it already callscleanup_cgroup_environment()internally if it fails.If
iocost_ms__load()fails, ifiocost_ms__attach()fails, or ifcgroup_setup_and_join()fails, won't callingcleanup_cgroup_environment()in those paths attempt to clean up an uninitialized or already-cleaned cgroup environment and log spurious errors for/mnt/cgroup.procs?[1] https://lore.kernel.org/r/[email protected]
[2] https://lore.kernel.org/r/[email protected]