Skip to contentSkip to conversation

blk-iocost: BPF struct_ops cost model

RFC PATCH Superseded Tao Cui 5 participants 25 messages Oct 28 – Oct 29

Subsystems (8)

v11 of 14 Superseded Latest is v14 →

lore
Share & tools
lore

Tao Cui

author
#0 lore raw

v11 cover blk-iocost: BPF struct_ops cost model

From: Tao Cui <[email protected]>

This is v11 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.

The series is based on next-20261027, which includes flush cost support (LCOEF_FLUSH) in the builtin model: once a model is attached, the BPF path takes over flushes like every other charged IO, and the builtin flush coefficients stay for the linear model. The definitions shared between blk-iocost.c and the new BPF file moved to a private block/blk-iocost.h, and the model cost path lives in inline helpers which compile away completely when the BPF support is disabled.

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 on the pre-LCOEF_FLUSH model, 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 is per device: 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 with the queue frozen; the attach and detach take the freeze before rq_qos_mutex, the order ioc_qos_write() uses. Enabling stays with io.cost.qos and wbt stays with it too. The ops carries no device state: the attachment records the owning link in the ioc and holds a map reference, so a stale link cannot tear down a newer attachment, and a second attach of an attached map fails with -EBUSY. 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 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 exactly: iocg_init() is delivered from ioc_pd_online(), which blkg_create() only calls after the blkg has been inserted into the radix tree and the queue's blkg list, and on attach to every cgroup which is already online on the device; iocg_free() is delivered at detach to the cgroups which still exist then and at pd_free() time for the rest, gated per iocg on a delivered flag. The attach and detach walks go over q->blkg_list under q->blkcg_mutex and q->queue_lock, the same locking blkg creation and destruction use.

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/5: blk-iocost: move shared definitions to blk-iocost.h; the
enums, structs and accessors private to blk-iocost.c move to a private header, with no functional change
2/5: the BPF struct_ops cost model support: Kconfig, ops
definition, per-device attachment, unified dispatch and verifier checks
3/5: 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
4/5: add an iocost_ioc_tick tracepoint emitting the per-period
controller state, so model quality can be evaluated without drgn (existing events are state-change driven and silent in steady state)
5/5: 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 (3/5) on the same setup, 4k IOs at weight 1000, builtin vs the model:

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

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

On next-20261027 (qemu x86_64 with null_blk) the selftests pass, including the device-removal case, and the 2x example model doubles the charged cost over the builtin, returning to ~1.1x after "model=linear".

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

Changes in v11:
- the shared definitions move to a private block/blk-iocost.h: the pluggable model interface has no users outside the two block files and no longer sits in include/linux; the model cost path lives in inline helpers and the ioc/iocg state is #ifdef'd, so a kernel without the BPF support compiles the whole thing away
- the ops carries no device state: the bdev/q members are gone, the attachment records the owning link in the ioc and holds a map reference for as long as it is set, and detaching re-checks the attachment under rq_qos_mutex and only freezes the queue when it still matches, so a removal ejection racing a detach cannot quiesce a queue whose tag set is already being freed
- reg validates completeness: calc_cost and both transfer coefficients are required, and zero coefficients are rejected before the model can be registered, with a selftest for it
- iocg_init()/iocg_free() pair exactly: init is delivered from ioc_pd_online(), which runs only after the radix tree insert, so the v10 caveat about a blkg keeping an init without a free after a failed radix_tree_insert() is gone; free is additionally gated on the per-iocg delivered flag
- the ioc_tick tracepoint drops the running field: the lock is held from the active count to the emission, so running would always equal active != 0
- the documentation uses "linear" or "bpf" for the model readback and the attachment paragraph is split into attaching, model selection and detaching
- selftests: added a device-removal test (attach, remove the null_blk device out from under the model, verify the ejection and the re-attach pairing) and pairing assertions
- ioc_bpf_attach() and ioc_bpf_detach() are goto-free: every error path unwinds inline and the blkcg_mutex is scoped to the walks, so the tail bdev put runs outside of it - dropping the last device reference can reach disk_release() -> blkg_destroy_all(), which takes q->blkcg_mutex
- the transfer coefficients are bounded at validate time (at most VTIME_PER_SEC >> IOC_SECT_TO_PAGE_SHIFT per page) and the completion-time sizing result is clamped to VTIME_PER_SEC, so a broken model cannot wrap the pricing arithmetic
- reg() only checks the device: validate() runs on the map-update path of both map flavors, so repeating the completeness check there was unreachable
- the interface comment states that calc_cost() may run for a (cgroup, device) pair before iocg_init() has been delivered for it, so models relying on per-pair state must tolerate that window
- the nr_active counting moved to the tracepoint patch which reads it, MAINTAINERS gains include/trace/events/iocost.h, and the documentation now states the -EBUSY exclusivity, that the builtin coefficients stay readable and writable but inert while the BPF model is in use, that attaching does not enable the controller, and that the profile selected from the device class still applies while the BPF model is in use

author
#1 lore raw

PATCH v11 1/5 blk-iocost: move shared definitions to blk-iocost.h

From: Tao Cui <[email protected]>

The BPF cost model code to be added in the following patch needs the ioc/ioc_gq definitions and the queue accessors which are private to blk-iocost.c. Move the enums, the structs and the accessors into a private blk-iocost.h so that everything can go where it belongs. blkcg_policy_iocost becomes an extern declaration in the header so that the inline accessors can be used from both translation units.

No functional change intended.

---
 MAINTAINERS        |   1 +
 block/blk-iocost.c | 415 +-----------------------------------------
 block/blk-iocost.h | 436 +++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 439 insertions(+), 413 deletions(-)
 create mode 100644 block/blk-iocost.h
MAINTAINERS +1 -0
index 365bec8eb7fb..b3b421ee262e 100644
@@ -6827,6 +6827,7 @@ F:	Documentation/admin-guide/cgroup-v1/blkio-controller.rst
 F:	block/bfq-cgroup.c
 F:	block/blk-cgroup.c
 F:	block/blk-iocost.c
+F:	block/blk-iocost.h
 F:	block/blk-iolatency.c
 F:	block/blk-throttle.c
 F:	include/linux/blk-cgroup.h
block/blk-iocost.c +2 -413

445 lines not on this page · raw message

block/blk-iocost.h new file +436 -0

436 lines not on this page · raw message

Signature · 1 line
2.43.0
author
#4 lore raw

PATCH v11 2/5 blk-iocost: add BPF struct_ops cost model support

In reply to Tao Cui

From: Tao Cui <[email protected]>

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

Attaching an iocost_model_ops struct_ops binds the model to one
device: the target is set in the dev member from userspace, .reg creates the ioc if needed like an io.cost.model write and switches the device to the model with the queue frozen before rq_qos_mutex like an io.cost.qos write. The attachment records the owning link in the ioc and holds a reference on the map; detach verifies the attachment under rq_qos_mutex and device removal ejects the model, so a stale link cannot tear down a newer attachment. io.cost.model selects between the attached and builtin models without detaching the struct_ops; only .unreg or device removal detaches.

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

The cgroup callbacks pair with the iocg policy lifetime:
iocg_init() is delivered from ioc_pd_online() and, on attach, to cgroups already online on the device; iocg_free() on detach and at pd_free(), so each (cgroup, device) pair sees exactly one init and one free.

---
 MAINTAINERS            |   1 +
 block/Kconfig          |   4 +
 block/Makefile         |   1 +
 block/blk-iocost-bpf.c | 464 +++++++++++++++++++++++++++++++++++++++++
 block/blk-iocost.c     | 124 ++++++++++-
 block/blk-iocost.h     | 181 +++++++++++++++-
 6 files changed, 763 insertions(+), 12 deletions(-)
 create mode 100644 block/blk-iocost-bpf.c
MAINTAINERS +1 -0
index b3b421ee262e..598a5f65423d 100644
@@ -6826,6 +6826,7 @@ T:	git git://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux.git
 F:	Documentation/admin-guide/cgroup-v1/blkio-controller.rst
 F:	block/bfq-cgroup.c
 F:	block/blk-cgroup.c
+F:	block/blk-iocost-bpf.c
 F:	block/blk-iocost.c
 F:	block/blk-iocost.h
 F:	block/blk-iolatency.c
block/Kconfig +4 -0
index 70e4a66d941f..8eaa2a803b61 100644
@@ -229,6 +229,10 @@ config BLK_ERROR_INJECTION
 
 	  See Documentation/block/error-injection.rst for details.
 
+config BLK_CGROUP_IOCOST_BPF
+	def_bool y
+	depends on BLK_CGROUP_IOCOST && BPF_SYSCALL && BPF_JIT && DEBUG_INFO_BTF
+
 source "block/Kconfig.iosched"
 
 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 +464 -0

464 lines not on this page · raw message

block/blk-iocost.c +113 -11

214 lines not on this page · raw message

block/blk-iocost.h +180 -1

203 lines not on this page · raw message

Signature · 1 line
2.43.0
author
#9 lore raw

PATCH v11 3/5 selftests/bpf: add iocost cost model test

In reply to Tao Cui

From: Tao Cui <[email protected]>

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

The first model implements the builtin linear HDD formula at double cost, plus iocg_init()/iocg_free() counters for the pairing checks. 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 the maps are declared ".struct_ops.link" so that a test dying in between does not leave the model attached.

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

