Skip to contentSkip to conversation

blk-iocost: BPF struct_ops cost model

RFC PATCH Superseded Tao Cui 3 participants 10 messages Sep 16

Subsystems (8)

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

RFC PATCH v4 1/5 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
author
#4 lore raw

RFC PATCH v4 2/5 selftests/bpf: add iocost cost model test

In reply to Tao Cui

From: Tao Cui <[email protected]>

Add an example cost model implementing the full builtin linear HDD formula at double cost, including flush pricing, and a runner which registers it as a struct_ops and binds it to a device through io.cost.model with "model=iocost_2x", verifying the readback and restoring "model=linear" afterwards, checking the write error and errno of every step including the restoration. Binding an unknown model name is verified to fail with ENOENT. Under the same workload the doubled model charges exactly twice the builtin model (verified 2882us -> 5722us per IO, completed IO count halved).

Per-cgroup stream state uses a CGRP_STORAGE map keyed by the cgroup of the blkcg argument, so the model inherits the cgroup lifetime and never leaks or reuses stale state. opf carries the full bio->bi_opf including REQ_* flag bits, so the operation must be extracted with a mask, not compared for equality.

All writes go through write(2) rather than stdio, since the kernel's rejection happens in the write() syscall, not in the userspace buffer copy. 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.

The runner is skipped unless $IOCOST_TEST_DEV gives a major:minor of a device with iocost enabled.

---
 tools/testing/selftests/bpf/config            |   2 +
 .../selftests/bpf/prog_tests/iocost_model.c   | 165 ++++++++++++++++++
 .../selftests/bpf/progs/iocost_model.c        | 135 ++++++++++++++
 3 files changed, 302 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/iocost_model.c
 create mode 100644 tools/testing/selftests/bpf/progs/iocost_model.c
tools/testing/selftests/bpf/config +2 -0
index 2f79688dcf7ce..67a630cb56148 100644
@@ -138,3 +138,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 +165 -0

165 lines not on this page · raw message

tools/testing/selftests/bpf/progs/iocost_model.c new file +135 -0

135 lines not on this page · raw message

Signature · 1 line
2.43.0
author
#6 lore raw

RFC PATCH v4 3/5 blk-iocost: add iocost_ioc_tick tracepoint for per-period device summary

In reply to Tao Cui

From: Tao Cui <[email protected]>

The existing iocost tracepoints are state-change driven: vrate_adj fires only when the adjustment logic runs, inuse_* only on surplus state transitions, activate/idle only on cgroup state changes. In a steady state none of them fire. The only other way to observe the controller (period length, vrate, busy level, active cgroup count, device utilization) is iocost_monitor.py, which reads kernel memory through drgn and is not usable in most production environments.

Add 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 runs, 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.

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            | 32 +++++++++++++++++++++++++
 include/trace/events/iocost.h | 45 +++++++++++++++++++++++++++++++++++
 2 files changed, 77 insertions(+)
block/blk-iocost.c +32 -0
index 65d4371e4ac45..73c8dcfda65b2 100644
@@ -2244,6 +2244,10 @@ 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;
+	u32 tick_period_us;
+	u64 tick_vrate, tick_dur;
+	int tick_busy, tick_running;
 	u64 usage_us_sum = 0;
 	u32 ppm_rthr;
 	u32 ppm_wthr;
@@ -2280,6 +2284,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.
@@ -2441,6 +2447,14 @@ static void ioc_timer_fn(struct timer_list *timer)
 
 	ioc->busy_level = clamp(ioc->busy_level, -1000, 1000);
 
+	/*
+	 * vrate and period_us change right below; snapshot the values
+	 * this period ran in so the tick below reports the period's own
+	 * parameters instead of the next period's.
+	 */
+	tick_period_us = ioc->period_us;
+	tick_vrate = ioc->vtime_base_rate;
+
 	ioc_adjust_base_vrate(ioc, rq_wait_pct, nr_lagging, nr_shortages,
 			      prev_busy_level, missed_ppm);
 
