Skip to contentSkip to conversation

blk-iocost: BPF struct_ops cost model

RFC PATCH Superseded Tao Cui 4 participants 14 messages Nov 6 – Nov 17

Subsystems (8)

v13 of 14 Superseded Latest is v14 →

lore
Share & tools
lore

Tao Cui

author
#0 lore raw

v13 cover blk-iocost: BPF struct_ops cost model

From: Tao Cui <[email protected]>

This series lets a BPF program take over the cost model of one device. The BPF model provides calc_cost() for charged IOs plus two transfer coefficients for the completion-time sizing, io.cost.model selects between the attached model and the builtin one, and enabling and disabling the controller stays with io.cost.qos.

The builtin model is a linear formula derived from a handful of device parameters, and the right formula is device specific. A BPF model can be adapted to the device and updated without rebuilding the kernel.

The series is based on next-20261105.

Tao Cui (4):
blk-iocost: add BPF struct_ops cost model support
blk-iocost: add iocost_ioc_tick tracepoint for per-period device
summary
selftests/bpf: add iocost cost model test
docs: cgroup-v2: document the iocost BPF cost model attachment

 Documentation/admin-guide/cgroup-v2.rst       |  49 +-
 MAINTAINERS                                   |   1 +
 block/Kconfig                                 |   4 +
 block/blk-iocost.c                            | 284 +++++-
 include/trace/events/iocost.h                 |  43 +
 tools/testing/selftests/bpf/config            |   2 +
 .../selftests/bpf/prog_tests/iocost_model.c   | 812 ++++++++++++++++++
 .../selftests/bpf/progs/iocost_model.c        | 180 ++++
 tools/testing/selftests/bpf/progs/iocost_ms.c | 197 +++++
 9 files changed, 1560 insertions(+), 12 deletions(-)
 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

Changes since v12:

- the iocost_ioc_tick emission now sits inside the trace_iocost_ioc_tick_enabled() check, as tracepoints.rst requires, and the usage_pct trace field is widened to u64
- detaching a model resets the autop stepping timestamps, so the cooldown restarts fresh when the builtin model comes back
- iocost_bpf_supported() probes kernel BTF for the struct_ops wrapper type instead of /proc/config.gz, so an unavailable config no longer skips the tests, and the probe result is cached across cases
- the selftest sets up its private mount namespace and configfs mount once instead of stacking them across cases
- the multi-stream case feeds two interleaved streams and asserts that calc_cost() actually priced them
- the selftest cgroup names are created inside the per-pid work directory (leading '/'), nullb_create() rolls back the instance on its own error paths, and the streams test cleans up in the right order
- docs: document the attach rejection codes (-EOPNOTSUPP, -ENODEV, -EBUSY) and that root-cgroup IOs still use the attached model's transfer coefficients for completion-time sizing

Tested on next-20261105 (qemu x86_64): the selftests pass, and the 2x example model doubles the charged cost over the builtin on a rotational device (2.00x measured), returning to 1.00x after "model=linear".

author
#1 lore raw

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

From: Tao Cui <[email protected]>

iocost prices IO with a linear model derived from a handful of device parameters. The real cost of an IO depends on device internals the formula cannot capture and the right formula is device specific. This lets a BPF program take over pricing for a device so that the model can be adapted to it without rebuilding the kernel.

Attaching an iocost_model_ops struct_ops binds the model to one
device: the target is set in the dev member from userspace and .reg creates the ioc if needed like an io.cost.model write and publishes the model with the queue frozen and rq_qos_mutex held like an io.cost.qos write. The attachment records the owning link in the ioc, so a second attach on the same device fails with -EBUSY, and device removal ejects the model. Detaching takes only rq_qos_mutex in a single critical section, and the map is freed after an RCU grace period so that a calc_cost() already running can finish. io.cost.model selects between the attached and builtin models without detaching the struct_ops; only .unreg or device removal detaches, and .unreg detaches only its own attachment so a reused dev_t cannot tear down a newer one. While a model is selected, the automatic profile stepping of ctrl=auto is suspended; it resumes when the model is switched off or detached.

While in use, the BPF model prices every charged IO: calc_cost() is called from the submission path with the bio and returns the cost in vtime units, clamped to VTIME_PER_SEC by the caller. The struct_ops also carries the transfer coefficients used by the completion-time request sizing, so latency tracking and vrate adjustment follow the model's pricing. Models without calc_cost or with zero or out-of-range transfer coefficients are rejected at registration.

The kernel keeps no per-cgroup state for the model; models which need per-cgroup data keep it in their own maps, created and freed with the cgroups. Without CONFIG_BLK_CGROUP_IOCOST_BPF the struct_ops is not built and the builtin model is the only choice.

---
 block/Kconfig      |   4 +
 block/blk-iocost.c | 266 ++++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 266 insertions(+), 4 deletions(-)
block/Kconfig +4 -0
index 70e4a66d941f..26badf54a477 100644
@@ -161,6 +161,10 @@ config BLK_CGROUP_IOCOST
 	distributes IO capacity between different groups based on
 	their share of the overall weight distribution.
 