---
 tools/testing/selftests/bpf/config            |   2 +
 .../selftests/bpf/prog_tests/iocost_model.c   | 806 ++++++++++++++++++
 .../selftests/bpf/progs/iocost_model.c        | 201 +++++
 tools/testing/selftests/bpf/progs/iocost_ms.c | 175 ++++
 4 files changed, 1184 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/iocost_model.c
 create mode 100644 tools/testing/selftests/bpf/progs/iocost_model.c
 create mode 100644 tools/testing/selftests/bpf/progs/iocost_ms.c
tools/testing/selftests/bpf/config +2 -0
index 49dfe939467c..78ed59f83a16 100644
@@ -141,3 +141,5 @@ CONFIG_SMC_HS_CTRL_BPF=y
 CONFIG_DIBS=y
 CONFIG_DIBS_LO=y
 CONFIG_PM_WAKELOCKS=y
+CONFIG_BLK_CGROUP_IOCOST=y
+CONFIG_BLK_DEV_NULL_BLK=y
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +806 -0

806 lines not on this page · raw message

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

201 lines not on this page · raw message

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

175 lines not on this page · raw message

Signature · 1 line
2.43.0
author
#14 lore raw

PATCH v11 4/5 blk-iocost: add iocost_ioc_tick tracepoint for per-period device summary

In reply to Tao Cui

From: Tao Cui <[email protected]>

Add iocost_ioc_tick, emitted once per period from ioc_timer_fn() with the overall controller state: period_us, vrate, busy_level, active iocg count and usage percentage. 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.

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

---
 MAINTAINERS                   |  1 +
 block/blk-iocost.c            | 13 +++++++++++
 include/trace/events/iocost.h | 43 +++++++++++++++++++++++++++++++++++
 3 files changed, 57 insertions(+)
MAINTAINERS +1 -0
index 598a5f65423d..a6a39279d266 100644
@@ -6832,6 +6832,7 @@ F:	block/blk-iocost.h
 F:	block/blk-iolatency.c
 F:	block/blk-throttle.c
 F:	include/linux/blk-cgroup.h
+F:	include/trace/events/iocost.h
 
 CONTROL GROUP - CPUSET
 M:	Waiman Long <[email protected]>
block/blk-iocost.c +13 -0
index 1e84232e6740..9f7f5e5f0ebb 100644
@@ -1839,6 +1839,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;
@@ -1875,6 +1876,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.
@@ -2036,6 +2039,16 @@ 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. usage is wall time over wall time, summed over iocgs, and is
+	 * not capped at 100. Emit before the refresh below so the event reads
+	 * the completed period directly.
+	 */
+	trace_iocost_ioc_tick(ioc, &now, nr_active, usage_us_sum);
+
 	ioc_adjust_base_vrate(ioc, rq_wait_pct, nr_lagging, nr_shortages,
 			      prev_busy_level, missed_ppm);
 
include/trace/events/iocost.h +43 -0

49 lines not on this page · raw message

Signature · 1 line
2.43.0
author
#17 lore raw

PATCH v11 5/5 docs: cgroup-v2: document the iocost BPF cost model attachment

In reply to Tao Cui

From: Tao Cui <[email protected]>

Document the BPF cost model attachment in the io.cost.model section of the cgroup v2 documentation: attaching an iocost_model_ops struct_ops to a device by its major:minor, the model=bpf readback while attached (ctrl keeps describing the coefficients), the builtin model coming back on detach, and ctrl writes never selecting a model. The device's line is populated by attaching too, and the attachment paragraph is split into attaching, model selection and detaching.

---
 Documentation/admin-guide/cgroup-v2.rst | 46 ++++++++++++++++++++-----
 1 file changed, 38 insertions(+), 8 deletions(-)
Documentation/admin-guide/cgroup-v2.rst +38 -8
index 9e3c67b02ae2..fd274037a9df 100644
@@ -2056,8 +2056,9 @@ IO Interface Files
 	currently implements "io.weight" proportional control.  Lines
 	are keyed by $MAJ:$MIN device numbers and not ordered.  The
 	line for a given device is populated on the first write for
-	the device on "io.cost.qos" or "io.cost.model".  The following
-	nested keys are defined.
+	the device on "io.cost.qos" or "io.cost.model", or when a BPF
+	cost model is attached to it.  The following nested keys are
+	defined.
 
 	  ======	=====================================
 	  enable	Weight-based control enable
@@ -2111,13 +2112,41 @@ IO Interface Files
 	implements "io.weight" proportional control.  Lines are keyed
 	by $MAJ:$MIN device numbers and not ordered.  The line for a
 	given device is populated on the first write for the device on
-	"io.cost.qos" or "io.cost.model".  The following nested keys
-	are defined.
+	"io.cost.qos" or "io.cost.model", or when a BPF cost model is
+	attached to it.  The following nested keys are defined.
 
-	  =====		================================
+	  =====		==========================================
 	  ctrl		"auto" or "user"
-	  model		The cost model in use - "linear"
-	  =====		================================
+	  model		The cost model in use - "linear" or "bpf"
+	  =====		==========================================
+
+	When 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, switches the device's pricing to
+	the model and populates the device's line in this file and in
+	"io.cost.qos" if it did not exist yet.  Attaching fails with
+	-EBUSY if the device already has a model attached.  The
+	attached model prices IOs only while the controller is
+	enabled through "io.cost.qos"; attaching does not enable it.
+
+	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.  The automatic profile stepping does
+	not switch profiles while the BPF model is in use; as with
+	user-set parameters, the profile selected from the device
+	class still applies.
 
 	When "ctrl" is "auto", the kernel may change all parameters
 	dynamically.  When "ctrl" is set to "user" or any other
@@ -2125,7 +2154,8 @@ IO Interface Files
 	automatic changes are disabled.
 
 	When "model" is "linear", the following model parameters are
-	defined.
+	defined.  They remain readable and writable while "model" is
+	"bpf" but take effect only after switching back to "linear".
 
 	  =============	========================================
 	  [r|w]bps	The maximum sequential IO throughput
Signature · 1 line
2.43.0
#10 lore raw

Re: [PATCH 3/5] selftests/bpf: add iocost cost model test

In reply to Tao Cui
Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider: - [Medium] selftests/bpf: unused any variable and false test skip in iocost_bpf_supported() - [Medium]…

Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [Medium] selftests/bpf: unused any variable and false test skip in iocost_bpf_supported()
- [Medium] selftests/bpf: missing MS_PRIVATE in iocost_test_env() leaks configfs mounts
- [Medium] selftests/bpf: iocost_model attaches to iocost_ioc_tick before it is added
- [Low] selftests/bpf: missing bpf_link__destroy() in serial_test_iocost_model()
- [Low] selftests/bpf: missing rmdir() on error paths in nullb_create()
--

commit 6b66848245188ed8cc601a3e3e3fb4d06a7f79b3
Author: Tao Cui <[email protected]>

selftests/bpf: add iocost cost model test

This commit adds two example BPF iocost cost models (a 2x linear HDD model and a multi-stream sequentiality model) along with selftests exercising model attachment, switching, pricing, tracepoints, and device removal using null_blk via configfs.

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

[ ... ]