@@ -2448,6 +2462,24 @@ static void ioc_timer_fn(struct timer_list *timer)
 
 	ioc_forgive_debts(ioc, usage_us_sum, nr_debtors, &now);
 
+	/*
+	 * Snapshot the state this period ran in before the idle
+	 * transition below wipes it, so the final tick reports the period's
+	 * own busy level (e.g. the saturation that drove the controller
+	 * idle) instead of the cleared one.  usage is normalized by the
+	 * measured period length, captured before ioc_start_period()
+	 * overwrites period_at, the same way the donation loop does.
+	 * Emitted before cur_period is bumped, so the tick carries the
+	 * number of the period it describes.
+	 */
+	tick_busy = ioc->busy_level;
+	tick_running = ioc->running;
+	tick_dur = now.now - ioc->period_at;
+
+	trace_iocost_ioc_tick(ioc, nr_active, usage_us_sum,
+			      tick_period_us, tick_vrate,
+			      tick_busy, tick_running, tick_dur);
+
 	/*
 	 * This period is done.  Move onto the next one.  If nothing's
 	 * going on with the device, stop the timer.
include/trace/events/iocost.h +45 -0

51 lines not on this page · raw message

Signature · 1 line
2.43.0
author
#7 lore raw

RFC PATCH v4 4/5 selftests/bpf: add multi-stream sequentiality example model

In reply to Tao Cui

From: Tao Cui <[email protected]>

Add a second example cost model which replaces the builtin single-cursor sequentiality heuristic with a per-cgroup table of stream slots: an IO is sequential iff its sector matches the expected next sector of any tracked stream. Interleaved sequential readers in one cgroup keep their own slots instead of ping-ponging a single cursor, and random IO inside a hot window rarely matches a moving expectation. Merged bios skip the base cost but still advance the matched stream position, so a merge at the expected sector does not make the following new IO look random.

Stream state lives in a CGRP_STORAGE map keyed by the cgroup of the blkcg argument, following the cgroup lifetime; there is no fixed-size registry to exhaust.

Measured (QEMU, virtio-blk with the HDD profile, 4k IOs, w=1000):
two sequential readers in one cgroup are priced 1961us/op by the builtin model (judged random) and 23us/op by this model (judged sequential), the completed IO count rises from 4495 to 207505; random IO inside an 8M window is priced 24us/op by builtin (undercharge) and 2607us/op by this model; single-stream sequential and whole-disk random pricing are unchanged.

Stream updates are lockless like the builtin cursor; a lost update misclassifies a single IO. Slots are only advanced for bios the builtin prices. The streams test lives here with the model it loads. The page count truncates like the builtin.

---
 .../selftests/bpf/prog_tests/iocost_model.c   |  34 ++++
 tools/testing/selftests/bpf/progs/iocost_ms.c | 156 ++++++++++++++++++
 2 files changed, 190 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/progs/iocost_ms.c
tools/testing/selftests/bpf/prog_tests/iocost_model.c +34 -0
index 94c633b975277..ba1de8b2309ab 100644
@@ -4,6 +4,7 @@
 #include <fcntl.h>
 #include <unistd.h>
 #include "iocost_model.skel.h"
+#include "iocost_ms.skel.h"
 
 /*
  * Write a line to io.cost.model with write(2) and return the errno of
@@ -163,3 +164,36 @@ void serial_test_iocost_model(void)
 
 	iocost_model__destroy(skel);
 }
+
+/*
+ * Same check for the multi-stream example model.  Only one model can
+ * be bound to a device at a time; both tests bind and restore, so
+ * they are serial and independent.
+ */
+void serial_test_iocost_model_streams(void)
+{
+	struct iocost_ms *skel;
+	char *dev;
+	int err;
+
+	dev = getenv("IOCOST_TEST_DEV");
+	if (!dev || geteuid() != 0) {
+		test__skip();
+		return;
+	}
+	if (!dev_has_iocost(dev)) {
+		printf("skip: %s has no iocost enabled\n", dev);
+		test__skip();
+		return;
+	}
+
+	skel = iocost_ms__open_and_load();
+	if (!ASSERT_OK_PTR(skel, "skel_open_load"))
+		return;
+
+	err = iocost_ms__attach(skel);
+	if (ASSERT_OK(err, "attach"))
+		ASSERT_OK(bind_model(dev, "iocost_ms"), "bind_and_readback");
+
+	iocost_ms__destroy(skel);
+}
tools/testing/selftests/bpf/progs/iocost_ms.c new file +156 -0

