Linux cgroups development
 help / color / mirror / Atom feed
From: Tao Cui <cui.tao@linux.dev>
To: tj@kernel.org, josef@toxicopanda.com, axboe@kernel.dk,
	ast@kernel.org, alexei.starovoitov@gmail.com
Cc: cgroups@vger.kernel.org, linux-block@vger.kernel.org,
	linux-kernel@vger.kernel.org, bpf@vger.kernel.org,
	andrii@kernel.org, eddyz87@gmail.com, daniel@iogearbox.net,
	linux-kselftest@vger.kernel.org, cui.tao@linux.dev,
	cuitao@kylinos.cn, ameryhung@gmail.com
Subject: [PATCH v15 1/4] blk-iocost: add BPF struct_ops cost model support
Date: Thu,  3 Dec 2026 23:03:35 +0800	[thread overview]
Message-ID: <20261203150338.2625598-2-cui.tao@linux.dev> (raw)
In-Reply-To: <20261203150338.2625598-1-cui.tao@linux.dev>

From: Tao Cui <cuitao@kylinos.cn>

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: each device has at most one attached model, and
attaching switches the device's pricing to it while io.cost.qos
keeps controlling whether the device is throttled at all. The
attached model also resets the per-iocg accounting, dropping
what was priced under the builtin model. "model=linear" and
"model=bpf" select between the attached model and the builtin
one across io.cost.model writes, and the model steps down when
the struct_ops link is deleted or the device is removed, at
which point the device reverts to the builtin model; a device
with no attached model rejects removal with -EOPNOTSUPP.
Attaching does not enable the controller.

Switching between the builtin and a BPF model changes the
pricing, and debts, delays and waiters priced by the previous
model would keep the cgroup near-stalled while they pay back.
The accounting therefore starts fresh on a switch: debts and
delays are dropped, waiters are released without being charged,
and vtime snaps to the activation target. Leaving a BPF model
waits for an RCU grace period first so every bio it priced has
finished accounting; the reset runs only when the model is
still selected, and in-flight payoffs are clamped to vtime so
stale costs cannot push done_vtime past it.

The model cannot go away while it is pricing: the bdev
reference from .reg() pins the queue until .unreg() drops it, so
the queue stays reachable even after del_gendisk() has unhashed
the bdev, and the link holds the model until .unreg() has run,
so iocost keeps no reference of its own. ioc_rqos_exit() ejects
through a work item because it runs under rq_qos_mutex; the
eject holds the link against a concurrent close. Models
without calc_cost or with zero or out-of-range transfer
coefficients are rejected when attached.

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

Suggested-by: Tejun Heo <tj@kernel.org>
Signed-off-by: Tao Cui <cuitao@kylinos.cn>
Acked-by: Alexei Starovoitov <ast@kernel.org>
---
 block/Kconfig      |   4 +
 block/blk-iocost.c | 692 +++++++++++++++++++++++++++++++++++++++++++--
 2 files changed, 669 insertions(+), 27 deletions(-)

diff --git a/block/Kconfig b/block/Kconfig
index 70e4a66d941f..26badf54a477 100644
--- a/block/Kconfig
+++ b/block/Kconfig
@@ -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
diff --git a/block/blk-iocost.c b/block/blk-iocost.c
index 0ffe34bd95b7..49622bf69fe3 100644
--- a/block/blk-iocost.c
+++ b/block/blk-iocost.c
@@ -34,7 +34,7 @@
  * device time.  If a given IO is estimated to cost 10ms, the device should
  * be able to process ~100 of those IOs in a second.
  *
- * Currently, there's only one builtin cost model - linear.  Each IO is
+ * The builtin cost model is linear. Each IO is
  * classified as sequential or random and given a base cost accordingly.
  * On top of that, a size cost proportional to the length of the IO is
  * added.  While simple, this model captures the operational
@@ -179,8 +179,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"
@@ -405,6 +409,47 @@ struct ioc_pcpu_stat {
 	u64				last_rq_wait_ns;
 };
 