+config BLK_CGROUP_IOCOST_BPF
+	def_bool y
+	depends on BLK_CGROUP_IOCOST && BPF_SYSCALL && BPF_JIT && DEBUG_INFO_BTF
+
 config BLK_CGROUP_IOPRIO
 	bool "Cgroup I/O controller for assigning an I/O priority class"
 	depends on BLK_CGROUP
block/blk-iocost.c +262 -4

366 lines not on this page · raw message

Signature · 1 line
2.53.0
author
#5 lore raw

RFC PATCH v13 2/4 blk-iocost: add iocost_ioc_tick tracepoint for per-period device summary

In reply to Tao Cui

From: Tao Cui <[email protected]>

Add iocost_ioc_tick, emitted once per period from ioc_timer_fn() with the overall controller state: period_us, vrate, busy_level, active iocg count and usage percentage. busy_level, cur_period, nr_active and usage_us_sum are complete at the emission point. usage is wall time over wall time, summed over iocgs, and is not capped at 100. vrate and period_us reflect the current controller state, which an io.cost.qos write may have changed mid-period.

The event fires every period the controller is running, including steady states, plus one final tick before the controller goes idle, so the transition to dormancy is directly visible. The active iocg count is only gathered when the tracepoint is enabled.

---
 MAINTAINERS                   |  1 +
 block/blk-iocost.c            | 18 +++++++++++++++
 include/trace/events/iocost.h | 43 +++++++++++++++++++++++++++++++++++
 3 files changed, 62 insertions(+)
MAINTAINERS +1 -0
index aa647f5d37dd..2000a38dbc9c 100644
@@ -6852,6 +6852,7 @@ F:	block/blk-iocost.c
 F:	block/blk-iolatency.c
 F:	block/blk-throttle.c
 F:	include/linux/blk-cgroup.h
+F:	include/trace/events/iocost.h
 
 CONTROL GROUP - CPUSET
 M:	Waiman Long <[email protected]>
block/blk-iocost.c +18 -0
index c3d195fe4a89..d2007b7b73bf 100644
@@ -2349,6 +2349,7 @@ static void ioc_timer_fn(struct timer_list *timer)
 	struct ioc_now now;
 	LIST_HEAD(surpluses);
 	int nr_debtors, nr_shortages = 0, nr_lagging = 0;
+	int nr_active = 0;
 	u64 usage_us_sum = 0;
 	u32 ppm_rthr;
 	u32 ppm_wthr;
@@ -2546,6 +2547,23 @@ static void ioc_timer_fn(struct timer_list *timer)
 
 	ioc->busy_level = clamp(ioc->busy_level, -1000, 1000);
 
+	/*
+	 * busy_level, cur_period, nr_active and usage_us_sum are complete
+	 * here. usage is wall time over wall time, summed over iocgs, and
+	 * is not capped at 100. vrate and period_us reflect the current
+	 * controller state, which an io.cost.qos write may have changed
+	 * mid-period. Emit before the refresh and the period transition.
+	 */
+	if (trace_iocost_ioc_tick_enabled()) {
+		struct ioc_gq *active_iocg;
+
+		list_for_each_entry(active_iocg, &ioc->active_iocgs,
+				    active_list)
+			nr_active++;
+
+		trace_iocost_ioc_tick(ioc, &now, nr_active, usage_us_sum);
+	}
+
 	ioc_adjust_base_vrate(ioc, rq_wait_pct, nr_lagging, nr_shortages,
 			      prev_busy_level, missed_ppm);
 
include/trace/events/iocost.h +43 -0

49 lines not on this page · raw message

Signature · 1 line
2.53.0
author
#9 lore raw

RFC PATCH v13 3/4 selftests/bpf: add iocost cost model test

In reply to Tao Cui

From: Tao Cui <[email protected]>

Add two example iocost cost models and tests which attach them to a null_blk instance the tests create through configfs, so everything runs without external setup.

The first model implements the builtin linear HDD formula at double cost. The second implements multi-stream sequentiality detection: it keeps a per-cgroup table of stream slots instead of the single builtin cursor, so concurrent sequential streams in one cgroup are priced sequentially. Both set the target device through the struct_ops member before load, and the maps are declared ".struct_ops.link" so that a test dying in between does not leave the model attached.

The tests verify the model=bpf readback while attached, that ctrl=bpf is rejected, that a second model on the same device fails with -EBUSY, that model=linear and model=bpf switch between the attached and builtin models without detaching, and that detaching restores the builtin model. With the controller enabled through io.cost.qos, they also verify that IOs are priced through calc_cost() and that the iocost_ioc_tick tracepoint is seen from BPF. They also verify that device removal under the attached model ejects it, with a recreated device attachable again.

---
 tools/testing/selftests/bpf/config            |   2 +
 .../selftests/bpf/prog_tests/iocost_model.c   | 812 ++++++++++++++++++
 .../selftests/bpf/progs/iocost_model.c        | 180 ++++
 tools/testing/selftests/bpf/progs/iocost_ms.c | 197 +++++
 4 files changed, 1191 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
index 49dfe939467c..78ed59f83a16 100644
@@ -141,3 +141,5 @@ CONFIG_SMC_HS_CTRL_BPF=y
 CONFIG_DIBS=y
 CONFIG_DIBS_LO=y
 CONFIG_PM_WAKELOCKS=y
+CONFIG_BLK_CGROUP_IOCOST=y
+CONFIG_BLK_DEV_NULL_BLK=y
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +812 -0