156 lines not on this page · raw message

Signature · 1 line
2.43.0
author
#8 lore raw

RFC PATCH v4 5/5 docs: cgroup-v2: document io.cost model=<name> binding

In reply to Tao Cui

From: Tao Cui <[email protected]>

Document the named-model binding of io.cost.model in the io.cost.model section of the cgroup v2 documentation: the binding and restore syntax, the unknown-name rejection, the full-replacement semantics of a bound model and the unregister lifetime.

---
 Documentation/admin-guide/cgroup-v2.rst | 12 ++++++++++++
 1 file changed, 12 insertions(+)
Documentation/admin-guide/cgroup-v2.rst +12 -0
index 8d2603751c51a..0d2d0525255cb 100644
@@ -2124,6 +2124,18 @@ IO Interface Files
 	parameters are written to, "ctrl" become "user" and the
 	automatic changes are disabled.
 
+	When CONFIG_BLK_CGROUP_IOCOST_BPF is enabled, "model" also accepts
+	the name of a registered iocost_model_ops BPF struct_ops model:
+	"model=<name>" binds the model to the device and the model fully
+	replaces the builtin linear pricing, for every operation including
+	flushes; "model=linear" (or "ctrl=auto/user") restores the builtin
+	model.  Writing an unknown name fails with ENOENT and nothing is
+	applied.  Unregistering a model removes its name so it can no
+	longer be selected; devices already bound keep using it, and keep
+	receiving cgroup lifecycle notifications, until switched back to
+	the builtin model.  See
+	include/linux/blk-iocost.h for the model interface.
+
 	When "model" is "linear", the following model parameters are
 	defined.
 
Signature · 1 line
2.43.0
#2 lore raw

Re: [RFC PATCH v4 1/5] blk-iocost: add BPF struct_ops cost model support

In reply to Tao Cui
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [High] bpf: resource leak and broken blkcg notifications on BPF model unbind - [High] bpf…

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] bpf: resource leak and broken blkcg notifications on BPF model unbind
- [High] bpf: coefficient-only writes fail if bound model is unregistered
- [Low] bpf: multi-line comments do not follow modern kernel style
--

commit 4e914860298423131f3423ab63f79ed4a655051f
Author: Tao Cui <[email protected]>

blk-iocost: add BPF struct_ops cost model support

This commit introduces a BPF struct_ops based cost model for blk-iocost, replacing the builtin linear model on a device. It implements a registration framework where sysfs bindings map a registered model to 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 50

