Skip to contentSkip to conversation

blk-iocost: add BPF struct_ops cost model support

RFC PATCH Superseded Tao Cui 5 participants 19 messages Oct 3 – Oct 19

Subsystems (8)

v10 of 14 Superseded Latest is v14 →

lore
Share & tools
lore

Tao Cui

author
#0 lore raw

v10 cover blk-iocost: add BPF struct_ops cost model support

From: Tao Cui <[email protected]>

This is v10 of the RFC. A BPF program can now take over the cost model of one device: attaching an iocost_model_ops struct_ops creates the ioc if needed and switches the device to the model, io.cost.model selects between the attached and the builtin model, and detaching or device removal restores the builtin one. The attachment, the cgroup callback pairing and the removal paths are serialized with what blkg creation and destruction actually use.

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

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

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

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

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

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

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

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

How
---

Attachment follows the hid_bpf_ops model: the target device is set in the dev member of the struct_ops from userspace before load; the device is looked up with blkdev_get_no_open() and disk_live() is checked under rq_qos_mutex, like blkg_conf_open_bdev(). Attaching creates the ioc if needed, like an io.cost.model write does, and switches the model under the same freeze and quiesce those writes go through; enabling stays with io.cost.qos and wbt stays with it too. When the disk goes away, the model is ejected completely.

Attachment is independent of the model selection and of the controller state: while a model is attached, "model" selects between it and the builtin model - "model=bpf" switches to the attached model, "model=linear" switches back to the builtin model, and neither detaches the struct_ops; only detaching removes the model, after which "model=bpf" fails. "ctrl" keeps describing the builtin coefficients, which are kept while the BPF model is in use and take effect again when switched back. Enabling and disabling the controller, and with it the wbt handover, remains with io.cost.qos.

A bound model in use owns pricing for every charged IO on the
device: it is called from the bio charging path and prices every operation including flushes. The completion-time request sizing which feeds the latency met/missed accounting uses the transfer cost coefficients the struct_ops carries (vtime per page for reads and writes), so the builtin latency tracking and vrate adjustment follow the model's pricing while it is in use; extending the model to the QoS side itself is left for a later interface.

The cgroup callbacks are bound to the iocg policy lifetime and pair
up: iocg_init() is delivered to every cgroup which already has a blkg on the device when the model is attached, and to each one appearing afterwards; iocg_free() is delivered to the cgroups which still exist when the model is detached. The existing iocgs are walked over q->blkg_list under q->blkcg_mutex, the same walk the blkcg policy teardown uses; cgroups without a blkg on the device yet are not missed, as their callbacks are delivered at blkg creation and destruction.

u64 calc_cost(struct bio *bio, u64 model_flags)

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

Patch overview:

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

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

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

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

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

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

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

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

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

Changes in v9:
- the attach holds rq_qos_mutex from the disk_live() check through the unfreeze, like an io.cost.model write does, instead of releasing it between creating the ioc and switching the model; the queue reference, the second q_to_ioc() and the lockless traversal it needed are gone
- the attachment is published, cleared and the blkg list is walked under blkcg_mutex and queue_lock: blkg creation runs ioc_pd_init() and adds to q->blkg_list under queue_lock only, so the previous blkcg_mutex-only serialization could double-deliver iocg_init() or deliver iocg_free() without iocg_init(). The init walk now goes parents first, like blkcg_activate_policy()
- the device removal ejection reads ops->bdev before clearing ops->q:
once q is NULL .unreg returns without a lock and the map can be freed, so touching ops afterwards was a use-after-free window. The ejection moved to an ioc_bpf_eject() helper
- .unreg only detaches when the closing link is the one which owns the attachment, so a map re-attached to a new device through a newer link is not torn down by an old link; the v8 ops->q re-entry guard at .reg is gone, a second attach of an attached map now fails with -EBUSY like any other model would
- the ioc->attached and ioc->model pointers are unconditional and blk_get_queue_rcu() is declared in block/blk.h without an export, which drops the local prototypes and the remaining #ifdefs
- the unused struct_ops .init name lookup, the bdev/q cases in .init_member (the core already rejects nonzero non-function members it does not claim) and the unused write_cost_model() buffers are gone; the -EOPNOTSUPP selftest paths call test__skip()
- the selftest writes the dev member through the skeleton's typed struct_ops access instead of assuming it is the first member, and the maps are ".struct_ops.link" so closing the fd detaches; the example model's seek judgement is gated on a non-zero IO size so a dataless flush is priced sequentially, and write_cost_model() returns the negated errno ASSERT_ERR() expects
- the tick tracepoint's running field reports the active iocg list instead of ioc->running, which has not transitioned to IOC_IDLE at the emit point, so the final tick reads active=0 running=0
- the attach and detach take the queue freeze before rq_qos_mutex, like ioc_qos_write() does; taking the mutex around the freeze instead formed a lockdep cycle with the io.cost.qos write path, and .unreg's link recheck moved under the mutex inside ioc_bpf_detach()
- the io.cost.model documentation states that detaching restores the builtin model and that ctrl only accepts "auto" and "user" and never selects the model, says attaching rather than loading binds the model, and that removing the device removes the model as well, with the struct_ops link still having to be closed afterwards

Changes in v10:
- one map binds one device at a time: the attach rejects a second attach while the ops is still bound, which the v9 owning-link rework had dropped. Without it, attaching the same map to a second device clobbered the single device slot, leaked the first bdev reference and left the first device pointing at the ops
- the detach takes the queue the caller holds a reference on as an argument instead of re-reading ops->q, fetches the ioc under rq_qos_mutex, and re-checks the owning link under the mutex, so closing an old link after an ejection and a re-attach no longer tears down the newer attachment
- iocg_free() is only delivered to a cgroup which received iocg_init(), tracked per iocg, so a blkg appearing between the attach walk and its own pd_init no longer gets an unpaired iocg_free(); a blkg whose radix_tree_insert() failed may still keep an iocg_init() without iocg_free(), which is now documented in the interface comment

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

author
#1 lore raw

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

iocost prices IO with a linear model derived from a handful of device parameters. The model is reasonable for common device classes, but the real cost of an IO depends on device internals the linear formula cannot capture (write amplification, GC, compression, cache behavior), and the right formula is device specific. This lets a BPF program take over pricing for a device, so the formula can be adapted to the device and updated without rebuilding the kernel.

An iocost_model_ops struct_ops is attached to one device: the target device is set in the dev member from userspace before load and .reg attaches the model to it, creating the ioc if needed, like an io.cost.model write does, and switching the device to the model under the same queue freeze and quiesce those writes go through. io.cost.model selects between the attached model and the builtin one:
"model=bpf" switches to the attached model, "model=linear" back to the builtin coefficients; neither detaches the struct_ops, and only .unreg or device removal does. Enabling and disabling the controller stays with io.cost.qos.

While the BPF model is the one in use, it prices every charged IO:
calc_cost() is called from the IO submission path with RCU read lock held, receives the bio itself and returns the cost in vtime units, clamped to one second of device time per IO. IOs which are never charged, root cgroup IOs and IOs while the controller is disabled, do not reach it. The struct_ops also carries the transfer cost coefficients, vtime per page for reads and writes, which the completion-time request sizing of READ and WRITE requests uses, so the latency tracking and vrate adjustment follow the model's pricing for those requests.

The cgroup callbacks are bound to the iocg policy lifetime, one (cgroup, device) pair per invocation: iocg_init() is delivered on attach to every cgroup which already has a blkg on the device and to each one appearing afterwards, iocg_free() on detach to every cgroup still existing then, and at policy deactivation time for the rest, so init and free pair up, except for a blkg whose radix_tree_insert() failed inside blkg_create(): it had iocg_init() delivered but never reaches the blkg list, so the detach walk misses it and iocg_free() may not be delivered. The attach and detach paths walk the blkg list under blkcg_mutex and queue_lock, which is what blkg creation and destruction synchronize on; device removal only clears the attachment, as the policy deactivation which precedes it has already delivered the remaining iocg_free() calls.

Device removal ejects the model completely, and .unreg only detaches when the link which owns the attachment is closed, so a map re-attached to a new device through a newer link is not torn down by an old one.

---
 block/Kconfig              |  10 +
 block/Makefile             |   1 +
 block/blk-core.c           |  16 ++
 block/blk-iocost-bpf.c     | 184 +++++++++++++++
 block/blk-iocost.c         | 459 ++++++++++++++++++++++++++++++++++++-
 block/blk.h                |   1 +
 include/linux/blk-iocost.h | 126 ++++++++++
 7 files changed, 789 insertions(+), 8 deletions(-)
 create mode 100644 block/blk-iocost-bpf.c
 create mode 100644 include/linux/blk-iocost.h