812 lines not on this page · raw message

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

180 lines not on this page · raw message

tools/testing/selftests/bpf/progs/iocost_ms.c new file +197 -0

197 lines not on this page · raw message

Signature · 1 line
2.53.0
author
#13 lore raw

RFC PATCH v13 4/4 docs: cgroup-v2: document the iocost BPF cost model attachment

In reply to Tao Cui

From: Tao Cui <[email protected]>

Document the BPF cost model attachment in the io.cost.model section of the cgroup v2 documentation: attaching an iocost_model_ops struct_ops to a device by its major:minor, the model=bpf readback while attached (ctrl keeps describing the coefficients), the builtin model coming back on detach, and ctrl writes never selecting a model.

---
 Documentation/admin-guide/cgroup-v2.rst | 49 +++++++++++++++++++++----
 1 file changed, 41 insertions(+), 8 deletions(-)
Documentation/admin-guide/cgroup-v2.rst +41 -8
index 9e3c67b02ae2..608ebd311b79 100644
@@ -2056,8 +2056,9 @@ IO Interface Files
 	currently implements "io.weight" proportional control.  Lines
 	are keyed by $MAJ:$MIN device numbers and not ordered.  The
 	line for a given device is populated on the first write for
-	the device on "io.cost.qos" or "io.cost.model".  The following
-	nested keys are defined.
+	the device on "io.cost.qos" or "io.cost.model", or when a BPF
+	cost model is attached to it.  The following nested keys are
+	defined.
 
 	  ======	=====================================
 	  enable	Weight-based control enable
@@ -2111,13 +2112,44 @@ IO Interface Files
 	implements "io.weight" proportional control.  Lines are keyed
 	by $MAJ:$MIN device numbers and not ordered.  The line for a
 	given device is populated on the first write for the device on
-	"io.cost.qos" or "io.cost.model".  The following nested keys
-	are defined.
+	"io.cost.qos" or "io.cost.model", or when a BPF cost model is
+	attached to it.  The following nested keys are defined.
 
-	  =====		================================
+	  =====		==========================================
 	  ctrl		"auto" or "user"
-	  model		The cost model in use - "linear"
-	  =====		================================
+	  model		The cost model in use - "linear" or "bpf"
+	  =====		==========================================
+
+	When BPF cost model support is available, a BPF cost model
+	can be bound to a device by attaching an
+	"iocost_model_ops" struct_ops carrying the whole disk's
+	major:minor as encoded by makedev(3) in its "dev" member (a
+	partition's major:minor is rejected).  Attaching creates the
+	controller if needed, like
+	an io.cost.model write does, switches the device's pricing to
+	the model and populates the device's line in this file and in
+	"io.cost.qos" if it did not exist yet.  Attaching fails with
+	-EBUSY if the device already has a model attached.  It fails
+	with -EOPNOTSUPP if dev names a partition or a device without
+	a multiqueue queue, and with -ENODEV if the device has gone
+	away.  The attached model prices IOs only while the controller
+	is enabled through "io.cost.qos"; attaching does not enable it.
+	IOs issued directly by the root cgroup bypass the model's
+	per-IO pricing; the completion-time sizing of their requests
+	still uses the attached model's transfer coefficients.
+
+	While a model is attached, "model" selects between it and the
+	builtin model: "model=bpf" switches to the attached model and
+	"model=linear" switches back to the builtin model, and neither
+	detaches the struct_ops.
+
+	Detaching removes the model, after which "model=bpf"
+	fails and the device prices with the builtin model again.
+	Device removal ejects the attached model as well, while the
+	struct_ops link remains until userspace destroys it.  "ctrl"
+	accepts only "auto" and "user" and never selects a model.  It
+	keeps describing the builtin coefficients, which take effect
+	again when switched back.
 
 	When "ctrl" is "auto", the kernel may change all parameters
 	dynamically.  When "ctrl" is set to "user" or any other
@@ -2125,7 +2157,8 @@ IO Interface Files
 	automatic changes are disabled.
 
 	When "model" is "linear", the following model parameters are
-	defined.
+	defined.  They remain readable and writable while "model" is
+	"bpf".
 
 	  =============	========================================
 	  [r|w]bps	The maximum sequential IO throughput
Signature · 1 line
2.53.0
#10 lore raw

Re: [RFC PATCH v13 3/4] selftests/bpf: add iocost cost model test

In reply to Tao Cui
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] selftests/bpf: pread() in serial_test_iocost_model_streams() hits page cache --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] selftests/bpf: pread() in serial_test_iocost_model_streams() hits page cache
--

commit 371817062abb0b837764b9a93458f77eb2057dd2
Author: Tao Cui <[email protected]>

selftests/bpf: add iocost cost model test

This commit adds BPF selftests and two example struct_ops cost models for blk-iocost using a configfs-backed null_blk device.

Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +0 -0
new file mode 100644
index 0000000000000..a714507c040e3