Quoted 8 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +8 -0
+static int nullb_create(const char *name, char *dev, size_t dev_sz)
+{
+	char path[128];
+	char p2[128];
+	int err;
+
+	snprintf(path, sizeof(path), "/sys/kernel/config/nullb/%s", name);
+	if (mkdir(path, 0755)) {

[ ... ]

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

Quoted 11 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +11 -0
+	}
+
+	snprintf(path, sizeof(path), "/sys/kernel/config/nullb/%s/size", name);
+	err = configfs_write(path, "128");
+	if (err)
+		return err;
+
+	snprintf(path, sizeof(path), "/sys/kernel/config/nullb/%s/power", name);
+	err = configfs_write(path, "1");
+	if (err)
+		return err;

[Severity: Low]
Does nullb_create() leak the configfs directory and its underlying struct nullb_device if writing to the size or power attribute fails?

When mkdir() creates /sys/kernel/config/nullb/<name>, configfs allocates the device item via nullb_group_make_group(). If either configfs_write() call for size or power fails, nullb_create() returns early without calling rmdir(path) (unlike the read_file_token() failure path below), and callers such as serial_test_iocost_model() and serial_test_iocost_model_streams() return immediately without calling nullb_remove().

Should these error paths also remove the created configfs directory before returning?

[ ... ]

Quoted 8 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +8 -0
+static bool iocost_bpf_supported(void)
+{
+	FILE *f;
+	char line[128];
+	bool any = false, on = false;
+
+	f = popen("zcat /proc/config.gz 2>/dev/null", "r");
+	if (!f)

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

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +10 -0
+		return false;
+	while (fgets(line, sizeof(line), f)) {
+		if (strstr(line, "CONFIG_"))
+			any = true;
+		if (strstr(line, "CONFIG_BLK_CGROUP_IOCOST_BPF=y"))
+			on = true;
+	}
+	pclose(f);
+	return on;
+}

[Severity: Medium]
Will iocost_bpf_supported() falsely skip all tests in this file when /proc/config.gz is not available?

In iocost_bpf_supported(), the local variable any is set when configuration lines are read from /proc/config.gz, but any is never used in the return statement (which also triggers an unused-but-set variable warning). Because tools/testing/selftests/bpf/config does not enable ikconfig in procfs, popen() succeeds while fgets() reads zero lines when /proc/config.gz or zcat is absent, leaving both any and on as false.

As a result, iocost_test_env()->iocost_bpf_supported() returns false and skips serial_test_iocost_model(), serial_test_iocost_model_streams(), and serial_test_iocost_model_removal() even when the running kernel has iocost BPF support enabled.

Was this meant to return !any || on, or check for struct iocost_model_ops in vmlinux BTF instead?

Quoted 3 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +3 -0
+
+static bool iocost_test_env(void)
+{

[ ... ]

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

Quoted 9 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +9 -0
+	/* isolate the configfs and cgroup mounts from the host */
+	if (unshare(CLONE_NEWNS)) {
+		printf("%s:SKIP:unshare(CLONE_NEWNS) failed: %s\n",
+		       __func__, strerror(errno));
+		test__skip();
+		return false;
+	}
+	mkdir("/sys/kernel/config", 0755);
+	(void)mount("none", "/sys/kernel/config", "configfs", 0, NULL);

[Severity: Medium]
Can this configfs mount in iocost_test_env() propagate back into the host mount namespace and accumulate across tests?

On systems where / or /sys uses shared mount propagation (the systemd default), calling unshare() with a new mount namespace followed immediately by mount() without first setting private mount propagation:

    mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL);

causes the new /sys/kernel/config mount to propagate back to the host mount namespace. In addition, because serial_test_iocost_model(), serial_test_iocost_model_streams(), and serial_test_iocost_model_removal() each call iocost_test_env() without unmounting on teardown, three stacked configfs mounts accumulate on /sys/kernel/config.

[ ... ]

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

[ ... ]

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

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +10 -0
+		/*
+		 * detach implicitly by closing the link fd instead of
+		 * calling bpf_link__destroy() explicitly: the release
+		 * path must detach the model just like the explicit
+		 * call does
+		 */
+		lfd = bpf_link__fd(skel->links.iocost_2x);
+		bpf_link__disconnect(skel->links.iocost_2x);
+		close(lfd);
+		skel->links.iocost_2x = NULL;

[Severity: Low]
Does setting skel->links.iocost_2x = NULL here without calling bpf_link__destroy() leak the struct bpf_link_struct_ops allocation?

In tools/lib/bpf/libbpf.c, bpf_link__disconnect() only marks the link as disconnected so that bpf_link__destroy() will skip calling link->detach():

    void bpf_link__disconnect(struct bpf_link *link)
    {
        link->disconnected = true;
    }

Clearing skel->links.iocost_2x to NULL before bpf_link__destroy() or iocost_model__destroy(skel) runs prevents link->dealloc() from freeing the heap-allocated struct bpf_link_struct_ops created by bpf_map__attach_struct_ops(), which triggers a LeakSanitizer failure under address sanitizer builds.

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

[ ... ]

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

Quoted 8 lines
tools/testing/selftests/bpf/progs/iocost_model.c new file +8 -0
+/* consumes the new iocost_ioc_tick tracepoint from BPF side */
+SEC("tp_btf/iocost_ioc_tick")
+__u64 BPF_PROG(iocost_2x_tick_count, struct ioc *ioc,
+	       const struct ioc_now *now, int nr_active, u64 usage_us_sum)
+{
+	ioc_ticks++;
+	return 0;
+}

[Severity: Medium]
Does iocost_model__load() fail at this commit because the iocost_ioc_tick tracepoint has not been introduced yet?

Here iocost_2x_tick_count() is defined with SEC("tp_btf/iocost_ioc_tick") and is autoloaded when serial_test_iocost_model() and serial_test_iocost_model_removal() call iocost_model__load(), and serial_test_iocost_model() also asserts that skel->bss->ioc_ticks is greater than zero.

However, the iocost_ioc_tick tracepoint in include/trace/events/iocost.h and block/blk-iocost.c is only added in the next patch in the series ("blk-iocost:
add iocost_ioc_tick tracepoint for per-period device summary"), so loading the skeleton at this point in the series fails in libbpf_find_attach_btf_id() When looking up btf_trace_iocost_ioc_tick.

Should the patch adding the iocost_ioc_tick tracepoint come before this selftest patch so bisection works cleanly?

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

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

In reply to Tao Cui
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] blk-iocost: duplicate comment opener in block/blk-iocost-bpf.c --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] blk-iocost: duplicate comment opener in block/blk-iocost-bpf.c
--

commit 8a9cd6a3cb263ab4dbba729b48cb1180333ad71b
Author: Tao Cui <[email protected]>

blk-iocost: add BPF struct_ops cost model support

This commit adds BPF struct_ops support (iocost_model_ops) to blk-iocost so a BPF program can take over IO cost pricing for a block device and track online cgroups via iocg_init() and iocg_free() callbacks.

Quoted 6 lines
block/blk-iocost-bpf.c new file +0 -0
new file mode 100644
index 0000000000000..8ff51c26fb253
@@ -0,0 +1,464 @@

[ ... ]

Quoted 7 lines
block/blk-iocost-bpf.c new file +7 -0
+#include <linux/blk-mq.h>
+#include <linux/mutex.h>
+#include "blk.h"
+
+/*
+/*
+ * Deliver iocg_init()/iocg_free() to the cgroups already online on the

block/blk-iocost-bpf.c line 37

Quoted 10 lines
block/blk-iocost-bpf.c new file +10 -0
+ * queue: init walks q->blkg_list in reverse so parents receive it first,
+ * like blkcg_activate_policy(); free walks it forward like the blkcg
+ * policy teardown. The queue is frozen and quiesced; queue_lock
+ * serializes against blkg creation and blkcg_mutex against the delayed
+ * list removal in blkg destruction; the callbacks are called with
+ * ioc->lock held, the same lock the attachment updates take.
+ */
+static void ioc_bpf_deliver_iocg_callbacks(struct ioc *ioc,
+					   const struct iocost_model_ops *ops,
+					   bool init)

[Severity: Low]
Does the duplicated comment opener above ioc_bpf_deliver_iocg_callbacks() in block/blk-iocost-bpf.c trigger a -Wcomment compiler warning (or break the build under CONFIG_WERROR=y) when CONFIG_BLK_CGROUP_IOCOST_BPF is enabled?

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

Re: [PATCH 3/5] selftests/bpf: add iocost cost model test

In reply to Tao Cui
TL;DR: Nit only: in the iocost_model selftest, the comment before the final "pair_balanced_again" assertion describes the re-attach init check, not the detach-time init/free pairing it actually tests.
Quoted 1 line

selftests/bpf: add iocost cost model test

TL;DR: Nit only: in the iocost_model selftest, the comment before the final "pair_balanced_again" assertion describes the re-attach init check, not the detach-time init/free pairing it actually tests.

Quoted 6 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +0 -0
new file mode 100644
index 000000000000..5373d52d93a6
@@ -0,0 +1,806 @@

[ ... ]

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

[ ... ]

Quoted 9 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +9 -0
+	err = iocost_model__attach(skel2);
+	if (!ASSERT_OK(err, "attach_again"))
+		goto out2;
+
+	err = readback_model(dev, model, sizeof(model));
+	if (ASSERT_OK(err, "readback_again"))
+		ASSERT_STREQ(model, "bpf", "model_bpf_again");
+	ASSERT_GT(skel2->bss->iocg_inits, 0, "pair_init_again");
+

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

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +10 -0
+	bpf_link__destroy(skel2->links.iocost_2x);
+	skel2->links.iocost_2x = NULL;
+
+	err = readback_model(dev, model, sizeof(model));
+	if (ASSERT_OK(err, "readback_after_detach_again"))
+		ASSERT_STREQ(model, "linear", "model_linear_again");
+
+	/* the re-attach walk delivered init for the recreated device */
+	ASSERT_EQ(skel2->bss->iocg_frees, skel2->bss->iocg_inits,
+		  "pair_balanced_again");

This isn't a bug, but the comment above the final assertion doesn't seem to describe the check below it.

The comment says "the re-attach walk delivered init for the recreated device", while the assertion that follows compares iocg_frees against iocg_inits after bpf_link__destroy(), which is the detach walk delivering a matching iocg_free() for every iocg_init(). The init side is the ASSERT_GT(skel2->bss->iocg_inits, 0, "pair_init_again") check a few lines earlier, right after the attach.

Should this comment sit next to the "pair_init_again" check, or say that the detach walk paired every init with a free?

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

#6 lore raw

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

In reply to Tao Cui
TL;DR: Nit only, not a bug: the long iocost_model_ops interface comment in blk-iocost.h repeats attach/teardown details documented elsewhere and names call sites; suggests trimming it to the…
Quoted 1 line

blk-iocost: add BPF struct_ops cost model support

TL;DR: Nit only, not a bug: the long iocost_model_ops interface comment in blk-iocost.h repeats attach/teardown details documented elsewhere and names call sites; suggests trimming it to the model-author contract.

Quoted 44 lines
block/blk-iocost.h +36 -0
index e4e517ef6a0f..6d62b4fd0c54 100644
@@ -22,6 +22,79 @@
 #include <asm/local64.h>
 #include "blk-rq-qos.h"
 