+/*
+ * Flags for iocost_model_ops.calc_cost(), named after the callback
+ * they're passed to so that BPF programs can look them up through BTF.
+ */
+enum iocost_calc_flags {
+	/*
+	 * The bio is being merged into an IO which was already charged
+	 * its base cost. The model should price only the incremental
+	 * cost: the builtin model skips the seek component and charges
+	 * the page cost in this case.
+	 */
+	IOCOST_CALC_MERGE	= 1 << 0,
+};
+
+/* bpf cost model of one device */
+struct iocost_model_ops {
+	/* whole disk, in the new_encode_dev() encoding */
+	dev_t dev;
+
+	/* used by the completion path instead of LCOEF_[RW]PAGE */
+	u64 read_vtime_per_page;
+	u64 write_vtime_per_page;
+
+	/*
+	 * Called from the submission and merge paths for every charged
+	 * bio (reads, writes, zone appends and flush-flagged bios)
+	 * under rcu_read_lock(), possibly with a scheduler lock held
+	 * on the merge path; must not sleep. Returns the cost of the
+	 * bio in vtime units, clamped to VTIME_PER_SEC by the caller.
+	 */
+	u64 (*calc_cost)(struct bio *bio, u64 calc_flags);
+	/* display name, shown in io.cost.model while this model is selected */
+	char				name[16];
+
+	/*
+	 * private: the bdev reference .reg hands to .unreg; kernel
+	 * owned, the BPF program cannot set it.
+	 */
+	struct block_device		*bdev;
+};
+
 /* per device */
 struct ioc {
 	struct rq_qos			rqos;
@@ -448,6 +493,30 @@ struct ioc {
 	int				autop_idx;
 	bool				user_qos_params:1;
 	bool				user_cost_model:1;
+
+	/*
+	 * The currently attached model, NULL if none is attached.
+	 * While a model is attached, the struct_ops link keeps it
+	 * alive: the link holds its map reference until .unreg() has
+	 * run, so iocost keeps no reference of its own. The link can
+	 * outlive the device - after rq_qos_exit() has torn the ioc
+	 * down, closing the link still runs .unreg(), which finds no
+	 * ioc and only drops the bdev reference that .reg() took.
+	 *
+	 * The attached and attached_link fields are protected by
+	 * rq_qos_mutex.
+	 *
+	 * The bpf_model field is written under rq_qos_mutex and
+	 * ioc->lock, and read with either RCU or ioc->lock held; the
+	 * timer and the io.cost.model show paths read it under
+	 * ioc->lock without rq_qos_mutex.
+	 */
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	const struct iocost_model_ops	*attached;
+	struct bpf_link			*attached_link;
+	/* either NULL (linear) or ->attached */
+	const struct iocost_model_ops __rcu *bpf_model;
+#endif
 };
 
 struct iocg_pcpu_stat {
@@ -672,6 +741,39 @@ static struct ioc *q_to_ioc(struct request_queue *q)
 	return rqos_to_ioc(rq_qos_id(q, RQ_QOS_COST));
 }
 
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+static const struct iocost_model_ops *ioc_bpf_model(struct ioc *ioc)
+{
+	return rcu_dereference_check(ioc->bpf_model, lockdep_is_held(&ioc->lock));
+}
+
+static const struct iocost_model_ops *ioc_bpf_attached(struct ioc *ioc)
+{
+	return ioc->attached;
+}
+
+static void ioc_bpf_model_set(struct ioc *ioc,
+			      const struct iocost_model_ops *ops)
+{
+	rcu_assign_pointer(ioc->bpf_model, ops);
+}
+#else	/* CONFIG_BLK_CGROUP_IOCOST_BPF */
+static const struct iocost_model_ops *ioc_bpf_model(struct ioc *ioc)
+{
+	return NULL;
+}
+
+static const struct iocost_model_ops *ioc_bpf_attached(struct ioc *ioc)
+{
+	return NULL;
+}
+
+static void ioc_bpf_model_set(struct ioc *ioc,
+			      const struct iocost_model_ops *ops)
+{
+}
+#endif	/* CONFIG_BLK_CGROUP_IOCOST_BPF */
+
 static const char __maybe_unused *ioc_name(struct ioc *ioc)
 {
 	struct gendisk *disk = ioc->rqos.disk;
@@ -857,7 +959,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_bpf_model(ioc))
 		return idx;
 
 	/* step up/down based on the vrate */
@@ -1543,6 +1645,30 @@ static int iocg_wake_fn(struct wait_queue_entry *wq_entry, unsigned mode,
 	return 0;
 }
 
+/*
+ * Release every pending waiter without charging the cost it was queued
+ * with. Used on cost model switch where the recorded costs are
+ * denominated in the outgoing model's prices; the waiters' bios are
+ * issued as-is and the accounting starts fresh with the new model.
+ *
+ * Called with iocg->waitq.lock held.
+ */
+static void iocg_release_waiters(struct ioc_gq *iocg)
+{
+	struct wait_queue_entry *wq_entry, *next;
+
+	lockdep_assert_held(&iocg->waitq.lock);
+
+	list_for_each_entry_safe(wq_entry, next, &iocg->waitq.head, entry) {
+		struct iocg_wait *wait =
+			container_of(wq_entry, struct iocg_wait, wait);
+
+		wait->committed = true;
+		default_wake_function(wq_entry, TASK_NORMAL, 0, NULL);
+		list_del_init_careful(&wq_entry->entry);
+	}
+}
+
 /*
  * Calculate the accumulated budget, pay debt if @pay_debt and wake up waiters
  * accordingly. When @pay_debt is %true, the caller must be holding ioc->lock in
@@ -2599,7 +2725,7 @@ static u64 adjust_inuse_and_calc_cost(struct ioc_gq *iocg, u64 vtime,
 }
 
 static void calc_vtime_cost_builtin(struct bio *bio, struct ioc_gq *iocg,
-				    bool is_merge, u64 *costp)
+				    u64 calc_flags, u64 *costp)
 {
 	struct ioc *ioc = iocg->ioc;
 	u64 coef_seqio, coef_randio, coef_page;
@@ -2641,7 +2767,7 @@ static void calc_vtime_cost_builtin(struct bio *bio, struct ioc_gq *iocg,
 		seek_pages >>= IOC_SECT_TO_PAGE_SHIFT;
 	}
 
-	if (!is_merge) {
+	if (!(calc_flags & IOCOST_CALC_MERGE)) {
 		if (seek_pages > LCOEF_RANDIO_PAGES) {
 			cost += coef_randio;
 		} else {
@@ -2653,11 +2779,54 @@ static void calc_vtime_cost_builtin(struct bio *bio, struct ioc_gq *iocg,
 	*costp = cost;
 }
 
-static u64 calc_vtime_cost(struct bio *bio, struct ioc_gq *iocg, bool is_merge)
+static u64 calc_vtime_cost(struct bio *bio, struct ioc_gq *iocg, u64 calc_flags)
 {
 	u64 cost;
 
-	calc_vtime_cost_builtin(bio, iocg, is_merge, &cost);
+	if (IS_ENABLED(CONFIG_BLK_CGROUP_IOCOST_BPF)) {
+		const struct iocost_model_ops *model;
+
+		guard(rcu)();
+		model = ioc_bpf_model(iocg->ioc);
+		if (model) {
+			bool is_flush = (bio->bi_opf & REQ_PREFLUSH) ||
+				((bio->bi_opf & REQ_FUA) &&
+				 !bdev_fua(bio->bi_bdev));
+
+			/*
+			 * Keep the pricing scope the same as the builtin
+			 * model: bios with no data and no flush state, and
+			 * ops other than reads, writes and zone appends,
+			 * cost nothing. Flushes are passed through so that
+			 * the model can price them from the bio flags.
+			 */
+			switch (bio_op(bio)) {
+			case REQ_OP_READ:
+			case REQ_OP_WRITE:
+			case REQ_OP_ZONE_APPEND:
+				if (!bio->bi_iter.bi_size && !is_flush)
+					return 0;
+				break;
+			default:
+				if (!is_flush)
+					return 0;
+				break;
+			}
+
+			cost = model->calc_cost(bio, calc_flags);
+
+			/*
+			 * Cap a single bio at one IO-second of vtime.  The
+			 * builtin formula never gets anywhere near this for
+			 * any realistic bio, and the bound keeps a broken
+			 * or hostile model from saddling a cgroup with
+			 * unbounded vtime debt from a single bio.
+			 */
+			return min(cost, VTIME_PER_SEC);
+		}
+	}
+
+	calc_vtime_cost_builtin(bio, iocg, calc_flags, &cost);
 	return cost;
 }
 
