Skip to contentSkip to conversation

blk-iocost: BPF struct_ops cost model

RFC PATCH Superseded Tao Cui 4 participants 20 messages Sep 24 – Sep 30

Subsystems (8)

v7 of 14 Superseded Latest is v14 →

lore
Share & tools
lore

Tao Cui

author
#0 lore raw

v7 cover blk-iocost: BPF struct_ops cost model

This is v7 of the RFC. The attachment model is reworked: the struct_ops instance is now per-device, following the hid_bpf_ops pattern. The name registry, the binding through io.cost.model writes, the lifecycle list and the refcounting are gone.

Why a pluggable model at all
----------------------------

When iocost landed in 2019, its commit message already promised that "a later patch will also allow using bpf progs for cost models", and the code has carried the split for it ever since: calc_vtime_cost() is a dispatcher whose only implementation is calc_vtime_cost_builtin(). Seven years later the builtin linear model is still the only one. This series fills that slot: builtin algorithms remain the default while new ones can be prototyped in BPF.

The measured problems
---------------------

The builtin model prices each IO with a binary sequential/random base picked by a single per-cgroup cursor and a 16MB seek threshold, plus a per-page cost. On a virtio-blk device with the HDD autop profile, a 4k IO costs ~24us when judged sequential and ~2.7ms when judged random, a 112x spread, so a wrong judgement becomes a wrong price. Three classes of mispricing, all measured:

1. Heuristic rigidity. Two legitimate sequential readers in one cgroup (a database with multiple tablespaces, a threaded backup) ping-pong the single cursor and are all priced random: a measured 89x overcharge collapses throughput under the same weight. Random IO within a hot window smaller than the 16MB threshold is priced sequential: measured 107x undercharge, an accounting escape for hotspot workloads. No setting of the six builtin parameters seems able to fix this: telling the streams apart requires per-IO state tracking, which looks like logic rather than coefficients.

2. Device nonlinearity. SLC-cache phases, SMR band placement and shared controllers (multiple NVMe namespaces multiplexing one device) make the real cost of an identical IO vary by an order of magnitude over time or across namespaces. A static 6-parameter linear model has no way to express that.

3. Unpriced operations. Flush and zone append fall through to a cost of zero and bypass throttling entirely, and the same pattern extends to device quirks the builtin model was never taught.

Mispricing feeds directly into the control loop: vtime budgets, surplus donation and the vrate feedback all consume the model's output, so a wrong model can skew the whole controller.

How
---

Attachment follows the hid_bpf_ops model: the target device is set in the dev member of the struct_ops from userspace before load, as a major:minor in the usual userspace encoding (decoded with new_decode_dev() on the kernel side); loading attaches the model to that device and switches it away from the builtin linear model, detaching the struct_ops restores the builtin model, and the struct_ops core owns the program lifetime. There is no registry and no bound-state bookkeeping; attaching a second model to a device with one already attached fails with -EBUSY.

A bound 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 which feeds the latency met/missed accounting uses the transfer cost coefficients the struct_ops carries (vtime per page for reads and writes), so the builtin latency tracking and vrate adjustment follow the model's pricing while it is attached; extending the model to the QoS side itself is left for a later 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 attached to, unlike the builtin cursor which is per (cgroup, device); iocg_init()/iocg_free() callbacks, invoked from the iocg policy init and free paths with the same per (cgroup, device) lifetime, let models manage their own per-cgroup state.

While a model is attached, "model" reads back "bpf" and "ctrl" keeps describing the builtin coefficients, which are inert then:
coefficient writes are stored and take effect again after detach, and the automatic profile stepping does not switch profiles. Writing "ctrl=bpf" or "model=bpf" is accepted as a no-op so a saved configuration still parses; re-attaching the model requires loading the struct_ops again, not writing to this file.

u64 calc_cost(struct bio *bio, u64 model_flags)

The model reads whatever it needs from the bio itself: the operation flags (the operation must be extracted with a mask, and the REQ_* flag bits, including PREFLUSH/FUA, are part of it), the size, the start sector and the issuing cgroup through bio->bi_blkg. model_flags carries iocost-specific metadata which is not a property of the bio, such as whether the cost calculation is for a merged request; the return value is vtime, clamped to 1 second of device time per IO. Per-cgroup state can be stored in BPF_MAP_TYPE_CGRP_STORAGE keyed by the cgroup of bi_blkg; it follows the cgroup lifetime. Sleepable models are rejected at verification, since calc_cost() runs under RCU read lock.

Patch overview:

1/4: the BPF struct_ops cost model support: Kconfig, ops
definition, per-device attachment, unified dispatch and verifier checks
2/4: selftests with two example models (the full builtin linear
HDD formula at double cost, and a multi-stream sequentiality model) plus a runner and the selftest kernel config entries
3/4: add an iocost_ioc_tick tracepoint emitting the per-period
controller state, so model quality can be evaluated without drgn (existing events are state-change driven and silent in steady state)
4/4: document the attachment in cgroup-v2.rst

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

Mechanism, verified functionally on a virtio-blk device (HDD profile, sequential-read workload from a 1%-weight cgroup, builtin vs the 2x example model):

- per-IO charge: 2882us -> 5722us, a factor of 1.985x; the completed IO count halves and total cost.usage is conserved, i.e. the model output drives both charging and budgeting
- attachment: model=bpf readback while attached (ctrl keeps describing the inert builtin coefficients), EBUSY for a second model on the same device, a second device attaches an independent model, detaching restores the builtin readback
- edge cases: binding an unknown device fails and nothing is applied; the selftest runner checks the write error and errno of every step, including the restoration

Workload-shape verification (same setup, 4k IOs at weight 1000, builtin vs the 2x example model):

- flush-heavy workload (read/write/fsync alternating): priced 1.99x the builtin, i.e. flushes no longer reset the cursor and misjudge the following IO as random
- non-page-multiple IO (6 KiB): priced ~2x, matching the builtin's truncating page count
- first IO from a high LBA (past 16 MiB): priced 2.01x, i.e. a fresh cgroup's zero cursor no longer misjudges the first IO as random

Payoff, demonstrated with the multi-stream example model (2/4) on the same setup, 4k IOs at weight 1000, builtin vs the model:

- two sequential readers in one cgroup: priced 1961us/op by builtin (both judged random by the single cursor) and 23us/op by the model (each stream keeps its own slot); the completed IO count rises by two orders of magnitude
- random IO inside an 8M window: priced 24us/op by builtin (undercharge, an accounting escape) and 2607us/op by the model
- single-stream sequential and whole-disk random pricing are unchanged, so the model fixes both directions of mispricing without introducing a new one

Non-interference, measured on enterprise NVMe: no measurable overhead when the BPF model is not attached.

Changes in v7:
- the attachment model is reworked along the lines of the v1 review
feedback: the struct_ops instance is per-device following hid_bpf_ops, with the device in the dev member set from userspace before load, binding in .reg, unbinding in .unreg and the struct_ops core owning the lifetime; the name registry, the model-name handling in io.cost.model writes, the lifecycle list and the refcounting are removed
- calc_cost() receives the bio itself and reads the operation flags, size, sector and issuing cgroup from it; only the merge indicator stays in the separate flags argument
- the cgroup callbacks are bound to the iocg policy init/free paths instead of the blkcg css, giving the model the builtin cursor's per (cgroup, device) lifetime and dropping the global mutex from the cgroup online/offline paths
- the struct_ops carries the transfer cost coefficients (vtime per page for reads and writes), used by the completion-time request sizing so the builtin latency tracking and vrate adjustment follow the model's pricing while it is attached
- the tick tracepoint is emitted at the end of the period it reports, before the refresh, and the temporary snapshots are dropped
- the two selftest patches are combined

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

 Documentation/admin-guide/cgroup-v2.rst       |  17 ++
 block/Kconfig                                 |  10 +
 block/Makefile                                |   1 +
 block/blk-iocost-bpf.c                        | 165 ++++++++++
 block/blk-iocost.c                            | 283 +++++++++++++++++-
 include/linux/blk-iocost.h                    |  96 ++++++
 include/trace/events/iocost.h                 |  45 +++
 tools/testing/selftests/bpf/config            |   2 +
 .../selftests/bpf/prog_tests/iocost_model.c   | 180 +++++++++++
 .../selftests/bpf/progs/iocost_model.c        | 138 +++++++++
 tools/testing/selftests/bpf/progs/iocost_ms.c | 159 ++++++++++
 11 files changed, 1092 insertions(+), 4 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 v7 1/4 blk-iocost: add BPF struct_ops cost model support