Quoted 7 lines
block/blk-iocost-bpf.c new file +7 -0
+const struct iocost_model_ops *iocost_bpf_model_get(const char *name)
+{
+	struct iocost_bpf_model *m;
+	const struct iocost_model_ops *ops = ERR_PTR(-ENOENT);
+
+	mutex_lock(&iocost_bpf_reg_lock);
+	list_for_each_entry(m, &iocost_bpf_models, list) {

[Severity: High]
Will this lookup fail to find models that are unregistered but still actively bound to devices? If a user issues a coefficient-only write on a device using an unregistered model, ioc_cost_model_write() passes the name here, but since this only searches the registry (iocost_bpf_models), it returns -ENOENT and rejects the write.

Quoted 1 line
block/blk-iocost-bpf.c new file +1 -0
+		if (!strcmp(m->ops->name, name)) {

[ ... ]

block/blk-iocost-bpf.c line 238

Quoted 12 lines
block/blk-iocost-bpf.c new file +12 -0
+static void bpf_iocost_unreg(void *kdata, struct bpf_link *link)
+{
+	struct iocost_model_ops *ops = kdata;
+	struct iocost_bpf_model *m;
+
+	mutex_lock(&iocost_bpf_reg_lock);
+	m = iocost_bpf_model_lookup(ops);
+	if (m) {
+		/* keep the linkage queryable so model_put() can tell a
+		 * still-registered node (one ref held by the registry)
+		 * from one kept alive only by device bindings
+		 */

[Severity: Low]
Does this comment style follow the BPF subsystem requirements? The standard specifies that multi-line comments should have the opening /* on its own line.

Quoted 1 line
block/blk-iocost-bpf.c new file +1 -0
+		list_del_init(&m->list);

[ ... ]

Quoted 6 lines
block/blk-iocost-bpf.c new file +6 -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) {

block/blk-iocost-bpf.c line 261

Quoted 10 lines
block/blk-iocost-bpf.c new file +10 -0
+		if (m->ops == ops)
+			break;
+	}
+	if (&m->lifecycle != &iocost_bpf_lifecycle) {
+		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
+		 */

[Severity: Low]
Similarly here, this multi-line comment is missing the opening /* on its own line.

block/blk-iocost-bpf.c line 269

Quoted 8 lines
block/blk-iocost-bpf.c new file +8 -0
+		if (freed || !list_empty(&m->list))
+			list_del(&m->lifecycle);
+		mutex_unlock(&iocost_bpf_reg_lock);
+		bpf_struct_ops_put(ops);
+		if (freed)
+			kfree(m);
+		return;
+	}

[Severity: High]
Can this sequence prematurely detach registered models from the lifecycle list and leak BPF map references?

When the first device is unbound from a registered model, !list_empty(&m->list) will evaluate to true. This removes the model from the lifecycle list early, breaking blkcg notifications.

When subsequent devices are unbound, list_for_each_entry() at the start of iocost_bpf_model_put() will fail to find the model, causing execution to jump over this block completely. The bpf_struct_ops_put() call will be skipped, leading to a map reference leak.

Quoted 7 lines
block/blk-iocost-bpf.c new file +2 -0
+	mutex_unlock(&iocost_bpf_reg_lock);
+}
block/blk-iocost.c +0 -0
index 2745bffcd5eef..22b2ece52fa58 100644

[ ... ]

Quoted 4 lines
block/blk-iocost.c +0 -0
@@ -3591,6 +3628,24 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 	spin_lock_irq(&ioc->lock);
 	memcpy(u, ioc->params.i_lcoefs, sizeof(u));
 	user = ioc->user_cost_model;

block/blk-iocost.c static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input, · line 3640

Quoted 10 lines
block/blk-iocost.c +10 -0
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	{
+		const struct iocost_model_ops *model =
+			rcu_dereference_protected(ioc->model,
+					lockdep_is_held(&ioc->lock));
+
+		/* seed from the 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
+		 */

[Severity: Low]
This comment also places text on the same line as the opening /*, which diverges from the preferred BPF multi-line comment style.

Quoted 2 lines
block/blk-iocost.c +2 -0
+		if (model)
+			strscpy(bpf_model, model->name, sizeof(bpf_model));
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#5 lore raw

Re: [RFC PATCH v4 2/5] selftests/bpf: add iocost cost model test

In reply to Tao Cui
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] bpf: iocost_2x model misses cursor updates during merges - [Low] bpf: invalid multi-line comment…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] bpf: iocost_2x model misses cursor updates during merges
- [Low] bpf: invalid multi-line comment style in bind_model
--

commit 0857836334950bc87bf809661e8e366dfa84c06a
Author: Tao Cui <[email protected]>

selftests/bpf: add iocost cost model test

This commit adds an example cost model implementing the full builtin linear HDD formula at double cost. It registers it as a struct_ops and binds it to a device to verify readback and write operations.

Quoted 3 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +0 -0

[ ... ]

Quoted 14 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +14 -0
+static int bind_model(const char *dev, const char *name)
+{
+	char buf[300], got[64];
+	int err;
+
+	snprintf(buf, sizeof(buf), "%s model=%s\n", dev, name);
+	err = write_cost_model(buf);
+	if (err)
+		return err > 0 ? -err : -EIO;
+	err = readback_model(dev, got, sizeof(got));
+	if (!err && !strcmp(got, name)) {
+		/*
+		 * restore the builtin linear model on every path so
+		 * the device is not left bound to a model the caller

tools/testing/selftests/bpf/prog_tests/iocost_model.c line 91

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +10 -0
+		 * may unregister right after; the write is checked too
+		 */
+		snprintf(buf, sizeof(buf), "%s model=linear\n", dev);
+		err = write_cost_model(buf);
+		return err > 0 ? -err : (err ? -EIO : 0);
+	}
+
+	/* bind failed or does not read back: still restore, but report
+	 * the original failure rather than the restore result
+	 */

[Severity: Low]
This isn't a bug, but does this multi-line comment violate the BPF subsystem's strict comment style?

The opening /* must be on its own line, but here the text starts on the same line.

Quoted 3 lines
tools/testing/selftests/bpf/progs/iocost_model.c new file +0 -0

[ ... ]

Quoted 4 lines
tools/testing/selftests/bpf/progs/iocost_model.c new file +4 -0
+SEC("struct_ops")
+u64 BPF_PROG(iocost_2x_calc_cost, u64 opf, u64 nbytes, u64 sector,
+	     struct blkcg *blkcg, u64 model_flags)
+{

[ ... ]

tools/testing/selftests/bpf/progs/iocost_model.c line 119

Quoted 11 lines
tools/testing/selftests/bpf/progs/iocost_model.c new file +11 -0
+		cur = *cursor;
+		if (cur && priced) {
+			seek_pages = sector > cur ? sector - cur
+						   : cur - sector;
+			seek_pages >>= IOC_SECT_TO_PAGE_SHIFT;
+			if (seek_pages > LCOEF_RANDIO_PAGES)
+				base = randio;
+		}
+		if (priced && nbytes &&
+		    !(model_flags & IOCOST_COST_F_MERGE))
+			*cursor = sector + RU(nbytes, 512);

[Severity: Medium]
Does skipping the cursor update when IOCOST_COST_F_MERGE is set permanently lose track of the end of merged requests?

If a sequence of backmerged bio submissions triggers calc_cost with IOCOST_COST_F_MERGE set, it seems this branch will skip advancing the cursor, leaving it pinned at the end of the first bio in the merged sequence.

If a stream builds up more than 16MB of data through merges, would subsequent contiguous IOs calculate a seek distance > 16MB and falsely incur massive random IO charges?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#9 lore raw

Re: [RFC PATCH v4 5/5] docs: cgroup-v2: document io.cost model=<name> binding

In reply to Tao Cui
Does this section need to document what io.cost.model reads back with a BPF model bound?
Quoted 4 lines
Documentation/admin-guide/cgroup-v2.rst +0 -0
index 86a2a0099178e..5786d86eceeae 100644

[ ... ]

Quoted 6 lines
Documentation/admin-guide/cgroup-v2.rst +2 -0
@@ -2120,6 +2120,18 @@ IO Interface Files
 	parameters are written to, "ctrl" become "user" and the
 	automatic changes are disabled.
 
+	When CONFIG_BLK_CGROUP_IOCOST_BPF is enabled, "model" also accepts
+	the name of a registered iocost_model_ops BPF struct_ops model:

Documentation/admin-guide/cgroup-v2.rst IO Interface Files · line 2134

Quoted 10 lines
Documentation/admin-guide/cgroup-v2.rst +10 -0
+	"model=<name>" binds the model to the device and the model fully
+	replaces the builtin linear pricing, for every operation including
+	flushes; "model=linear" (or "ctrl=auto/user") restores the builtin
+	model.  Writing an unknown name fails with ENOENT and nothing is
+	applied.  Unregistering a model removes its name so it can no
+	longer be selected; devices already bound keep using it, and keep
+	receiving cgroup lifecycle notifications, until switched back to
+	the builtin model.  See
+	include/linux/blk-iocost.h for the model interface.
+

Does this section need to document what io.cost.model reads back with a BPF model bound?

Looking at ioc_cost_model_prfill() in block/blk-iocost.c, when a BPF model is bound, the file prints:

    seq_printf(sf, "%s ctrl=%s model=%s\n",
        dname, model ? "bpf" : ioc->user_cost_model ? "user" : "auto",
        model ? model->name : "linear");

So with a model bound, io.cost.model reads back "ctrl=bpf model=<name>".

The nested-key table nine lines above this paragraph lists the possible values:

    =====           ================================
    ctrl            "auto" or "user"
    model           The cost model in use - "linear"
    =====           ================================

This table doesn't include "bpf" as a ctrl value or "<name>" as a model value. The new paragraph also doesn't mention that "ctrl=bpf" is accepted on write - ioc_cost_model_write() special-cases it so saved configurations can be restored:

    } else if (!strcmp(buf, "bpf")) {
        /* readback value; keep the bound model */
        continue;
    }

Should the table be updated to include the "bpf" ctrl value and the "<name>" model value, so the section documents what the kernel actually prints?

---
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/35070283830

author
#3 lore raw

Re: [RFC PATCH v4 1/5] blk-iocost: add BPF struct_ops cost model support

In reply to [email protected]
Quoted 4 lines · 在 2026/9/16 15:34, [email protected] 写道:

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] bpf: resource leak and broken blkcg notifications on BPF model unbind
- [High] bpf: coefficient-only writes fail if bound model is unregistered
- [Low] bpf: multi-line comments do not follow modern kernel style

Thanks for the reviews. All five findings across the two patches are confirmed and will be fixed in the next revision:

- the lookup in iocost_bpf_model_get() only searched the registry, so a coefficient-only write on a device using an unregistered model failed with ENOENT; the lookup will fall back to the notify list, keeping such a model selectable by name until the last device unbinds

- the notify-list detach condition in iocost_bpf_model_put() was wrong for a registered model bound to several devices: the first unbind removed the node from the lifecycle list early and the last unbind then failed to find it, leaking the BPF map reference; the node will leave the notify list only with the last binding

- the 2x example model did not advance its cursor for merged bios, unlike the builtin backmerge behaviour, so a long merged stream could drift past the 16MB seek threshold and misprice the following IO as random

- the multi-line comments use the opening marker on its own line

While testing those fixes we also found and fixed a problem of our
own: two racing io.cost.model writes resolving the same model each took a reference on it, but the write whose commit found the model already bound did not drop one, leaking a map reference. The commit path now drops the redundant reference.

The next revision will follow shortly.

Quoted 136 lines

--

commit 4e914860298423131f3423ab63f79ed4a655051f
Author: Tao Cui <[email protected]>

blk-iocost: add BPF struct_ops cost model support

This commit introduces a BPF struct_ops based cost model for blk-iocost, replacing the builtin linear model on a device. It implements a registration framework where sysfs bindings map a registered model to 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 50

Quoted 7 lines
block/blk-iocost-bpf.c new file +7 -0
+const struct iocost_model_ops *iocost_bpf_model_get(const char *name)
+{
+	struct iocost_bpf_model *m;
+	const struct iocost_model_ops *ops = ERR_PTR(-ENOENT);
+
+	mutex_lock(&iocost_bpf_reg_lock);
+	list_for_each_entry(m, &iocost_bpf_models, list) {

[Severity: High]
Will this lookup fail to find models that are unregistered but still actively bound to devices? If a user issues a coefficient-only write on a device using an unregistered model, ioc_cost_model_write() passes the name here, but since this only searches the registry (iocost_bpf_models), it returns -ENOENT and rejects the write.

Quoted 1 line
block/blk-iocost-bpf.c new file +1 -0
+		if (!strcmp(m->ops->name, name)) {

[ ... ]

block/blk-iocost-bpf.c line 238

Quoted 12 lines
block/blk-iocost-bpf.c new file +12 -0
+static void bpf_iocost_unreg(void *kdata, struct bpf_link *link)
+{
+	struct iocost_model_ops *ops = kdata;
+	struct iocost_bpf_model *m;
+
+	mutex_lock(&iocost_bpf_reg_lock);
+	m = iocost_bpf_model_lookup(ops);
+	if (m) {
+		/* keep the linkage queryable so model_put() can tell a
+		 * still-registered node (one ref held by the registry)
+		 * from one kept alive only by device bindings
+		 */

[Severity: Low]
Does this comment style follow the BPF subsystem requirements? The standard specifies that multi-line comments should have the opening /* on its own line.

Quoted 1 line
block/blk-iocost-bpf.c new file +1 -0
+		list_del_init(&m->list);

[ ... ]

Quoted 6 lines
block/blk-iocost-bpf.c new file +6 -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) {

block/blk-iocost-bpf.c line 261

Quoted 10 lines
block/blk-iocost-bpf.c new file +10 -0
+		if (m->ops == ops)
+			break;
+	}
+	if (&m->lifecycle != &iocost_bpf_lifecycle) {
+		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
+		 */

[Severity: Low]
Similarly here, this multi-line comment is missing the opening /* on its own line.

block/blk-iocost-bpf.c line 269

Quoted 8 lines
block/blk-iocost-bpf.c new file +8 -0
+		if (freed || !list_empty(&m->list))
+			list_del(&m->lifecycle);
+		mutex_unlock(&iocost_bpf_reg_lock);
+		bpf_struct_ops_put(ops);
+		if (freed)
+			kfree(m);
+		return;
+	}

[Severity: High]
Can this sequence prematurely detach registered models from the lifecycle list and leak BPF map references?

When the first device is unbound from a registered model, !list_empty(&m->list) will evaluate to true. This removes the model from the lifecycle list early, breaking blkcg notifications.

When subsequent devices are unbound, list_for_each_entry() at the start of iocost_bpf_model_put() will fail to find the model, causing execution to jump over this block completely. The bpf_struct_ops_put() call will be skipped, leading to a map reference leak.

Quoted 7 lines
block/blk-iocost-bpf.c new file +2 -0
+	mutex_unlock(&iocost_bpf_reg_lock);
+}
block/blk-iocost.c +0 -0
index 2745bffcd5eef..22b2ece52fa58 100644

[ ... ]

Quoted 4 lines
block/blk-iocost.c +0 -0
@@ -3591,6 +3628,24 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 	spin_lock_irq(&ioc->lock);
 	memcpy(u, ioc->params.i_lcoefs, sizeof(u));
 	user = ioc->user_cost_model;

block/blk-iocost.c static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input, · line 3640

Quoted 10 lines
block/blk-iocost.c +10 -0
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	{
+		const struct iocost_model_ops *model =
+			rcu_dereference_protected(ioc->model,
+					lockdep_is_held(&ioc->lock));
+
+		/* seed from the 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
+		 */

[Severity: Low]
This comment also places text on the same line as the opening /*, which diverges from the preferred BPF multi-line comment style.

Quoted 2 lines
block/blk-iocost.c +2 -0
+		if (model)
+			strscpy(bpf_model, model->name, sizeof(bpf_model));