[ ... ]

Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +2 -0
+void serial_test_iocost_model_streams(void)
+{

[ ... ]

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +10 -0
+		devfd = open(path, O_RDONLY);
+		if (ASSERT_OK(devfd < 0 ? -errno : 0, "open_dev_ms")) {
+			char iobuf[4096];
+			unsigned long long u1 = 0, u2 = 0;
+
+			ASSERT_OK(read_cost_usage("/iocost_ms",
+						  dev, &u1), "cost_usage_pre");
+			for (i = 0; i < 500; i++)
+				(void)read(devfd, iobuf, sizeof(iobuf));
+			/*

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

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +10 -0
+			 * Two interleaved sequential streams: exercise the
+			 * stream table, not just a single cursor.
+			 */
+			for (i = 0; i < 200; i++) {
+				(void)pread(devfd, iobuf, sizeof(iobuf),
+									(i + 1) * sizeof(iobuf));
+				(void)pread(devfd, iobuf, sizeof(iobuf),
+									(1 << 20) +
+									(i + 1) * sizeof(iobuf));
+			}

[Severity: Medium]
Do these interleaved pread() calls get satisfied from the block device page cache without reaching iocost_ms_calc_cost()?

Because devfd is opened without O_DIRECT, the preceding 500 sequential 4096-byte read() calls populate the page cache for bytes [0, 2048000). Both pread() streams read within that cached range ([4096, 823296) and [1052672, 1871872)), so no interleaved bios are submitted to the block layer and the multi-stream slot table is not exercised while the subsequent assertions pass from the initial read() loop alone.

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

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

In reply to Tao Cui
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] blk-iocost: stale autop timestamps in ioc_cost_model_write() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] blk-iocost: stale autop timestamps in ioc_cost_model_write() --

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

blk-iocost: add BPF struct_ops cost model support

This commit adds BPF struct_ops support (iocost_model_ops) to allow custom per-device IO cost models in blk-iocost.

Quoted 4 lines
block/blk-iocost.c +0 -0
index 1c1fe07a96eaf..876f819d2586f 100644

[ ... ]

Quoted 32 lines
block/blk-iocost.c +28 -0
@@ -2976,10 +3036,40 @@ static void ioc_rqos_queue_depth_changed(struct rq_qos *rqos)
 	spin_unlock_irq(&ioc->lock);
 }
 
+/* Called by .unreg and by device removal, whichever is first. */
+static void ioc_detach_model(struct ioc *ioc)
+{
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	const struct iocost_model_ops *ops = ioc->attached;
+
+	lockdep_assert_held(&ioc->rqos.disk->queue->rq_qos_mutex);
+
+	if (!ops)
+		return;
+
+	spin_lock_irq(&ioc->lock);
+	rcu_assign_pointer(ioc->model, NULL);
+	ioc->attached = NULL;
+	ioc->attached_link = NULL;
+	/*
+	 * stepping resumes with the timestamps at their pre-attach
+	 * values, which would immediately satisfy the 10s cooldown;
+	 * start it fresh instead
+	 */
+	ioc->autop_too_fast_at = 0;
+	ioc->autop_too_slow_at = 0;
+	spin_unlock_irq(&ioc->lock);
+
+	/* calc_cost() can still run. The map is freed after an RCU gp. */
+	bpf_struct_ops_put(ops);
+#endif
+}

[ ... ]

Quoted 14 lines
block/blk-iocost.c +5 -1
@@ -3632,7 +3725,11 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 			continue;
 		case COST_MODEL:
 			match_strlcpy(buf, &args[0], sizeof(buf));
-			if (strcmp(buf, "linear"))
+			if (!strcmp(buf, "linear"))
+				model = NULL;
+			else if (!strcmp(buf, "bpf") && ioc->attached)
+				model = ioc->attached;
+			else
 				goto unlock;
 			continue;
 		}

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

Quoted 5 lines
block/blk-iocost.c +1 -0
@@ -3652,6 +3749,7 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 	} else {
 		ioc->user_cost_model = false;
 	}
+	rcu_assign_pointer(ioc->model, model);
 	ioc_refresh_params(ioc, true);

[Severity: Medium]
Can switching back to model=linear via io.cost.model evaluate stale ioc->autop_too_fast_at and ioc->autop_too_slow_at timestamps and trigger an immediate profile step?

ioc_bpf_reg() attaches the BPF model without clearing those timestamps, and while the BPF model is active ioc_autop_idx() returns early so they remain at their pre-attach values. Although ioc_detach_model() zeroes them on detach, writing model=linear to io.cost.model sets ioc->model to NULL before calling ioc_refresh_params(ioc, true), where ioc_refresh_params_disk() calls ioc_autop_idx() before zeroing autop_too_fast_at and autop_too_slow_at:

block/blk-iocost.c:ioc_refresh_params_disk() {
    ...
	idx = ioc_autop_idx(ioc, disk);
	p = &autop[idx];

	if (idx == ioc->autop_idx && !force)
		return false;

	if (idx != ioc->autop_idx) {
		atomic64_set(&ioc->vtime_rate, VTIME_PER_USEC);
		ioc->vtime_base_rate = VTIME_PER_USEC;
	}

	ioc->autop_idx = idx;
	ioc->autop_too_fast_at = 0;
	ioc->autop_too_slow_at = 0;
    ...
}

Because ioc->model is already NULL when ioc_autop_idx() runs, a pre-attach timestamp older than AUTOP_CYCLE_NSEC (10s) immediately steps ioc->autop_idx and resets vtime_rate without waiting for the cooldown.

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