block/Kconfig +10 -0
index 70e4a66d941ff..1cafc1bd0dda3 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 e7bd320e3d697..ee5cebeea006f 100644
@@ -39,3 +39,4 @@ obj-$(CONFIG_BLK_INLINE_ENCRYPTION)	+= blk-crypto.o blk-crypto-profile.o \
 					   blk-crypto-sysfs.o
 obj-$(CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK)	+= blk-crypto-fallback.o
 obj-$(CONFIG_BLOCK_HOLDER_DEPRECATED)	+= holder.o
+obj-$(CONFIG_BLK_CGROUP_IOCOST_BPF)	+= blk-iocost-bpf.o
block/blk-core.c +16 -0
index 13dc70e8f55d9..a902736d381a5 100644
@@ -536,6 +536,22 @@ bool blk_get_queue(struct request_queue *q)
 }
 EXPORT_SYMBOL(blk_get_queue);
 
+/**
+ * blk_get_queue_rcu - get a queue reference regardless of the dying flag
+ * @q: the request_queue to reference
+ *
+ * Unlike blk_get_queue(), this succeeds on a dying queue, so a caller
+ * which holds the queue only through RCU (e.g. a detach path which
+ * read the pointer locklessly) can still take a reference and touch
+ * the queue under its own lifetime.  The caller must hold
+ * rcu_read_lock() so the memory is valid.  Fails only when the
+ * refcount already dropped to zero.
+ */
+bool blk_get_queue_rcu(struct request_queue *q)
+{
+	return refcount_inc_not_zero(&q->refs);
+}
+
 #ifdef CONFIG_FAIL_MAKE_REQUEST
 
 static DECLARE_FAULT_ATTR(fail_make_request);
block/blk-iocost-bpf.c new file +184 -0

184 lines not on this page · raw message

block/blk-iocost.c +451 -8

577 lines not on this page · raw message

block/blk.h +1 -0
index 2cc03aa54c532..2ef75df930d6f 100644
@@ -112,6 +112,7 @@ static inline void blk_wait_io(struct completion *done)
 }
 
 struct block_device *blkdev_get_no_open(dev_t dev, bool autoload);
+bool blk_get_queue_rcu(struct request_queue *q);
 void blkdev_put_no_open(struct block_device *bdev);
 
 bool bvec_try_merge_hw_page(struct request_queue *q, struct bio_vec *bv,
include/linux/blk-iocost.h new file +126 -0

126 lines not on this page · raw message

Signature · 1 line
2.43.0
author
#7 lore raw

RFC PATCH v10 2/4 selftests/bpf: add iocost cost model test

In reply to Tao Cui

Add two example iocost cost models and tests which attach them to one device, given as major:minor in $IOCOST_TEST_DEV.

The first model implements the builtin linear HDD formula at double cost. The second implements the 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 attaching the struct_ops binds the model to the device; the maps are declared ".struct_ops.link" so that a test dying in between does not leave the model attached.

The test verifies 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.

---
 tools/testing/selftests/bpf/config            |   2 +
 .../selftests/bpf/prog_tests/iocost_model.c   | 233 ++++++++++++++++++
 .../selftests/bpf/progs/iocost_model.c        | 141 +++++++++++
 tools/testing/selftests/bpf/progs/iocost_ms.c | 163 ++++++++++++
 4 files changed, 539 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 2b883b388f90c..c5634ee91e690 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 +233 -0

233 lines not on this page · raw message

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

141 lines not on this page · raw message

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

163 lines not on this page · raw message

Signature · 1 line
2.43.0
author
#10 lore raw

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

In reply to 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, usage percentage and whether the controller still has active iocgs. It reads the values the period ran in:
the event is emitted before the vrate adjustment and the period transition, so each tick reports the completed period. ioc->running has not transitioned to IOC_IDLE at the emit point, so the running field reports the active iocg list instead.

It fires every period the controller is running, including steady states, plus one final tick before the controller goes idle, which reads active=0 running=0, making the transition to dormancy (e.g. a device saturated entirely by uncharged IO) directly visible.

---
 block/blk-iocost.c            | 14 +++++++++++
 include/trace/events/iocost.h | 45 +++++++++++++++++++++++++++++++++++
 2 files changed, 59 insertions(+)
block/blk-iocost.c +14 -0
index 509ae36f99edf..a565892b1be07 100644
@@ -2278,6 +2278,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;
@@ -2314,6 +2315,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.
@@ -2475,6 +2478,17 @@ 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, cur_period hasn'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; ioc->running has
+	 * not transitioned to IOC_IDLE yet, so the running field reports
+	 * the active iocg list instead.
+	 */
+	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 +45 -0

51 lines not on this page · raw message

Signature · 1 line
2.43.0
author
#13 lore raw

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

In reply to Tao Cui

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 ctrl= 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 7fe950425216c..f883d1c9e67d7 100644
@@ -2117,8 +2117,30 @@ IO Interface Files
 	  =====		================================
 	  ctrl		"auto" or "user"
 	  model		The cost model in use - "linear"
+			or "bpf" while the BPF model
+			is in use
 	  =====		================================
 
+	When CONFIG_BLK_CGROUP_IOCOST_BPF is enabled, a BPF cost model
+	can be bound to a device by attaching an "iocost_model_ops"
+	struct_ops carrying the whole disk's major:minor in its "dev"
+	member (a partition's major:minor is rejected).  Attaching
+	creates the controller if needed, like an io.cost.model write
+	does, and
+	switches the device's pricing to the model; enabling and
+	disabling the controller stays with io.cost.qos.  While a model
+	is attached, "model" selects between it and the builtin model:
+	"model=bpf" switches to the attached model and "model=linear"
+	switches back to the builtin model, and neither detaches the
+	struct_ops; only detaching removes the model, after which
+	"model=bpf" fails 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, and the automatic profile stepping
+	does not switch profiles while the BPF model is in use.
+
 	When "ctrl" is "auto", the kernel may change all parameters
 	dynamically.  When "ctrl" is set to "user" or any other
 	parameters are written to, "ctrl" become "user" and the
Signature · 1 line
2.43.0
#2 lore raw
In reply to Tao Cui
TL;DR: Documentation issue only: cgroup-v2.rst isn't updated for io.cost.model accepting "model=bpf", and writing "model=linear" now switches a device off an attached BPF model, which may surprise…
Quoted 1 line

blk-iocost: add BPF struct_ops cost model support

TL;DR: Documentation issue only: cgroup-v2.rst isn't updated for io.cost.model accepting "model=bpf", and writing "model=linear" now switches a device off an attached BPF model, which may surprise existing tools.

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

[ ... ]

Quoted 17 lines
block/blk-iocost.c +10 -3
@@ -3536,9 +3961,25 @@ 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"))
-				goto unlock;
-			continue;
+			if (!strcmp(buf, "linear")) {
+				/* staged and committed below, so a parse
+				 * error later in the same write leaves
+				 * the model selection untouched
+				 */
+				new_model = NULL;
+				model_write = true;
+				continue;
+			}
+			if (!strcmp(buf, "bpf")) {

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

Quoted 10 lines
block/blk-iocost.c +9 -0
+				new_model = rcu_dereference_protected(
+						ioc->attached,
+						lockdep_is_held(&ioc->lock));
+				if (!new_model)
+					goto unlock;
+				model_write = true;
+				continue;
+			}
+			goto unlock;
 		}

Does this change to the io.cost.model interface need a matching update to Documentation/admin-guide/cgroup-v2.rst?

ioc_cost_model_write() now accepts "model=bpf", and "model=linear" is no longer only a value check. It now clears ioc->model and moves the device off an attached BPF model. ioc_cost_model_prfill() can also print "model=bpf".

The documentation still describes the key as:

model The cost model in use - "linear"

and says nothing about "bpf" or the new effect of writing "linear".

Existing tools that write lines like "MAJ:MIN ctrl=user model=linear rbps=..." will now silently switch a device away from an attached BPF model. Could cgroup-v2.rst be updated to cover the new value and the changed semantics?

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

#3 lore raw
In reply to Tao Cui
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] blk: lock inversion between rq_qos_mutex and queue freeze - [Low] bpf: multi-line comment style…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] blk: lock inversion between rq_qos_mutex and queue freeze
- [Low] bpf: multi-line comment style violation in BPF-related files
--

commit 54129eafa6fdb7e951520269403d0945a53f2d20
Author: Tao Cui <[email protected]>

