Skip to contentSkip to conversation

blk-iocost: BPF struct_ops cost model

RFC PATCH Superseded Tao Cui 2 participants 3 messages Sep 16

Subsystems (5)
Block layer Kselftest BPF cgroup +1 more subsystems

v4 of 14 Superseded Latest is v14 →

lore
Share & tools
lore

Tao Cui

author
#0 lore raw

v4 cover blk-iocost: BPF struct_ops cost model

From: Tao Cui <[email protected]>

This is v4 of the RFC. The changes since v3 are listed in the changelog at the bottom.

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, following the TCP congestion control model registration pattern: 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
---

A bound BPF model fully owns pricing for every IO on the device:
it is called from the bio charging path and prices every operation including flushes. The completion-time request sizing for the latency met/missed accounting still uses the builtin coefficients (the request's bio, and with it the issuing cgroup, is gone by then); extending the model there is left open by this interface. The builtin cursor is not exposed; a model is expected to track its own stream state. Model state keyed by the blkcg alone is shared across every device the model is bound to, unlike the builtin cursor which is per (cgroup, device).

u64 calc_cost(u64 opf, u64 nbytes, sector_t sector,
struct blkcg *blkcg, u64 model_flags)

opf is the full bio->bi_opf (the operation must be extracted with a mask, and the REQ_* flag bits, including PREFLUSH/FUA, are part of it); model_flags carries iocost-specific metadata which is not part of the bio operation flags, 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. blkcg is passed so the model can key per-cgroup state; state stored in BPF_MAP_TYPE_CGRP_STORAGE follows the cgroup lifetime, and optional blkcg_online()/ blkcg_offline() callbacks mirror the css lifecycle for models which want eager setup or teardown.

The registration and binding model follows the TCP congestion control model registration pattern: registering a struct_ops makes the model available by its name, while io.cost.model binds one registered model to a device with "model=<name>" and restores the builtin model with "model=linear". Unregistering a model removes it from the registry so it can no longer be selected by name; devices already using the model keep using it until they are switched back to the builtin model, at which point the reference is released. A model which does not implement calc_cost is rejected at load. Sleepable models are rejected at verification, since calc_cost() runs under RCU read lock. Patch overview:

1/5: the BPF struct_ops cost model support: Kconfig, ops
definition, name registry, registration, io.cost.model binding, unified dispatch and verifier checks
2/5: selftest with the 2x example model (the full builtin linear
HDD formula at double cost) plus a runner and the selftest kernel config entries
3/5: 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/5: a second example model which replaces the single-cursor
sequentiality heuristic with per-cgroup multi-stream detection keyed by the cgroup, the first consumer of the state interface
5/5: document the model=<name> binding in cgroup-v2.rst

Does it work
------------

Mechanism, verified functionally (QEMU, virtio-blk with the 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
- edge cases: binding an unknown model name fails with ENOENT and nothing is applied; unregistering a bound model leaves the device correctly priced (2x) until it is switched back; the readback shows the bound model name; the selftest runner checks the write error and errno of every step, including the restoration

Workload-shape verification added in this revision (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 (4/5) 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 v4 (fixes from the v3 reviews):
- a model which does not implement calc_cost is rejected at load: the missing member stays NULL (kvalue is zeroed at map allocation and function members are only written when the BPF side provides a prog) and the dispatch would call it on every bio
- io.cost.model writes preserve the bound model: bpf_model is seeded from the currently bound model so a coefficient-only write keeps it bound; ctrl=auto/user and model=linear remain the explicit ways back to the builtin model
- ctrl=bpf is accepted on write (it is what the read path prints), so a saved configuration can be restored as-is
- the builtin model keeps the reserved name "linear" (model=linear unbinds), so a BPF model registering under that name is rejected
- .reg/.unreg no longer take an extra reference on the kdata: the struct_ops core already holds a map reference while the model is registered; each device binding takes and drops its own reference, which keeps an unregistered but still-bound model alive
- blkcg online/offline notifications follow the device binding, not the registration: a model receives them exactly while at least one device has it bound; a model bound to several devices stays on the notify list until the last of them unbinds, even when it is unregistered in between
- drop the redundant BPF_FUNC_cgrp_storage_get case from get_func_proto (bpf_base_func_proto already covers it) and make iocost_bpf_model_get() return an ops pointer or ERR_PTR
- IOCOST_COST_F_MERGE is an enum so BPF models get it from vmlinux.h instead of redefining the flag; the example models drop their local copies of the constants vmlinux.h already provides; the example model zeroes the base cost on the storage-failure path and formats multi-line comments with the opening marker on its own line; the tick event divides by the measured duration with div64_u64() so a divisor of 2^32 microseconds does not truncate to zero

Tao Cui (5):
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
selftests/bpf: add multi-stream sequentiality example model
docs: cgroup-v2: document io.cost model=<name> binding

 Documentation/admin-guide/cgroup-v2.rst       |  12 +
 block/Kconfig                                 |   9 +
 block/Makefile                                |   1 +
 block/blk-cgroup.c                            |   4 +
 block/blk-iocost-bpf.c                        | 310 ++++++++++++++++++
 block/blk-iocost.c                            | 227 +++++++++++++--
 include/linux/blk-iocost.h                    |  84 +++++
 include/trace/events/iocost.h                 |  45 +++
 tools/testing/selftests/bpf/config            |   2 +
 .../selftests/bpf/prog_tests/iocost_model.c   | 199 ++++++++++++
 .../selftests/bpf/progs/iocost_model.c        | 135 ++++++++
 tools/testing/selftests/bpf/progs/iocost_ms.c | 156 +++++++++
  12 files changed, 1166 insertions(+), 18 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
author
#1 lore raw

PATCH 1/1 blk-iocost: add BPF struct_ops cost model support

From: Tao Cui <[email protected]>

Add the iocost_model_ops struct_ops: a bound BPF model fully replaces the builtin linear model on a device. calc_cost() receives the full bio->bi_opf (including REQ_PREFLUSH and REQ_FUA), the IO size, the start sector (sector_t), the issuing blkcg and the iocost-specific call metadata (the merge-path indicator), and is called from the bio charging path, so a model owns pricing for every IO on the device. The completion-time request sizing used for the latency met/missed accounting still uses the builtin linear coefficients: blk-mq has already cleared the request's bio by the time the controller sees the completion, so there is no issuing cgroup to pass to the model at that point; extending the model to the sizing path is left open by this interface. The builtin cursor is not exposed: a model is expected to track its own stream state.

The registration and binding model follows the TCP congestion model registration pattern: registering a struct_ops makes the model available by its name (char name[IOCOST_MODEL_NAME_LEN], validated at init_member), while
io.cost.model binds one registered model to a device with "model=<name>" and unbinds with "model=linear" or "ctrl=auto/user". Unregistering a model removes it from the registry so it can no longer be selected by name; devices already using the model continue to do so until switched back to the builtin model. The struct_ops core holds a map reference while the model is registered, so .reg/.unreg take no extra reference; each device binding takes one with bpf_struct_ops_get() and releases it when the device switches back to the builtin model, which keeps the kdata of an unregistered but still-bound model alive.

calc_cost() runs under RCU read lock; sleepable programs are rejected in .check_member. blkcg_online()/blkcg_offline() callbacks mirroring the blkcg css lifecycle let models manage per-cgroup state; a model receives these notifications exactly while at least one device has it bound, not while it is merely registered.

- a model which does not implement calc_cost is rejected at load:
kvalue is zeroed at map allocation and function members are only written when the BPF side provides a prog, so the missing member stays NULL and the dispatch would call it on every bio
- the builtin model keeps the reserved name "linear" (model=linear unbinds), so a BPF model registering under that name is rejected
- io.cost.model writes preserve the bound model: bpf_model is seeded from the currently bound model so a coefficient-only write keeps it bound; ctrl=auto/user and model=linear are the explicit ways back to the builtin model
- ctrl=bpf is accepted on write (it is what the read path prints), so a saved configuration can be restored as-is

---
 block/Kconfig              |   9 ++
 block/Makefile             |   1 +
 block/blk-cgroup.c         |   4 +
 block/blk-iocost-bpf.c     | 310 +++++++++++++++++++++++++++++++++++++
 block/blk-iocost.c         | 195 ++++++++++++++++++++---
 include/linux/blk-iocost.h |  84 ++++++++++
 6 files changed, 585 insertions(+), 18 deletions(-)
 create mode 100644 block/blk-iocost-bpf.c
 create mode 100644 include/linux/blk-iocost.h
block/Kconfig +9 -0
index 70e4a66d941ff..91e808f86d28d 100644
@@ -231,4 +231,13 @@ 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 a device it is bound to
+	 through io.cost.model.
+
 endif # BLOCK
block/Makefile +1 -0
index e7bd320e3d697..ee5cebeea006f 100644
@@ -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-cgroup.c +4 -0
index b56db1cc6778f..b08ceb94a281b 100644
@@ -32,6 +32,7 @@
 #include <linux/part_stat.h>
 #include "blk.h"
 #include "blk-cgroup.h"
+#include <linux/blk-iocost.h>
 #include "blk-ioprio.h"
 #include "blk-throttle.h"
 
@@ -1341,6 +1342,7 @@ void blkcg_unpin_online(struct cgroup_subsys_state *blkcg_css)
  */
 static void blkcg_css_offline(struct cgroup_subsys_state *css)
 {
+	iocost_notify_blkcg_offline(css_to_blkcg(css));
 	/* this prevents anyone from attaching or migrating to this blkcg */
 	wb_blkcg_offline(css);
 
@@ -1447,6 +1449,8 @@ static int blkcg_css_online(struct cgroup_subsys_state *css)
 {
 	struct blkcg *parent = blkcg_parent(css_to_blkcg(css));
 
+	iocost_notify_blkcg_online(css_to_blkcg(css));
+
 	/*
 	 * blkcg_pin_online() is used to delay blkcg offline so that blkgs
 	 * don't go offline while cgwbs are still active on them.  Pin the
block/blk-iocost-bpf.c new file +310 -0

310 lines not on this page · raw message

block/blk-iocost.c +177 -18

281 lines not on this page · raw message

include/linux/blk-iocost.h new file +84 -0

84 lines not on this page · raw message

Signature · 1 line
2.43.0
#2 lore raw

Re: [PATCH] blk-iocost: add BPF struct_ops cost model support

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] bpf: premature removal from lifecycle list causes map/memory leaks --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] bpf: premature removal from lifecycle list causes map/memory leaks --

commit e92f1828b80c32e5c3b26c9b38e384109bedf0de
Author: Tao Cui <[email protected]>

blk-iocost: add BPF struct_ops cost model support

Add the iocost_model_ops struct_ops: a bound BPF model fully replaces the builtin linear model on a device.

Quoted 5 lines
block/blk-iocost-bpf.c new file +0 -0
new file mode 100644
index 0000000000000..7f1f9a2e51cb2

[ ... ]

block/blk-iocost-bpf.c line 255

Quoted 10 lines
block/blk-iocost-bpf.c new file +10 -0
+void iocost_bpf_model_put(const struct iocost_model_ops *ops)
+{
+	struct iocost_bpf_model *m;
+
+	mutex_lock(&iocost_bpf_reg_lock);
+	list_for_each_entry(m, &iocost_bpf_lifecycle, lifecycle) {
+		if (m->ops == ops)
+			break;
+	}
+	if (&m->lifecycle != &iocost_bpf_lifecycle) {

[Severity: High]
If a single registered BPF iocost model is bound to multiple block devices and one of them unbinds it, does this skip the cleanup block entirely on subsequent unbinds?

Because the model is prematurely removed from the lifecycle list below, subsequent unbinds will fail to find it in the loop above.

This causes iocost_bpf_model_put() to return early, permanently leaking BPF struct_ops map references and iocost_bpf_model structures, as well as missing blkcg online/offline notifications for active bindings.

block/blk-iocost-bpf.c line 263

Quoted 8 lines
block/blk-iocost-bpf.c new file +8 -0
+		bool freed = refcount_dec_and_test(&m->refs);
+
+		/* leave the notify list with the last binding: the
+		 * remaining ref is either the registry's (node still on
+		 * iocost_bpf_models) or zero and the node is freed
+		 */
+		if (freed || !list_empty(&m->list))
+			list_del(&m->lifecycle);

[Severity: High]
Can this condition cause the model to be removed from the lifecycle list on the very first unbind?

The condition !list_empty(&m->list) evaluates to true unconditionally for any registered model because m->list remains actively linked in the registry (iocost_bpf_models) until it is unregistered.

Quoted 8 lines
block/blk-iocost-bpf.c new file +8 -0
+		mutex_unlock(&iocost_bpf_reg_lock);
+		bpf_struct_ops_put(ops);
+		if (freed)
+			kfree(m);
+		return;
+	}
+	mutex_unlock(&iocost_bpf_reg_lock);
+}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1