@@ -2683,6 +2852,27 @@ static u64 calc_size_vtime_cost(struct request *rq, struct ioc *ioc)
 {
 	u64 cost;
 
+	if (IS_ENABLED(CONFIG_BLK_CGROUP_IOCOST_BPF)) {
+		const struct iocost_model_ops *model;
+		unsigned int pages;
+
+		guard(rcu)();
+		model = ioc_bpf_model(ioc);
+		if (model) {
+			/* same op scope as the builtin model */
+			pages = blk_rq_stats_sectors(rq) >> IOC_SECT_TO_PAGE_SHIFT;
+			switch (req_op(rq)) {
+			case REQ_OP_READ:
+				return pages * model->read_vtime_per_page;
+			case REQ_OP_ZONE_APPEND:
+			case REQ_OP_WRITE:
+				return pages * model->write_vtime_per_page;
+			default:
+				return 0;
+			}
+		}
+	}
+
 	calc_size_vtime_cost_builtin(rq, ioc, &cost);
 	return cost;
 }
@@ -2785,13 +2975,27 @@ static void ioc_rqos_throttle(struct rq_qos *rqos, struct bio *bio)
 	if (!ioc->enabled || !iocg || !iocg->level)
 		return;
 
+	/*
+	 * Hold RCU from pricing through accounting: a bio priced by a BPF
+	 * model must have been committed, charged as debt or queued on a
+	 * waitq before its RCU read section ends, so that a model switch
+	 * can reset the accumulated per-iocg state after a grace period
+	 * without leaving a stale-priced bio in flight. The section must
+	 * end before sleeping on the waitq below.
+	 */
+	rcu_read_lock();
+
 	/* calculate the absolute vtime cost */
