blk-iocost: add BPF struct_ops cost model support
Subsystems (8)
v8 cover blk-iocost: add BPF struct_ops cost model support
This is v8 of the RFC. The attachment model is independent of controller enablement: attaching creates the ioc if needed and switches the model under the same queue freeze and quiesce as io.cost.model writes, while enabling stays with io.cost.qos; the cgroup callbacks now pair up across attach/detach.
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 v8:
- attachment no longer enables the controller: attaching creates the ioc under rq_qos_mutex (with the disk_live() check blkg_conf_open_bdev() does) and switches the model under the same freeze and quiesce as the io.cost.model writes; the implicit enable and the wbt handover are gone, and "model=bpf"/ "model=linear" switch between the attached model and the builtin model without detaching, per the v7 review
- iocg_init()/iocg_free() now pair up: the existing iocgs are walked over q->blkg_list under q->blkcg_mutex on attach and the remaining ones on detach, the same walk the blkcg policy teardown uses; cgroups without a blkg on the device yet get their callbacks at blkg creation
- ctrl=bpf is rejected (it never reads back), model=bpf fails when no model is attached
- a helper returning the model in use (stubbed to NULL when !CONFIG_BLK_CGROUP_IOCOST_BPF) replaces the scattered #ifdefs and unifies the duplicated seq_printf() in ioc_cost_model_prfill()
- the completion-time sizing is back to a plain pages * coeff like the builtin, which also removes the 64-bit division
- the bdev file pin is gone: the attach instead holds a no_open bdev reference, dropped by the removal ejection or by .unreg, whichever detaches the model first, mirroring hid_bpf's per-ops device reference without pinning the driver module. The device is looked up with
blkdev_get_no_open() and disk_live() under rq_qos_mutex, .reg rejects re-attach, and ioc_rqos_exit() ejects the model completely on device removal
- the tick tracepoint passes only ioc, &now, nr_active and usage_us_sum, and reads the rest from ioc in TP_fast_assign() like the other iocost events
- .unreg takes a queue reference before waiting on rq_qos_mutex, with an RCU tryget helper so a reference can be taken on a queue read locklessly, and re-checks whether the removal ejection already detached the model; the model clearing and the iocg_free() walk on detach are synchronized against ioc_pd_init()/ioc_pd_free() with q->blkcg_mutex
- the attach holds a queue reference across the window where it is off rq_qos_mutex between creating the ioc and switching the model, so concurrent device removal cannot free the queue from under it
- the two bpf-ci reported attach issues (re-attach check, disk_live()) and the bot selftest findings (endianness of the dev write, comment fixes) are addressed
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
Documentation/admin-guide/cgroup-v2.rst | 19 + block/Kconfig | 10 + block/Makefile | 1 + block/blk-iocost-bpf.c | 198 +++++++++++ block/blk-iocost.c | 334 +++++++++++++++++- include/linux/blk-iocost.h | 110 ++++++ include/trace/events/iocost.h | 43 +++ tools/testing/selftests/bpf/config | 2 - .../selftests/bpf/prog_tests/iocost_model.c | 233 ++++++++++++ .../selftests/bpf/progs/iocost_model.c | 138 ++++++++ tools/testing/selftests/bpf/progs/iocost_ms.c | 159 +++++++++ 11 files changed, 1237 insertions(+), 10 deletions(-) create mode 100644 block/blk-iocost-bpf.c create mode 100644 include/linux/blk-iocost.h 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
Signature · 1 line
2.43.0
RFC PATCH v8 1/4 blk-iocost: add BPF struct_ops cost model support
Add the iocost_model_ops struct_ops. Attachment follows the hid_bpf_ops model: the struct_ops instance is per-device, the target device is set in the dev member from userspace before load, .reg attaches the model to that device and switches it away from the builtin linear model, and .unreg detaches it and restores the builtin model. The struct_ops core owns the program lifetime, so there is no name registry and no bound-state bookkeeping.
calc_cost() receives the bio itself and reads whatever it needs (operation flags, size, sector, the issuing cgroup through bi_blkg->blkcg); the merge indicator stays in the separate flags argument as it is not a property of the bio. It is called from the bio charging path, so the model owns pricing for every IO on the device. The completion-time request sizing uses the transfer cost coefficients carried in the struct_ops (vtime per page for reads and writes) while the model is in use, so the builtin latency tracking and vrate adjustment follow the model's pricing; letting a model take over the QoS side is left for a later extension.
The cgroup callbacks are bound to the iocg policy init/free paths, one (cgroup, device) pair per invocation, matching the builtin cursor's lifetime, instead of the blkcg css lifecycle, which also drops the mutex from the cgroup online/offline paths.
calc_cost() runs under RCU read lock; sleepable programs are rejected in .check_member.
--- block/Kconfig | 10 + block/Makefile | 1 + block/blk-core.c | 17 ++ block/blk-iocost-bpf.c | 220 ++++++++++++++++++++++ block/blk-iocost.c | 368 ++++++++++++++++++++++++++++++++++++- include/linux/blk-iocost.h | 110 +++++++++++ 6 files changed, 718 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 +17 -0
@@ -536,6 +536,23 @@ 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); +} +EXPORT_SYMBOL (blk_get_queue_rcu); +#ifdef CONFIG_FAIL_MAKE_REQUEST static DECLARE_FAULT_ATTR (fail_make_request);
block/blk-iocost-bpf.c new file +220 -0
220 lines not on this page · raw message
block/blk-iocost.c +360 -8
474 lines not on this page · raw message
include/linux/blk-iocost.h new file +110 -0
110 lines not on this page · raw message
Signature · 1 line
2.43.0
RFC PATCH v8 2/4 selftests/bpf: add iocost cost model test
In reply to Tao CuiAdd an example cost model implementing the full builtin linear HDD formula at double cost, and a test which attaches it to one device:
the dev member of the struct_ops is written through the map's initial value before load, as hid_bpf tests do with hid_id, and loading the struct_ops attaches the model to the device. The test verifies the ctrl=bpf readback while attached, that a second model on the same device fails with -EBUSY, and that detaching restores the builtin model.
Under the same workload the doubled model charges 1.99x the builtin model (measured 2882us -> 5722us per IO, completed IO count halved). The example also sets the transfer cost coefficients so the builtin sizing follows the doubled pricing.
Per-cgroup stream state uses a CGRP_STORAGE map keyed by the cgroup of the issuing bio, so the model inherits the cgroup lifetime and frees the state with the cgroup, so a
cgroup that comes back starts fresh. opf carries the full bio->bi_opf including REQ_* flag bits, so the operation must be extracted with a mask, not compared for equality.
CONFIG_BLK_CGROUP_IOCOST and CONFIG_BLK_CGROUP_IOCOST_BPF are added to the selftest kernel config: without them vmlinux.h does not contain iocost_model_ops and the skeletons fail to build; the runtime skip cannot avoid a build dependency.
Requires root, cgroup v2 and a device given as major:minor in $IOCOST_TEST_DEV.
--- tools/testing/selftests/bpf/config | 2 + .../selftests/bpf/prog_tests/iocost_model.c | 245 ++++++++++++++++++ .../selftests/bpf/progs/iocost_model.c | 140 ++++++++++ tools/testing/selftests/bpf/progs/iocost_ms.c | 159 ++++++++++++ 4 files changed, 546 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 +245 -0
245 lines not on this page · raw message
tools/testing/selftests/bpf/progs/iocost_model.c new file +140 -0
140 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 v8 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 the tail of ioc_timer_fn() with the overall controller state: period_us, vrate, busy_level, active iocg count, usage percentage and running state. It fires every period the controller is running, including steady states, plus one final tick before the controller goes idle, which makes dormancy (e.g. a device saturated entirely by uncharged IO) directly visible.
Unlike the existing iocost tracepoints, which are state-change driven and silent in steady state, this allows a bound cost model's behaviour to be evaluated without drgn.
Depending on the autop profile this is 2-100 events per second per device; the added cost outside the tracepoint static key is one increment per active cgroup per period.
--- block/blk-iocost.c | 12 ++++++++++ include/trace/events/iocost.h | 44 +++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+)
block/blk-iocost.c +12 -0
@@ -2290,6 +2290,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;
@@ -2326,6 +2327,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.
@@ -2487,6 +2490,15 @@ 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, running and cur_period haven'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. +*/ +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 +44 -0
50 lines not on this page · raw message
Signature · 1 line
2.43.0
RFC PATCH v8 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 | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+)
Documentation/admin-guide/cgroup-v2.rst +19 -0
@@ -2117,8 +2117,27 @@ 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 attached to a device by loading an "iocost_model_ops" + struct_ops with 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. "ctrl" 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 reviewRe: [RFC PATCH v8 2/4] selftests/bpf: add iocost cost model test
In reply to Tao CuiThank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] bpf: tests exit without calling test__skip() on unsupported device - [Low] bpf: unused array…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] bpf: tests exit without calling test__skip() on unsupported device
- [Low] bpf: unused array variables in write_cost_model consume stack space --
commit e990a9d15cbbcc9c7a94ea98646f25abaa1003cf
Author: Tao Cui <[email protected]>
selftests/bpf: add iocost cost model test
This commit adds an iocost cost model test for BPF, including a double-cost linear HDD formula and a multi-stream sequentiality detection model. It verifies attaching, detaching, and cost readbacks on a block device.
Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +0
-0
[ ... ]
tools/testing/selftests/bpf/prog_tests/iocost_model.c line 49
Quoted 3 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +3
-0+static int write_cost_model (const char *dev,const char *what) +{ +char buf[128 ], line[256 ], word[256 ];
[Severity: Low]
Are the arrays line and word needed here? They consume 512 bytes of stack space but do not appear to be used anywhere in write_cost_model().
Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +5
-0+FILE *fp; +int err =0 ; + +snprintf (buf,sizeof (buf),"%s %s" , dev, what); + fp =fopen ("/sys/fs/cgroup/io.cost.model" ,"w" );
[ ... ]
Quoted 3 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +3
-0+void serial_test_iocost_model (void ) +{ +struct iocost_model *skel, *second;
[ ... ]
tools/testing/selftests/bpf/prog_tests/iocost_model.c line 112
Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +6
-0+ err =iocost_model__attach (skel); +if (err == -EOPNOTSUPP ) { +printf ("%s: device is not blk-mq or iocost unavailable, skipping\n" , + __func__); +iocost_model__destroy (skel); +return ;
[Severity: Medium]
Without calling test__skip(), the test runner might incorrectly report this test as PASSED rather than SKIPPED when the device lacks support.
Should this error path call test__skip() before returning?
Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +2
-0+ } +if (ASSERT_OK (err,"attach" )) {
[ ... ]
Quoted 3 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +3
-0+void serial_test_iocost_model_streams (void ) +{ +struct iocost_ms *skel;
[ ... ]
tools/testing/selftests/bpf/prog_tests/iocost_model.c line 230
Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +6
-0+ err =iocost_ms__attach (skel); +if (err == -EOPNOTSUPP ) { +printf ("%s: device is not blk-mq or iocost unavailable, skipping\n" , + __func__); +iocost_ms__destroy (skel); +return ;
[Severity: Medium]
Similarly, does this error path also need to call test__skip() so the test runner knows the execution was skipped rather than successfully passed?
Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +2
-0+ } +if (ASSERT_OK (err,"attach" )) {
[ ... ]
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
[email protected]
AI reviewThank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] block: Use-After-Free in q_to_ioc() list traversal due to dropped rq_qos_mutex --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] block: Use-After-Free in q_to_ioc() list traversal due to dropped rq_qos_mutex --
commit 18772c6b40ac8eb626b52af0f79d379ddd873095
Author: Tao Cui <[email protected]>
blk-iocost: add BPF struct_ops cost model support
This commit adds BPF struct_ops support to blk-iocost, allowing a BPF program to fully replace the builtin linear cost model for a device. It registers the iocost_model_ops struct_ops type and binds the custom cost model to the target device's block cgroup paths.
Quoted 8 lines
block/blk-iocost.c +1
-0@@ -3584,6 +3584,204 @@ static int ioc_cost_model_show(struct seq_file *sf, void *v)return 0 ; } +#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
[ ... ]
Quoted 8 lines
block/blk-iocost.c +8
-0+int ioc_bpf_attach (struct iocost_model_ops *ops) +{ +struct block_device *bdev; +struct request_queue *q; +struct gendisk *disk; +struct ioc *ioc; +unsigned int memflags; +int ret;
[ ... ]
block/blk-iocost.c static int ioc_cost_model_show(struct seq_file *sf, void *v) · line 3670
Quoted 13 lines
block/blk-iocost.c +13
-0+mutex_lock (&q->rq_qos_mutex); +if (!disk_live (disk) || !blk_get_queue (q)) { +mutex_unlock (&q->rq_qos_mutex); + ret = -ENODEV ; + goto put; + } + ioc =q_to_ioc (q); +if (!ioc) { + ret =blk_iocost_init (disk); +mutex_unlock (&q->rq_qos_mutex); +if (ret) + goto put_q; + ioc =q_to_ioc (q);
[Severity: High]
Is it safe to call q_to_ioc() here after dropping rq_qos_mutex?
q_to_ioc() internally calls rq_qos_id(), which traverses the non-RCU q->rq_qos linked list locklessly. Because the protecting rq_qos_mutex is unlocked just prior to this call, could a concurrent thread (such as one disabling another QoS policy via sysfs, or a device removal triggering rq_qos_exit()) modify the list and cause a use-after-free during this unprotected traversal?
Quoted 4 lines
block/blk-iocost.c +4
-0+ }else { +mutex_unlock (&q->rq_qos_mutex); + } +
[ ... ]
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
[email protected]
AI reviewRe: [RFC PATCH v8 4/4] docs: cgroup-v2: document the iocost BPF cost model attachment
In reply to Tao CuiTL;DR: Commit message only: it claims the docs cover detach restoring the builtin model and ctrl= never selecting a model, but the added text may not say either; add a sentence or trim the message.
Quoted 1 line
docs: cgroup-v2: document the iocost BPF cost model attachment
TL;DR: Commit message only: it claims the docs cover detach restoring the builtin model and ctrl= never selecting a model, but the added text may not say either; add a sentence or trim the message.
Quoted 10 lines
docs: cgroup-v2: document the iocost BPF cost model attachment
Document the BPF cost model attachment in the io.cost.model section of the cgroup v2 documentation: attaching an
iocost_model_opsstruct_opsto 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.Signed-off-by Tao Cui <[email protected]>
The commit message says the patch documents "that detaching restores the builtin model, and that ctrl= writes never select a model". Does the added text actually cover both of those points?
The new paragraph says:
only detaching removes the model, after which "model=bpf" fails. "ctrl" keeps describing the builtin coefficients, ...
It never says that the device goes back to the builtin model on detach, although ioc_bpf_detach() clears ioc->model and the readback then shows "linear".
It also never says that a ctrl= write cannot select the BPF model. That is what the code does:
block/blk-iocost.c:ioc_cost_model_write() {
...
accepts only ctrl=auto and ctrl=user, and any other value takes 'goto unlock' and returns -EINVAL
...
}
Could a sentence be added to the documentation saying that "ctrl" accepts only "auto" or "user" and that detaching returns the device to the builtin model? Otherwise, could those two clauses be dropped from the commit message?
---
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/36689638400
Hello,
Quoted 3 lines · 在 2026/9/30 16:11, [email protected] 写道:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] block: Use-After-Free inq_to_ioc()list traversal due to droppedrq_qos_mutex--
The findings are confirmed; here is
how each will be addressed in the next revision:
1. Lockless q_to_ioc() in the attach path (sashiko, patch 1).
Confirmed. After blk_iocost_init() succeeds, the attach path called q_to_ioc() with rq_qos_mutex released. Although the returned value was not used, q_to_ioc() walks the non-RCU rq_qos list and should not be called outside its synchronization. The unnecessary lookup is removed.
2. Missing test__skip() on -EOPNOTSUPP (sashiko, patch 2).
Confirmed. Both attach paths now call test__skip() before returning so skipped tests are reported correctly. The unused line[256]/word[256] arrays in write_cost_model() are removed as well.
3. Documentation commit message vs. text (bpf-ci, patch 4).
Confirmed. The commit message described two behaviors that were not stated explicitly in the documentation. The documentation is extended to say that detaching restores the builtin model, and that the ctrl field accepts only "auto" and "user" and never selects the active model.
Thanks,
Tao
Tejun Heo
maintainerHello, Tao.
The following is a Claude-generated review.
Quoted 7 lines · Tao Cui
Add the
iocost_model_opsstruct_ops. Attachment follows thehid_bpf_opsmodel: thestruct_opsinstance is per-device, the target device is set in the dev member from userspace before load, .reg attaches the model to that device and switches it away from the builtin linear model, and .unreg detaches it and restores the builtin model. Thestruct_opscore owns the program lifetime, so there is no name registry and no bound-state bookkeeping.
...
Quoted 4 lines
The cgroup callbacks are bound to the iocg policy init/free paths, one (cgroup, device) pair per invocation, matching the builtin cursor's lifetime, instead of the blkcg css lifecycle, which also drops the mutex from the cgroup online/offline paths.
The description is written against earlier versions. There is no name registry, css lifecycle binding or mutex in the tree, so a reader of the commit can't follow it. Can you open with why a pluggable model is wanted and then describe what the patch does: attach creates the ioc and switches the model under the same freeze as io.cost.model writes, model=bpf and model=linear select between the attached and builtin models, device removal ejects the model, and so on? Also, the model prices every charged IO, not every IO. Root cgroup IOs and IOs while the controller is disabled never reach it.
Quoted 5 lines
block/blk-core.c +5
-0+bool blk_get_queue_rcu (struct request_queue *q) +{ +return refcount_inc_not_zero (&q->refs); +} +EXPORT_SYMBOL (blk_get_queue_rcu);
...
block/blk-iocost-bpf.c line 28
Quoted 4 lines
block/blk-iocost-bpf.c new file +4
-0+struct block_device *blkdev_get_no_open (dev_t dev,bool autoload); +void blkdev_put_no_open (struct block_device *bdev); +bool blk_get_queue_rcu (struct request_queue *q); +void blk_put_queue (struct request_queue *q);
blk_get_queue_rcu() has no prototype in any header, so every build warns on it. Can you declare it in block/blk.h, include "blk.h" from blk-iocost-bpf.c and drop these local prototypes? blkdev_get_no_open() and blkdev_put_no_open() are already in blk.h and blk_put_queue() in blkdev.h. The export isn't needed either as the only user is built-in.
Quoted 1 line
block/blk-iocost-bpf.c new file +1
-0+case offsetof(struct iocost_model_ops , bdev):
...
block/blk-iocost-bpf.c line 87
Quoted 1 line
block/blk-iocost-bpf.c new file +1
-0+case offsetof(struct iocost_model_ops , q):
The struct_ops core rejects non-zero non-function members that init_member doesn't claim and kvalue starts zeroed, so these two cases can go. Same for the name lookup in .init, the core has already found the struct by then.
block/blk-iocost-bpf.c line 148
Quoted 2 lines
block/blk-iocost-bpf.c new file +2
-0+rcu_read_lock (); + q =rcu_dereference (ops->q);
ops->q isn't __rcu annotated, so sparse will complain here. Either annotate it and use RCU_INIT_POINTER() for the stores, or READ_ONCE() it. The RCU section protects the queue, not the ops pointer.
Quoted 8 lines
block/blk-iocost.c +8
-0+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF + { +struct iocost_model_ops *ops; + +spin_lock_irq (&ioc->lock); + ops = (struct iocost_model_ops *)rcu_dereference_protected ( + ioc->attached,lockdep_is_held (&ioc->lock)); +rcu_assign_pointer (ioc->attached,NULL );
block/blk-iocost.c static void ioc_rqos_exit(struct rq_qos *rqos) · line 3005
Quoted 10 lines
block/blk-iocost.c +10
-0+rcu_assign_pointer (ioc->model,NULL ); +spin_unlock_irq (&ioc->lock); + +/* eject the model completely on device removal */ +if (ops) { +WRITE_ONCE (ops->q,NULL ); +blkdev_put_no_open (ops->bdev); + } + } +#endif
Once ops->q is NULL, .unreg returns without taking rq_qos_mutex, the link can go away and the struct_ops map which holds ops can be freed after a grace period. This path isn't in an RCU read section, so reading ops->bdev after the store is a use-after-free window. Read bdev first and make the NULL store the last access.
This is also a block scoping a variable. Can you make it an ioc_bpf_eject() helper next to attach and detach, with an empty stub for !CONFIG_BLK_CGROUP_IOCOST_BPF? That removes the #ifdef and the const cast. The remaining #ifdefs in ioc_cost_model_write() would go away too if the two pointers in struct ioc were unconditional.
Quoted 7 lines
+ * Deliver iocg_init()/iocg_free() to the cgroups which already have a
+ * blkg on the queue, the sameq->blkg_listwalk the blkcg policy
+ * teardown uses. The queue is frozen and quiesced andblkcg_mutex
+ * serializes against blkg creation and destruction. Cgroups without
+ * a blkg on the device yet are not missed: their blkg is created
+ * later and ioc_pd_init()/ioc_pd_free() deliver the callbacks then.
+ */
blkcg_mutex doesn't serialize blkg creation. The IO path creates blkgs from bio_associate_blkg() through blkg_lookup_create(), before bio_queue_enter(), so the freeze doesn't stop it either, and blkg_create() runs pd_init and then list_add() to q->blkg_list under queue_lock only. Against the attach:
1. ioc->attached is published, blkg_create() runs ioc_pd_init() which delivers iocg_init(), then list_add(), then the walk delivers iocg_init() again.
2. blkg_create() runs ioc_pd_init() while attached is NULL, the walk runs before list_add(), and the blkg never gets iocg_init() but gets iocg_free() from ioc_pd_free() or the detach walk.
Detach has the mirror cases. The walk is also the only q->blkg_list walker without queue_lock, and a plain list_for_each_entry() against a concurrent list_add() isn't safe. The teardown walk this mirrors holds blkcg_mutex and queue_lock. Can you publish and clear ioc->attached and walk under queue_lock as well? ioc_pd_init() already calls iocg_init() under queue_lock, so nothing changes for the BPF side.
While at it, the walk goes newest first, so children usually get iocg_init() before their parents. blkcg_activate_policy() walks in reverse for that reason.
block/blk-iocost.c static int ioc_cost_model_show(struct seq_file *sf, void *v) · line 3630
Quoted 3 lines
block/blk-iocost.c +3
-0+/* prevent multiple attach of the same struct_ops */ +if (ops->q) +return -EINVAL ;
On the link path the map stays READY after .unreg, so a map can be attached again through a new link. If the device goes away, the ejection clears ops->q while the old link is still open, a device with the same dev_t comes back and a new link attaches the same map, closing the old link then detaches the new attachment. Recording the owning link in the ops and having .unreg detach only when it matches would close that.
Quoted 13 lines
block/blk-iocost.c +13
-0+/* +* check liveness and create the ioc under rq_qos_mutex, like +* blkg_conf_open_bdev() does; enabling stays with io.cost.qos +* +* the queue reference is held across the unlocked window below: +* the bdev reference does not pin the queue, bdev only holds a +* raw bd_queue pointer, and concurrent device removal may eject +* the model and free the ioc while we are off the mutex, so +* without our own reference the second mutex_lock() would touch +* a freed queue +*/ +mutex_lock (&q->rq_qos_mutex); +if (!disk_live (disk) || !blk_get_queue (q)) {
...
block/blk-iocost.c static int ioc_cost_model_show(struct seq_file *sf, void *v) · line 3667
Quoted 4 lines
block/blk-iocost.c +4
-0+ ioc =q_to_ioc (q); +if (!ioc) { + ret =blk_iocost_init (disk); +mutex_unlock (&q->rq_qos_mutex);
Why drop rq_qos_mutex here? ioc_cost_model_write() holds it from blkg_conf_open_bdev() across blk_iocost_init() and its own freeze and quiesce, so attach can hold it from the disk_live() check through the unfreeze. Then the ioc can't be freed under us and the queue reference, the second q_to_ioc() check and this comment go away. The comment is also
wrong: a whole-disk no-open bdev reference holds the disk device, and disk_release() is what drops the queue reference.
Thanks.
--
tejun
Tejun Heo
maintainerRe: [RFC PATCH v8 2/4] selftests/bpf: add iocost cost model test
In reply to Tao CuiHello, Tao.
The following is a Claude-generated review.
Quoted 8 lines · Tao Cui
Add an example cost model implementing the full builtin linear HDD formula at double cost, and a test which attaches it to one device:
the dev member of thestruct_opsis written through the map's initial value before load, ashid_bpftests do withhid_id, and loading thestruct_opsattaches the model to the device. The test verifies the ctrl=bpf readback while attached, that a second model on the same device fails with-EBUSY, and that detaching restores the builtin model.
...
Quoted 3 lines
cgroup that comes back starts fresh. opf carries the full
bio->bi_opfincluding REQ_* flag bits, so the operation must be extracted with a mask, not compared for equality.
The description is out of date. The test reads back model=bpf and checks that ctrl=bpf is rejected, calc_cost() takes the bio so there is no opf argument, attaching rather than loading binds the model, and the multi-stream model and its test aren't mentioned at all.
Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +5
-0+if (fwrite (buf,1 ,strlen (buf), fp) !=strlen (buf)) + err =ferror (fp) ? errno :EIO ; +if (fclose (fp) && !err) + err = errno; +return err;
...
tools/testing/selftests/bpf/prog_tests/iocost_model.c line 159
Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +2
-0+ err =write_cost_model (dev,"ctrl=bpf" ); +ASSERT_ERR (err,"ctrl_bpf_rejected" );
write_cost_model() returns a positive errno while ASSERT_ERR() wants a negative value, so this and model_bpf_after_detach fail with "unexpected
success: 22" on a correct kernel. Return -errno. Can you double check that the posted runner passes against the posted kernel?
tools/testing/selftests/bpf/prog_tests/iocost_model.c line 94
Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +2
-0+/* dev is the first member of struct iocost_model_ops */ + ops_dev =bpf_map__initial_value (skel->maps.iocost_2x,NULL );
The skeleton exposes the struct_ops shadow type, so skel->struct_ops.iocost_2x->dev = ... is type checked and drops the layout assumption. Same for iocost_ms.
tools/testing/selftests/bpf/progs/iocost_model.c line 134
Quoted 2 lines
tools/testing/selftests/bpf/progs/iocost_model.c new file +2
-0+SEC(".struct_ops") +struct iocost_model_ops iocost_2x = {
With a plain struct_ops map, a test that dies between attach and detach leaves the model attached until something deletes the map element. The hid and sched_ext selftests use ".struct_ops.link" so that closing the fd detaches. Can you use that here too?
tools/testing/selftests/bpf/progs/iocost_model.c line 118
Quoted 4 lines
tools/testing/selftests/bpf/progs/iocost_model.c new file +4
-0+ cur = *cursor; +if (cur && priced) { + seek_pages = sector > cur ? sector - cur + : cur - sector;
A dataless flush is REQ_OP_WRITE|REQ_PREFLUSH at sector 0 with bi_size 0, so priced is set here. Once a cgroup's cursor is past 16MB, every fsync is judged a random write and charged 2 * (WRANDIO + WPAGE), about 5ms, not the one-page write the header comment describes, and iocost_ms.c prices the same bio with the sequential base. Can you gate the seek judgement on a non-zero size?
Thanks.
--
tejun
Tejun Heo
maintainerRe: [RFC PATCH v8 3/4] blk-iocost: add iocost_ioc_tick tracepoint for per-period device summary
In reply to Tao CuiHello, Tao.
The following is a Claude-generated review.
Quoted 7 lines · Tao Cui
Add
iocost_ioc_tick, emitted once per period from the tail ofioc_timer_fn()with the overall controller state:period_us, vrate,busy_level, active iocg count, usage percentage and running state. It fires every period the controller is running, including steady states, plus one final tick before the controller goes idle, which makes dormancy (e.g. a device saturated entirely by uncharged IO) directly visible.
...
include/trace/events/iocost.h TRACE_EVENT(iocost_ioc_vrate_adj, · line 215
Quoted 1 line
include/trace/events/iocost.h +1
-0+ __entry->running = ioc->running;
The timer only runs while ioc->running is IOC_RUNNING and the switch to IOC_IDLE happens after the trace call, so this field always reads running except when racing ioc_rqos_exit(). The final tick before going idle reads active=0 running=1, and dormancy is only visible through the ticks stopping, not through the field. Can you either drop the field or report list_empty(&ioc->active_iocgs), and adjust the description? The event is also emitted before the vrate adjustment and the period transition, not from the tail of the function.
Thanks.
--
tejun
Tejun Heo
maintainerRe: [RFC PATCH v8 4/4] docs: cgroup-v2: document the iocost BPF cost model attachment
In reply to Tao CuiHello, Tao.
The following is a Claude-generated review.
Quoted 3 lines · Tao Cui
Documentation/admin-guide/cgroup-v2.rst +3
-0+ When CONFIG_BLK_CGROUP_IOCOST_BPF is enabled, a BPF cost model + can be attached to a device by loading an "iocost_model_ops" + struct_ops with the whole disk's major:minor in its "dev" member
...
Documentation/admin-guide/cgroup-v2.rst IO Interface Files · line 2135
Quoted 3 lines
Documentation/admin-guide/cgroup-v2.rst +3
-0+ 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
Attaching, not loading, binds the model. The test loads a second model fine and only its attach fails. Device removal also removes the model, and the user still has to tear down the struct_ops link afterwards. Can you mention that too?
Thanks.
--
tejun
Hello, Tejun.
Quoted 18 lines · Tejun Heo
Hello, Tao.
The following is a Claude-generated review.
Quoted 7 lines · Tao Cui
Add the
iocost_model_opsstruct_ops. Attachment follows thehid_bpf_opsmodel: thestruct_opsinstance is per-device, the target device is set in the dev member from userspace before load, .reg attaches the model to that device and switches it away from the builtin linear model, and .unreg detaches it and restores the builtin model. Thestruct_opscore owns the program lifetime, so there is no name registry and no bound-state bookkeeping....
Quoted 4 lines
The cgroup callbacks are bound to the iocg policy init/free paths, one (cgroup, device) pair per invocation, matching the builtin cursor's lifetime, instead of the blkcg css lifecycle, which also drops the mutex from the cgroup online/offline paths.
Quoted 10 lines
The description is written against earlier versions. There is no name registry, css lifecycle binding or mutex in the tree, so a reader of the commit can't follow it. Can you open with why a pluggable model is wanted and then describe what the patch does: attach creates the ioc and switches the model under the same freeze as io.cost.model writes, model=bpf and model=linear select between the attached and builtin models, device removal ejects the model, and so on? Also, the model prices every charged IO, not every IO. Root cgroup IOs and IOs while the controller is disabled never reach it.
The commit message is rewritten to open with why a pluggable model is wanted and describe the current behavior. It also clarifies that the model prices every charged IO rather than every IO.
Quoted 6 lines
Quoted 5 lines
block/blk-core.c +5
-0+bool blk_get_queue_rcu (struct request_queue *q) +{ +return refcount_inc_not_zero (&q->refs); +} +EXPORT_SYMBOL (blk_get_queue_rcu);...
Quoted 11 lines
block/blk-iocost-bpf.c line 28
Quoted 4 lines
block/blk-iocost-bpf.c new file +4
-0+struct block_device *blkdev_get_no_open (dev_t dev,bool autoload); +void blkdev_put_no_open (struct block_device *bdev); +bool blk_get_queue_rcu (struct request_queue *q); +void blk_put_queue (struct request_queue *q);
blk_get_queue_rcu()has no prototype in any header, so every build warns on it. Can you declare it inblock/blk.h, include "blk.h" fromblk-iocost-bpf.cand drop these local prototypes?blkdev_get_no_open()andblkdev_put_no_open()are already inblk.handblk_put_queue()inblkdev.h. The export isn't needed either as the only user is built-in.
Done: declared in block/blk.h without the export, and blk-iocost-bpf.c includes "blk.h" instead of carrying local prototypes.
Quoted 9 lines
Quoted 1 line
block/blk-iocost-bpf.c new file +1
-0+case offsetof(struct iocost_model_ops , bdev):...
block/blk-iocost-bpf.c line 87
Quoted 1 line
block/blk-iocost-bpf.c new file +1
-0+case offsetof(struct iocost_model_ops , q):The
struct_opscore rejects non-zero non-function members thatinit_memberdoesn't claim and kvalue starts zeroed, so these two cases can go. Same for the name lookup in .init, the core has already found the struct by then.
The bdev and q cases in .init_member() are gone, and the redundant name lookup is removed from .init().
Quoted 7 lines
block/blk-iocost-bpf.c line 148
Quoted 2 lines
block/blk-iocost-bpf.c new file +2
-0+rcu_read_lock (); + q =rcu_dereference (ops->q);
ops->qisn't__rcuannotated, so sparse will complain here. Either annotate it and useRCU_INIT_POINTER()for the stores, orREAD_ONCE()it. The RCU section protects the queue, not the ops pointer.
ops->q and the owning link are written with WRITE_ONCE() and read with READ_ONCE().
Quoted 16 lines
Quoted 16 lines
block/blk-iocost.c +16
-0+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF + { +struct iocost_model_ops *ops; + +spin_lock_irq (&ioc->lock); + ops = (struct iocost_model_ops *)rcu_dereference_protected ( + ioc->attached,lockdep_is_held (&ioc->lock)); +rcu_assign_pointer (ioc->attached,NULL ); +rcu_assign_pointer (ioc->model,NULL ); +spin_unlock_irq (&ioc->lock); + +/* eject the model completely on device removal */ +if (ops) { +WRITE_ONCE (ops->q,NULL ); +blkdev_put_no_open (ops->bdev); + }
Quoted 9 lines
Review
Quoted 2 lines
(quoted diff) +2
-0+ } +#endifOnce
ops->qis NULL, .unreg returns without takingrq_qos_mutex, the link can go away and thestruct_opsmap which holds ops can be freed after a grace period. This path isn't in an RCU read section, so readingops->bdevafter the store is a use-after-free window. Read bdev first and make the NULL store the last access.
Done: the ejection reads bdev into a local before clearing ops->q.
Quoted 6 lines
This is also a block scoping a variable. Can you make it an
ioc_bpf_eject()helper next to attach and detach, with an empty stub for !CONFIG_BLK_CGROUP_IOCOST_BPF? That removes the #ifdef and the const cast. The remaining #ifdefs inioc_cost_model_write()would go away too if the two pointers in struct ioc were unconditional.
Done: ioc_bpf_eject() with a stub drops the #ifdef from ioc_rqos_exit(), and the attached and model pointers in struct ioc are unconditional, so the remaining #ifdefs in ioc_cost_model_write() are gone too.
Quoted 29 lines
Quoted 7 lines
+ * Deliver iocg_init()/iocg_free() to the cgroups which already have a
+ * blkg on the queue, the sameq->blkg_listwalk the blkcg policy
+ * teardown uses. The queue is frozen and quiesced andblkcg_mutex
+ * serializes against blkg creation and destruction. Cgroups without
+ * a blkg on the device yet are not missed: their blkg is created
+ * later and ioc_pd_init()/ioc_pd_free() deliver the callbacks then.
+ */
blkcg_mutexdoesn't serialize blkg creation. The IO path creates blkgs frombio_associate_blkg()throughblkg_lookup_create(), beforebio_queue_enter(), so the freeze doesn't stop it either, andblkg_create()runspd_initand thenlist_add()toq->blkg_listunderqueue_lockonly. Against the attach:1.
ioc->attachedis published,blkg_create()runsioc_pd_init()which deliversiocg_init(), thenlist_add(), then the walk deliversiocg_init()again.2.
blkg_create()runsioc_pd_init()while attached is NULL, the walk runs beforelist_add(), and the blkg never getsiocg_init()but getsiocg_free()fromioc_pd_free()or the detach walk.Detach has the mirror cases. The walk is also the only
q->blkg_listwalker withoutqueue_lock, and a plainlist_for_each_entry()against a concurrentlist_add()isn't safe. The teardown walk this mirrors holdsblkcg_mutexandqueue_lock. Can you publish and clearioc->attachedand walk underqueue_lockas well?ioc_pd_init()already callsiocg_init()underqueue_lock, so nothing changes for the BPF side.
Quoted 4 lines
While at it, the walk goes newest first, so children usually get
iocg_init()before their parents.blkcg_activate_policy()walks in reverse for that reason.
You were right that blkcg_mutex alone did not serialize against blkg creation from the IO path. The attachment is now published and cleared under blkcg_mutex and queue_lock, and the blkg walk is performed under the same locking; the init walk goes parents first like blkcg_activate_policy().
Quoted 11 lines
block/blk-iocost.c static int ioc_cost_model_show(struct seq_file *sf, void *v) · line 3630
Quoted 3 lines
block/blk-iocost.c +3
-0+/* prevent multiple attach of the same struct_ops */ +if (ops->q) +return -EINVAL ;On the link path the map stays READY after .unreg, so a map can be attached again through a new link. If the device goes away, the ejection clears
ops->qwhile the old link is still open, a device with the samedev_tcomes back and a new link attaches the same map, closing the old link then detaches the new attachment. Recording the owning link in the ops and having .unreg detach only when it matches would close that.
Done: .unreg records the owning link in the ops and only detaches when the closing link matches.
Quoted 14 lines
Quoted 13 lines
block/blk-iocost.c +13
-0+/* +* check liveness and create the ioc under rq_qos_mutex, like +* blkg_conf_open_bdev() does; enabling stays with io.cost.qos +* +* the queue reference is held across the unlocked window below: +* the bdev reference does not pin the queue, bdev only holds a +* raw bd_queue pointer, and concurrent device removal may eject +* the model and free the ioc while we are off the mutex, so +* without our own reference the second mutex_lock() would touch +* a freed queue +*/ +mutex_lock (&q->rq_qos_mutex); +if (!disk_live (disk) || !blk_get_queue (q)) {...
Quoted 13 lines
block/blk-iocost.c static int ioc_cost_model_show(struct seq_file *sf, void *v) · line 3667
Quoted 4 lines
block/blk-iocost.c +4
-0+ ioc =q_to_ioc (q); +if (!ioc) { + ret =blk_iocost_init (disk); +mutex_unlock (&q->rq_qos_mutex);Why drop
rq_qos_mutexhere?ioc_cost_model_write()holds it fromblkg_conf_open_bdev()acrossblk_iocost_init()and its own freeze and quiesce, so attach can hold it from thedisk_live()check through the unfreeze. Then the ioc can't be freed under us and the queue reference, the secondq_to_ioc()check and this comment go away. The comment is also
wrong: a whole-disk no-open bdev reference holds the disk device, anddisk_release()is what drops the queue reference.
Done: the attach holds rq_qos_mutex from the disk_live() check through the unfreeze, like ioc_cost_model_write() does, so the unlock window, the queue reference, the second q_to_ioc() and its comment are gone.
Thanks.
Tao
Quoted 4 lines
Thanks.
--
tejun
Re: [RFC PATCH v8 2/4] selftests/bpf: add iocost cost model test
In reply to Tejun HeoHello, Tejun.
Quoted 14 lines · Tejun Heo
Hello, Tao.
The following is a Claude-generated review.
Quoted 8 lines · Tao Cui
Add an example cost model implementing the full builtin linear HDD formula at double cost, and a test which attaches it to one device:
the dev member of thestruct_opsis written through the map's initial value before load, ashid_bpftests do withhid_id, and loading thestruct_opsattaches the model to the device. The test verifies the ctrl=bpf readback while attached, that a second model on the same device fails with-EBUSY, and that detaching restores the builtin model....
Quoted 9 lines
Quoted 3 lines
cgroup that comes back starts fresh. opf carries the full
bio->bi_opfincluding REQ_* flag bits, so the operation must be extracted with a mask, not compared for equality.The description is out of date. The test reads back model=bpf and checks that ctrl=bpf is rejected,
calc_cost()takes the bio so there is no opf argument, attaching rather than loading binds the model, and the multi-stream model and its test aren't mentioned at all.
The commit message is rewritten to describe the current test, including the multi-stream model.
Quoted 6 lines
Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +5
-0+if (fwrite (buf,1 ,strlen (buf), fp) !=strlen (buf)) + err =ferror (fp) ? errno :EIO ; +if (fclose (fp) && !err) + err = errno; +return err;...
Quoted 8 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c line 159
Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +2
-0+ err =write_cost_model (dev,"ctrl=bpf" ); +ASSERT_ERR (err,"ctrl_bpf_rejected" );
write_cost_model()returns a positive errno whileASSERT_ERR()wants a negative value, so this andmodel_bpf_after_detachfail with "unexpected
success: 22" on a correct kernel. Return -errno. Can you double check that the posted runner passes against the posted kernel?
Fixed, it returns -errno. The posted runner had not been run against the posted kernel; it now passes against the v9 kernel.
Quoted 7 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c line 94
Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +2
-0+/* dev is the first member of struct iocost_model_ops */ + ops_dev =bpf_map__initial_value (skel->maps.iocost_2x,NULL );The skeleton exposes the
struct_opsshadow type, soskel->struct_ops.iocost_2x->dev= ... is type checked and drops the layout assumption. Same foriocost_ms.
Done for both models.
Quoted 8 lines
tools/testing/selftests/bpf/progs/iocost_model.c line 134
Quoted 2 lines
tools/testing/selftests/bpf/progs/iocost_model.c new file +2
-0+SEC(".struct_ops") +struct iocost_model_ops iocost_2x = {With a plain
struct_opsmap, a test that dies between attach and detach leaves the model attached until something deletes the map element. The hid andsched_extselftests use ".struct_ops.link" so that closing the fd detaches. Can you use that here too?
Done, both maps are ".struct_ops.link".
Quoted 12 lines
tools/testing/selftests/bpf/progs/iocost_model.c line 118
Quoted 4 lines
tools/testing/selftests/bpf/progs/iocost_model.c new file +4
-0+ cur = *cursor; +if (cur && priced) { + seek_pages = sector > cur ? sector - cur + : cur - sector;A dataless flush is REQ_OP_WRITE|REQ_PREFLUSH at sector 0 with
bi_size0, so priced is set here. Once a cgroup's cursor is past 16MB, every fsync is judged a random write and charged 2 * (WRANDIO + WPAGE), about 5ms, not the one-page write the header comment describes, andiocost_ms.cprices the same bio with the sequential base. Can you gate the seek judgement on a non-zero size?
Done: the seek judgement is now gated on a non-zero IO size, so a dataless flush is priced as a size-zero sequential write, matching the builtin model.
Thanks.
Tao
Quoted 4 lines
Thanks.
--
tejun
Re: [RFC PATCH v8 3/4] blk-iocost: add iocost_ioc_tick tracepoint for per-period device summary
In reply to Tejun HeoHello, Tejun.
Quoted 13 lines · Tejun Heo
Hello, Tao.
The following is a Claude-generated review.
Quoted 7 lines · Tao Cui
Add
iocost_ioc_tick, emitted once per period from the tail ofioc_timer_fn()with the overall controller state:period_us, vrate,busy_level, active iocg count, usage percentage and running state. It fires every period the controller is running, including steady states, plus one final tick before the controller goes idle, which makes dormancy (e.g. a device saturated entirely by uncharged IO) directly visible....
Quoted 11 lines
include/trace/events/iocost.h TRACE_EVENT(iocost_ioc_vrate_adj, · line 215
Quoted 1 line
include/trace/events/iocost.h +1
-0+ __entry->running = ioc->running;The timer only runs while
ioc->runningisIOC_RUNNINGand the switch toIOC_IDLEhappens after the trace call, so this field always reads running except when racingioc_rqos_exit(). The final tick before going idle reads active=0 running=1, and dormancy is only visible through the ticks stopping, not through the field. Can you either drop the field or reportlist_empty(&ioc->active_iocgs), and adjust the description? The event is also emitted before the vrate adjustment and the period transition, not from the tail of the function.
Done. The field now reports whether the active_iocgs list is empty, rather than ioc->running, so the final tick directly reflects the transition to dormancy. The description is updated accordingly: the event is emitted before the vrate adjustment and the period transition, not from the tail of ioc_timer_fn().
Thanks.
Tao
Quoted 4 lines
Thanks.
--
tejun
Re: [RFC PATCH v8 4/4] docs: cgroup-v2: document the iocost BPF cost model attachment
In reply to Tejun HeoHello, Tejun.
Quoted 9 lines · Tejun Heo
Hello, Tao.
The following is a Claude-generated review.
Quoted 3 lines · Tao Cui
Documentation/admin-guide/cgroup-v2.rst +3
-0+ When CONFIG_BLK_CGROUP_IOCOST_BPF is enabled, a BPF cost model + can be attached to a device by loading an "iocost_model_ops" + struct_ops with the whole disk's major:minor in its "dev" member...
Quoted 9 lines
Documentation/admin-guide/cgroup-v2.rst IO Interface Files · line 2135
Quoted 3 lines
Documentation/admin-guide/cgroup-v2.rst +3
-0+ 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 builtinAttaching, not loading, binds the model. The test loads a second model fine and only its attach fails. Device removal also removes the model, and the user still has to tear down the
struct_opslink afterwards. Can you mention that too?
Done: the documentation now says attaching binds the model, that removing the device ejects it as well, and that the user still has to tear down the struct_ops link afterwards.
Thanks.
Tao
Quoted 4 lines
Thanks.
--
tejun