From: Tao Cui <[email protected]>

Add the iocost_model_ops struct_ops. Attachment follows the hid_bpf_ops model: the struct_ops instance is per-device, the target device is set in the dev member from userspace before load, .reg attaches the model to that device and switches it away from the builtin linear model, and .unreg detaches it and restores the builtin model. The struct_ops core owns the program lifetime, so there is no name registry and no bound-state bookkeeping.

calc_cost() receives the bio itself and reads whatever it needs from it (operation flags, size, sector, the issuing cgroup); the merge indicator stays in the separate flags
argument as it is not a property of the bio. It is called from the bio charging path, so the model owns pricing for every IO on the device. The completion-time request sizing uses the transfer cost coefficients carried in the struct_ops (vtime per page for reads and writes) while a model is attached, so the builtin latency tracking and vrate adjustment follow the model's pricing; letting a model take over the QoS side is left for a later extension.

Attaching to a partition's device number is rejected: the model prices the whole queue. Enabling iocost implicitly through the attach disables wbt, matching io.cost.qos.

The cgroup callbacks are bound to the iocg policy init/free paths, one (cgroup, device) pair per invocation, matching the builtin cursor's lifetime, instead of the blkcg css lifecycle, which also drops the mutex from the cgroup online/offline paths.

calc_cost() runs under RCU read lock; sleepable programs are rejected in .check_member.

---
 block/Kconfig              |  10 ++
 block/Makefile             |   1 +
 block/blk-iocost-bpf.c     | 171 +++++++++++++++++++++++
 block/blk-iocost.c         | 275 ++++++++++++++++++++++++++++++++++++-
 include/linux/blk-iocost.h | 103 ++++++++++++++
 5 files changed, 556 insertions(+), 4 deletions(-)
 create mode 100644 block/blk-iocost-bpf.c
 create mode 100644 include/linux/blk-iocost.h
block/Kconfig +10 -0
index 70e4a66d941f..1cafc1bd0dda 100644
@@ -231,4 +231,14 @@ config BLK_ERROR_INJECTION
 
 source "block/Kconfig.iosched"
 
+config BLK_CGROUP_IOCOST_BPF
+	bool "Enable BPF pluggable cost model support for the cost IO controller"
+	depends on BLK_CGROUP_IOCOST && BPF_SYSCALL && BPF_JIT && DEBUG_INFO_BTF
+	help
+	 Enabling this option registers the "iocost_model_ops" BPF
+	 struct_ops type, which allows a BPF program to fully replace
+	 the builtin linear cost model on the device it is attached
+	 to.  The struct_ops is attached per device, following the
+	 hid_bpf_ops model.
+
 endif # BLOCK
block/Makefile +1 -0
index e7bd320e3d69..ee5cebeea006 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-iocost-bpf.c new file +171 -0

171 lines not on this page · raw message

block/blk-iocost.c +271 -4

374 lines not on this page · raw message

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

103 lines not on this page · raw message

Signature · 1 line
2.43.0
#2 lore raw

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

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] block: direct 64-bit division in calc_size_vtime_cost() --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] block: direct 64-bit division in calc_size_vtime_cost()
--

commit 848a45831f82ba85b8460e41c4e1203c6310b105
Author: Tao Cui <[email protected]>
blk-iocost: add BPF struct_ops cost model support

This commit adds the iocost_model_ops BPF struct_ops type, allowing BPF programs to replace the built-in linear cost model for blk-iocost. It attaches per-device following the hid_bpf_ops model and takes over pricing for every IO on the device.

Quoted 4 lines
block/blk-iocost.c +0 -0
index 2745bffcd5eef..21e4f8cbd9f25 100644

[ ... ]

Quoted 25 lines
block/blk-iocost.c +17 -1
@@ -2594,10 +2620,41 @@ static void calc_size_vtime_cost_builtin(struct request *rq, struct ioc *ioc,
 	}
 }
 