-	abs_cost = calc_vtime_cost(bio, iocg, false);
-	if (!abs_cost)
+	abs_cost = calc_vtime_cost(bio, iocg, 0);
+	if (!abs_cost) {
+		rcu_read_unlock();
 		return;
+	}
 
-	if (!iocg_activate(iocg, &now))
+	if (!iocg_activate(iocg, &now)) {
+		rcu_read_unlock();
 		return;
+	}
 
 	/* dataless bios have no meaningful position for seq/rand detection */
 	if (bio->bi_iter.bi_size)
@@ -2807,6 +3011,7 @@ static void ioc_rqos_throttle(struct rq_qos *rqos, struct bio *bio)
 	if (!waitqueue_active(&iocg->waitq) && !iocg->abs_vdebt &&
 	    time_before_eq64(vtime + cost, now.vnow)) {
 		iocg_commit_bio(iocg, bio, abs_cost, cost);
+		rcu_read_unlock();
 		return;
 	}
 
@@ -2842,13 +3047,17 @@ static void ioc_rqos_throttle(struct rq_qos *rqos, struct bio *bio)
 		goto retry_lock;
 	case action_commit:
 		iocg_commit_bio(iocg, bio, abs_cost, cost);
+		rcu_read_unlock();
 		return;
 	case action_return:
+		rcu_read_unlock();
 		return;
 	case action_wait:
 		break;
 	}
 