Re: [RFC PATCH v13 2/4] blk-iocost: add iocost_ioc_tick tracepoint for per-period device summary

In reply to Tao Cui
TL;DR: Commit message only: it restates the code comment instead of giving the motivation (monitoring without drgn) for the new iocost_ioc_tick tracepoint. Not a bug.
Quoted 1 line

blk-iocost: add iocost_ioc_tick tracepoint for per-period device summary

TL;DR: Commit message only: it restates the code comment instead of giving the motivation (monitoring without drgn) for the new iocost_ioc_tick tracepoint. Not a bug.

Quoted 10 lines

blk-iocost: add iocost_ioc_tick tracepoint for per-period device summary

Add iocost_ioc_tick, emitted once per period from ioc_timer_fn() with the overall controller state: period_us, vrate, busy_level, active iocg count and usage percentage. busy_level, cur_period, nr_active and usage_us_sum are complete at the emission point. usage is wall time over wall time, summed over iocgs, and is not capped at 100. vrate and period_us reflect the current controller state, which an io.cost.qos write may have changed mid-period.

Quoted 7 lines

The event fires every period the controller is running, including steady states, plus one final tick before the controller goes idle, so the transition to dormancy is directly visible. The active iocg count is only gathered when the tracepoint is enabled.

this isn't a bug, but the middle of the first paragraph ("busy_level, cur_period, nr_active and usage_us_sum are complete at the emission point ... which an io.cost.qos write may have changed mid-period") restates the block comment added above the tracepoint call in ioc_timer_fn() almost word for word.

The reason for adding the event only appears in the comment in include/trace/events/iocost.h ("so basic monitoring doesn't require drgn").

Could the changelog say why a per-period summary event is needed, for example the monitoring-without-drgn motivation, rather than repeating the code comment?

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

#12 lore raw

Re: [RFC PATCH v13 3/4] selftests/bpf: add iocost cost model test

In reply to Tao Cui
TL;DR: Nits only in the iocost selftest models: stale deviation comments, macros duplicated across both progs, and a redundant op check in iocost_ms.c.
Quoted 1 line

selftests/bpf: add iocost cost model test

TL;DR: Nits only in the iocost selftest models: stale deviation comments, macros duplicated across both progs, and a redundant op check in iocost_ms.c.

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

[ ... ]

Quoted 5 lines

+ * One known deviation, mispricing only: the builtin does not move its cursor
+ * for an IO whose cgroup fails to activate; this model does not see the
+ * activation result. Another, narrower one: with "flushiops"
+ * configured, the builtin also advances its cursor for a
+ * preflushed discard, which this model still ignores.

This isn't a bug, but submit_bio_noacct() already fails any bio carrying REQ_PREFLUSH or REQ_FUA unless its op is REQ_OP_WRITE or REQ_OP_ZONE_APPEND:

    if (WARN_ON_ONCE(bio_op(bio) != REQ_OP_WRITE &&
                     bio_op(bio) != REQ_OP_ZONE_APPEND))
            goto end_io;

so a preflushed discard never reaches iocost. Could the deviation lists in the header comments of both progs be trimmed to the cases that can actually happen? The same "flushiops" sentence is repeated in the iocost_ms.c header, which also carries the "measured 89x overcharge, 12.9x throughput collapse" and "measured 107x undercharge" figures that might fit better in the changelog.

[ ... ]

Quoted 11 lines
tools/testing/selftests/bpf/progs/iocost_model.c new file +11 -0
+#define IOCOST_REQ_OP_MASK	0xff		/* REQ_OP_MASK, not in BTF */
+
+/*
+ * DIV64_U64_ROUND_UP / DIV_ROUND_UP_ULL equivalents, folded at
+ * compile time
+ */
+#define RU(x, y)		((x) / (y) + (((x) % (y)) ? 1 : 0))
+
+#define RBPS	174019176ULL
+#define RSEQIOPS	41708ULL
+#define RRANDIOPS	370ULL

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

Quoted 10 lines
tools/testing/selftests/bpf/progs/iocost_model.c new file +10 -0
+#define WBPS	178075866ULL
+#define WSEQIOPS	42705ULL
+#define WRANDIOPS	378ULL
+
+#define RPAGE	(RU(VTIME_PER_SEC, RU(RBPS, IOC_PAGE_SIZE)))
+#define RSEQIO	(RU(VTIME_PER_SEC, RSEQIOPS) - RPAGE)
+#define RRANDIO	(RU(VTIME_PER_SEC, RRANDIOPS) - RPAGE)
+#define WPAGE	(RU(VTIME_PER_SEC, RU(WBPS, IOC_PAGE_SIZE)))
+#define WSEQIO	(RU(VTIME_PER_SEC, WSEQIOPS) - WPAGE)
+#define WRANDIO	(RU(VTIME_PER_SEC, WRANDIOPS) - WPAGE)

This isn't a bug, but these macros (IOCOST_REQ_OP_MASK, RU(), the six AUTOP_HDD parameters and the derived coefficients) and the READ/WRITE/ZONE_APPEND classification in calc_cost() appear verbatim in both progs/iocost_model.c and progs/iocost_ms.c.

Could they go into a small progs/iocost_common.h, the way bpf_qdisc_common.h is shared by bpf_qdisc_fifo.c and bpf_qdisc_fq.c, so the two models don't drift apart?