+/*
+ * Called from the request completion path, where no ioc->lock is
+ * held; the model pointer is read under RCU, matching the bio-side
+ * calc_vtime_cost().
+ */
 static u64 calc_size_vtime_cost(struct request *rq, struct ioc *ioc)
 {
 	u64 cost;
-
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	const struct iocost_model_ops *model;
+
+	rcu_read_lock();
+	model = rcu_dereference(ioc->model);
+	if (model && (req_op(rq) == REQ_OP_READ ||
+		      req_op(rq) == REQ_OP_WRITE)) {
+		unsigned int pages =
+			blk_rq_stats_sectors(rq) >> IOC_SECT_TO_PAGE_SHIFT;
+		u64 coeff = req_op(rq) == REQ_OP_READ ?
+			model->read_vtime_per_page :
+			model->write_vtime_per_page;

block/blk-iocost.c static void calc_size_vtime_cost_builtin(struct request *rq, struct ioc *ioc, · line 2652

Quoted 10 lines
block/blk-iocost.c +10 -0
+
+		rcu_read_unlock();
+		/* sub-page IO: nothing to transfer-price */
+		if (!pages)
+			return 0;
+		/* zero transfer cost is a legal model; guard the division */
+		if (!coeff)
+			return 0;
+		/* pages * coeff can wrap and dodge the clamp below */
+		if (coeff > VTIME_PER_SEC || pages > VTIME_PER_SEC / coeff)

[Severity: Low]
Does this direct 64-bit division cause build failures on 32-bit architectures?

Using the division operator for 64-bit integers like VTIME_PER_SEC / coeff forces the compiler to emit a call to __udivdi3, which is omitted in the Linux kernel and results in an undefined reference link-time error when CONFIG_BLK_CGROUP_IOCOST_BPF is enabled.

Could this be changed to use div64_u64() instead?

Quoted 8 lines
block/blk-iocost.c +5 -0
+			return VTIME_PER_SEC;
+		return min(pages * coeff, VTIME_PER_SEC);
+	}
+	rcu_read_unlock();
+#endif
 	calc_size_vtime_cost_builtin(rq, ioc, &cost);
 	return cost;
 }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#3 lore raw

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

In reply to Tao Cui
Does this guard against multiple registrations of the same struct_ops?
Quoted 5 lines
block/blk-iocost-bpf.c new file +0 -0
new file mode 100644
index 000000000000..2306c5fd6d8d

[ ... ]

block/blk-iocost-bpf.c line 124

Quoted 9 lines
block/blk-iocost-bpf.c new file +9 -0
+static int bpf_iocost_reg(void *kdata, struct bpf_link *link)
+{
+	struct iocost_model_ops *ops = kdata;
+
+	if (!ops->dev)
+		return -EINVAL;
+
+	return ioc_bpf_attach(ops);
+}

Does this guard against multiple registrations of the same struct_ops?

bpf_struct_ops_link_create() allows several links from one BPF_F_LINK map. bpf_struct_ops_valid_to_reg() only checks the map type, BPF_F_LINK flag, and the READY state. The state stays READY after a link is created, so every bpf_link_create() on the map calls ->reg(st_map->kvalue.data, link) on the same kdata.

hid_bpf_reg(), which the commit message names as the model, guards this case:

    /* prevent multiple attach of the same struct_ops */
    if (ops->hdev)
        return -EINVAL;

While the first link is attached, a second link on the same device is refused by the ioc->model check in ioc_bpf_attach() with -EBUSY. That check stops working once the device goes away:

1. link1 = bpf_link_create(map). ioc_bpf_attach() opens f1 = bdev_file_open_by_dev(dev) and stores ops->q = q1 and ops->bdev_file = f1.
2. The disk is removed, for example a null_blk device deleted through configfs. null_del_dev() calls ida_free(&nullb_indexes, nullb->index) and then del_gendisk(). __del_gendisk() -> rq_qos_exit() -> ioc_rqos_exit() clears ioc->model and calls ioc_bpf_detach(), which does WRITE_ONCE(ops->q, NULL) but deliberately leaves ops->bdev_file = f1. The old disk and queue stay alive because f1 pins them. __del_gendisk() also calls bdev_unhash(), so the old bdev can no longer be looked up by dev_t.
3. A new null_blk device is created. It gets the same index, and so the same dev_t, because null_add_dev() sets disk->first_minor = nullb->index and the index was already freed.
4. link2 = bpf_link_create(map). bpf_iocost_reg() sees ops->dev != 0. ioc_bpf_attach() opens f2 on the new disk and finds no model on the new ioc. It then runs:

       rcu_assign_pointer(ioc->model, ops);
       ops->q = q;
       ops->bdev_file = bdevf;

This overwrites f1, and nothing ever releases f1. The dead gendisk, request_queue, bdev and the driver module reference held through the open file are leaked, so null_blk can no longer be unloaded.
5. Closing link1 then runs bpf_iocost_unreg() -> ioc_bpf_unreg(). It reads q = new queue and bdevf = f2, detaches the model from the new device and fputs f2. link2 is still alive but its model has been silently removed. When link2 is released, ops->q and ops->bdev_file are both NULL and nothing happens.

The map's dev cannot be changed after the first update, because map_update_elem requires state INIT, so dev_t reuse is the trigger. Every step can be reached by a user with CAP_BPF, CAP_PERFMON and the ability to add and remove block devices.

Quoted 4 lines
block/blk-iocost.c +0 -0
index 2745bffcd5ee..21e4f8cbd9f2 100644

[ ... ]

Quoted 28 lines
block/blk-iocost.c +28 -0
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+/*
+ * Attach a BPF cost model to the device named by ops->dev: resolve the
+ * queue, make sure iocost is on it, and publish the model.  Attaching
+ * switches the device away from the builtin linear model; detaching
+ * restores it.  The struct_ops core holds the program alive for the
+ * whole registered period, so no extra reference is taken on the ops.
+ */
+int ioc_bpf_attach(struct iocost_model_ops *ops)
+{
+	struct block_device *bdev;
+	struct request_queue *q;
+	struct ioc *ioc;
+	const struct iocost_model_ops *old;
+	struct file *bdevf;
+	int ret;
+
+	bdevf = bdev_file_open_by_dev(new_decode_dev(ops->dev),
+				      BLK_OPEN_READ, NULL, NULL);
+	if (IS_ERR(bdevf))
+		return PTR_ERR(bdevf);
+	bdev = file_bdev(bdevf);
+
+	if (bdev_is_partition(bdev)) {
+		fput(bdevf);
+		return -EINVAL;
+	}
+

block/blk-iocost.c static int ioc_cost_model_show(struct seq_file *sf, void *v) · line 3609

Quoted 10 lines
block/blk-iocost.c +10 -0
+	q = bdev->bd_queue;
+	if (!queue_is_mq(q)) {
+		fput(bdevf);
+		return -EOPNOTSUPP;
+	}
+
+	mutex_lock(&q->rq_qos_mutex);
+	ioc = q_to_ioc(q);
+	if (!ioc) {
+		ret = blk_iocost_init(bdev->bd_disk);

Does this check that the disk is still live?

ioc_bpf_attach() takes q->rq_qos_mutex and, if the queue has no ioc, calls blk_iocost_init() to add one. It never checks that the disk is still live. The only liveness check is the one bdev_file_open_by_dev() does under open_mutex at open time, and __del_gendisk() does not wait for existing openers.

The blkcg config path handles the same race explicitly in blkg_conf_open_bdev():

    mutex_lock(&bdev->bd_queue->rq_qos_mutex);
    if (!disk_live(bdev->bd_disk)) {
        blkdev_put_no_open(bdev);
        mutex_unlock(&bdev->bd_queue->rq_qos_mutex);
        return -ENODEV;
    }

Without that check, this interleaving is possible:

1. bpf_iocost_reg() -> ioc_bpf_attach(): bdev_file_open_by_dev() succeeds while the disk is live.
2. __del_gendisk() on another CPU: bdev_unhash, GD_DEAD, blk_unregister_queue, device_del, blk_mq_freeze_queue_wait, then rq_qos_exit(q). rq_qos_exit() unlinks every rqos under rq_qos_mutex and runs ioc_rqos_exit(), so q->rq_qos no longer has an ioc.
3. ioc_bpf_attach() then gets rq_qos_mutex. q_to_ioc(q) is NULL, so blk_iocost_init() runs on the dead disk. rq_qos_add() only checks for a duplicate id, so it links a new rqos, and blkcg_activate_policy() succeeds because the blkgs are only destroyed later in disk_release(). The model is then published and blk_stat accounting is turned on.

Nothing tears down an rqos added after rq_qos_exit(). disk_release() only calls blkcg_exit_disk(), and blk_free_queue() does not look at q->rq_qos. The consequences depend on who owns the queue:

- GD_OWNS_QUEUE: the ioc and its pcpu_stat leak.
- Queue not owned by the disk, e.g. SCSI sd, where __del_gendisk() unfreezes the queue and it is reused for the next disk on sd rebind: the stale ioc stays on q->rq_qos with ioc->rqos.disk pointing at the freed old gendisk. The following paths then dereference it:
- the next rq_qos_exit(), via ioc_rqos_exit() ->

    blkcg_deactivate_policy(rqos->disk, ...)
  - ioc_rqos_queue_depth_changed() -> ioc_refresh_params() ->
    ioc_refresh_params_disk(ioc, force, ioc->rqos.disk)

- an io.cost.qos write on the new disk, where q_to_ioc() returns the stale ioc

[ ... ]

Quoted 6 lines
block/blk-iocost.c +2 -0
@@ -3531,11 +3778,31 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 				user = false;
 			else if (!strcmp(buf, "user"))
 				user = true;
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+			else if (!strcmp(buf, "bpf")) {

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

Quoted 10 lines
block/blk-iocost.c +8 -0
+				/*
+				 * readback value while a BPF model is
+				 * attached; attaching is done by loading
+				 * the struct_ops, not through this file
+				 */
+				continue;
+			}
+#endif
 			else
 				goto unlock;

Is ctrl=bpf meant to be accepted here?

The COST_CTRL case now accepts "ctrl=bpf" as a silent no-op. Before this patch the write failed with -EINVAL. The comment justifies this as a "readback value while a BPF model is attached", and the documentation (da89d4c2165e) says ctrl=bpf is accepted "so a saved configuration still parses". But the read side never produces ctrl=bpf. ioc_cost_model_prfill() still prints only

    dname, ioc->user_cost_model ? "user" : "auto",
    model ? "bpf" : "linear",

so only model= can read back as "bpf". The same docs commit also says "ctrl keeps describing the builtin coefficients" and lists ctrl as "auto" or "user". So no saved configuration can contain ctrl=bpf, and the stated reason for accepting it does not hold.

The branch adds a write-only io.cost.model token with no read-side counterpart and no effect. As user ABI it would have to be kept forever. It is also accepted when no BPF model is attached, so a mistyped config is taken silently where it used to be rejected.

The model=bpf branch in COST_MODEL is consistent with the readback and is not affected.

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

maintainer
#4 lore raw

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

In reply to Tao Cui

Hello, Tao.

block/blk-iocost.c static int ioc_autop_idx(struct ioc *ioc, struct gendisk *disk) · line 821

Quoted 12 lines · Tao Cui
block/blk-iocost.c +10 -2
-	/* if user is overriding anything, maintain what was there */
-	if (ioc->user_qos_params || ioc->user_cost_model)
+	/* if user is overriding anything, maintain what was there; the
+	 * same while a BPF model is attached: the builtin coefficients
+	 * are inert then, so stepping the profile is pointless
+	 */
+	if (ioc->user_qos_params || ioc->user_cost_model
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	    || rcu_dereference_protected(ioc->model,
+					 lockdep_is_held(&ioc->lock))
+#endif
+	   )

Can you add a helper which returns the model in use with a stub returning NULL for !CONFIG_BLK_CGROUP_IOCOST_BPF? That'd remove most of the #ifdefs including the one in this condition and the duplicated seq_printf() in ioc_cost_model_prfill().

block/blk-iocost.c static void calc_size_vtime_cost_builtin(struct request *rq, struct ioc *ioc, · line 2654

Quoted 10 lines
block/blk-iocost.c +10 -0
+		/* sub-page IO: nothing to transfer-price */
+		if (!pages)
+			return 0;
+		/* zero transfer cost is a legal model; guard the division */
+		if (!coeff)
+			return 0;
+		/* pages * coeff can wrap and dodge the clamp below */
+		if (coeff > VTIME_PER_SEC || pages > VTIME_PER_SEC / coeff)
+			return VTIME_PER_SEC;
+		return min(pages * coeff, VTIME_PER_SEC);

This can just be pages * coeff like the builtin. An overflow only skews the met/missed accounting, same as a user-set linear coefficient, and it also gets rid of the 64-bit division.

block/blk-iocost.c static int ioc_cost_model_show(struct seq_file *sf, void *v) · line 3590

Quoted 2 lines
block/blk-iocost.c +2 -0
+	bdevf = bdev_file_open_by_dev(new_decode_dev(ops->dev),
+				      BLK_OPEN_READ, NULL, NULL);

When the disk goes away, the model should be ejected completely. ioc_rqos_exit() unbinds it but the open bdev file keeps the dead disk and the driver module pinned until the link is destroyed. Can you drop all device references on removal like hid_bpf_destroy_device() does and look up the device like blkg_conf_open_bdev() does, with blkdev_get_no_open() and disk_live() checked under rq_qos_mutex? The two attach issues bpf-ci reported, the missing re-attach check in .reg and the missing disk_live() check, are real.

Thanks.

--
tejun

author
#5 lore raw

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

Hello, Tejun.

Quoted 13 lines · Tejun Heo

Hello, Tao.

Quoted 9 lines · Tao Cui
block/blk-iocost.c +7 -2
-	/* if user is overriding anything, maintain what was there */
-	if (ioc->user_qos_params || ioc->user_cost_model)
+	/* if user is overriding anything, maintain what was there; the
+	 * same while a BPF model is attached: the builtin coefficients
+	 * are inert then, so stepping the profile is pointless
+	 */
+	if (ioc->user_qos_params || ioc->user_cost_model
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	    || rcu_dereference_protected(ioc->model,
Quoted 8 lines

block/blk-iocost.c static int ioc_autop_idx(struct ioc *ioc, struct gendisk *disk) · line 821

Quoted 3 lines
block/blk-iocost.c +3 -0
+					 lockdep_is_held(&ioc->lock))
+#endif
+	   )

Can you add a helper which returns the model in use with a stub returning NULL for !CONFIG_BLK_CGROUP_IOCOST_BPF? That'd remove most of the #ifdefs including the one in this condition and the duplicated seq_printf() in ioc_cost_model_prfill().

Done. ioc_model_in_use() and a locked variant return the model in use, with NULL stubs for !CONFIG_BLK_CGROUP_IOCOST_BPF; the autop condition, both calc paths, the pd callbacks and the prfill now call the helpers, and the duplicated seq_printf() is unified.

Quoted 16 lines

block/blk-iocost.c static void calc_size_vtime_cost_builtin(struct request *rq, struct ioc *ioc, · line 2654

Quoted 11 lines
block/blk-iocost.c +10 -0
+		/* sub-page IO: nothing to transfer-price */
+		if (!pages)
+			return 0;
+		/* zero transfer cost is a legal model; guard the division */
+		if (!coeff)
+			return 0;
+		/* pages * coeff can wrap and dodge the clamp below */
+		if (coeff > VTIME_PER_SEC || pages > VTIME_PER_SEC / coeff)
+			return VTIME_PER_SEC;
+		return min(pages * coeff, VTIME_PER_SEC);

This can just be pages * coeff like the builtin. An overflow only skews the met/missed accounting, same as a user-set linear coefficient, and it also gets rid of the 64-bit division.

Done; the guards and the division are gone and the completion-time sizing is back to a plain pages * coeff, like the builtin.

Quoted 12 lines

block/blk-iocost.c static int ioc_cost_model_show(struct seq_file *sf, void *v) · line 3590

Quoted 2 lines
block/blk-iocost.c +2 -0
+	bdevf = bdev_file_open_by_dev(new_decode_dev(ops->dev),
+				      BLK_OPEN_READ, NULL, NULL);

When the disk goes away, the model should be ejected completely. ioc_rqos_exit() unbinds it but the open bdev file keeps the dead disk and the driver module pinned until the link is destroyed. Can you drop all device references on removal like hid_bpf_destroy_device() does and look up the device like blkg_conf_open_bdev() does, with blkdev_get_no_open() and disk_live() checked under rq_qos_mutex? The two attach issues bpf-ci reported, the missing re-attach check in .reg and the missing disk_live() check, are real.

Done. The struct file is gone: the attach looks the device up with blkdev_get_no_open() and checks disk_live() under rq_qos_mutex like blkg_conf_open_bdev(), .reg rejects re-attach via ops->q, and ioc_rqos_exit() ejects the model completely on removal, clearing the queue pointer.

To keep the queue alive across detach, the attach now holds a no_open bdev reference, similar to hid_bpf's per-ops device reference but without a struct file or driver-module pin; the reference is dropped by whichever path detaches the model first, either ioc_rqos_exit() during removal or .unreg, and .unreg re-checks ops->q under rq_qos_mutex.

That leaves one race: .unreg may observe a non-NULL ops->q before ioc_rqos_exit() clears it, then block on rq_qos_mutex while the ejection drops the last bdev reference. This looks analogous to hid_bpf's .unreg vs. destroy_device synchronization.

Does that seem acceptable here too, or would you rather have .unreg own the final reference unconditionally?

Thanks.
Tao

Quoted 4 lines

Thanks.

--
tejun

maintainer
#6 lore raw

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

Hello, Tao.

Quoted 7 lines · Tao Cui

That leaves one race: .unreg may observe a non-NULL ops->q before ioc_rqos_exit() clears it, then block on rq_qos_mutex while the ejection drops the last bdev reference. This looks analogous to hid_bpf's .unreg vs. destroy_device synchronization.

Does that seem acceptable here too, or would you rather have .unreg own the final reference unconditionally?

No, there can't be a crash window like that. The underlying problem is that .unreg sleeps on a mutex inside a queue it holds no reference on. The model should still be ejected when the device goes away, but exactly when doesn't matter much as long as it happens in a reasonable amount of time.

request_queues are RCU-freed, so maybe .unreg can rcu_dereference() ops->q and try to get a queue reference under rcu_read_lock()? blk_get_queue() fails on a dying queue, so this would need a tryget wrapper around q->refs. Holding its own reference, .unreg can then take rq_qos_mutex and test ops->q for NULL to tell whether removal already ejected the model.

Also, when .unreg detaches, the device is still live and the BPF code may be running. Freezing and quiescing the queue covers the IO paths but not iocg_init() and iocg_free() called from ioc_pd_init() and ioc_pd_free(), so the iocg_free() walk and clearing the model need to be synchronized against those too.

Thanks.

--
tejun

author
#7 lore raw

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

Hello, Tejun.

Quoted 16 lines · Tejun Heo

Hello, Tao.

Quoted 7 lines · Tao Cui

That leaves one race: .unreg may observe a non-NULL ops->q before ioc_rqos_exit() clears it, then block on rq_qos_mutex while the ejection drops the last bdev reference. This looks analogous to hid_bpf's .unreg vs. destroy_device synchronization.

Does that seem acceptable here too, or would you rather have .unreg own the final reference unconditionally?

No, there can't be a crash window like that. The underlying problem is that .unreg sleeps on a mutex inside a queue it holds no reference on. The model should still be ejected when the device goes away, but exactly when doesn't matter much as long as it happens in a reasonable amount of time.

Quoted 6 lines

request_queues are RCU-freed, so maybe .unreg can rcu_dereference() ops->q and try to get a queue reference under rcu_read_lock()? blk_get_queue() fails on a dying queue, so this would need a tryget wrapper around q->refs. Holding its own reference, .unreg can then take rq_qos_mutex and test ops->q for NULL to tell whether removal already ejected the model.

.unreg now takes a queue reference before entering the queue: it rcu_dereferences ops->q under rcu_read_lock() and uses a queue reference tryget helper to keep the queue valid across the mutex wait. With the reference held, .unreg freezes and quiesces the queue, takes rq_qos_mutex and re-checks ops->q for NULL, so it can handle both the normal detach path and the case where removal has already ejected the model.

Quoted 6 lines

Also, when .unreg detaches, the device is still live and the BPF code may be running. Freezing and quiescing the queue covers the IO paths but not iocg_init() and iocg_free() called from ioc_pd_init() and ioc_pd_free(), so the iocg_free() walk and clearing the model need to be synchronized against those too.

Clearing the model and the iocg_free() walk are now synchronized under q->blkcg_mutex. This is the same mutex used when blkg_create() and blkg_free_workfn() invoke pd_init_fn() and pd_free_fn(), so the detach path is synchronized with the normal pd callback paths.

While reworking the attach path, I also fixed two related issues I
noticed: the attach path no longer uses the ioc after releasing rq_qos_mutex, and blkdev_get_no_open() failures are handled correctly for unknown dev_t values.

v8 will follow shortly.

Thanks.
Tao

Quoted 4 lines

Thanks.

--
tejun

author
#8 lore raw

RFC PATCH v7 2/4 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, and a test which attaches it to one device:
the dev member of the struct_ops is written through the map's initial value before load, as hid_bpf tests do with hid_id, and attaching the struct_ops attaches the model to the device. The test verifies the model=bpf readback while attached, that a second model on the same device fails with -EBUSY, and that detaching restores the builtin model.

Under the same workload the doubled model charges 1.99x the builtin model (measured 2882us -> 5722us per IO, completed IO count halved). The example also sets the transfer cost coefficients so the builtin sizing follows the doubled pricing.

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

CONFIG_BLK_CGROUP_IOCOST and CONFIG_BLK_CGROUP_IOCOST_BPF are added to the selftest kernel config: without them vmlinux.h does not contain iocost_model_ops and the skeletons fail to build; the runtime skip cannot avoid a build dependency.

Requires root, cgroup v2 and a device given as major:minor in $IOCOST_TEST_DEV.

---
 tools/testing/selftests/bpf/config            |   2 +
 .../selftests/bpf/prog_tests/iocost_model.c   | 182 ++++++++++++++++++
 .../selftests/bpf/progs/iocost_model.c        | 139 +++++++++++++
 tools/testing/selftests/bpf/progs/iocost_ms.c | 159 +++++++++++++++
 4 files changed, 482 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 d292cb60a5a4..6e005145d3a8 100644
@@ -140,3 +140,5 @@ CONFIG_SMC_HS_CTRL_BPF=y
 CONFIG_DIBS=y
 CONFIG_DIBS_LO=y
 CONFIG_PM_WAKELOCKS=y
+CONFIG_BLK_CGROUP_IOCOST=y
+CONFIG_BLK_CGROUP_IOCOST_BPF=y
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +182 -0

182 lines not on this page · raw message

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

139 lines not on this page · raw message

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

159 lines not on this page · raw message

Signature · 1 line
2.43.0
#9 lore raw

Re: [RFC PATCH v7 2/4] selftests/bpf: add iocost cost model test

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] selftests/bpf: endianness bug when writing 64-bit device ID to 32-bit dev field --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] selftests/bpf: endianness bug when writing 64-bit device ID to 32-bit dev field --

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

selftests/bpf: add iocost cost model test

Add an example cost model implementing the full builtin linear HDD formula at double cost, and a test which attaches it to one device:
the dev member of the struct_ops is written through the map's initial value before load, as hid_bpf tests do with hid_id, and attaching the struct_ops attaches the model to the device.

Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +0 -0
new file mode 100644
index 0000000000000..156c75367af05
@@ -0,0 +1,182 @@

[ ... ]

Quoted 7 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +7 -0
+void serial_test_iocost_model(void)
+{
+	struct iocost_model *skel, *second;
+	unsigned int maj, min;
+	__u64 *ops_dev, *sdev;
+	int err;
+	char model[32], *dev;

[ ... ]

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

Quoted 7 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +7 -0
+	/* dev is the first member of struct iocost_model_ops */
+	ops_dev = bpf_map__initial_value(skel->maps.iocost_2x, NULL);
+	if (!ASSERT_OK_PTR(ops_dev, "initial_value")) {
+		iocost_model__destroy(skel);
+		return;
+	}
+	*ops_dev = makedev(maj, min);

[Severity: Medium]
Will this 64-bit write cause an endianness issue on big-endian architectures?

Since the first member dev of struct iocost_model_ops is a 32-bit dev_t, casting the pointer to __u64 * and writing a 64-bit value will place the actual device ID into the trailing padding on big-endian systems, leaving the dev field as 0. Could this cause the test to fail by attaching to the wrong device or being rejected by the kernel?

[ ... ]

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

Quoted 8 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +8 -0
+		/* a second model on the same device fails with -EBUSY */
+		second = iocost_model__open();
+		if (ASSERT_OK_PTR(second, "second_open")) {
+			sdev = bpf_map__initial_value(
+					second->maps.iocost_2x, NULL);
+			if (!ASSERT_OK_PTR(sdev, "second_initial_value"))
+				goto out_destroy;
+			*sdev = makedev(maj, min);

[Severity: Medium]
Does this have the same 64-bit write endianness issue on big-endian systems as the first model?

[ ... ]

Quoted 7 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +7 -0
+void serial_test_iocost_model_streams(void)
+{
+	struct iocost_ms *skel;
+	unsigned int maj, min;
+	__u64 *ops_dev;
+	int err;
+	char model[32], *dev;

[ ... ]

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

Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +6 -0
+	ops_dev = bpf_map__initial_value(skel->maps.iocost_ms, NULL);
+	if (!ASSERT_OK_PTR(ops_dev, "initial_value")) {
+		iocost_ms__destroy(skel);
+		return;
+	}
+	*ops_dev = makedev(maj, min);

[Severity: Medium]
Does this also share the same 64-bit write endianness issue for the 32-bit dev field?

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

Re: [RFC PATCH v7 2/4] selftests/bpf: add iocost cost model test

In reply to Tao Cui
Is this description accurate? The comment says "loading attaches the model to the device", but the code and commit message indicate otherwise.
Quoted 15 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +9 -0
new file mode 100644
index 000000000000..156c75367af0
@@ -0,0 +1,182 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <test_progs.h>
+#include <fcntl.h>
+#include <sys/sysmacros.h>
+#include <unistd.h>
+#include "iocost_model.skel.h"
+#include "iocost_ms.skel.h"
+
+/*

[ ... ]

Quoted 6 lines

+/*
+ * Attach the example model to one device, given as major:minor in
+ * $IOCOST_TEST_DEV: the dev member is written through the struct_ops
+ * map's initial value before load, as hid_bpf_ops does with hid_id,
+ * and loading attaches the model to the device. Detaching the
+ * struct_ops restores the builtin model.

Is this description accurate? The comment says "loading attaches the model to the device", but the code and commit message indicate otherwise.

For non-link SEC(".struct_ops") maps, the kernel only calls .reg from bpf_struct_ops_map_update_elem(), and libbpf issues that BPF_MAP_UPDATE_ELEM only from bpf_map__attach_struct_ops(). So the attach happens during iocost_model__attach(), not during iocost_model__load().

The test itself relies on this distinction. It calls iocost_model__load(second) at line 103 while the first model is attached and expects the load to succeed (line 103, ASSERT_OK(err, "second_load")). The -EBUSY failure is expected only from bpf_map__attach_struct_ops() at line
110. The commit message also says "attaching the struct_ops attaches the model to the device".

Should the comment say "attaching" rather than "loading"?

Quoted 5 lines

+ * Requires root, cgroup v2 and a device with iocost support.
+ */

tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +3 -0
+void serial_test_iocost_model(void)
+{
+	struct iocost_model *skel, *second;

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

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +10 -0
+	unsigned int maj, min;
+	__u64 *ops_dev, *sdev;
+	int err;
+	char model[32], *dev;
+
+	dev = getenv("IOCOST_TEST_DEV");
+	if (!dev || geteuid() != 0 || sscanf(dev, "%u:%u", &maj, &min) != 2) {
+		test__skip();
+		return;
+	}

A subsystem pattern flags this as potentially concerning: both serial_test_iocost_model() and serial_test_iocost_model_streams() call test__skip() without printing a message. Three different conditions lead
there: IOCOST_TEST_DEV not set, not running as root, or a malformed major:minor string. Since IOCOST_TEST_DEV is never set in CI, these tests are always skipped, and nothing in the output explains that IOCOST_TEST_DEV=<maj>:<min> is needed to run them.

Many prog_tests print a short message before test__skip() to explain why (like "printf(\"%s:SKIP: set IOCOST_TEST_DEV=<maj>:<min>\\n\", __func__);"). test_progs still prints a SKIP status line for the test, so the skip is not entirely silent, but the message would tell a developer how to opt in.

Also, ioc_bpf_attach() returns -EOPNOTSUPP when the device's queue is not blk-mq or lacks iocost support. The tests assert ASSERT_OK(err, "attach") at lines 84 and 169, so a device without the right support is reported as a failure rather than a skip. Is this the intended behavior?

Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +2 -0
+
+	skel = iocost_model__open();

[ ... ]

Quoted 21 lines
tools/testing/selftests/bpf/progs/iocost_model.c new file +15 -0
new file mode 100644
index 000000000000..369818bda1cf
@@ -0,0 +1,139 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Example iocost cost model: the builtin linear HDD formula with all
+ * costs doubled, for one device given by the dev member of the
+ * struct_ops.
+ *
+ * The constants mirror what calc_lcoefs() derives from the AUTOP_HDD
+ * defaults (rbps=174019176 rseqiops=41708 rrandiops=370, w-side
+ * analog) in vtime units where 1s == 2^37.  On a rotational device
+ * still on ctrl=auto, a device with this model attached charges
+ * twice the builtin model under the same workload, so the
+ * doubled cost is a direct check that accounting goes through the
+ * BPF path.  On a non-rotational device, or one with user-pinned
+ * coefficients, the ratio to the builtin model is arbitrary.
+ *

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

Quoted 10 lines
tools/testing/selftests/bpf/progs/iocost_model.c new file +10 -0
+ * A zero cursor means "no previous IO".  The cursor advances for
+ * every priced bio with a non-zero size (READ/WRITE), merged ones
+ * included, truncating to whole sectors like the builtin, so flushes
+ * and discards leave it alone and merged streams do not drift past
+ * the 16MB seek threshold.
+ *
+ * The model implements the full linear formula itself, including
+ * flushes: there is no fallback to the builtin model, a dataless
+ * A dataless WRITE|REQ_PREFLUSH keeps the write base: the op is still
+ * WRITE, so it carries WSEQIO (or WRANDIO after a seek) plus one page.

Two things here: there's a broken sentence ("... a dataless\n * A dataless WRITE|REQ_PREFLUSH ..."), and the description contradicts what the code actually does.

Lines 3-4 say the model is "the builtin linear HDD formula with all costs doubled", and lines 10-11 say it "charges twice the builtin model under the same workload". The commit message also describes it as "the full builtin linear HDD formula at double cost".

However, the builtin linear formula does not price flushes. calc_vtime_cost_builtin() starts with if (!bio->bi_iter.bi_size) goto out; and returns cost 0, so ioc_rqos_throttle() does not charge a zero-cost bio. This model instead charges a dataless WRITE|REQ_PREFLUSH as
2 * (base + 1 * WPAGE).

An empty flush bio also has bi_sector == 0 (blkdev_issue_flush() calls bio_init() with no sector). The cur && priced branch at lines 114-119 therefore measures the "seek" as the absolute cursor position. So once the cgroup has done any IO beyond the first 16MB, every fsync-style flush is priced as WRANDIO: 2 * (360433855 + 3161261) = 727190232 vtime, about 5.3ms of device time, where the builtin charges 0.

The same header in iocost_ms.c (lines 16-17) says "The model implements the full builtin linear formula itself, including flush pricing", but the builtin has no flush pricing, so that is inaccurate too. On any workload with flushes (or discards, see below), the "twice the builtin" claim and the commit message's 1.99x figure do not hold.

Could the header be clarified to state that flushes are priced even though the builtin charges them nothing, and that because a flush carries sector 0 it is effectively always priced as random IO?

Quoted 5 lines
tools/testing/selftests/bpf/progs/iocost_model.c new file +5 -0
+ */
+
+#include "vmlinux.h"
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>

[ ... ]

Quoted 11 lines
tools/testing/selftests/bpf/progs/iocost_model.c new file +11 -0
+	if ((opf & IOCOST_REQ_OP_MASK) == REQ_OP_READ) {
+		base = RSEQIO; coef_page = RPAGE; randio = RRANDIO;
+	} else if ((opf & IOCOST_REQ_OP_MASK) == REQ_OP_WRITE) {
+		base = WSEQIO; coef_page = WPAGE; randio = WRANDIO;
+	} else {
+		/*
+		 * a fully owning model must price every op; unknown
+		 * ops are priced as a single page write
+		 */
+		base = 0; coef_page = WPAGE; randio = 0;
+	}

[ ... ]

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

Quoted 3 lines
tools/testing/selftests/bpf/progs/iocost_model.c new file +3 -0
+
+	cost = 2 * (base + pages * coef_page);
+	return cost;

Does the comment match the code? The comment says "unknown ops are priced as a single page write", but the code prices them per page of bi_size.

pages is computed earlier as nbytes >> IOC_PAGE_SHIFT (clamped to at least 1), so the charge is 2 * pages * coef_page. For REQ_OP_DISCARD, REQ_OP_WRITE_ZEROES and REQ_OP_SECURE_ERASE, bi_iter.bi_size is the size of the range, not a transfer size. A 1MB write-zeroes bio is 256 pages, which is about 1.6e9 vtime (~12ms). Any range of about 85MB or more hits the VTIME_PER_SEC clamp in calc_vtime_cost(), so each such bio is charged a full second of device time. A single page write would be about 6.3e6 vtime (~46us).

For comparison, calc_vtime_cost_builtin() takes default: goto out; for these ops and returns 0, and ioc_rqos_throttle() then skips the bio with if (!abs_cost) return;. So these ops are not "twice the builtin" either.

The sibling iocost_ms.c has identical code with the comment "unknown ops are priced as per-page writes", which matches its code, so the iocost_model.c comment looks stale.

Since this file is presented as the reference example for the new iocost_model_ops API, should the comment say per-page pricing, or should pages be forced to 1 for these ops if a single page was intended?

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

author
#11 lore raw

RFC PATCH v7 3/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 the tail of ioc_timer_fn() with the overall controller state: period_us, vrate, busy_level, active iocg count, usage percentage and running state. It fires every period the controller is running, including steady states, plus one final tick before the controller goes idle, which makes dormancy (e.g. a device saturated entirely by uncharged IO) directly visible.

Unlike the existing iocost tracepoints, which are state-change driven and silent in steady state, this allows a bound cost model's behaviour to be evaluated without drgn.

Depending on the autop profile this is 2-100 events per second per device; the added cost outside the tracepoint static key is one increment per active cgroup per period.

---
 block/blk-iocost.c            | 15 ++++++++++++
 include/trace/events/iocost.h | 45 +++++++++++++++++++++++++++++++++++
 2 files changed, 60 insertions(+)
block/blk-iocost.c +15 -0
index 21e4f8cbd9f2..a48751b6dbdd 100644
@@ -2252,6 +2252,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;
@@ -2288,6 +2289,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.
@@ -2449,6 +2452,18 @@ static void ioc_timer_fn(struct timer_list *timer)
 
 	ioc->busy_level = clamp(ioc->busy_level, -1000, 1000);
 
+	/*
+	 * Everything the tick reports is final here: busy_level was just
+	 * computed, running and cur_period haven't changed, nr_active and
+	 * usage_us_sum are complete, and vrate and period_us still hold
+	 * the values this period ran in.  Emit before the refresh below
+	 * so the event reads the completed period directly.
+	 */
+	trace_iocost_ioc_tick(ioc, nr_active, usage_us_sum,
+			      ioc->period_us, ioc->vtime_base_rate,
+			      ioc->busy_level, ioc->running,
+			      now.now - ioc->period_at);
+
 	ioc_adjust_base_vrate(ioc, rq_wait_pct, nr_lagging, nr_shortages,
 			      prev_busy_level, missed_ppm);
 
include/trace/events/iocost.h +45 -0

51 lines not on this page · raw message

Signature · 1 line
2.43.0
#12 lore raw

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

This isn't a bug, but since the ioc pointer is already passed and cur_period is read from it inside TP_fast_assign, could period_us, vrate and busy_level also be read from ioc here?
Quoted 4 lines
block/blk-iocost.c +0 -0
index 21e4f8cbd9f2..a48751b6dbdd 100644

[ ... ]

Quoted 30 lines
include/trace/events/iocost.h +22 -0
index e772b1bc60d6..32f19861a78f 100644
@@ -178,6 +178,51 @@ TRACE_EVENT(iocost_ioc_vrate_adj,
 	)
 );
 
+/*
+ * Periodic per-device summary, emitted once per period from the tail of
+ * ioc_timer_fn().  Unlike the state-change events above, this fires every
+ * period the controller is running, including steady states, and carries
+ * the overall controller state so basic monitoring doesn't require drgn.
+ */
+TRACE_EVENT(iocost_ioc_tick,
+
+	TP_PROTO(struct ioc *ioc, int nr_active, u64 usage_us_sum,
+		 u32 tick_period_us, u64 tick_vrate,
+		 int tick_busy, int tick_running, u64 tick_dur),
+
+	TP_ARGS(ioc, nr_active, usage_us_sum, tick_period_us, tick_vrate,
+		tick_busy, tick_running, tick_dur),
+
+	TP_STRUCT__entry (
+		__string(devname, ioc_name(ioc))
+		__field(u64, cur_period)
+		__field(u32, period_us)
+		__field(u64, vrate)
+		__field(int, busy_level)
+		__field(int, nr_active)

include/trace/events/iocost.h TRACE_EVENT(iocost_ioc_vrate_adj, · line 212

Quoted 10 lines
include/trace/events/iocost.h +10 -0
+		__field(u32, usage_pct)
+		__field(int, running)
+	),
+
+	TP_fast_assign(
+		__assign_str(devname);
+		__entry->cur_period = atomic64_read(&ioc->cur_period);
+		__entry->period_us = tick_period_us;
+		__entry->vrate = tick_vrate;
+		__entry->busy_level = tick_busy;

This isn't a bug, but since the ioc pointer is already passed and cur_period is read from it inside TP_fast_assign, could period_us, vrate and busy_level also be read from ioc here?

The neighbouring iocost_ioc_vrate_adj event reads ioc->vtime_base_rate and ioc->busy_level directly from the ioc pointer in its TP_fast_assign. Reading them directly would make this event's prototype consistent with that pattern.

Quoted 6 lines
include/trace/events/iocost.h +6 -0
+		__entry->nr_active = nr_active;
+		__entry->usage_pct = tick_dur ?
+			div64_u64(usage_us_sum * 100, tick_dur) : 0;
+		__entry->running = tick_running;
+	),
+

include/trace/events/iocost.h TRACE_EVENT(iocost_ioc_vrate_adj, · line 228

Quoted 10 lines
include/trace/events/iocost.h +7 -0
+	TP_printk("[%s] period=%llu:%uus vrate=%llu busy=%d active=%d usage=%u%% running=%d",
+		__get_str(devname), __entry->cur_period, __entry->period_us,
+		__entry->vrate, __entry->busy_level, __entry->nr_active,
+		__entry->usage_pct, __entry->running
+	)
+);
+
 TRACE_EVENT(iocost_iocg_forgive_debt,
 
 	TP_PROTO(struct ioc_gq *iocg, const char *path, struct ioc_now *now,

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

maintainer
#13 lore raw

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

In reply to Tao Cui

Hello, Tao.

block/blk-iocost.c static void ioc_timer_fn(struct timer_list *timer) · line 2465

Quoted 4 lines · Tao Cui
block/blk-iocost.c +4 -0
+	trace_iocost_ioc_tick(ioc, nr_active, usage_us_sum,
+			      ioc->period_us, ioc->vtime_base_rate,
+			      ioc->busy_level, ioc->running,
+			      now.now - ioc->period_at);

These are still passed in. Can you pass only ioc, &now, nr_active and usage_us_sum and read the rest from ioc in TP_fast_assign() like the other iocost events do?

Thanks.

--
tejun

author
#14 lore raw

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

Hello, Tejun.

Quoted 4 lines · Tejun Heo

Hello, Tao.

On Thu, 24 Sep 2026 13:45:48 +0800, Tao Cui wrote:

Quoted 9 lines

block/blk-iocost.c static void ioc_timer_fn(struct timer_list *timer) · line 2465

Quoted 4 lines
block/blk-iocost.c +4 -0
+	trace_iocost_ioc_tick(ioc, nr_active, usage_us_sum,
+			      ioc->period_us, ioc->vtime_base_rate,
+			      ioc->busy_level, ioc->running,
+			      now.now - ioc->period_at);

These are still passed in. Can you pass only ioc, &now, nr_active and usage_us_sum and read the rest from ioc in TP_fast_assign() like the other iocost events do?

Done. The event now takes only ioc, &now, nr_active and usage_us_sum. TP_fast_assign() reads period_us, vrate, busy_level and running from ioc directly, and derives the elapsed period for the usage percentage as now->now - ioc->period_at.

Thanks.
Tao> Thanks.

Quoted 3 lines

--
tejun

author
#15 lore raw

RFC PATCH v7 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), that detaching restores the builtin model, and that writes never select a model.

---
 Documentation/admin-guide/cgroup-v2.rst | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)
Documentation/admin-guide/cgroup-v2.rst +22 -0
index 8d2603751c51..306cc929c88d 100644
@@ -2117,8 +2117,30 @@ IO Interface Files
 	  =====		================================
 	  ctrl		"auto" or "user"
 	  model		The cost model in use - "linear"
+			or "bpf" while a BPF model is
+			attached
 	  =====		================================
 
+	When CONFIG_BLK_CGROUP_IOCOST_BPF is enabled, a BPF cost model
+	can be attached to a device by loading an "iocost_model_ops"
+	struct_ops with the whole disk's major:minor in its "dev" member
+	(a partition's major:minor is rejected);
+	attaching switches the device's pricing to the model, detaching
+	the struct_ops restores the builtin linear model.  While a model
+	is attached, "model" reads back "bpf"; "ctrl" keeps describing
+	the builtin coefficients, which are inert while the model is
+	attached: coefficient writes are stored and take effect again
+	after the struct_ops is detached, and the automatic profile
+	stepping does not switch profiles.  Writing "ctrl=bpf" or
+	"model=bpf" is accepted as a no-op so a saved configuration
+	still parses, but re-attaching the model requires loading the
+	struct_ops again, not writing to this file.  Attaching
+	implicitly enables the controller if needed (disabling wbt
+	like io.cost.qos does); detaching does not disable it again,
+	and writing "enable=0" to io.cost.qos suspends the model's
+	pricing until the controller is re-enabled, while it stays
+	attached.
+
 	When "ctrl" is "auto", the kernel may change all parameters
 	dynamically.  When "ctrl" is set to "user" or any other
 	parameters are written to, "ctrl" become "user" and the
Signature · 1 line
2.43.0
maintainer
#16 lore raw
In reply to Tao Cui

Hello, Tao.

Quoted 4 lines · Tao Cui

loading attaches the model to
that device and switches it away from the builtin linear model, detaching the struct_ops restores the builtin model, and the struct_ops core owns the program lifetime.

I don't think attaching should enable the controller. v7 currently turns it on without the queue freeze and quiesce that ioc_qos_write() goes through. Attaching can create the ioc if needed like an io.cost.model write does and switch the model under the same freeze and quiesce, leaving enabling to io.cost.qos.

This is different from what I said on v1, where switching back to the builtin model detached the struct_ops, but with the controller state left to io.cost.qos it seems more consistent to keep the attachment independent too. Writing enable=0 or model=linear wouldn't detach the struct_ops, model=bpf would switch back to the attached model, and only detaching would remove it. This is the same as the linear coefficients, which are kept while the BPF model is in use and take effect again when switched back.

Quoted 4 lines

iocg_init()/iocg_free()
callbacks, invoked from the iocg policy init and free paths with the same per (cgroup, device) lifetime, let models manage their own per-cgroup state.

Existing cgroups don't get iocg_init() on attach and iocg_free() isn't delivered on detach, so init and free don't pair up. Can you call iocg_init() for all existing iocgs on attach and iocg_free() for the remaining ones on detach? That's what sched_ext does with ops.cgroup_init() and ops.cgroup_exit() on enable and disable.

Quoted 3 lines

Writing "ctrl=bpf" or "model=bpf" is accepted as a no-op so a saved configuration still parses; re-attaching the model requires loading the struct_ops again, not writing to this file.

ctrl keeps describing the coefficients and never reads back "bpf", so ctrl=bpf shouldn't be accepted. model=bpf should fail when no model is attached.

Thanks.

--
tejun

author
#17 lore raw

Hello, Tejun.

Quoted 15 lines · Tejun Heo

Hello, Tao.

Quoted 4 lines · Tao Cui

loading attaches the model to
that device and switches it away from the builtin linear model, detaching the struct_ops restores the builtin model, and the struct_ops core owns the program lifetime.

I don't think attaching should enable the controller. v7 currently turns it on without the queue freeze and quiesce that ioc_qos_write() goes through. Attaching can create the ioc if needed like an io.cost.model write does and switch the model under the same freeze and quiesce, leaving enabling to io.cost.qos.

Quoted 9 lines

This is different from what I said on v1, where switching back to the builtin model detached the struct_ops, but with the controller state left to io.cost.qos it seems more consistent to keep the attachment independent too. Writing enable=0 or model=linear wouldn't detach the struct_ops, model=bpf would switch back to the attached model, and only detaching would remove it. This is the same as the linear coefficients, which are kept while the BPF model is in use and take effect again when switched back.

Done. The implicit enable and the wbt_disable_default() are gone. Attaching now checks disk_live() and creates the ioc under rq_qos_mutex, like blkg_conf_open_bdev() does, and switches the active model under the same freeze and quiesce sequence as the io.cost.model writes.

To make sure I understood correctly: attaching switches the active model to the attached BPF model, while model=linear and model=bpf only switch between the attached model and the builtin model without affecting the attachment itself. The attachment survives enable=0, and only .unreg removes it. Please shout if I still got that wrong.

Quoted 11 lines
Quoted 4 lines

iocg_init()/iocg_free()
callbacks, invoked from the iocg policy init and free paths with the same per (cgroup, device) lifetime, let models manage their own per-cgroup state.

Existing cgroups don't get iocg_init() on attach and iocg_free() isn't delivered on detach, so init and free don't pair up. Can you call iocg_init() for all existing iocgs on attach and iocg_free() for the remaining ones on detach? That's what sched_ext does with ops.cgroup_init() and ops.cgroup_exit() on enable and disable.

Done. One note on the implementation: the existing iocgs are walked over q->blkg_list under q->blkcg_mutex, the same walk the blkcg policy teardown uses, rather than over the cgroup tree - this is a per-device walk and the queue is frozen and quiesced at that point. Cgroups without a blkg on the device yet are not missed: their blkg is created later and ioc_pd_init()/ioc_pd_free() deliver the callbacks then, so init and free pair up either way.

Quoted 8 lines
Quoted 3 lines

Writing "ctrl=bpf" or "model=bpf" is accepted as a no-op so a saved configuration still parses; re-attaching the model requires loading the struct_ops again, not writing to this file.

ctrl keeps describing the coefficients and never reads back "bpf", so ctrl=bpf shouldn't be accepted. model=bpf should fail when no model is attached.

Done as suggested; the bpf-ci review of v7 reported the same two.

Thanks.
Tao> Thanks.

Quoted 3 lines

--
tejun

maintainer
#18 lore raw

Hello, Tao.

Quoted 5 lines · Tao Cui

To make sure I understood correctly: attaching switches the active model to the attached BPF model, while model=linear and model=bpf only switch between the attached model and the builtin model without affecting the attachment itself. The attachment survives enable=0, and only .unreg removes it. Please shout if I still got that wrong.

Yes, except that removing the device also removes the attachment, as ioc_rqos_exit() ejects the model.

Thanks.

--
tejun

author
#19 lore raw

Hello, Tejun.

Quoted 12 lines · Tejun Heo

Hello, Tao.

Quoted 5 lines · Tao Cui

To make sure I understood correctly: attaching switches the active model to the attached BPF model, while model=linear and model=bpf only switch between the attached model and the builtin model without affecting the attachment itself. The attachment survives enable=0, and only .unreg removes it. Please shout if I still got that wrong.

Yes, except that removing the device also removes the attachment, as ioc_rqos_exit() ejects the model.

Thanks for confirming. I had left out the device removal case in the summary. v8 keeps the attachment independent from controller state and model selection; only .unreg and device removal (where ioc_rqos_exit() ejects the model) remove the attachment.

Thanks.
Tao> Thanks.

Quoted 3 lines

--
tejun