+	rcu_read_unlock();
+
 	while (true) {
 		set_current_state(TASK_UNINTERRUPTIBLE);
 		if (wait.committed)
@@ -2874,7 +3083,14 @@ static void ioc_rqos_merge(struct rq_qos *rqos, struct request *rq,
 	if (!ioc->enabled || !iocg || !iocg->level)
 		return;
 
-	abs_cost = calc_vtime_cost(bio, iocg, true);
+	/*
+	 * Hold RCU across pricing and accounting like ioc_rqos_throttle()
+	 * so that a model switch's grace period also covers bios priced by
+	 * the outgoing BPF model and charged as debt here.
+	 */
+	guard(rcu)();
+
+	abs_cost = calc_vtime_cost(bio, iocg, IOCOST_CALC_MERGE);
 	if (!abs_cost)
 		return;
 
@@ -2923,8 +3139,24 @@ static void ioc_rqos_done_bio(struct rq_qos *rqos, struct bio *bio)
 {
 	struct ioc_gq *iocg = blkg_to_iocg(bio->bi_blkg);
 
-	if (iocg && bio->bi_iocost_cost)
-		atomic64_add(bio->bi_iocost_cost, &iocg->done_vtime);
+	if (iocg && bio->bi_iocost_cost) {
+		/*
+		 * A model switch reset re-anchors vtime and done_vtime
+		 * while bios priced by the old model are still in flight.
+		 * Their completion would pay the stale cost into done_vtime
+		 * and can push it past vtime, breaking the (vtime -
+		 * done_vtime) invariant the accounting relies on until new
+		 * IO advances vtime again. Clamp the payoff to vtime; the
+		 * excess is priced by a model that no longer exists and is
+		 * what the reset drops.
+		 */
+		u64 vtime = atomic64_read(&iocg->vtime);
+		u64 vdone = atomic64_read(&iocg->done_vtime);
+
+		atomic64_add(min(bio->bi_iocost_cost,
+				 vtime - min(vtime, vdone)),
+			     &iocg->done_vtime);
+	}
 }
 
 static void ioc_rqos_done(struct rq_qos *rqos, struct request *rq)
@@ -2980,10 +3212,105 @@ static void ioc_rqos_queue_depth_changed(struct rq_qos *rqos)
 	spin_unlock_irq(&ioc->lock);
 }
 
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+/* Called by .unreg and by device removal, whichever is first. */
+struct ioc_bpf_detach {
+	struct work_struct	work;
+	struct bpf_link		*link;
+};
+
+static void ioc_bpf_detach_workfn(struct work_struct *work)
+{
+	struct ioc_bpf_detach *d = container_of(work, struct ioc_bpf_detach,
+						work);
+
+	/* the usual detach path: this ends up in .unreg */
+	d->link->ops->detach(d->link);
+	bpf_link_put(d->link);
+	kfree(d);
+}
+
+static void iocg_model_switch_reset(struct ioc *ioc);
+
+static void ioc_detach_model(struct ioc *ioc)
+{
+	const struct iocost_model_ops *ops = ioc->attached;
+	bool still_selected;
+
+	lockdep_assert_held(&ioc->rqos.disk->queue->rq_qos_mutex);
+
+	if (!ops)
+		return;
+
+	spin_lock_irq(&ioc->lock);
+	still_selected = ioc->bpf_model == ops;
+	rcu_assign_pointer(ioc->bpf_model, NULL);
+	spin_unlock_irq(&ioc->lock);
+	ioc->attached = NULL;
+	ioc->attached_link = NULL;
+
+	/*
+	 * If io.cost.model already deselected the model, the accounting
+	 * was reset there and only the remaining pointers are dropped.
+	 * Otherwise pricing just switched back to the builtin model:
+	 * reset the per-iocg accounting like those switches do - the
+	 * outstanding debts and delays were priced by the outgoing
+	 * model - after a grace period so that every bio priced by it
+	 * has finished accounting.
+	 */
+	if (still_selected) {
+		synchronize_rcu();
+		spin_lock_irq(&ioc->lock);
+		iocg_model_switch_reset(ioc);
+		spin_unlock_irq(&ioc->lock);
+	}
+
+	/*
+	 * calc_cost() can still run until .unreg; the link holds the map
+	 * until .unreg has run, so there is no iocost-owned reference to
+	 * drop here anymore.
+	 */
+}
+#endif	/* CONFIG_BLK_CGROUP_IOCOST_BPF */
+
 static void ioc_rqos_exit(struct rq_qos *rqos)
 {
 	struct ioc *ioc = rqos_to_ioc(rqos);
 
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	/*
+	 * Detaching inline is not possible: the struct_ops detach path
+	 * serializes on update_mutex, which must not be taken under the
+	 * rq_qos_mutex held here, and running .unreg's grace period and
+	 * full accounting reset inside this teardown is not wanted
+	 * either. Queue the detach instead: the bdev reference taken by
+	 * .reg pins the queue until .unreg has run, so the eject only
+	 * has to happen within a reasonable amount of time. Hold the
+	 * link for the work in case the link is being closed
+	 * concurrently.
+	 */
+	if (ioc->attached_link) {
+		struct bpf_link *link = bpf_link_inc_not_zero(ioc->attached_link);
+		struct ioc_bpf_detach *d;
+
+		/* the closing link detaches through its own path */
+		if (!IS_ERR_OR_NULL(link)) {
+			d = kzalloc(sizeof(*d), GFP_NOIO);
+			if (d) {
+				d->link = link;
+				INIT_WORK(&d->work, ioc_bpf_detach_workfn);
+				queue_work(system_wq, &d->work);
+			} else {
+				/*
+				 * allocation failed: the eject is deferred
+				 * to the link's close path, which drops
+				 * the references through .unreg
+				 */
+				bpf_link_put(link);
+			}
+		}
+	}
+#endif	/* CONFIG_BLK_CGROUP_IOCOST_BPF */
 	blkcg_deactivate_policy(rqos->disk, &blkcg_policy_iocost);
 
 	spin_lock_irq(&ioc->lock);
@@ -3535,14 +3862,37 @@ 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 ", dname,
+		   ioc->user_cost_model ? "user" : "auto");
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	{
+		const struct iocost_model_ops __rcu *ops;
+
+		rcu_read_lock();
+		ops = rcu_dereference(ioc->bpf_model);
+		if (ops)
+			seq_printf(sf, "model=bpf name=%.*s\n",
+				   (int)sizeof(ops->name), ops->name);
+		else
+			seq_printf(sf, "model=linear "
+				   "rbps=%llu rseqiops=%llu rrandiops=%llu "
+				   "wbps=%llu wseqiops=%llu wrandiops=%llu "
+				   "flushiops=%llu\n",
+				   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]);
+		rcu_read_unlock();
+	}
+#else	/* CONFIG_BLK_CGROUP_IOCOST_BPF */
+	seq_printf(sf, "model=linear "
 		   "rbps=%llu rseqiops=%llu rrandiops=%llu "
 		   "wbps=%llu wseqiops=%llu wrandiops=%llu "
 		   "flushiops=%llu\n",
-		   dname, ioc->user_cost_model ? "user" : "auto",
 		   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]);