[ ... ]

Quoted 1 line
tools/testing/selftests/bpf/progs/iocost_ms.c +0 -0

[ ... ]

tools/testing/selftests/bpf/progs/iocost_ms.c line 116

Quoted 8 lines
tools/testing/selftests/bpf/progs/iocost_ms.c +8 -0
+	/*
+	 * only bios the builtin prices participate in stream tracking;
+	 * the early return below skips the merge discount, which only
+	 * applies to tracked data bios
+	 */
+	if (!(((opf & IOCOST_REQ_OP_MASK) == REQ_OP_READ ||
+	       (opf & IOCOST_REQ_OP_MASK) == REQ_OP_WRITE ||
+	       (opf & IOCOST_REQ_OP_MASK) == REQ_OP_ZONE_APPEND) && nbytes)) {

This isn't a bug, but the earlier if/else chain in iocost_ms_calc_cost() already returns 0 for every op other than REQ_OP_READ, REQ_OP_WRITE and REQ_OP_ZONE_APPEND. By this point the three-way op test is always true, so could this condition just be:

    if (!nbytes) {

?

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

author
#7 lore raw

Re: [RFC PATCH v13 2/4] blk-iocost: add iocost_ioc_tick tracepoint for per-period device summary

In reply to [email protected]

Hello,

Quoted 4 lines · 在 2026/11/6 20:56, [email protected] 写道:
Quoted 1 line

blk-iocost: add iocost_ioc_tick tracepoint for per-period device summary

TL;DR: Commit message only: it restates the code comment instead of giving the motivation (monitoring without drgn) for the new iocost_ioc_tick tracepoint.

Right, the changelog ended up restating the code comment. I'll rewrite it to lead with the motivation: the tracepoint gives a per-period summary so monitoring iocost doesn't require drgn. The emission semantics stay documented in the code.

Thanks,
Tao

Quoted 39 lines

Not a bug.

Quoted 10 lines

blk-iocost: add iocost_ioc_tick tracepoint for per-period device summary

Add iocost_ioc_tick, emitted once per period from ioc_timer_fn() with the overall controller state: period_us, vrate, busy_level, active iocg count and usage percentage. busy_level, cur_period, nr_active and usage_us_sum are complete at the emission point. usage is wall time over wall time, summed over iocgs, and is not capped at 100. vrate and period_us reflect the current controller state, which an io.cost.qos write may have changed mid-period.

Quoted 7 lines

The event fires every period the controller is running, including steady states, plus one final tick before the controller goes idle, so the transition to dormancy is directly visible. The active iocg count is only gathered when the tracepoint is enabled.

this isn't a bug, but the middle of the first paragraph ("busy_level, cur_period, nr_active and usage_us_sum are complete at the emission point ... which an io.cost.qos write may have changed mid-period") restates the block comment added above the tracepoint call in ioc_timer_fn() almost word for word.

The reason for adding the event only appears in the comment in include/trace/events/iocost.h ("so basic monitoring doesn't require drgn").

Could the changelog say why a per-period summary event is needed, for example the monitoring-without-drgn motivation, rather than repeating the code comment?

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

author
#11 lore raw

Re: [RFC PATCH v13 3/4] selftests/bpf: add iocost cost model test

In reply to [email protected]

Hello,

Quoted 4 lines · 在 2026/11/6 20:44, [email protected] 写道:

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] selftests/bpf: pread() in serial_test_iocost_model_streams() hits page cache

Confirmed. The initial buffered read() loop populates the page cache, so the later pread() calls are served without issuing bios and don't necessarily exercise the multi-stream path in iocost_ms_calc_cost().

I'll rework the test so the interleaved reads generate actual block I/O instead of relying on cached pages.

Thanks,
Tao

Quoted 51 lines

--

commit 371817062abb0b837764b9a93458f77eb2057dd2
Author: Tao Cui <[email protected]>

selftests/bpf: add iocost cost model test

This commit adds BPF selftests and two example struct_ops cost models for blk-iocost using a configfs-backed null_blk device.

Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +0 -0
new file mode 100644
index 0000000000000..a714507c040e3

[ ... ]

Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +2 -0
+void serial_test_iocost_model_streams(void)
+{

[ ... ]

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +10 -0
+		devfd = open(path, O_RDONLY);
+		if (ASSERT_OK(devfd < 0 ? -errno : 0, "open_dev_ms")) {
+			char iobuf[4096];
+			unsigned long long u1 = 0, u2 = 0;
+
+			ASSERT_OK(read_cost_usage("/iocost_ms",
+						  dev, &u1), "cost_usage_pre");
+			for (i = 0; i < 500; i++)
+				(void)read(devfd, iobuf, sizeof(iobuf));
+			/*

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

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +10 -0
+			 * Two interleaved sequential streams: exercise the
+			 * stream table, not just a single cursor.
+			 */
+			for (i = 0; i < 200; i++) {
+				(void)pread(devfd, iobuf, sizeof(iobuf),
+									(i + 1) * sizeof(iobuf));
+				(void)pread(devfd, iobuf, sizeof(iobuf),
+									(1 << 20) +
+									(i + 1) * sizeof(iobuf));
+			}

[Severity: Medium]
Do these interleaved pread() calls get satisfied from the block device page cache without reaching iocost_ms_calc_cost()?

Because devfd is opened without O_DIRECT, the preceding 500 sequential 4096-byte read() calls populate the page cache for bytes [0, 2048000). Both pread() streams read within that cached range ([4096, 823296) and [1052672, 1871872)), so no interleaved bios are submitted to the block layer and the multi-stream slot table is not exercised while the subsequent assertions pass from the initial read() loop alone.

maintainer
#3 lore raw

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

In reply to Tao Cui

Hello, Tao.

Quoted 4 lines · Tao Cui

Attaching an iocost_model_ops struct_ops binds the model to one
device: the target is set in the dev member from userspace and .reg creates the ioc if needed like an io.cost.model write and
...

From here on, the description mostly walks through what the code does. Can it instead explain why it works this way and what it guarantees, and leave the mechanics to the code?

block/blk-iocost.c struct ioc_pcpu_stat { · line 414

Quoted 3 lines
block/blk-iocost.c +3 -0
+enum {
+	IOCOST_COST_F_MERGE	= 1 << 0,	/* called from the merge path */
+};

Maybe name the flags after the callback they're passed to, e.g. enum iocost_calc_flags, IOCOST_CALC_MERGE and a calc_flags parameter, the way sched_ext pairs ops.enqueue()'s enq_flags with enum scx_enq_flags and SCX_ENQ_*? An unnamed enum type can't be looked up by name through BTF, so BPF programs can't test whether a flag exists.

Also, can the comment say what the flag means to the model rather than where the call comes from? The bio is being merged into an IO which was already charged its base cost.

block/blk-iocost.c struct ioc { · line 481

Quoted 5 lines
block/blk-iocost.c +5 -0
+	/* holds a reference on the struct_ops map, NULL if none is attached */
+	const struct iocost_model_ops	*attached;
+	struct bpf_link			*attached_link;
+	/* either NULL (linear) or ->attached */
+	const struct iocost_model_ops __rcu *model;

Can the comment say why iocost holds its own reference on the map? If the link is destroyed after del_gendisk() has unhashed the bdev but before rq_qos_exit(), .unreg can't look up the disk and returns without detaching, and the link drops its reference. iocost's reference keeps the map alive until ioc_rqos_exit() detaches the model.

Also, why are attached and attached_link updated under ioc->lock in ioc_bpf_reg() and ioc_detach_model()? Everything which reads the two holds rq_qos_mutex: .reg, .unreg, ioc_detach_model() and ioc_cost_model_write(), which gets it from blkg_conf_open_bdev(). Only model is read under ioc->lock alone, by ioc_autop_idx() from the timer and the io.cost.model show path, besides the RCU readers. What is ioc->lock protecting for the two? Can you document the locking on the fields?

block/blk-iocost.c static struct ioc *q_to_ioc(struct request_queue *q) · line 711

Quoted 6 lines
block/blk-iocost.c +6 -0
+static const struct iocost_model_ops *ioc_model(struct ioc *ioc)
+{
+	if (!IS_ENABLED(CONFIG_BLK_CGROUP_IOCOST_BPF))
+		return NULL;
+	return rcu_dereference_check(ioc->model, lockdep_is_held(&ioc->lock));
+}

ioc_model() returns NULL while the builtin linear model is in use, which is a model too. Maybe rename the accessor and the field together, e.g. ioc_bpf_model() and bpf_model, or ioc_model_bpf() and model_bpf?

block/blk-iocost.c static void ioc_rqos_queue_depth_changed(struct rq_qos *rqos) · line 3063

Quoted 5 lines
block/blk-iocost.c +4 -0
+	spin_lock_irq(&ioc->lock);
+	rcu_assign_pointer(ioc->model, NULL);
...
+	ioc->autop_too_fast_at = 0;
+	ioc->autop_too_slow_at = 0;

Resetting to 0 is right, but maybe ioc_bpf_reg() is a better place for it? .reg is the only path which switches pricing to the BPF model without a forced ioc_refresh_params(), which is what zeroes the timestamps for io.cost.qos and io.cost.model writes. If ioc_bpf_reg() zeroes them, they stay zero while the BPF model is in use, which covers both detach and the "model=linear" switch sashiko reported on this posting.

Thanks.

--
tejun

maintainer Acked-by on v13 2/4
#8 lore raw

Re: [RFC PATCH v13 2/4] blk-iocost: add iocost_ioc_tick tracepoint for per-period device summary

In reply to Tao Cui
Quoted 8 lines · Tao Cui

Add iocost_ioc_tick, emitted once per period from ioc_timer_fn() with the overall controller state: period_us, vrate, busy_level, active iocg count and usage percentage. busy_level, cur_period, nr_active and usage_us_sum are complete at the emission point. usage is wall time over wall time, summed over iocgs, and is not capped at 100. vrate and period_us reflect the current controller state, which an io.cost.qos write may have changed mid-period.

Quoted 7 lines

The event fires every period the controller is running, including steady states, plus one final tick before the controller goes idle, so the transition to dormancy is directly visible. The active iocg count is only gathered when the tracepoint is enabled.

Thanks.

--
tejun

author
#4 lore raw

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

In reply to Tejun Heo

Hello, Tejun.

Quoted 12 lines · Tejun Heo

Hello, Tao.

Quoted 4 lines · Tao Cui

Attaching an iocost_model_ops struct_ops binds the model to one
device: the target is set in the dev member from userspace and .reg creates the ioc if needed like an io.cost.model write and
...

From here on, the description mostly walks through what the code does. Can it instead explain why it works this way and what it guarantees, and leave the mechanics to the code?

Rewritten. The commit message now describes what the attachment
guarantees: one attached model per device, pricing follows the model across io.cost.model writes, attaching doesn't enable the controller, and the model can't go away while it's pricing. The freeze ordering and the detach mechanics are left to the code.

Quoted 10 lines

block/blk-iocost.c struct ioc_pcpu_stat { · line 414

Quoted 3 lines
block/blk-iocost.c +3 -0
+enum {
+	IOCOST_COST_F_MERGE	= 1 << 0,	/* called from the merge path */
+};

Maybe name the flags after the callback they're passed to, e.g. enum iocost_calc_flags, IOCOST_CALC_MERGE and a calc_flags parameter, the way sched_ext pairs ops.enqueue()'s enq_flags with enum scx_enq_flags and SCX_ENQ_*? An unnamed enum type can't be looked up by name through BTF, so BPF programs can't test whether a flag exists.

Renamed. The enum is now iocost_calc_flags with IOCOST_CALC_MERGE and the calc_cost parameter is calc_flags. The named enum is used for the kernel-side definition; the BPF callback argument remains u64, matching the existing struct_ops interface style.

Quoted 4 lines

Also, can the comment say what the flag means to the model rather than where the call comes from? The bio is being merged into an IO which was already charged its base cost.

Updated accordingly.

Quoted 12 lines

block/blk-iocost.c struct ioc { · line 481

Quoted 5 lines
block/blk-iocost.c +5 -0
+	/* holds a reference on the struct_ops map, NULL if none is attached */
+	const struct iocost_model_ops	*attached;
+	struct bpf_link			*attached_link;
+	/* either NULL (linear) or ->attached */
+	const struct iocost_model_ops __rcu *model;

Can the comment say why iocost holds its own reference on the map? If the link is destroyed after del_gendisk() has unhashed the bdev but before rq_qos_exit(), .unreg can't look up the disk and returns without detaching, and the link drops its reference. iocost's reference keeps the map alive until ioc_rqos_exit() detaches the model.

The field comment now says exactly this.

Quoted 9 lines

Also, why are attached and attached_link updated under ioc->lock in ioc_bpf_reg() and ioc_detach_model()? Everything which reads the two holds rq_qos_mutex: .reg, .unreg, ioc_detach_model() and ioc_cost_model_write(), which gets it from blkg_conf_open_bdev(). Only model is read under ioc->lock alone, by ioc_autop_idx() from the timer and the io.cost.model show path, besides the RCU readers. What is ioc->lock protecting for the two? Can you document the locking on the fields?

attached and attached_link themselves are protected by rq_qos_mutex. The ioc->lock coverage is only needed for bpf_model, which is read under ioc->lock by the timer and io.cost.model show paths. The field comments now document the locking rules.

Quoted 11 lines

block/blk-iocost.c static struct ioc *q_to_ioc(struct request_queue *q) · line 711

Quoted 6 lines
block/blk-iocost.c +6 -0
+static const struct iocost_model_ops *ioc_model(struct ioc *ioc)
+{
+	if (!IS_ENABLED(CONFIG_BLK_CGROUP_IOCOST_BPF))
+		return NULL;
+	return rcu_dereference_check(ioc->model, lockdep_is_held(&ioc->lock));
+}

ioc_model() returns NULL while the builtin linear model is in use, which is a model too. Maybe rename the accessor and the field together, e.g. ioc_bpf_model() and bpf_model, or ioc_model_bpf() and model_bpf?

Renamed to ioc_bpf_model() and bpf_model.

Quoted 4 lines
Quoted 4 lines
block/blk-iocost.c +3 -0
+	spin_lock_irq(&ioc->lock);
+	rcu_assign_pointer(ioc->model, NULL);
...
+	ioc->autop_too_fast_at = 0;
Quoted 9 lines

block/blk-iocost.c static void ioc_rqos_queue_depth_changed(struct rq_qos *rqos) · line 3063

Quoted 1 line
block/blk-iocost.c +1 -0
+	ioc->autop_too_slow_at = 0;

Resetting to 0 is right, but maybe ioc_bpf_reg() is a better place for it? .reg is the only path which switches pricing to the BPF model without a forced ioc_refresh_params(), which is what zeroes the timestamps for io.cost.qos and io.cost.model writes. If ioc_bpf_reg() zeroes them, they stay zero while the BPF model is in use, which covers both detach and the "model=linear" switch sashiko reported on this posting.

Moved. ioc_bpf_reg() zeroes the timestamps inside the ioc->lock section together with the settle, and the zero in ioc_detach_model() is dropped; as you say, they stay zero for the whole BPF period, which covers both the detach and the model=linear switch.

Besides your comments, p1 also picked up two fixes from testing:
calc_cost() now matches the builtin pricing scope, and a dead owning map now reports -ENODEV instead of -EBUSY.

Thanks,
Tao

Quoted 4 lines

Thanks.

--
tejun