+struct bpf_link;
+
+/*
+ * Pluggable cost model interface for blk-iocost.
+ *
+ * A BPF struct_ops implementation can take over the cost model of one device.
+ * The device is identified by the dev member, which is set from userspace
+ * before the program is loaded; the struct_ops core owns the program lifetime.
+ * Attaching creates the ioc if needed, like an io.cost.model write, and
+ * switches the device to the BPF model with the queue frozen before
+ * rq_qos_mutex, like an io.cost.qos write, and delivers iocg_init() to the
+ * cgroups which already exist on the device. Enabling and disabling the
+ * controller stays with io.cost.qos.
+ *
+ * While a model is attached, io.cost.model selects between it and the builtin
+ * model: "model=bpf" switches to the attached model and "model=linear" back to
+ * the builtin. Neither detaches the struct_ops; only detaching does. The
+ * builtin linear coefficients are kept while the BPF model is in use and take
+ * effect again when switched back.
+ *
+ * While in use, the BPF model prices every charged IO on the device, including
+ * flushes, from the bio charging path. calc_cost() is called from the IO
+ * submission path with RCU read lock held and must not sleep. It receives the
+ * bio itself so that the model can use what it needs (operation flags, size,
+ * sector, the issuing cgroup through bio->bi_blkg, which is guaranteed
+ * non-NULL) and returns the cost of the IO in vtime units, where 1 second
+ * of device time equals VTIME_PER_SEC (2^37,
+ * available to BPF programs through vmlinux.h). The return value is clamped to
+ * 1 second of device time per IO.
+ *
+ * The struct_ops also carries the transfer cost coefficients, vtime per page
+ * for reads and writes. While the BPF model is in use, they replace the
+ * builtin coefficients in the completion-time request sizing of READ and
+ * WRITE requests, with ZONE_APPEND counted as a write. Taking over the QoS
+ * side (latency tracking, vrate control) is left for later extensions.
+ *

block/blk-iocost.h line 70

Quoted 10 lines
block/blk-iocost.h +10 -0
+ * The cgroup callbacks are bound to the iocg policy lifetime, one (cgroup,
+ * device) pair per invocation. iocg_init() is delivered from ioc_pd_online()
+ * and on attach to the cgroups already online on the device; iocg_free() on
+ * detach to the cgroups which still exist then and at pd_free() time for the
+ * rest, so that init and free pair up exactly. iocg_free() is gated on a
+ * per-iocg delivered flag, as bios can still be priced between the blkg going
+ * offline and its free. Both callbacks are called with ioc->lock held and must
+ * not sleep; the delivery points nest inside queue_lock except for iocg_free()
+ * from ioc_pd_free() in blkg_free_workfn().
+ */

[ ... ]

this isn't a bug, but could this interface comment be cut down to the contract a model author needs (calling context, units, clamping, locking)?

The attach description repeats what is already at the top of block/blk-iocost-bpf.c:

* attaches the model to that device, creating the ioc if needed and switching
* to the model with the queue frozen before rq_qos_mutex, like io.cost.qos
* writes, and .unreg detaches it; enabling and disabling the controller stays
* with io.cost.qos.

The init/free pairing rules and the "bios can still be priced between the blkg going offline and its free" reasoning are repeated in the comments above ioc_pd_online(), ioc_pd_free() and ioc_bpf_deliver_iocg_callbacks().

The comment also names implementation call sites:

* not sleep; the delivery points nest inside queue_lock except for iocg_free()
* from ioc_pd_free() in blkg_free_workfn().

Would it be better to leave the attach and teardown mechanics to the comments next to that code, so this one does not go stale when those paths change?

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

#20 lore raw
In reply to Tao Cui
Quoted 9 lines · Tao Cui

The cgroup callbacks are bound to the iocg policy lifetime and pair up exactly: iocg_init() is delivered from ioc_pd_online(), which blkg_create() only calls after the blkg has been inserted into the radix tree and the queue's blkg list, and on attach to every cgroup which is already online on the device; iocg_free() is delivered at detach to the cgroups which still exist then and at pd_free() time for the rest, gated per iocg on a delivered flag. The attach and detach walks go over q->blkg_list under q->blkcg_mutex and q->queue_lock, the same locking blkg creation and destruction use.

Who needs iocg_init() and iocg_free()?
Both example models keep their state in BPF_MAP_TYPE_CGRP_STORAGE. The only user of the callbacks is a pair of counters in the selftest.

One struct_ops map is bound to one device. So the cgroup storage of a model is per (cgroup, device) already.
The blkg holds the blkcg css until blkg_free_workfn(). The storage is freed with the cgroup or with the map. So it outlives the iocg.

The v11 changelog says that calc_cost() can run before iocg_init(). So a model has to create its state in calc_cost() anyway. iocg_init() runs under queue_lock and ioc->lock. An allocation there is not better than in calc_cost().

v8, v9, v10 and v11 all reworked the pairing of these two callbacks.

Lets drop them. A struct_ops can get new members later, when a model needs them.
I'd like to hear from Tejun whether such a model is planned.

Without the callbacks there is no walk of q->blkg_list:

  what                v11                          without callbacks
  ------------------  ---------------------------  ------------------
  attach takes        freeze, rq_qos_mutex,        freeze,
                      quiesce, blkcg_mutex,        rq_qos_mutex,
                      queue_lock, ioc->lock        ioc->lock
  detach takes        rq_qos_mutex, queue_lock,    rq_qos_mutex,
                      ioc->lock to check, then     ioc->lock
                      freeze and the same again,
                      quiesce, blkcg_mutex,
                      queue_lock, ioc->lock
  state per iocg      bpf_iocg_inited              none
  hooks in            ioc_pd_online(),             none
                      ioc_pd_free()
  teardown            ioc_bpf_detach(),            ioc_detach_model()
                      ioc_bpf_eject()

calc_cost() runs under rcu_read_lock(). bpf_map_put() frees a struct_ops map after an RCU gp. So detach doesn't need to freeze the queue. The rest fits into blk-iocost.c and patch 1 is not needed.

The diff keeps the map reference, the owning link and the model=linear/bpf switch. It has no docs, no selftests and no tracepoint.

Something like this (compile tested only):

block/Kconfig +4 -0
index 70e4a66..26badf5 100644
@@ -161,6 +161,10 @@ config BLK_CGROUP_IOCOST
 	distributes IO capacity between different groups based on
 	their share of the overall weight distribution.
 
+config BLK_CGROUP_IOCOST_BPF
+	def_bool y
+	depends on BLK_CGROUP_IOCOST && BPF_SYSCALL && BPF_JIT && DEBUG_INFO_BTF
+
 config BLK_CGROUP_IOPRIO
 	bool "Cgroup I/O controller for assigning an I/O priority class"
 	depends on BLK_CGROUP
block/blk-iocost.c +235 -3

336 lines not on this page · raw message

Quoted 7 lines

3/5: 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
4/5: add an iocost_ioc_tick tracepoint emitting the per-period
controller state, so model quality can be evaluated without drgn (existing events are state-change driven and silent in steady state)

Also progs/iocost_model.c in patch 3 has SEC("tp_btf/iocost_ioc_tick"). Patch 4 adds this tracepoint. At patch 3 iocost_model__load() fails. Swap the two patches.

pw-bot: cr

maintainer
#21 lore raw

Hello, Alexei.

Quoted 3 lines · Alexei Starovoitov

Lets drop them. A struct_ops can get new members later, when a model needs them.
I'd like to hear from Tejun whether such a model is planned.

The callbacks would only be worth having if they could do something calc_cost() can't, e.g. sleep, but I forgot that pd allocations are opportunistic to begin with. A blkg and its pds are created on the bio path under queue_lock with GFP_NOWAIT, so iocg_init() can't sleep either. Agreed, let's drop them.

Quoted 4 lines

...
calc_cost() runs under rcu_read_lock(). bpf_map_put() frees a struct_ops map after an RCU gp. So detach doesn't need to freeze the queue. The rest fits into blk-iocost.c and patch 1 is not needed.

Agreed on both.

Thanks.

--
tejun

maintainer
#23 lore raw
In reply to Tao Cui

Hello, Tao.

Besides the restructuring agreed in my reply to Alexei, dropping iocg_init()/iocg_free() and moving everything into blk-iocost.c, the series still has problems, which I replied to on the patches. The cover letter is still long and narrates mechanics, and it still carries the v9 and v10 changelogs.

Thanks.

--
tejun

maintainer
#2 lore raw

Re: [PATCH 1/5] blk-iocost: move shared definitions to blk-iocost.h

In reply to Tao Cui

Hello, Tao.

block/blk-iocost.c static const u32 vrate_adj_pct[] = · line 662

Quoted 4 lines · Tao Cui
block/blk-iocost.c +0 -4
-static struct blkcg_policy blkcg_policy_iocost;
-
-/* accessors and helpers */
-static struct ioc *rqos_to_ioc(struct rq_qos *rqos)

This isn't a pure move. The comment is dropped here.

Quoted 4 lines

}

-
static int ioc_weight_show(struct seq_file *sf, void *v)

The blank line removal is unrelated to the move.

block/blk-iocost.h line 264

Quoted 4 lines
block/blk-iocost.h new file +4 -0
+	bool				user_qos_params:1;
+	bool				user_cost_model:1;
+
+};

The blank line is new, and 2/5 then replaces it.

Thanks.

--
tejun

maintainer
#7 lore raw

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

In reply to Tao Cui

Hello, Tao.

block/blk-iocost-bpf.c line 27