+#endif	/* CONFIG_BLK_CGROUP_IOCOST_BPF */
 	spin_unlock_irq(&ioc->lock);
 	return 0;
 }
@@ -3573,15 +3923,68 @@ static const match_table_t i_lcoef_tokens = {
 	{ NR_I_LCOEFS,		NULL		},
 };
 
+/*
+ * A cost model switch changes the pricing: per-iocg vtime debt and delays
+ * accumulated under the previous model's pricing are meaningless under the
+ * new one and would stall IO for as long as they take to pay back. Reset
+ * each active iocg: drop the debts and delays, release the waiters queued
+ * with the old prices, restore the inuse that debt handling collapsed and
+ * close the debt/delay accounting windows, and snap vtime to the activation
+ * target budget, the same start iocg_activate() gives a newly activated
+ * iocg.
+ *
+ * The caller must have drained all bios priced by the outgoing BPF model
+ * with a grace period - see ioc_cost_model_write().
+ *
+ * Called with ioc->lock held.
+ */
+static void iocg_model_switch_reset(struct ioc *ioc)
+{
+	struct ioc_gq *iocg;
+	struct ioc_now now;
+
+	lockdep_assert_held(&ioc->lock);
+
+	ioc_now(ioc, &now);
+
+	list_for_each_entry(iocg, &ioc->active_iocgs, active_list) {
+		u64 vtime, vtarget;
+
+		spin_lock(&iocg->waitq.lock);
+		iocg->abs_vdebt = 0;
+		if (iocg->delay) {
+			iocg->delay = 0;
+			blkcg_clear_delay(iocg_to_blkg(iocg));
+		}
+		iocg->indebt_since = 0;
+		iocg->indelay_since = 0;
+		vtarget = now.vnow - ioc->margins.target;
+		vtime = atomic64_read(&iocg->vtime);
+		atomic64_add(vtarget - vtime, &iocg->vtime);
+		atomic64_add(vtarget - vtime, &iocg->done_vtime);
+		/*
+		 * The payoff paths normally restore inuse when the debt
+		 * drains; restore it here since the state is dropped
+		 * wholesale.
+		 */
+		propagate_weights(iocg, iocg->active,
+				  iocg->last_inuse ?: iocg->weight, true, &now);
+		iocg_release_waiters(iocg);
+		iocg_kick_waitq(iocg, false, &now);
+		spin_unlock(&iocg->waitq.lock);
+	}
+}
+
 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, *old_model;
 	struct blkg_conf_ctx ctx;
 	struct request_queue *q;
 	unsigned int memflags;
 	struct ioc *ioc;
 	u64 u[NR_I_LCOEFS];