blk-iocost: add BPF struct_ops cost model support

This commit introduces BPF struct_ops support for the block iocost controller, allowing a BPF program to replace the builtin linear cost model. It adds attach and detach paths for the BPF model and modifies the cost model sysfs write path to allow switching between the linear and BPF models.

Quoted 4 lines
block/blk-iocost-bpf.c new file +0 -0
new file mode 100644

[ ... ]

block/blk-iocost-bpf.c static void bpf_iocost_unreg(void *kdata, struct bpf_link *link) · line 119

Quoted 13 lines
block/blk-iocost-bpf.c new file +0 -0
@@ -108,13 +108,13 @@ static void bpf_iocost_unreg(void *kdata, struct bpf_link *link)
 	struct iocost_model_ops *ops = kdata;
 	struct request_queue *q;
 
 	/*
 	 * ops->q may already have been cleared by the removal ejection;
 	 * take a queue reference under RCU before entering the queue,
 	 * as the queue may be dying and its memory is only guaranteed
 	 * under rcu_read_lock()
 	 */
 	rcu_read_lock();
 	/* pairs with the smp_store_release() in the attach: a non-NULL
 	 * q guarantees the owning link store is visible */

[Severity: Low]
This isn't a bug, but does this multi-line comment violate the BPF subsystem comment style? The opening /* is expected to be on its own line for multi-line comments in BPF-related files.

Quoted 1 line
block/blk-iocost-bpf.c new file +0 -0
 	q = smp_load_acquire(&ops->q);

[ ... ]

Quoted 3 lines
block/blk-iocost.c +0 -0

[ ... ]

Quoted 1 line
block/blk-iocost.c +0 -0
@@ -3621,7 +3621,265 @@ static int ioc_cost_model_show(struct seq_file *sf, void *v)

[ ... ]

Quoted 2 lines
block/blk-iocost.c +2 -0
+int ioc_bpf_attach(struct iocost_model_ops *ops, struct bpf_link *link)
+{

[ ... ]

Quoted 5 lines
block/blk-iocost.c +5 -0
+	if (!queue_is_mq(q)) {
+		ret = -EOPNOTSUPP;
+		goto put;
+	}
+

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

Quoted 10 lines
block/blk-iocost.c +10 -0
+	/*
+	 * the freeze is taken before rq_qos_mutex; taking the mutex
+	 * around the freeze instead cycles against the io.cost.qos
+	 * write path, which freezes with the mutex held.  Holding
+	 * rq_qos_mutex from the disk_live() check through the model
+	 * switch keeps the ioc from being freed under us.
+	 */
+	memflags = blk_mq_freeze_queue(q);
+
+	mutex_lock(&q->rq_qos_mutex);

[Severity: High]
Could this locking sequence cause an ABBA deadlock? Here we freeze the queue and then acquire rq_qos_mutex. However, in ioc_cost_model_write() introduced further below, the order appears to be reversed.

Quoted 3 lines
block/blk-iocost.c +3 -0
+
+	/*
+	 * one map binds one device at a time: the ops carries a single

[ ... ]

Quoted 3 lines
block/blk-iocost.c +3 -0
+void ioc_bpf_detach(struct iocost_model_ops *ops, struct bpf_link *link,
+		   struct request_queue *q)
+{

[ ... ]

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

Quoted 10 lines
block/blk-iocost.c +10 -0
+	/*
+	 * the freeze is taken before rq_qos_mutex like in the attach;
+	 * the attachment and the link are re-checked under the mutex
+	 * below, as the ejection or a newer attachment through another
+	 * link may have won the race meanwhile
+	 */
+	memflags = blk_mq_freeze_queue(q);
+	blk_mq_quiesce_queue(q);
+
+	mutex_lock(&q->rq_qos_mutex);

[Severity: High]
Similar to ioc_bpf_attach(), this establishes the queue freeze -> rq_qos_mutex lock order.

Quoted 2 lines
block/blk-iocost.c +2 -0
+
+	ioc = q_to_ioc(q);

[ ... ]

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

Quoted 9 lines
block/blk-iocost.c +2 -0
@@ -3484,6 +3907,8 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 	bool user;
 	char *body, *p;
 	int ret;
+	const struct iocost_model_ops *new_model = NULL;
+	bool model_write = false;
 
 	blkg_conf_init(&ctx, input);
 

[Severity: High]
Does this code establish a reverse locking order compared to the attach and detach paths?

Further down in ioc_cost_model_write(), the call to blkg_conf_open_bdev() acquires rq_qos_mutex, and then blk_mq_freeze_queue() is called. This rq_qos_mutex -> queue freeze order looks like it will trigger a circular locking dependency warning in lockdep if someone loads a BPF struct_ops and writes to io.cost.model.

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

Quoted 12 lines
block/blk-iocost.c +5 -3
@@ -3536,9 +3961,25 @@ 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"))
-				goto unlock;
-			continue;
+			if (!strcmp(buf, "linear")) {
+				/* staged and committed below, so a parse
+				 * error later in the same write leaves
+				 * the model selection untouched
+				 */

[Severity: Low]
This isn't a bug, but this multi-line comment also appears to miss having the opening /* on its own line, which goes against the BPF subsystem formatting guidelines.

Quoted 4 lines
block/blk-iocost.c +4 -0
+				new_model = NULL;
+				model_write = true;
+				continue;
+			}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author
#16 lore raw
In reply to Tao Cui

Hello,Tejun

Quoted 10 lines · Tao Cui

From: Tao Cui <[email protected]>

This is v10 of the RFC. A BPF program can now take over the cost model of one device: attaching an iocost_model_ops struct_ops creates the ioc if needed and switches the device to the model, io.cost.model selects between the attached and the builtin model, and detaching or device removal restores the builtin one. The attachment, the cgroup callback pairing and the removal paths are serialized with what blkg creation and destruction actually use.

When you have a chance, could you take a look at this series? I'd appreciate your thoughts on whether the implementation still matches what we discussed, or whether it has drifted somewhere along the way.

Meanwhile, two review points came in on v10. Both are already addressed for v11, which I'm holding until this thread settles, as Alexei suggested.

Sashiko flagged a possible ABBA between the BPF paths and ioc_cost_model_write(): attach/detach take the queue freeze before q->rq_qos_mutex, while the cost-model write holds rq_qos_mutex across its freeze. That is indeed the current ordering, but I don't think this can deadlock because the queue freeze is a depth counter (mq_freeze_depth), not a lock: concurrent freezers simply stack, and while the write path holds the mutex it only waits for in-flight IO to drain, not for anything the attach path holds. A lockdep kernel under concurrent model-switch and attach/detach stress didn't report any lockdep warnings. If you'd prefer a uniform order anyway, the write path can take its freeze before the mutex, and I'm happy to restructure; either way this will be settled in v11.

The other point came from Alexei Starovoitov, replying to patch 1:
"device removal is still not tested." That's right. The selftest only used a device provided through $IOCOST_TEST_DEV. v11 adds a removal test to the same selftest: it creates its own null_blk instance through configfs, attaches to it, then removes the device out from under the attached model (rmdir of the configfs instance), and verifies that the ejection drops the device from the cgroup interface, that writes are rejected, and that detaching after the removal is a clean no-op; it then recreates the device, re-attaches and detaches again. I ran it locally under qemu on the v10 kernel; the new test passes cleanly with no dmesg warnings.

Thanks,
Tao

Quoted 245 lines

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

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

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

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

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

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

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

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

How
---

Attachment follows the hid_bpf_ops model: the target device is set in the dev member of the struct_ops from userspace before load; the device is looked up with blkdev_get_no_open() and disk_live() is checked under rq_qos_mutex, like blkg_conf_open_bdev(). Attaching creates the ioc if needed, like an io.cost.model write does, and switches the model under the same freeze and quiesce those writes go through; enabling stays with io.cost.qos and wbt stays with it too. When the disk goes away, the model is ejected completely.

Attachment is independent of the model selection and of the controller state: while a model is attached, "model" selects between it and the builtin model - "model=bpf" switches to the attached model, "model=linear" switches back to the builtin model, and neither detaches the struct_ops; only detaching removes the model, after which "model=bpf" fails. "ctrl" keeps describing the builtin coefficients, which are kept while the BPF model is in use and take effect again when switched back. Enabling and disabling the controller, and with it the wbt handover, remains with io.cost.qos.

A bound model in use owns pricing for every charged IO on the
device: it is called from the bio charging path and prices every operation including flushes. The completion-time request sizing which feeds the latency met/missed accounting uses the transfer cost coefficients the struct_ops carries (vtime per page for reads and writes), so the builtin latency tracking and vrate adjustment follow the model's pricing while it is in use; extending the model to the QoS side itself is left for a later interface.

The cgroup callbacks are bound to the iocg policy lifetime and pair
up: iocg_init() is delivered to every cgroup which already has a blkg on the device when the model is attached, and to each one appearing afterwards; iocg_free() is delivered to the cgroups which still exist when the model is detached. The existing iocgs are walked over q->blkg_list under q->blkcg_mutex, the same walk the blkcg policy teardown uses; cgroups without a blkg on the device yet are not missed, as their callbacks are delivered at blkg creation and destruction.

u64 calc_cost(struct bio *bio, u64 model_flags)

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

Patch overview:

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

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

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

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

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

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

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

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

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

Changes in v9:
- the attach holds rq_qos_mutex from the disk_live() check through the unfreeze, like an io.cost.model write does, instead of releasing it between creating the ioc and switching the model; the queue reference, the second q_to_ioc() and the lockless traversal it needed are gone
- the attachment is published, cleared and the blkg list is walked under blkcg_mutex and queue_lock: blkg creation runs ioc_pd_init() and adds to q->blkg_list under queue_lock only, so the previous blkcg_mutex-only serialization could double-deliver iocg_init() or deliver iocg_free() without iocg_init(). The init walk now goes parents first, like blkcg_activate_policy()
- the device removal ejection reads ops->bdev before clearing ops->q:
once q is NULL .unreg returns without a lock and the map can be freed, so touching ops afterwards was a use-after-free window. The ejection moved to an ioc_bpf_eject() helper
- .unreg only detaches when the closing link is the one which owns the attachment, so a map re-attached to a new device through a newer link is not torn down by an old link; the v8 ops->q re-entry guard at .reg is gone, a second attach of an attached map now fails with -EBUSY like any other model would
- the ioc->attached and ioc->model pointers are unconditional and blk_get_queue_rcu() is declared in block/blk.h without an export, which drops the local prototypes and the remaining #ifdefs
- the unused struct_ops .init name lookup, the bdev/q cases in .init_member (the core already rejects nonzero non-function members it does not claim) and the unused write_cost_model() buffers are gone; the -EOPNOTSUPP selftest paths call test__skip()
- the selftest writes the dev member through the skeleton's typed struct_ops access instead of assuming it is the first member, and the maps are ".struct_ops.link" so closing the fd detaches; the example model's seek judgement is gated on a non-zero IO size so a dataless flush is priced sequentially, and write_cost_model() returns the negated errno ASSERT_ERR() expects
- the tick tracepoint's running field reports the active iocg list instead of ioc->running, which has not transitioned to IOC_IDLE at the emit point, so the final tick reads active=0 running=0
- the attach and detach take the queue freeze before rq_qos_mutex, like ioc_qos_write() does; taking the mutex around the freeze instead formed a lockdep cycle with the io.cost.qos write path, and .unreg's link recheck moved under the mutex inside ioc_bpf_detach()
- the io.cost.model documentation states that detaching restores the builtin model and that ctrl only accepts "auto" and "user" and never selects the model, says attaching rather than loading binds the model, and that removing the device removes the model as well, with the struct_ops link still having to be closed afterwards

Changes in v10:
- one map binds one device at a time: the attach rejects a second attach while the ops is still bound, which the v9 owning-link rework had dropped. Without it, attaching the same map to a second device clobbered the single device slot, leaked the first bdev reference and left the first device pointing at the ops
- the detach takes the queue the caller holds a reference on as an argument instead of re-reading ops->q, fetches the ioc under rq_qos_mutex, and re-checks the owning link under the mutex, so closing an old link after an ejection and a re-attach no longer tears down the newer attachment
- iocg_free() is only delivered to a cgroup which received iocg_init(), tracked per iocg, so a blkg appearing between the attach walk and its own pd_init no longer gets an unpaired iocg_free(); a blkg whose radix_tree_insert() failed may still keep an iocg_init() without iocg_free(), which is now documented in the interface comment

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

maintainer
#17 lore raw

Hello, Tao.

Quoted 3 lines · Tao Cui

When you have a chance, could you take a look at this series? I'd appreciate your thoughts on whether the implementation still matches what we discussed, or whether it has drifted somewhere along the way.

The behavior matches what was discussed, but the implementation needs a lot of cleanup, and there are bugs in the detach path and the iocg_init()/iocg_free() pairing. Details are in the replies to the patches.

Quoted 5 lines

Sashiko flagged a possible ABBA between the BPF paths and ioc_cost_model_write(): attach/detach take the queue freeze before q->rq_qos_mutex, while the cost-model write holds rq_qos_mutex across its freeze. That is indeed the current ordering, but I don't think this can deadlock because the queue freeze is a depth counter

The attach and detach order matches ioc_qos_write(). The reverse order in ioc_cost_model_write() predates this series and is better fixed separately. An earlier attempt to convert it ran into blk_iocost_init()'s percpu allocation under the freeze:

https://lore.kernel.org/all/aV5OwAvw1sRF1IW1@fedora/

Thanks.

Signature · 1 line
tejun
maintainer
#5 lore raw
In reply to Tao Cui

Hello, Tao.

block/Kconfig config BLK_ERROR_INJECTION · line 236

Quoted 3 lines · Tao Cui
block/Kconfig +3 -0
+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

Does this need to be a separate config option? It doesn't add much code. Maybe just enable it when all the dependencies are available? bpf_tcp_ca.o, for example, is built whenever CONFIG_BPF_SYSCALL is set.

block/Kconfig config BLK_ERROR_INJECTION · line 242

Quoted 2 lines
block/Kconfig +2 -0
+	 to.  The struct_ops is attached per device, following the
+	 hid_bpf_ops model.

Can you drop the hid_bpf_ops references here, in the comments and in the selftest?

block/blk-core.c bool blk_get_queue(struct request_queue *q) · line 553

Quoted 4 lines
block/blk-core.c +4 -0
+bool blk_get_queue_rcu(struct request_queue *q)
+{
+	return refcount_inc_not_zero(&q->refs);
+}

I don't like the name. blk_get_queue() fails on a dying queue like css_tryget_online(), while this only fails once the refcount reaches zero like css_tryget(). Maybe blk_tryget_queue() or blk_queue_tryget()? I'd also put it in a separate patch, but it may not be needed at all, see below.

block/blk-iocost-bpf.c line 99

Quoted 6 lines
block/blk-iocost-bpf.c new file +6 -0
+static int bpf_iocost_validate(void *kdata)
+{
+	struct iocost_model_ops *ops = kdata;
+
+	return ops->calc_cost ? 0 : -EINVAL;
+}

read_vtime_per_page and write_vtime_per_page aren't checked. With zero, size_nsec in ioc_rqos_done() is zero for every READ and WRITE, and the whole on-queue time is judged against the latency targets. Maybe reject zero or fall back to the builtin coefficients?

Quoted 1 line

+#include <linux/blk-iocost.h>

The header's name doesn't match its content, which is only the BPF model interface. Only block/blk-iocost.c and block/blk-iocost-bpf.c include it, so it doesn't need to be in include/linux either. Its !CONFIG_BLK_CGROUP_IOCOST_BPF stubs for ioc_bpf_attach() and ioc_bpf_detach() are never used, as their only caller is built under the same option.

Quoted 1 line

+static const struct iocost_model_ops *ioc_model_in_use(struct ioc *ioc)

...

Quoted 1 line

+static const struct iocost_model_ops *ioc_attached_or_null(struct ioc *ioc)

...

Quoted 1 line

+ioc_model_in_use_locked(struct ioc *ioc)

Aren't ioc_attached_or_null() and ioc_model_in_use_locked() misnomers? ioc_model_in_use() returns NULL while the builtin model is in use, and "_or_null" doesn't add anything.

block/blk-iocost.c static void calc_vtime_cost_builtin(struct bio *bio, struct ioc_gq *iocg, · line 2621

Quoted 5 lines
block/blk-iocost.c +5 -0
+	rcu_read_lock();
+	model = ioc_model_in_use(iocg->ioc);
+	if (model) {
+		cost = model->calc_cost(bio,
+				is_merge ? IOCOST_COST_F_MERGE : 0);

Can the model cost calculation be wrapped in an inline helper in the header so that it compiles out completely when disabled?

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

Quoted 4 lines
block/blk-iocost.c +4 -0
+	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;

The model-specific calculation probably belongs on the BPF model side instead of being open-coded here. Also, ioc_rqos_done(), the only caller, returns early for anything but READ and WRITE, so the op test isn't needed.

Quoted 1 line

+static void ioc_bpf_eject(struct ioc *ioc)

The source file split doesn't make sense as is. ioc_bpf_eject() and ioc_bpf_walk_iocgs() are BPF-only but sit in blk-iocost.c because they need struct ioc and helpers which are private to it. If the BPF parts are to live in a separate file, can a prep patch move the common definitions into a private header so that everything can go where it belongs?

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

Quoted 2 lines
block/blk-iocost.c +2 -0
+	ops = (struct iocost_model_ops *)rcu_dereference_protected(
+			ioc->attached, lockdep_is_held(&ioc->lock));

The const cast is still here.

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

Quoted 7 lines
block/blk-iocost.c +7 -0
+	/*
+	 * ioc->attached and ioc->model are left set: the ioc is freed
+	 * right below, so clearing them buys nothing, and any
+	 * ioc_pd_free() which still runs finds the attachment and
+	 * delivers its iocg_free() through the struct_ops image grace
+	 * period instead of silently losing it.
+	 */

blkcg_deactivate_policy() has already freed and cleared the pd of every blkg on q->blkg_list, and nothing keeps the map alive once ops->q is cleared, so there is no such grace period.

Review

Quoted 1 line
(quoted diff) +1 -0
+	smp_store_release(&ops->q, NULL);

What's the smp_store_release() for? More on this below.

block/blk-iocost.c static void ioc_pd_init(struct blkg_policy_data *pd) · line 3187

Quoted 7 lines
block/blk-iocost.c +7 -0
+	rcu_read_lock();
+	model = ioc_attached_or_null(ioc);
+	if (model && model->iocg_init) {
+		model->iocg_init(blkg->blkcg, ioc->rqos.disk->queue);
+		iocg->bpf_iocg_inited = true;
+	}
+	rcu_read_unlock();

ioc_pd_init() isn't a hot path, and both of its callers hold queue_lock, which attach and detach also hold while changing ioc->attached. Can the synchronization be simplified?

block/blk-iocost.c static void ioc_pd_free(struct blkg_policy_data *pd) · line 3223

Quoted 3 lines
block/blk-iocost.c +3 -0
+		if (iocg->bpf_iocg_inited) {
+			rcu_read_lock();
+			model = ioc_attached_or_null(ioc);

Ditto. This runs under blkcg_mutex, which attach and detach also hold. Is the lockless dance necessary?

The pairing also has holes. blkg_create() calls pd_init before radix_tree_insert(), and a blkg whose insert fails never reaches q->blkg_list. If model A is detached and model B attached before that blkg is freed, neither walk sees it and ioc_pd_free() delivers B's iocg_free() for a cgroup which only got A's iocg_init(). The attach walk also delivers iocg_init() to blkgs which blkg_destroy() already took offline but which stay on q->blkg_list until blkg_free_workfn().

blkg_create() calls pd_online_fn only after a successful insert and list_add(), blkg_destroy() and blkcg_policy_teardown_pds() call pd_offline_fn, and pd->online tracks the state, all under queue_lock. Would delivering iocg_init() from a new ioc_pd_online() and iocg_free() from ioc_pd_offline(), with the walks skipping blkgs whose pd->online is clear, work? That would pair the callbacks exactly without bpf_iocg_inited or the radix_tree_insert() exception.

The catch is that iocg_free() then runs at blkg destruction, and bios still holding the blkg can be priced afterwards, e.g. the ones throtl_pd_offline() flushes. Moving only iocg_init() to pd_online and keeping the flag for iocg_free() avoids that.

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

Quoted 2 lines
block/blk-iocost.c +2 -0
+static void ioc_bpf_walk_iocgs(struct ioc *ioc,
+			       const struct iocost_model_ops *ops, bool init)

The name is a misnomer, this delivers the cgroup callbacks.

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

Quoted 2 lines
block/blk-iocost.c +2 -0
+	 * blkg_create() holds blkcg_mutex across ioc_pd_init() and the
+	 * list_add(), and blkg_free_workfn() holds blkcg_mutex across

On the bio path, blkg_create() runs from blkg_tryget_closest() under queue_lock only. The walk is correct because it also holds queue_lock, but this comment, the description and the cover letter still give the v8 reasoning.

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

Quoted 3 lines
block/blk-iocost.c +3 -0
+	 * the freeze is taken before rq_qos_mutex; taking the mutex
+	 * around the freeze instead cycles against the io.cost.qos
+	 * write path, which freezes with the mutex held.  Holding

ioc_qos_write() drops rq_qos_mutex before freezing. It's io.cost.model writes which freeze with the mutex held, so the cover letter's "under the same freeze and quiesce those writes go through" doesn't hold for the order either.

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

Quoted 6 lines
block/blk-iocost.c +6 -0
+	if (smp_load_acquire(&ops->q)) {
+		mutex_unlock(&q->rq_qos_mutex);
+		blk_mq_unfreeze_queue(q, memflags);
+		ret = -EBUSY;
+		goto put;
+	}

What's going on with the smp_load_acquire() here and the smp_store_release() above? The comment doesn't make clear what they're ordering against. Is this necessary?

They order the ops->link updates across different devices, which share no lock. However, ops->dev is set by init_member() while the map is still being initialized, so it can't change once .reg runs, and every attach of a map resolves the same dev_t. That should allow dropping bdev, q and link from the ops:

1. Attach looks up ops->dev and checks disk_live() under rq_qos_mutex as now, records the owning link in the ioc next to ioc->attached, takes a map reference with bpf_struct_ops_get(), and puts the bdev before returning.

2. .unreg looks up ops->dev the same way and detaches only if ioc->attached and the recorded link match. If the lookup fails, there is nothing to do, as removal ejects the model on its own.

3. Removal clears the ioc pointers and puts the map reference without touching the ops.

The map reference keeps ioc->attached valid when .unreg can't find a device which del_gendisk() has unhashed but not yet torn down. This would remove blk_get_queue_rcu(), the const cast and the acquire/release pairing.

Also, the error paths repeat the unlock sequences. Can this use guard()?

Quoted 2 lines
block/blk-iocost.c +2 -0
+void ioc_bpf_detach(struct iocost_model_ops *ops, struct bpf_link *link,
+		   struct request_queue *q)

...

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

Quoted 6 lines
block/blk-iocost.c +6 -0
+	memflags = blk_mq_freeze_queue(q);
+	blk_mq_quiesce_queue(q);
+
+	mutex_lock(&q->rq_qos_mutex);
+
+	ioc = q_to_ioc(q);

.unreg holds only a queue reference here, which doesn't keep the tag set around. If the device is removed after blk_get_queue_rcu(), e.g. virtblk_remove() running del_gendisk() and blk_mq_free_tag_set() and then freeing vblk, blk_mq_quiesce_queue() reads the freed q->tag_set in blk_mq_wait_quiesce_done(). This hasn't been reproduced.

Can the ioc and the owning link be checked under rq_qos_mutex before quiescing? Removal ejects the model under rq_qos_mutex before the driver frees the tag set, so a matching attachment under the mutex means the tag set is still there.

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

Quoted 4 lines
block/blk-iocost.c +4 -0
+				/* staged and committed below, so a parse
+				 * error later in the same write leaves
+				 * the model selection untouched
+				 */

This and the comment in bpf_iocost_unreg() put text on the /* or */ line. Also, let's not use double spaces after periods. I know there are some in these files already, but let's not spread them further. Lines are also broken prematurely in many places, e.g. the calc_cost() call above fits in 79 columns and the ioc_cost_model_prfill() hunk rewraps existing lines which fit, although I'm not sure what the block tree's policy is here.

Overall, this still looks sloppy. Can you go through the code and make sure that each part is necessary and sits in the right place?

Thanks.

Signature · 1 line
tejun
maintainer
#8 lore raw

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

In reply to Tao Cui

Hello, Tao.

Review

Quoted 1 line · Tao Cui
(quoted diff) +1 -0
+	dev = getenv("IOCOST_TEST_DEV");

Nothing in the tree sets IOCOST_TEST_DEV, so both tests always skip in CI. The null_blk instance the v11 removal test creates could serve these two as well.

Review

Quoted 2 lines
(quoted diff) +2 -0
+		if (ASSERT_OK(err, "readback"))
+			ASSERT_EQ(strcmp(model, "bpf"), 0, "model_bpf");

ASSERT_STREQ() prints both strings on failure.

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

Quoted 3 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +3 -0
+		bpf_link__destroy(skel->links.iocost_2x);
+		/* cleared, or the skeleton destroy below detaches again */
+		skel->links.iocost_2x = NULL;

Without clearing, the skeleton destroy would call bpf_link__destroy() on the freed link. It wouldn't detach again.

Quoted 6 lines

+ * The cursor handling follows the builtin: a zero cursor means "no
+ * previous IO", and the cursor is advanced for bios the builtin
+ * prices (READ/WRITE with a non-zero size; the builtin skips the
+ * whole update when the cost is zero), so flushes and discards
+ * leave it alone and long merged streams do not drift past the
+ * 16MB seek threshold.

The model advances the cursor for every merged READ or WRITE bio. ioc_rqos_merge() only moves it on a back merge into the request ending at the cursor, so a front merge leaves the builtin's cursor alone and moves the model's.

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

Quoted 6 lines
tools/testing/selftests/bpf/progs/iocost_ms.c new file +6 -0
+	} else {
+		base = randio;
+		for (i = 1; i < NSLOTS; i++) {
+			if (s->stamp[i] < s->stamp[victim])
+				victim = i;
+		}

A merged bio which matches no slot, e.g. a front merge or a merge into another stream's request, takes the LRU slot and can evict a live stream. Maybe skip the slot replacement for IOCOST_COST_F_MERGE?

Thanks.

Signature · 1 line
tejun
maintainer
#11 lore raw

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

In reply to Tao Cui

Hello, Tao.

Quoted 2 lines · Tao Cui

+ * Periodic per-device summary, emitted once per period from the tail of
+ * ioc_timer_fn(). Unlike the state-change events above, this fires every

The event is emitted before the vrate adjustment and the period transition, not from the tail.

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

Quoted 2 lines
include/trace/events/iocost.h +2 -0
+		/* whether the controller still has active iocgs */
+		__field(int, running)

nr_active counts every entry on ioc->active_iocgs, and ioc->lock is held from the count to the emit point, so running always equals active != 0. Maybe drop the field?

Thanks.

Signature · 1 line
tejun
maintainer
#14 lore raw

Re: [RFC PATCH v10 4/4] docs: cgroup-v2: document the iocost BPF cost model attachment

In reply to Tao Cui

Hello, Tao.

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

Quoted 3 lines · Tao Cui
Documentation/admin-guide/cgroup-v2.rst +2 -0
 	  model		The cost model in use - "linear"
+			or "bpf" while the BPF model
+			is in use

"linear" or "bpf" is enough here.

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

Quoted 7 lines
Documentation/admin-guide/cgroup-v2.rst +7 -0
+	When CONFIG_BLK_CGROUP_IOCOST_BPF is enabled, 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 in its "dev"
+	member (a partition's major:minor is rejected).  Attaching
+	creates the controller if needed, like an io.cost.model write
+	does, and
+	switches the device's pricing to the model; enabling and

Attaching now also populates the device's line, so the existing sentence saying the line is populated on the first write to "io.cost.qos" or "io.cost.model" needs updating. The paragraph also runs 21 lines with a leftover break after "does, and". Can it be split into three, attaching, model= selection and detaching, and removal and ctrl?

Thanks.

Signature · 1 line
tejun
author
#18 lore raw
In reply to Tejun Heo

Hello Tejun,

Quoted 12 lines · Tejun Heo

Hello, Tao.

Quoted 3 lines · Tao Cui

When you have a chance, could you take a look at this series? I'd appreciate your thoughts on whether the implementation still matches what we discussed, or whether it has drifted somewhere along the way.

The behavior matches what was discussed, but the implementation needs a lot of cleanup, and there are bugs in the detach path and the iocg_init()/iocg_free() pairing. Details are in the replies to the patches.

Thank you for the careful review, and especially for confirming that the behavior is where we wanted it.

The two bugs are mine to fix, and v11 reworks both. The detach path follows your map-reference suggestion, and the iocg_init()/iocg_free() pairing moves to ioc_pd_online() as you described, with iocg_free() keeping the delivered flag per your catch about bios still holding the blkg across offline.

Quoted 6 lines
Quoted 5 lines

Sashiko flagged a possible ABBA between the BPF paths and ioc_cost_model_write(): attach/detach take the queue freeze before q->rq_qos_mutex, while the cost-model write holds rq_qos_mutex across its freeze. That is indeed the current ordering, but I don't think this can deadlock because the queue freeze is a depth counter

Quoted 7 lines

The attach and detach order matches ioc_qos_write(). The reverse order in ioc_cost_model_write() predates this series and is better fixed separately. An earlier attempt to convert it ran into blk_iocost_init()'s percpu allocation under the freeze:

https://lore.kernel.org/all/aV5OwAvw1sRF1IW1@fedora/

Agreed. The write path ordering predates the series and I've left it alone there.

The implementation cleanup from the patch replies is in v11 as well.

Thanks,
Tao

Quoted 2 lines

Thanks.

author
#6 lore raw
In reply to Tejun Heo

Hello Tejun,

Quoted 11 lines · Tejun Heo

Hello, Tao.

block/Kconfig config BLK_ERROR_INJECTION · line 236

Quoted 3 lines · Tao Cui
block/Kconfig +3 -0
+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

Does this need to be a separate config option? It doesn't add much code. Maybe just enable it when all the dependencies are available? bpf_tcp_ca.o, for example, is built whenever CONFIG_BPF_SYSCALL is set.

Agreed, one less option is better. It's now a hidden def_bool with the dependency list and no prompt, so it's enabled automatically whenever the dependencies are available.

Quoted 6 lines

block/Kconfig config BLK_ERROR_INJECTION · line 242

Quoted 2 lines
block/Kconfig +2 -0
+	 to.  The struct_ops is attached per device, following the
+	 hid_bpf_ops model.

Can you drop the hid_bpf_ops references here, in the comments and in the selftest?

Dropped from the Kconfig (which is gone with the hidden option), from the file comment and from the selftest.

Quoted 11 lines

block/blk-core.c bool blk_get_queue(struct request_queue *q) · line 553

Quoted 4 lines
block/blk-core.c +4 -0
+bool blk_get_queue_rcu(struct request_queue *q)
+{
+	return refcount_inc_not_zero(&q->refs);
+}

I don't like the name. blk_get_queue() fails on a dying queue like css_tryget_online(), while this only fails once the refcount reaches zero like css_tryget(). Maybe blk_tryget_queue() or blk_queue_tryget()? I'd also put it in a separate patch, but it may not be needed at all, see below.

It's gone entirely with the rework below; the map reference covers the queue lifetime now, so the naming question resolves itself.

Quoted 12 lines

block/blk-iocost-bpf.c line 99

Quoted 6 lines
block/blk-iocost-bpf.c new file +6 -0
+static int bpf_iocost_validate(void *kdata)
+{
+	struct iocost_model_ops *ops = kdata;
+
+	return ops->calc_cost ? 0 : -EINVAL;
+}

read_vtime_per_page and write_vtime_per_page aren't checked. With zero, size_nsec in ioc_rqos_done() is zero for every READ and WRITE, and the whole on-queue time is judged against the latency targets. Maybe reject zero or fall back to the builtin coefficients?

You're right. The zero case would silently change the done path. v11 rejects zero: a model must provide both coefficients explicitly. Falling back to the builtin silently seemed worse than failing the load.

Quoted 9 lines
Quoted 1 line

+#include <linux/blk-iocost.h>

The header's name doesn't match its content, which is only the BPF model interface. Only block/blk-iocost.c and block/blk-iocost-bpf.c include it, so it doesn't need to be in include/linux either. Its !CONFIG_BLK_CGROUP_IOCOST_BPF stubs for ioc_bpf_attach() and ioc_bpf_detach() are never used, as their only caller is built under the same option.

Agreed on all three counts. blk-iocost.h moved to block/ as a private header holding the common definitions, the ops struct lives there now, and the unused stubs are gone.

Quoted 10 lines
Quoted 1 line

+static const struct iocost_model_ops *ioc_model_in_use(struct ioc *ioc)

...

Quoted 1 line

+static const struct iocost_model_ops *ioc_attached_or_null(struct ioc *ioc)

...

Quoted 1 line

+ioc_model_in_use_locked(struct ioc *ioc)

Aren't ioc_attached_or_null() and ioc_model_in_use_locked() misnomers? ioc_model_in_use() returns NULL while the builtin model is in use, and "_or_null" doesn't add anything.

You're right, the names described the call sites rather than what the functions return. ioc_attached_or_null() is now ioc_attached_model_locked() and ioc_model_in_use() is ioc_bpf_model_locked(); the hot-path dispatch moved into the ioc_model_calc_cost()/ioc_model_size_cost() helpers, which take and release rcu_read_lock() themselves.

Quoted 9 lines

block/blk-iocost.c static void calc_vtime_cost_builtin(struct bio *bio, struct ioc_gq *iocg, · line 2621

Quoted 5 lines
block/blk-iocost.c +5 -0
+	rcu_read_lock();
+	model = ioc_model_in_use(iocg->ioc);
+	if (model) {
+		cost = model->calc_cost(bio,
+				is_merge ? IOCOST_COST_F_MERGE : 0);

Can the model cost calculation be wrapped in an inline helper in the header so that it compiles out completely when disabled?

Done; it's an inline helper in the private header next to the ops struct, and with the BPF support compiled out it degenerates to the builtin dispatch and the whole path compiles away.

Quoted 10 lines

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

Quoted 4 lines
block/blk-iocost.c +4 -0
+	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;

The model-specific calculation probably belongs on the BPF model side instead of being open-coded here. Also, ioc_rqos_done(), the only caller, returns early for anything but READ and WRITE, so the op test isn't needed.

Moved t

Quoted 8 lines
Quoted 1 line

+static void ioc_bpf_eject(struct ioc *ioc)

The source file split doesn't make sense as is. ioc_bpf_eject() and ioc_bpf_walk_iocgs() are BPF-only but sit in blk-iocost.c because they need struct ioc and helpers which are private to it. If the BPF parts are to live in a separate file, can a prep patch move the common definitions into a private header so that everything can go where it belongs?

Yes, the split grew organically and ended up misplaced. The series now starts with a prep patch which moves the enums, struct ioc/ioc_gq and the accessors into block/blk-iocost.h, and the whole BPF side lives in blk-iocost-bpf.c now: attach, detach, the ejection and the callback delivery.

Quoted 5 lines

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

Quoted 2 lines
block/blk-iocost.c +2 -0
+	ops = (struct iocost_model_ops *)rcu_dereference_protected(
+			ioc->attached, lockdep_is_held(&ioc->lock));

The const cast is still here.

Sorry, missed that one. Gone with the rework; the recorded owner is a plain pointer.

Quoted 12 lines

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

Quoted 7 lines
block/blk-iocost.c +7 -0
+	/*
+	 * ioc->attached and ioc->model are left set: the ioc is freed
+	 * right below, so clearing them buys nothing, and any
+	 * ioc_pd_free() which still runs finds the attachment and
+	 * delivers its iocg_free() through the struct_ops image grace
+	 * period instead of silently losing it.
+	 */

blkcg_deactivate_policy() has already freed and cleared the pd of every blkg on q->blkg_list, and nothing keeps the map alive once ops->q is cleared, so there is no such grace period.

You're right, and thank you for the correction: that comment was just wrong, there is no grace period there. The v11 removal path clears the ioc pointers and drops the map reference, and the comment describes that.

Quoted 4 lines

Review

Quoted 1 line
(quoted diff) +1 -0
+	smp_store_release(&ops->q, NULL);

What's the smp_store_release() for? More on this below.

Quoted 12 lines

block/blk-iocost.c static void ioc_pd_init(struct blkg_policy_data *pd) · line 3187

Quoted 7 lines
block/blk-iocost.c +7 -0
+	rcu_read_lock();
+	model = ioc_attached_or_null(ioc);
+	if (model && model->iocg_init) {
+		model->iocg_init(blkg->blkcg, ioc->rqos.disk->queue);
+		iocg->bpf_iocg_inited = true;
+	}
+	rcu_read_unlock();

ioc_pd_init() isn't a hot path, and both of its callers hold queue_lock, which attach and detach also hold while changing ioc->attached. Can the synchronization be simplified?

Simplified as you suggest. The callbacks now read ioc->attached directly. ioc_pd_init() runs under queue_lock, the free path under blkcg_mutex, and attach/detach update the pointer while holding the corresponding lock.

Quoted 23 lines

block/blk-iocost.c static void ioc_pd_free(struct blkg_policy_data *pd) · line 3223

Quoted 3 lines
block/blk-iocost.c +3 -0
+		if (iocg->bpf_iocg_inited) {
+			rcu_read_lock();
+			model = ioc_attached_or_null(ioc);

Ditto. This runs under blkcg_mutex, which attach and detach also hold. Is the lockless dance necessary?

The pairing also has holes. blkg_create() calls pd_init before radix_tree_insert(), and a blkg whose insert fails never reaches q->blkg_list. If model A is detached and model B attached before that blkg is freed, neither walk sees it and ioc_pd_free() delivers B's iocg_free() for a cgroup which only got A's iocg_init(). The attach walk also delivers iocg_init() to blkgs which blkg_destroy() already took offline but which stay on q->blkg_list until blkg_free_workfn().

blkg_create() calls pd_online_fn only after a successful insert and list_add(), blkg_destroy() and blkcg_policy_teardown_pds() call pd_offline_fn, and pd->online tracks the state, all under queue_lock. Would delivering iocg_init() from a new ioc_pd_online() and iocg_free() from ioc_pd_offline(), with the walks skipping blkgs whose pd->online is clear, work? That would pair the callbacks exactly without bpf_iocg_inited or the radix_tree_insert() exception.

Quoted 5 lines

The catch is that iocg_free() then runs at blkg destruction, and bios still holding the blkg can be priced afterwards, e.g. the ones throtl_pd_offline() flushes. Moving only iocg_init() to pd_online and keeping the flag for iocg_free() avoids that.

You're right about the hole, and v11 follows that approach:
iocg_init() is delivered from a new ioc_pd_online(), which blkg_create() calls only after the successful radix_tree_insert() and list_add(), the walks skip blkgs whose pd->online is clear, and iocg_free() keeps the delivered flag so it is not delivered while bios can still be priced against the blkg.

Quoted 5 lines

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

Quoted 2 lines
block/blk-iocost.c +2 -0
+static void ioc_bpf_walk_iocgs(struct ioc *ioc,
+			       const struct iocost_model_ops *ops, bool init)

The name is a misnomer, this delivers the cgroup callbacks.

Renamed to ioc_bpf_deliver_iocg_callbacks().

Quoted 8 lines

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

Quoted 2 lines
block/blk-iocost.c +2 -0
+	 * blkg_create() holds blkcg_mutex across ioc_pd_init() and the
+	 * list_add(), and blkg_free_workfn() holds blkcg_mutex across

On the bio path, blkg_create() runs from blkg_tryget_closest() under queue_lock only. The walk is correct because it also holds queue_lock, but this comment, the description and the cover letter still give the v8 reasoning.

Updated; the comment and the description now say the walk is correct because it holds queue_lock, which is what the bio path uses.

Quoted 9 lines

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

Quoted 3 lines
block/blk-iocost.c +3 -0
+	 * the freeze is taken before rq_qos_mutex; taking the mutex
+	 * around the freeze instead cycles against the io.cost.qos
+	 * write path, which freezes with the mutex held.  Holding

ioc_qos_write() drops rq_qos_mutex before freezing. It's io.cost.model writes which freeze with the mutex held, so the cover letter's "under the same freeze and quiesce those writes go through" doesn't hold for the order either.

That's right, the comment was wrong. It now says the attach and detach order matches ioc_qos_write()'s, which is what the code does, and the cover letter no longer claims the io.cost.model write ordering.

Quoted 26 lines

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

Quoted 6 lines
block/blk-iocost.c +6 -0
+	if (smp_load_acquire(&ops->q)) {
+		mutex_unlock(&q->rq_qos_mutex);
+		blk_mq_unfreeze_queue(q, memflags);
+		ret = -EBUSY;
+		goto put;
+	}

What's going on with the smp_load_acquire() here and the smp_store_release() above? The comment doesn't make clear what they're ordering against. Is this necessary?

They order the ops->link updates across different devices, which share no lock. However, ops->dev is set by init_member() while the map is still being initialized, so it can't change once .reg runs, and every attach of a map resolves the same dev_t. That should allow dropping bdev, q and link from the ops:

1. Attach looks up ops->dev and checks disk_live() under rq_qos_mutex as now, records the owning link in the ioc next to ioc->attached, takes a map reference with bpf_struct_ops_get(), and puts the bdev before returning.

2. .unreg looks up ops->dev the same way and detaches only if ioc->attached and the recorded link match. If the lookup fails, there is nothing to do, as removal ejects the model on its own.

Quoted 8 lines

3. Removal clears the ioc pointers and puts the map reference without touching the ops.

The map reference keeps ioc->attached valid when .unreg can't find a device which del_gendisk() has unhashed but not yet torn down. This would remove blk_get_queue_rcu(), the const cast and the acquire/release pairing.

Thank you for spelling this out; it's a much cleaner shape. Reworked
accordingly: attach looks up ops->dev and checks disk_live() under rq_qos_mutex, records the owning link next to ioc->attached and takes a reference on the map with bpf_struct_ops_get(), putting the bdev before returning; .unreg looks the device up the same way and detaches only when ioc->attached and the recorded link both match, treating a failed lookup as nothing to do; the removal path clears the ioc pointers and drops the map reference without touching the ops. bdev, q and link are gone from the ops along with the acquire/release pairing.

Quoted 2 lines

Also, the error paths repeat the unlock sequences. Can this use guard()?

Switched to guard() for the mutex.

Quoted 16 lines
Quoted 2 lines
block/blk-iocost.c +2 -0
+void ioc_bpf_detach(struct iocost_model_ops *ops, struct bpf_link *link,
+		   struct request_queue *q)

...

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

Quoted 6 lines
block/blk-iocost.c +6 -0
+	memflags = blk_mq_freeze_queue(q);
+	blk_mq_quiesce_queue(q);
+
+	mutex_lock(&q->rq_qos_mutex);
+
+	ioc = q_to_ioc(q);

.unreg holds only a queue reference here, which doesn't keep the tag set around. If the device is removed after blk_get_queue_rcu(), e.g. virtblk_remove() running del_gendisk() and blk_mq_free_tag_set() and then freeing vblk, blk_mq_quiesce_queue() reads the freed q->tag_set in blk_mq_wait_quiesce_done(). This hasn't been reproduced.

Quoted 5 lines

Can the ioc and the owning link be checked under rq_qos_mutex before quiescing? Removal ejects the model under rq_qos_mutex before the driver frees the tag set, so a matching attachment under the mutex means the tag set is still there.

Good catch. v11 now performs an initial check under rq_qos_mutex before freezing, then re-checks after freezing before quiescing, so a successful second check guarantees that the tag set is still alive.

Quoted 12 lines

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

Quoted 4 lines
block/blk-iocost.c +4 -0
+				/* staged and committed below, so a parse
+				 * error later in the same write leaves
+				 * the model selection untouched
+				 */

This and the comment in bpf_iocost_unreg() put text on the /* or */ line. Also, let's not use double spaces after periods. I know there are some in these files already, but let's not spread them further. Lines are also broken prematurely in many places, e.g. the calc_cost() call above fits in 79 columns and the ioc_cost_model_prfill() hunk rewraps existing lines which fit, although I'm not sure what the block tree's policy is here.

The two comment openings are fixed in v11 already; the double spaces and the premature line breaks are cleaned up throughout, and the ioc_cost_model_prfill() hunk no longer rewraps lines that fit.

Quoted 3 lines

Overall, this still looks sloppy. Can you go through the code and make sure that each part is necessary and sits in the right place?

Fair. I went through the whole series again rather than just fixing the individual comments. A number of comments and helpers had drifted during the v8-v10 rework, so I cleaned those up as well. Hopefully v11 is a better reflection of the code now.

Thanks again for the review.

Tao

Quoted 2 lines

Thanks.

author
#9 lore raw

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

In reply to Tejun Heo

Hello Tejun,

Quoted 9 lines · Tejun Heo

Hello, Tao.

Review

Quoted 1 line · Tao Cui
(quoted diff) +1 -0
+	dev = getenv("IOCOST_TEST_DEV");

Nothing in the tree sets IOCOST_TEST_DEV, so both tests always skip in CI. The null_blk instance the v11 removal test creates could serve these two as well.

Right, that was an oversight. All three tests now create their own null_blk instance through configfs. The create/remove helpers from the removal test are shared, the $IOCOST_TEST_DEV handling is gone, and everything now runs in CI.

Quoted 5 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+		if (ASSERT_OK(err, "readback"))
+			ASSERT_EQ(strcmp(model, "bpf"), 0, "model_bpf");

ASSERT_STREQ() prints both strings on failure.

Switched.

Quoted 7 lines

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

Quoted 3 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +3 -0
+		bpf_link__destroy(skel->links.iocost_2x);
+		/* cleared, or the skeleton destroy below detaches again */
+		skel->links.iocost_2x = NULL;

Without clearing, the skeleton destroy would call bpf_link__destroy() on the freed link. It wouldn't detach again.

Good catch. The comment now says the link has already been destroyed and the field is cleared so iocost_model__destroy() doesn't try to destroy it again.

Quoted 7 lines
Quoted 6 lines

+ * The cursor handling follows the builtin: a zero cursor means "no
+ * previous IO", and the cursor is advanced for bios the builtin
+ * prices (READ/WRITE with a non-zero size; the builtin skips the
+ * whole update when the cost is zero), so flushes and discards
+ * leave it alone and long merged streams do not drift past the
+ * 16MB seek threshold.

Quoted 5 lines

The model advances the cursor for every merged READ or WRITE bio. ioc_rqos_merge() only moves it on a back merge into the request ending at the cursor, so a front merge leaves the builtin's cursor alone and moves the model's.

Fixed; the example model now moves the cursor the way ioc_rqos_merge() moves the builtin's, so front merges leave it alone.

Quoted 11 lines

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

Quoted 6 lines
tools/testing/selftests/bpf/progs/iocost_ms.c new file +6 -0
+	} else {
+		base = randio;
+		for (i = 1; i < NSLOTS; i++) {
+			if (s->stamp[i] < s->stamp[victim])
+				victim = i;
+		}

A merged bio which matches no slot, e.g. a front merge or a merge into another stream's request, takes the LRU slot and can evict a live stream. Maybe skip the slot replacement for IOCOST_COST_F_MERGE?

Agreed; a merged bio which matches no slot is now priced without touching the table, so a merge can no longer evict a live stream.

Thanks,
Tao

Quoted 2 lines

Thanks.

author
#12 lore raw

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

In reply to Tejun Heo

Hello Tejun,

Quoted 9 lines · Tejun Heo

Hello, Tao.

Quoted 2 lines · Tao Cui

+ * Periodic per-device summary, emitted once per period from the tail of
+ * ioc_timer_fn(). Unlike the state-change events above, this fires every

The event is emitted before the vrate adjustment and the period transition, not from the tail.

Updated both the commit message and the comment to say that the event is emitted before the vrate adjustment and the period transition.

Quoted 7 lines

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

Quoted 2 lines
include/trace/events/iocost.h +2 -0
+		/* whether the controller still has active iocgs */
+		__field(int, running)

nr_active counts every entry on ioc->active_iocgs, and ioc->lock is held from the count to the emit point, so running always equals active != 0. Maybe drop the field?

Dropped, along with the printk column and the corresponding commit message paragraph. With the lock held across the count and the tracepoint emission, it always equals active != 0, so it carries no additional information.

Thanks,
Tao

Quoted 2 lines

Thanks.

author
#15 lore raw

Re: [RFC PATCH v10 4/4] docs: cgroup-v2: document the iocost BPF cost model attachment

In reply to Tejun Heo

Hello Tejun,

Quoted 9 lines · Tejun Heo

Hello, Tao.

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

Quoted 3 lines · Tao Cui
Documentation/admin-guide/cgroup-v2.rst +2 -0
 	  model		The cost model in use - "linear"
+			or "bpf" while the BPF model
+			is in use

"linear" or "bpf" is enough here.

Shortened to "linear" or "bpf".

Quoted 5 lines
Quoted 5 lines
Documentation/admin-guide/cgroup-v2.rst +5 -0
+	When CONFIG_BLK_CGROUP_IOCOST_BPF is enabled, 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 in its "dev"
+	member (a partition's major:minor is rejected).  Attaching
+	creates the controller if needed, like an io.cost.model write
Quoted 9 lines

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

Quoted 2 lines
Documentation/admin-guide/cgroup-v2.rst +2 -0
+	does, and
+	switches the device's pricing to the model; enabling and

Attaching now also populates the device's line, so the existing sentence saying the line is populated on the first write to "io.cost.qos" or "io.cost.model" needs updating. The paragraph also runs 21 lines with a leftover break after "does, and". Can it be split into three, attaching, model= selection and detaching, and removal and ctrl?

Updated and split. The documentation now says the device's line appears on the first io.cost.qos or io.cost.model write, or when a model is attached. The same wording change also went into the io.cost.qos section.

The paragraph is now split into three parts: attaching, model= selection, and detaching/removal with ctrl. The stray line break after "does, and" is gone too.

Thanks,
Tao

Quoted 2 lines

Thanks.