Quoted 3 lines · Tao Cui
block/blk-iocost-bpf.c new file +3 -0
+/*
+/*
+ * Deliver iocg_init()/iocg_free() to the cgroups already online on the

The comment opens with "/*" twice. clang warns "'/*' within block comment [-Wcomment]" and CONFIG_WERROR builds break.

block/blk-iocost-bpf.c line 60

Quoted 6 lines
block/blk-iocost-bpf.c new file +5 -0
+			/*
+			 * A blkg which never went online never reached the
+			 * radix tree, so it must not receive an init either;
...
+			if (!iocg || !iocg->pd.online)
+				continue;

blkg_create() adds a blkg to q->blkg_list only after radix_tree_insert() succeeds, so the blkgs skipped here are the ones blkg_destroy() already took offline, not ones that never reached the radix tree.

block/blk-iocost-bpf.c line 117

Quoted 6 lines
block/blk-iocost-bpf.c new file +6 -0
+	if (!disk_live(disk)) {
+		mutex_unlock(&q->rq_qos_mutex);
+		blk_mq_unfreeze_queue(q, memflags);
+		blkdev_put_no_open(bdev);
+		return -ENODEV;
+	}

The guard() suggestion from v10 was only partly applied. This unlock, unfreeze and put sequence is repeated on three error paths.

block/blk-iocost-bpf.c line 139

Quoted 8 lines
block/blk-iocost-bpf.c new file +8 -0
+	/*
+	 * Scope the mutex so the tail bdev put runs with blkcg_mutex
+	 * already released: dropping the last device reference can
+	 * reach disk_release() -> blkcg_exit_disk() ->
+	 * blkg_destroy_all(), which takes q->blkcg_mutex.
+	 */
+	{
+		guard(mutex)(&q->blkcg_mutex);

The bare { } block isn't necessary, and ioc_bpf_detach() has the same block with the same comment. Can you drop them?

block/blk-iocost-bpf.c line 208

Quoted 12 lines
block/blk-iocost-bpf.c new file +11 -0
+	/*
+	 * The attachment is checked under rq_qos_mutex first, so an unmatched
+	 * detach exits without freezing.
+	 */
+	mutex_lock(&q->rq_qos_mutex);
+	spin_lock_irq(&q->queue_lock);
+	ioc = q_to_ioc(q);
+	if (ioc) {
+		spin_lock(&ioc->lock);
+		matched = ioc_attached_model_locked(ioc) == ops &&
+			  ioc->bpf_link == link;
...

The same 11 lines check the attachment again after the freeze. The check under rq_qos_mutex after the freeze is the one that matters.

Quoted 9 lines

+/*
+ * Pluggable cost model interface for blk-iocost.
+ *
+ * A BPF struct_ops implementation can take over the cost model of one device.
...
+ * offline and its free. Both callbacks are called with ioc->lock held and must
+ * not sleep; the delivery points nest inside queue_lock except for iocg_free()
+ * from ioc_pd_free() in blkg_free_workfn().
+ */

This restates the attach mechanics and lists the call sites. The comments and descriptions in general are still long and narrate mechanics.

Thanks.

--
tejun

maintainer
#12 lore raw

Re: [PATCH 3/5] selftests/bpf: add iocost cost model test

In reply to Tao Cui

Hello, Tao.

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

Quoted 10 lines · Tao Cui
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +8 -0
+static bool iocost_bpf_supported(void)
+{
+	FILE *f;
+	char line[128];
+	bool any = false, on = false;
...
+		if (strstr(line, "CONFIG_"))
+			any = true;
...
+	return on;

any is set but never read, so every test skips without /proc/config.gz.

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

Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +2 -0
+	/* isolate the configfs and cgroup mounts from the host */
+	if (unshare(CLONE_NEWNS)) {

unshare(CLONE_NEWNS) alone doesn't make the mounts private, so the configfs mount propagates to the host, one more per test.

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

Quoted 3 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +3 -0
+	ASSERT_OK(configfs_write("/sys/fs/cgroup/cgroup.subtree_control",
+				 "+io"), "subtree_io");
+	if (!ASSERT_OK(cgroup_mkdir("/sys/fs/cgroup/iocost_pairing"),

The "+io" write to the root cgroup's cgroup.subtree_control is never reverted, the cgroups are created directly under /sys/fs/cgroup and test_progs stays in the root cgroup. cgroup_helpers handles all of this.

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

Quoted 4 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +3 -0
+	err = iocost_model__attach(skel);
+	if (err == -EOPNOTSUPP || err == -ENODEV) {
...
+		test__skip();

-ENODEV and -EOPNOTSUPP from attaching to the test's own null_blk device are failures, not skips. The same goes for serial_test_iocost_model_streams().

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

Quoted 1 line
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +1 -0
+		ASSERT_GT(skel->bss->iocg_inits, 0, "pair_init");

This passes on the root blkg alone, so it doesn't show that the test cgroup got iocg_init(). The same goes for eject_had_inits and pair_init_again.

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

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +10 -0
+		/*
+		 * detach implicitly by closing the link fd instead of
+		 * calling bpf_link__destroy() explicitly: the release
+		 * path must detach the model just like the explicit
+		 * call does
+		 */
+		lfd = bpf_link__fd(skel->links.iocost_2x);
+		bpf_link__disconnect(skel->links.iocost_2x);
+		close(lfd);
+		skel->links.iocost_2x = NULL;

This leaks libbpf's link struct. The reason in the comment doesn't hold either. bpf_link__destroy() on a struct_ops link does the same close().

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

Quoted 8 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +7 -0
+void serial_test_iocost_model_streams(void)
...
+	if (ASSERT_OK(err, "attach")) {
+		err = readback_model(dev, model, sizeof(model));
+		if (ASSERT_OK(err, "readback"))
+			ASSERT_STREQ(model, "bpf", "model_bpf");
+
+		bpf_link__destroy(skel->links.iocost_ms);

The test never enables the controller, so iocost_ms's calc_cost() never runs. The multi-stream results in the cover letter aren't exercised by the test.

Thanks.

--
tejun

maintainer
#15 lore raw

Re: [PATCH 4/5] 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 1879

Quoted 4 lines · Tao Cui
block/blk-iocost.c +1 -0
 		u64 vdone, vtime, usage_us;
 		u32 hw_active, hw_inuse;
 
+		nr_active++;

nr_active is counted even when the tracepoint is disabled.

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

Quoted 5 lines
block/blk-iocost.c +5 -0
+	/*
+	 * 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. usage is wall time over wall time, summed over iocgs, and is

An io.cost.qos write in the middle of a period changes both period_us and vrate.

Thanks.

--
tejun

maintainer
#18 lore raw

Re: [PATCH 5/5] 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 2124

Quoted 2 lines · Tao Cui
Documentation/admin-guide/cgroup-v2.rst +2 -0
+	When CONFIG_BLK_CGROUP_IOCOST_BPF is enabled, a BPF cost
+	model can be bound to a device by attaching an

Users can't select CONFIG_BLK_CGROUP_IOCOST_BPF.

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

Quoted 4 lines
Documentation/admin-guide/cgroup-v2.rst +4 -0
+	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"

"Only detaching removes the model" is followed by "Device removal ejects the attached model as well".

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

Quoted 6 lines
Documentation/admin-guide/cgroup-v2.rst +6 -0
+	accepts only "auto" and "user" and never selects a model.  It
+	keeps describing the builtin coefficients, which take effect
+	again when switched back.  The automatic profile stepping does
+	not switch profiles while the BPF model is in use; as with
+	user-set parameters, the profile selected from the device
+	class still applies.

cgroup-v2.rst doesn't describe automatic profile stepping anywhere else.

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

Quoted 2 lines
Documentation/admin-guide/cgroup-v2.rst +2 -0
+	defined.  They remain readable and writable while "model" is
+	"bpf" but take effect only after switching back to "linear".

The builtin coefficients taking effect again after switching back is already said above.

Thanks.

--
tejun

author
#22 lore raw
In reply to Alexei Starovoitov

Hello Alexei,

Quoted 11 lines · Alexei Starovoitov
Quoted 9 lines · Tao Cui

The cgroup callbacks are bound to the iocg policy lifetime and pair up exactly: iocg_init() is delivered from ioc_pd_online(), which blkg_create() only calls after the blkg has been inserted into the radix tree and the queue's blkg list, and on attach to every cgroup which is already online on the device; iocg_free() is delivered at detach to the cgroups which still exist then and at pd_free() time for the rest, gated per iocg on a delivered flag. The attach and detach walks go over q->blkg_list under q->blkcg_mutex and q->queue_lock, the same locking blkg creation and destruction use.

Quoted 4 lines

Who needs iocg_init() and iocg_free()?
Both example models keep their state in BPF_MAP_TYPE_CGRP_STORAGE. The only user of the callbacks is a pair of counters in the selftest.

Agreed. There isn't a model planned that needs them.

Quoted 5 lines

One struct_ops map is bound to one device. So the cgroup storage of a model is per (cgroup, device) already.
The blkg holds the blkcg css until blkg_free_workfn(). The storage is freed with the cgroup or with the map. So it outlives the iocg.

Understood. That's already how the example models work.

Quoted 5 lines

The v11 changelog says that calc_cost() can run before iocg_init(). So a model has to create its state in calc_cost() anyway. iocg_init() runs under queue_lock and ioc->lock. An allocation there is not better than in calc_cost().

Right. There isn't anything the callbacks can do that calc_cost() can't.

Quoted 4 lines

v8, v9, v10 and v11 all reworked the pairing of these two callbacks.

Lets drop them. A struct_ops can get new members later, when a model needs them.

Dropped in v12. If a model needs them later, struct_ops can grow new members then.

Quoted 20 lines

I'd like to hear from Tejun whether such a model is planned.

Without the callbacks there is no walk of q->blkg_list:

  what                v11                          without callbacks
  ------------------  ---------------------------  ------------------
  attach takes        freeze, rq_qos_mutex,        freeze,
                      quiesce, blkcg_mutex,        rq_qos_mutex,
                      queue_lock, ioc->lock        ioc->lock
  detach takes        rq_qos_mutex, queue_lock,    rq_qos_mutex,
                      ioc->lock to check, then     ioc->lock
                      freeze and the same again,
                      quiesce, blkcg_mutex,
                      queue_lock, ioc->lock
  state per iocg      bpf_iocg_inited              none
  hooks in            ioc_pd_online(),             none
                      ioc_pd_free()
  teardown            ioc_bpf_detach(),            ioc_detach_model()
                      ioc_bpf_eject()
Quoted 4 lines

calc_cost() runs under rcu_read_lock(). bpf_map_put() frees a struct_ops map after an RCU gp. So detach doesn't need to freeze the queue. The rest fits into blk-iocost.c and patch 1 is not needed.

Done. The detach freeze is gone in v12, everything is folded back into blk-iocost.c, and patch 1 is dropped.

Quoted 383 lines

The diff keeps the map reference, the owning link and the model=linear/bpf switch. It has no docs, no selftests and no tracepoint.

Something like this (compile tested only):

block/Kconfig +4 -0
index 70e4a66..26badf5 100644
@@ -161,6 +161,10 @@ config BLK_CGROUP_IOCOST
 	distributes IO capacity between different groups based on
 	their share of the overall weight distribution.
 
+config BLK_CGROUP_IOCOST_BPF
+	def_bool y
+	depends on BLK_CGROUP_IOCOST && BPF_SYSCALL && BPF_JIT && DEBUG_INFO_BTF
+
 config BLK_CGROUP_IOPRIO
 	bool "Cgroup I/O controller for assigning an I/O priority class"
 	depends on BLK_CGROUP
block/blk-iocost.c +235 -3
index a81488c..5e65bf4 100644
@@ -178,8 +178,12 @@
 #include <linux/time64.h>
 #include <linux/parser.h>
 #include <linux/sched/signal.h>
+#include <linux/bpf.h>
+#include <linux/bpf_verifier.h>
+#include <linux/btf.h>
 #include <asm/local.h>
 #include <asm/local64.h>
+#include "blk.h"
 #include "blk-rq-qos.h"
 #include "blk-stat.h"
 #include "blk-wbt.h"
@@ -404,6 +408,22 @@ struct ioc_pcpu_stat {
 	u64				last_rq_wait_ns;
 };
 
+enum {
+	IOCOST_COST_F_MERGE	= 1 << 0,	/* called from the merge path */
+};
+
+/* bpf cost model of one device */
+struct iocost_model_ops {
+	/* whole disk, in the encoding of new_decode_dev() */
+	dev_t dev;
+
+	/* used by the completion path instead of LCOEF_[RW]PAGE */
+	u64 read_vtime_per_page;
+	u64 write_vtime_per_page;
+
+	u64 (*calc_cost)(struct bio *bio, u64 model_flags);
+};
+
 /* per device */
 struct ioc {
 	struct rq_qos			rqos;
@@ -447,6 +467,12 @@ struct ioc {
 	int				autop_idx;
 	bool				user_qos_params:1;
 	bool				user_cost_model:1;
+
+	/* holds a reference on the struct_ops map, NULL if none is attached */
+	const struct iocost_model_ops	*attached;
+	struct bpf_link			*attached_link;
+	/* either NULL (linear) or ->attached */
+	const struct iocost_model_ops __rcu *model;
 };
 
 struct iocg_pcpu_stat {
@@ -669,6 +695,13 @@ static struct ioc *q_to_ioc(struct request_queue *q)
 	return rqos_to_ioc(rq_qos_id(q, RQ_QOS_COST));
 }
 
+static const struct iocost_model_ops *ioc_model(struct ioc *ioc)
+{
+	if (!IS_ENABLED(CONFIG_BLK_CGROUP_IOCOST_BPF))
+		return NULL;
+	return rcu_dereference_check(ioc->model, lockdep_is_held(&ioc->lock));
+}
+
 static const char __maybe_unused *ioc_name(struct ioc *ioc)
 {
 	struct gendisk *disk = ioc->rqos.disk;
@@ -806,7 +839,7 @@ static int ioc_autop_idx(struct ioc *ioc, struct gendisk *disk)
 		return AUTOP_SSD_DFL;
 
 	/* if user is overriding anything, maintain what was there */
-	if (ioc->user_qos_params || ioc->user_cost_model)
+	if (ioc->user_qos_params || ioc->user_cost_model || ioc_model(ioc))
 		return idx;
 
 	/* step up/down based on the vrate */
@@ -2586,8 +2619,16 @@ out:
 
 static u64 calc_vtime_cost(struct bio *bio, struct ioc_gq *iocg, bool is_merge)
 {
+	const struct iocost_model_ops *model;
 	u64 cost;
 
+	guard(rcu)();
+	model = ioc_model(iocg->ioc);
+	if (model) {
+		cost = model->calc_cost(bio, is_merge ? IOCOST_COST_F_MERGE : 0);
+		return min(cost, VTIME_PER_SEC);
+	}
+
 	calc_vtime_cost_builtin(bio, iocg, is_merge, &cost);
 	return cost;
 }
@@ -2612,8 +2653,16 @@ static void calc_size_vtime_cost_builtin(struct request *rq, struct ioc *ioc,
 
 static u64 calc_size_vtime_cost(struct request *rq, struct ioc *ioc)
 {
+	const struct iocost_model_ops *model;
 	u64 cost;
 
+	guard(rcu)();
+	model = ioc_model(ioc);
+	if (model)
+		return (blk_rq_stats_sectors(rq) >> IOC_SECT_TO_PAGE_SHIFT) *
+			(req_op(rq) == REQ_OP_READ ? model->read_vtime_per_page :
+						     model->write_vtime_per_page);
+
 	calc_size_vtime_cost_builtin(rq, ioc, &cost);
 	return cost;
 }
@@ -2908,10 +2957,33 @@ static void ioc_rqos_queue_depth_changed(struct rq_qos *rqos)
 	spin_unlock_irq(&ioc->lock);
 }
 
+/* Called by .unreg and by device removal, whichever is first. */
+static void ioc_detach_model(struct ioc *ioc)
+{
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	const struct iocost_model_ops *ops = ioc->attached;
+
+	lockdep_assert_held(&ioc->rqos.disk->queue->rq_qos_mutex);
+
+	if (!ops)
+		return;
+
+	spin_lock_irq(&ioc->lock);
+	rcu_assign_pointer(ioc->model, NULL);
+	ioc->attached = NULL;
+	ioc->attached_link = NULL;
+	spin_unlock_irq(&ioc->lock);
+
+	/* calc_cost() can still run. The map is freed after an RCU gp. */
+	bpf_struct_ops_put(ops);
+#endif
+}
+
 static void ioc_rqos_exit(struct rq_qos *rqos)
 {
 	struct ioc *ioc = rqos_to_ioc(rqos);
 
+	ioc_detach_model(ioc);
 	blkcg_deactivate_policy(rqos->disk, &blkcg_policy_iocost);
 
 	spin_lock_irq(&ioc->lock);
@@ -3458,11 +3530,12 @@ static u64 ioc_cost_model_prfill(struct seq_file *sf,
 		return 0;
 
 	spin_lock_irq(&ioc->lock);
-	seq_printf(sf, "%s ctrl=%s model=linear "
+	seq_printf(sf, "%s ctrl=%s model=%s "
 		   "rbps=%llu rseqiops=%llu rrandiops=%llu "
 		   "wbps=%llu wseqiops=%llu wrandiops=%llu "
 		   "flushiops=%llu\n",
 		   dname, ioc->user_cost_model ? "user" : "auto",
+		   ioc_model(ioc) ? "bpf" : "linear",
 		   u[I_LCOEF_RBPS], u[I_LCOEF_RSEQIOPS], u[I_LCOEF_RRANDIOPS],
 		   u[I_LCOEF_WBPS], u[I_LCOEF_WSEQIOPS], u[I_LCOEF_WRANDIOPS],
 		   u[I_LCOEF_FLUSHIOPS]);
@@ -3499,6 +3572,7 @@ static const match_table_t i_lcoef_tokens = {
 static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 				    size_t nbytes, loff_t off)
 {
+	const struct iocost_model_ops *model;
 	struct blkg_conf_ctx ctx;
 	struct request_queue *q;
 	unsigned int memflags;
@@ -3535,6 +3609,7 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 	spin_lock_irq(&ioc->lock);
 	memcpy(u, ioc->params.i_lcoefs, sizeof(u));
 	user = ioc->user_cost_model;
+	model = ioc_model(ioc);
 
 	ret = -EINVAL;
 
@@ -3559,7 +3634,11 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 			continue;
 		case COST_MODEL:
 			match_strlcpy(buf, &args[0], sizeof(buf));
-			if (strcmp(buf, "linear"))
+			if (!strcmp(buf, "linear"))
+				model = NULL;
+			else if (!strcmp(buf, "bpf") && ioc->attached)
+				model = ioc->attached;
+			else
 				goto unlock;
 			continue;
 		}
@@ -3579,6 +3658,7 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 	} else {
 		ioc->user_cost_model = false;
 	}
+	rcu_assign_pointer(ioc->model, model);
 	ioc_refresh_params(ioc, true);
 
 	ret = 0;
@@ -3626,6 +3706,158 @@ static struct blkcg_policy blkcg_policy_iocost = {
 	.pd_stat_fn	= ioc_pd_stat,
 };
 
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+static int ioc_bpf_reg(void *kdata, struct bpf_link *link)
+{
+	struct iocost_model_ops *ops = kdata;
+	struct block_device *bdev;
+	struct request_queue *q;
+	unsigned int memflags;
+	struct ioc *ioc;
+	int ret;
+
+	bdev = blkdev_get_no_open(new_decode_dev(ops->dev), false);
+	if (!bdev)
+		return -ENODEV;
+
+	q = bdev_get_queue(bdev);
+	if (bdev_is_partition(bdev) || !queue_is_mq(q)) {
+		blkdev_put_no_open(bdev);
+		return -EOPNOTSUPP;
+	}
+
+	/* the order of ioc_qos_write() */
+	memflags = blk_mq_freeze_queue(q);
+	mutex_lock(&q->rq_qos_mutex);
+
+	ret = -ENODEV;
+	if (!disk_live(bdev->bd_disk))
+		goto out;
+
+	ioc = q_to_ioc(q);
+	if (!ioc) {
+		ret = blk_iocost_init(bdev->bd_disk);
+		if (ret)
+			goto out;
+		ioc = q_to_ioc(q);
+	}
+
+	ret = -EBUSY;
+	if (ioc->attached || !bpf_struct_ops_get(ops))
+		goto out;
+
+	spin_lock_irq(&ioc->lock);
+	ioc->attached = ops;
+	ioc->attached_link = link;
+	rcu_assign_pointer(ioc->model, ops);
+	spin_unlock_irq(&ioc->lock);
+	ret = 0;
+out:
+	mutex_unlock(&q->rq_qos_mutex);
+	blk_mq_unfreeze_queue(q, memflags);
+	blkdev_put_no_open(bdev);
+	return ret;
+}
+
+static void ioc_bpf_unreg(void *kdata, struct bpf_link *link)
+{
+	struct iocost_model_ops *ops = kdata;
+	struct block_device *bdev;
+	struct request_queue *q;
+	struct ioc *ioc;
+
+	/* del_gendisk() is in progress or done. ioc_rqos_exit() detaches. */
+	bdev = blkdev_get_no_open(new_decode_dev(ops->dev), false);
+	if (!bdev)
+		return;
+
+	q = bdev_get_queue(bdev);
+	mutex_lock(&q->rq_qos_mutex);
+	ioc = q_to_ioc(q);
+	/* the dev_t can belong to another disk and another model by now */
+	if (ioc && ioc->attached == ops && ioc->attached_link == link)
+		ioc_detach_model(ioc);
+	mutex_unlock(&q->rq_qos_mutex);
+	blkdev_put_no_open(bdev);
+}
+
+static int ioc_bpf_init(struct btf *btf)
+{
+	return 0;
+}
+
+static int ioc_bpf_check_member(const struct btf_type *t,
+				const struct btf_member *member,
+				const struct bpf_prog *prog)
+{
+	return prog->sleepable ? -EINVAL : 0;
+}
+
+static int ioc_bpf_init_member(const struct btf_type *t,
+			       const struct btf_member *member,
+			       void *kdata, const void *udata)
+{
+	const struct iocost_model_ops *uops = udata;
+	struct iocost_model_ops *ops = kdata;
+
+	switch (__btf_member_bit_offset(t, member) / 8) {
+	case offsetof(struct iocost_model_ops, dev):
+		ops->dev = uops->dev;
+		return 1;
+	case offsetof(struct iocost_model_ops, read_vtime_per_page):
+		ops->read_vtime_per_page = uops->read_vtime_per_page;
+		return 1;
+	case offsetof(struct iocost_model_ops, write_vtime_per_page):
+		ops->write_vtime_per_page = uops->write_vtime_per_page;
+		return 1;
+	}
+	return 0;
+}
+
+static int ioc_bpf_validate(void *kdata)
+{
+	struct iocost_model_ops *ops = kdata;
+
+	if (!ops->dev || !ops->calc_cost ||
+	    !ops->read_vtime_per_page || !ops->write_vtime_per_page)
+		return -EINVAL;
+	return 0;
+}
+
+static u64 ioc_bpf_calc_cost_stub(struct bio *bio, u64 model_flags)
+{
+	return 0;
+}
+
+static struct iocost_model_ops ioc_bpf_stubs = {
+	.calc_cost	= ioc_bpf_calc_cost_stub,
+};
+
+static const struct bpf_verifier_ops ioc_bpf_verifier_ops = {
+	.get_func_proto		= bpf_base_func_proto,
+	.is_valid_access	= bpf_tracing_btf_ctx_access,
+};
+
+static struct bpf_struct_ops ioc_bpf_struct_ops = {
+	.verifier_ops	= &ioc_bpf_verifier_ops,
+	.init		= ioc_bpf_init,
+	.check_member	= ioc_bpf_check_member,
+	.init_member	= ioc_bpf_init_member,
+	.validate	= ioc_bpf_validate,
+	.reg		= ioc_bpf_reg,
+	.unreg		= ioc_bpf_unreg,
+	.cfi_stubs	= &ioc_bpf_stubs,
+	.name		= "iocost_model_ops",
+	.owner		= THIS_MODULE,
+};
+
+static int __init ioc_bpf_struct_ops_init(void)
+{
+	return register_bpf_struct_ops(&ioc_bpf_struct_ops, iocost_model_ops);
+}
+late_initcall(ioc_bpf_struct_ops_init);
+#endif
+
 static int __init ioc_init(void)
 {
 	return blkcg_policy_register(&blkcg_policy_iocost);
Quoted 8 lines

3/5: 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
4/5: add an iocost_ioc_tick tracepoint emitting the per-period
controller state, so model quality can be evaluated without drgn (existing events are state-change driven and silent in steady state)

Quoted 4 lines

Also progs/iocost_model.c in patch 3 has SEC("tp_btf/iocost_ioc_tick"). Patch 4 adds this tracepoint. At patch 3 iocost_model__load() fails. Swap the two patches.

Swapped: the iocost_ioc_tick tracepoint is patch 2 now and the selftest is patch 3, so iocost_model__load() works at every commit. The selftest also drives IO through iocost_ms's calc_cost().

Thanks,
Tao

Quoted 1 line

pw-bot: cr

author
#24 lore raw
In reply to Tejun Heo

Hello Tejun,

Thank you for the review.

Quoted 5 lines · Tejun Heo

Hello, Tao.

Besides the restructuring agreed in my reply to Alexei, dropping iocg_init()/iocg_free() and moving everything into blk-iocost.c, the series still has problems, which I replied to on the patches.

I'll rework the series accordingly: drop iocg_init()/iocg_free(), remove the detach freeze, fold everything back into blk-iocost.c and drop patch 1, reducing the series to four patches.

The cover

Quoted 3 lines

letter is still long and narrates mechanics, and it still carries the v9 and v10 changelogs.

I'll shorten it, focus on the motivation, and drop the v9/v10 changelogs.

Thanks,
Tao

Quoted 4 lines

Thanks.

--
tejun

author
#3 lore raw

Re: [PATCH 1/5] blk-iocost: move shared definitions to blk-iocost.h

In reply to Tejun Heo

Hello Tejun,

Quoted 15 lines · Tejun Heo

Hello, Tao.

block/blk-iocost.c static const u32 vrate_adj_pct[] = · line 662

Quoted 4 lines · Tao Cui
block/blk-iocost.c +0 -4
-static struct blkcg_policy blkcg_policy_iocost;
-
-/* accessors and helpers */
-static struct ioc *rqos_to_ioc(struct rq_qos *rqos)

This isn't a pure move. The comment is dropped here.

Quoted 4 lines

}

-
static int ioc_weight_show(struct seq_file *sf, void *v)

Quoted 9 lines

The blank line removal is unrelated to the move.

block/blk-iocost.h line 264

Quoted 4 lines
block/blk-iocost.h new file +4 -0
+	bool				user_qos_params:1;
+	bool				user_cost_model:1;
+
+};

The blank line is new, and 2/5 then replaces it.

Dropping patch 1 resolves all three: v12 folds the definitions back into blk-iocost.c with the original comments and spacing intact, so there is no move left to keep pure.

Sorry, I should have caught these before posting.

Thanks,
Tao

Quoted 4 lines

Thanks.

--
tejun

author
#8 lore raw

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

In reply to Tejun Heo

Hello Tejun,

Quoted 10 lines · Tejun Heo

Hello, Tao.

block/blk-iocost-bpf.c line 27

Quoted 3 lines · Tao Cui
block/blk-iocost-bpf.c new file +3 -0
+/*
+/*
+ * Deliver iocg_init()/iocg_free() to the cgroups already online on the

The comment opens with "/*" twice. clang warns "'/*' within block comment [-Wcomment]" and CONFIG_WERROR builds break.

A stray line was left over from an earlier edit. Sorry about that.

Quoted 11 lines

block/blk-iocost-bpf.c line 60

Quoted 6 lines
block/blk-iocost-bpf.c new file +5 -0
+			/*
+			 * A blkg which never went online never reached the
+			 * radix tree, so it must not receive an init either;
...
+			if (!iocg || !iocg->pd.online)
+				continue;

blkg_create() adds a blkg to q->blkg_list only after radix_tree_insert() succeeds, so the blkgs skipped here are the ones blkg_destroy() already took offline, not ones that never reached the radix tree.

You're right, the comment described the wrong blkgs. It goes away with the walk, which I'll drop in v12 together with the callbacks.

Quoted 10 lines

block/blk-iocost-bpf.c line 117

Quoted 6 lines
block/blk-iocost-bpf.c new file +6 -0
+	if (!disk_live(disk)) {
+		mutex_unlock(&q->rq_qos_mutex);
+		blk_mq_unfreeze_queue(q, memflags);
+		blkdev_put_no_open(bdev);
+		return -ENODEV;
+	}

The guard() suggestion from v10 was only partly applied. This unlock, unfreeze and put sequence is repeated on three error paths.

I'll fold the reg error path into a single out label. Detach no longer needs the freeze after the v12 rework.

Quoted 12 lines

block/blk-iocost-bpf.c line 139

Quoted 8 lines
block/blk-iocost-bpf.c new file +8 -0
+	/*
+	 * Scope the mutex so the tail bdev put runs with blkcg_mutex
+	 * already released: dropping the last device reference can
+	 * reach disk_release() -> blkcg_exit_disk() ->
+	 * blkg_destroy_all(), which takes q->blkcg_mutex.
+	 */
+	{
+		guard(mutex)(&q->blkcg_mutex);

The bare { } block isn't necessary, and ioc_bpf_detach() has the same block with the same comment. Can you drop them?

I'll drop both.

Quoted 7 lines
Quoted 7 lines
block/blk-iocost-bpf.c new file +7 -0
+	/*
+	 * The attachment is checked under rq_qos_mutex first, so an unmatched
+	 * detach exits without freezing.
+	 */
+	mutex_lock(&q->rq_qos_mutex);
+	spin_lock_irq(&q->queue_lock);
+	ioc = q_to_ioc(q);
Quoted 9 lines

block/blk-iocost-bpf.c line 208

Quoted 5 lines
block/blk-iocost-bpf.c new file +4 -0
+	if (ioc) {
+		spin_lock(&ioc->lock);
+		matched = ioc_attached_model_locked(ioc) == ops &&
+			  ioc->bpf_link == link;
...

The same 11 lines check the attachment again after the freeze. The check under rq_qos_mutex after the freeze is the one that matters.

This goes away with the freeze removal: detach becomes a single mutex-critical section.

Quoted 10 lines
Quoted 9 lines

+/*
+ * Pluggable cost model interface for blk-iocost.
+ *
+ * A BPF struct_ops implementation can take over the cost model of one device.
...
+ * offline and its free. Both callbacks are called with ioc->lock held and must
+ * not sleep; the delivery points nest inside queue_lock except for iocg_free()
+ * from ioc_pd_free() in blkg_free_workfn().
+ */

Quoted 3 lines

This restates the attach mechanics and lists the call sites. The comments and descriptions in general are still long and narrate mechanics.

v12 folds everything back into blk-iocost.c, so the private header and the long interface comment both go away.

Thanks,
Tao

Quoted 4 lines

Thanks.

--
tejun

author
#13 lore raw

Re: [PATCH 3/5] selftests/bpf: add iocost cost model test

In reply to Tejun Heo

Hello Tejun,

Quoted 16 lines · Tejun Heo

Hello, Tao.

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

Quoted 10 lines · Tao Cui
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +8 -0
+static bool iocost_bpf_supported(void)
+{
+	FILE *f;
+	char line[128];
+	bool any = false, on = false;
...
+		if (strstr(line, "CONFIG_"))
+			any = true;
...
+	return on;

any is set but never read, so every test skips without /proc/config.gz.

I'll make the probe return whether CONFIG_BLK_CGROUP_IOCOST_BPF=y was seen.

Quoted 6 lines

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

Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +2 -0
+	/* isolate the configfs and cgroup mounts from the host */
+	if (unshare(CLONE_NEWNS)) {

unshare(CLONE_NEWNS) alone doesn't make the mounts private, so the configfs mount propagates to the host, one more per test.

I'll follow unshare() with mount(NULL, "/", NULL,
MS_REC | MS_PRIVATE, NULL).

Quoted 8 lines

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

Quoted 3 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +3 -0
+	ASSERT_OK(configfs_write("/sys/fs/cgroup/cgroup.subtree_control",
+				 "+io"), "subtree_io");
+	if (!ASSERT_OK(cgroup_mkdir("/sys/fs/cgroup/iocost_pairing"),

The "+io" write to the root cgroup's cgroup.subtree_control is never reverted, the cgroups are created directly under /sys/fs/cgroup and test_progs stays in the root cgroup. cgroup_helpers handles all of this.

I'll restore the "+io" setting on exit and move the test process back to the root cgroup before removing the test cgroups. I'll also switch the test over to cgroup_helpers.

Quoted 9 lines

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

Quoted 4 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +3 -0
+	err = iocost_model__attach(skel);
+	if (err == -EOPNOTSUPP || err == -ENODEV) {
...
+		test__skip();

-ENODEV and -EOPNOTSUPP from attaching to the test's own null_blk device are failures, not skips. The same goes for serial_test_iocost_model_streams().

Both become ASSERT_OK failures.

Quoted 6 lines

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

Quoted 1 line
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +1 -0
+		ASSERT_GT(skel->bss->iocg_inits, 0, "pair_init");

This passes on the root blkg alone, so it doesn't show that the test cgroup got iocg_init(). The same goes for eject_had_inits and pair_init_again.

Gone with the callbacks.

Quoted 5 lines
Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +5 -0
+		/*
+		 * detach implicitly by closing the link fd instead of
+		 * calling bpf_link__destroy() explicitly: the release
+		 * path must detach the model just like the explicit
+		 * call does
Quoted 9 lines

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

Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +5 -0
+		 */
+		lfd = bpf_link__fd(skel->links.iocost_2x);
+		bpf_link__disconnect(skel->links.iocost_2x);
+		close(lfd);
+		skel->links.iocost_2x = NULL;

This leaks libbpf's link struct. The reason in the comment doesn't hold either. bpf_link__destroy() on a struct_ops link does the same close().

I'll use bpf_link__destroy() instead.

Quoted 4 lines
Quoted 4 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +3 -0
+void serial_test_iocost_model_streams(void)
...
+	if (ASSERT_OK(err, "attach")) {
+		err = readback_model(dev, model, sizeof(model));
Quoted 9 lines

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

Quoted 4 lines
tools/testing/selftests/bpf/prog_tests/iocost_model.c new file +4 -0
+		if (ASSERT_OK(err, "readback"))
+			ASSERT_STREQ(model, "bpf", "model_bpf");
+
+		bpf_link__destroy(skel->links.iocost_ms);

The test never enables the controller, so iocost_ms's calc_cost() never runs. The multi-stream results in the cover letter aren't exercised by the test.

I'll enable the controller, move the test into a cgroup, drive IO through the device, and assert that the model is exercised.

Thanks,
Tao

Quoted 4 lines

Thanks.

--
tejun

author
#16 lore raw

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

In reply to Tejun Heo

Hello Tejun,

Quoted 10 lines · Tejun Heo

Hello, Tao.

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

Quoted 4 lines · Tao Cui
block/blk-iocost.c +1 -0
 		u64 vdone, vtime, usage_us;
 		u32 hw_active, hw_inuse;
 
+		nr_active++;

nr_active is counted even when the tracepoint is disabled.

Right. I'll only count nr_active when trace_iocost_ioc_tick_enabled() is true.

Quoted 9 lines

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

Quoted 5 lines
block/blk-iocost.c +5 -0
+	/*
+	 * 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. usage is wall time over wall time, summed over iocgs, and is

An io.cost.qos write in the middle of a period changes both period_us and vrate.

Right. I'll update the comment and the commit message to say that the emission point has busy_level, cur_period, nr_active and usage_us_sum complete, while vrate and period_us may already reflect a later io.cost.qos update.

Thanks,
Tao

Quoted 4 lines

Thanks.

--
tejun

author
#19 lore raw

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

In reply to Tejun Heo

Hello Tejun,

Quoted 8 lines · Tejun Heo

Hello, Tao.

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

Quoted 2 lines · Tao Cui
Documentation/admin-guide/cgroup-v2.rst +2 -0
+	When CONFIG_BLK_CGROUP_IOCOST_BPF is enabled, a BPF cost
+	model can be bound to a device by attaching an

Users can't select CONFIG_BLK_CGROUP_IOCOST_BPF.

The sentence now reads "When BPF cost model support is available".

Quoted 8 lines

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

Quoted 4 lines
Documentation/admin-guide/cgroup-v2.rst +4 -0
+	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"

"Only detaching removes the model" is followed by "Device removal ejects the attached model as well".

Dropped "Only".

Quoted 9 lines

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

Quoted 6 lines
Documentation/admin-guide/cgroup-v2.rst +6 -0
+	accepts only "auto" and "user" and never selects a model.  It
+	keeps describing the builtin coefficients, which take effect
+	again when switched back.  The automatic profile stepping does
+	not switch profiles while the BPF model is in use; as with
+	user-set parameters, the profile selected from the device
+	class still applies.

cgroup-v2.rst doesn't describe automatic profile stepping anywhere else.

Those sentences are removed.

Quoted 6 lines

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

Quoted 2 lines
Documentation/admin-guide/cgroup-v2.rst +2 -0
+	defined.  They remain readable and writable while "model" is
+	"bpf" but take effect only after switching back to "linear".

The builtin coefficients taking effect again after switching back is already said above.

Removed.

Thanks,
Tao

Quoted 4 lines

Thanks.

--
tejun