-	bool user;
+	bool user, switch_model;
 	char *body, *p;
 	int ret;
 
@@ -3606,12 +4009,11 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 		ioc = q_to_ioc(q);
 	}
 
-	memflags = blk_mq_freeze_queue(q);
-	blk_mq_quiesce_queue(q);
-
+	/* parse and validate the request without changing any state */
 	spin_lock_irq(&ioc->lock);
 	memcpy(u, ioc->params.i_lcoefs, sizeof(u));
 	user = ioc->user_cost_model;
+	old_model = model = ioc_bpf_model(ioc);
 
 	ret = -EINVAL;
 
@@ -3632,35 +4034,72 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 			else if (!strcmp(buf, "user"))
 				user = true;
 			else
-				goto unlock;
+				goto out_parse;
 			continue;
 		case COST_MODEL:
 			match_strlcpy(buf, &args[0], sizeof(buf));
-			if (strcmp(buf, "linear"))
-				goto unlock;
+			if (!strcmp(buf, "linear"))
+				model = NULL;
+			else if (!strcmp(buf, "bpf") && ioc_bpf_attached(ioc))
+				model = ioc_bpf_attached(ioc);
+			else
+				goto out_parse;
 			continue;
 		}
 
 		tok = match_token(p, i_lcoef_tokens, args);
 		if (tok == NR_I_LCOEFS)
-			goto unlock;
+			goto out_parse;
 		if (match_u64(&args[0], &v))
-			goto unlock;
+			goto out_parse;
 		u[tok] = v;
 		user = true;
 	}
 
+	switch_model = model != old_model;
+	if (switch_model && old_model) {
+		/*
+		 * Leaving a BPF model: clear it now and wait for a grace
+		 * period before resetting so that every bio priced by it
+		 * has committed, been charged as debt or joined a waitq by
+		 * the time the accumulated state is reset.
+		 */
+		ioc_bpf_model_set(ioc, model);
+	}
+	ret = 0;
+
+out_parse:
+	spin_unlock_irq(&ioc->lock);
+	if (ret)
+		goto close_bdev;
+
+	if (switch_model && old_model)
+		synchronize_rcu();
+
+	/*
+	 * Reset before freezing: the waiters queued with the old prices
+	 * are released here, so freezing the queue below no longer waits
+	 * on them.
+	 */
+	if (switch_model) {
+		spin_lock_irq(&ioc->lock);
+		iocg_model_switch_reset(ioc);
+		spin_unlock_irq(&ioc->lock);
+	}
+
+	memflags = blk_mq_freeze_queue(q);
+	blk_mq_quiesce_queue(q);
+
+	spin_lock_irq(&ioc->lock);
 	if (user) {
 		memcpy(ioc->params.i_lcoefs, u, sizeof(u));
 		ioc->user_cost_model = true;
 	} else {
 		ioc->user_cost_model = false;
 	}
+	if (!(switch_model && old_model))
+		ioc_bpf_model_set(ioc, model);
 	ioc_refresh_params(ioc, true);
-
-	ret = 0;
-
-unlock:
 	spin_unlock_irq(&ioc->lock);
 
 	blk_mq_unquiesce_queue(q);
@@ -3703,6 +4142,205 @@ 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;
+
+	/* the removal path keys the deferred detach on the link */
+	if (!link)
+		return -EOPNOTSUPP;
+
+	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);
+	}
+
+	if (ioc->attached) {
+		ret = -EBUSY;
+		goto out;
+	}
+	ioc->attached = ops;
+	ioc->attached_link = link;
+
+	spin_lock_irq(&ioc->lock);
+	rcu_assign_pointer(ioc->bpf_model, ops);
+	/*
+	 * Stepping is paused while a BPF model is selected. Drop any
+	 * pending builtin step candidate so it cannot fire against the
+	 * builtin model after a switchback.
+	 */
+	ioc->autop_too_fast_at = 0;
+	ioc->autop_too_slow_at = 0;
+	/*
+	 * Settle the autop state now that stepping is suspended; the
+	 * stale pre-attach profile would otherwise linger until the
+	 * next unrelated refresh event.
+	 */
+	iocg_model_switch_reset(ioc);
+	ioc_refresh_params(ioc, true);
+	spin_unlock_irq(&ioc->lock);
+
+	/*
+	 * Hand the bdev reference to .unreg: it drops the reference
+	 * after detaching the model. The reference is what keeps the
+	 * queue reachable across del_gendisk(), so .unreg never has to
+	 * look the device up by dev_t again.
+	 */
+	ops->bdev = bdev;
+	ret = 0;
+	goto done;
+out:
+	blkdev_put_no_open(bdev);
+done:
+	mutex_unlock(&q->rq_qos_mutex);
+	blk_mq_unfreeze_queue(q, memflags);
+	return ret;
+}
+
+static void ioc_bpf_unreg(void *kdata, struct bpf_link *link)
+{
+	struct iocost_model_ops *ops = kdata;
+	struct block_device *bdev = ops->bdev;
+	struct request_queue *q;
+	struct ioc *ioc;
+
+	/*
+	 * .reg handed us its bdev reference: the queue stays reachable
+	 * even after del_gendisk() has unhashed the bdev, so there is no
+	 * lookup window here anymore.
+	 */
+	if (!bdev)
+		return;
+
+	q = bdev_get_queue(bdev);
+	mutex_lock(&q->rq_qos_mutex);
+	ioc = q_to_ioc(q);
+	if (ioc && ioc->attached == ops && ioc->attached_link == link)
+		ioc_detach_model(ioc);
+	ops->bdev = NULL;
+	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;
+	case offsetof(struct iocost_model_ops, name):
+		memcpy(ops->name, uops->name, sizeof(ops->name));
+		return 1;
+	case offsetof(struct iocost_model_ops, bdev):
+		/* kernel-owned; the BPF program cannot set it */
+		ops->bdev = NULL;
+		return 1;
+	}
+	return 0;
+}
+
+static int ioc_bpf_validate(void *kdata)
+{
+	struct iocost_model_ops *ops = kdata;
+
+	/*
+	 * Bound the transfer coefficients so that coefficient * pages
+	 * cannot wrap u64 for any possible request size.
+	 */
+	if (ops->read_vtime_per_page > (VTIME_PER_SEC >> IOC_SECT_TO_PAGE_SHIFT) ||
+	    ops->write_vtime_per_page > (VTIME_PER_SEC >> IOC_SECT_TO_PAGE_SHIFT))
+		return -EINVAL;
+
+	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);
-- 
2.43.0


  reply	other threads:[~2026-12-03 15:03 UTC|newest]

Thread overview: 6+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-03 15:03 [PATCH v15 0/4] blk-iocost: BPF struct_ops cost model Tao Cui
2026-12-03 15:03 ` Tao Cui [this message]
2026-12-03 15:03 ` [PATCH v15 2/4] blk-iocost: add iocost_ioc_tick tracepoint for per-period device summary Tao Cui
2026-12-03 15:03 ` [PATCH v15 3/4] selftests/bpf: add iocost cost model test Tao Cui
2026-12-03 15:33   ` bot+bpf-ci
2026-12-03 15:03 ` [PATCH v15 4/4] docs: cgroup-v2: document the iocost BPF cost model attachment Tao Cui

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261203150338.2625598-2-cui.tao@linux.dev \
    --to=cui.tao@linux.dev \
    --cc=alexei.starovoitov@gmail.com \
    --cc=ameryhung@gmail.com \
    --cc=andrii@kernel.org \
    --cc=ast@kernel.org \
    --cc=axboe@kernel.dk \
    --cc=bpf@vger.kernel.org \
    --cc=cgroups@vger.kernel.org \
    --cc=cuitao@kylinos.cn \
    --cc=daniel@iogearbox.net \
    --cc=eddyz87@gmail.com \
    --cc=josef@toxicopanda.com \
    --cc=linux-block@vger.kernel.org \
    --cc=linux-kernel@vger.kernel.org \
    --cc=linux-kselftest@vger.kernel.org \
    --cc=tj@kernel.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox