* [PATCH v15 1/4] blk-iocost: add BPF struct_ops cost model support
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
2026-12-03 15:44 ` bot+bpf-ci
2026-12-03 15:03 ` [PATCH v15 2/4] blk-iocost: add iocost_ioc_tick tracepoint for per-period device summary Tao Cui
` (2 subsequent siblings)
3 siblings, 1 reply; 7+ messages in thread
From: Tao Cui @ 2026-12-03 15:03 UTC (permalink / raw)
To: tj, josef, axboe, ast, alexei.starovoitov
Cc: cgroups, linux-block, linux-kernel, bpf, andrii, eddyz87, daniel,
linux-kselftest, cui.tao, cuitao, ameryhung
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
^ permalink raw reply related [flat|nested] 7+ messages in thread* [PATCH v15 3/4] selftests/bpf: add iocost cost model test
2026-12-03 15:03 [PATCH v15 0/4] blk-iocost: BPF struct_ops cost model Tao Cui
2026-12-03 15:03 ` [PATCH v15 1/4] blk-iocost: add BPF struct_ops cost model support Tao Cui
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 ` 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
3 siblings, 1 reply; 7+ messages in thread
From: Tao Cui @ 2026-12-03 15:03 UTC (permalink / raw)
To: tj, josef, axboe, ast, alexei.starovoitov
Cc: cgroups, linux-block, linux-kernel, bpf, andrii, eddyz87, daniel,
linux-kselftest, cui.tao, cuitao, ameryhung
From: Tao Cui <cuitao@kylinos.cn>
Add two example iocost cost models and tests which attach them to a
null_blk instance the tests create through configfs, so everything
runs without external setup.
The first model implements the builtin linear HDD formula at double
cost. The second implements multi-stream sequentiality detection: it
keeps a per-cgroup table of stream slots instead of the single builtin
cursor, so concurrent sequential streams in one cgroup are priced
sequentially. Both set the target device through the struct_ops
member before load, and the maps are declared ".struct_ops.link" so
that a test dying in between does not leave the model attached.
The tests verify the model=bpf readback while attached, that ctrl=bpf
is rejected, that a second model on the same device fails with -EBUSY,
that model=linear and model=bpf switch between the attached and
builtin models without detaching, and that detaching restores the
builtin model. With the controller enabled through io.cost.qos, they
also verify that IOs are priced through calc_cost() and that the
iocost_ioc_tick tracepoint is seen from BPF. They also verify that
device removal under the attached model ejects it, with a recreated
device attachable again.
Suggested-by: Tejun Heo <tj@kernel.org>
Signed-off-by: Tao Cui <cuitao@kylinos.cn>
---
tools/testing/selftests/bpf/config | 2 +
.../selftests/bpf/prog_tests/iocost_model.c | 1021 +++++++++++++++++
.../selftests/bpf/progs/iocost_model.c | 189 +++
tools/testing/selftests/bpf/progs/iocost_ms.c | 206 ++++
4 files changed, 1418 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
diff --git a/tools/testing/selftests/bpf/config b/tools/testing/selftests/bpf/config
index ce0db4be4d26..ef9d2b794f0c 100644
--- a/tools/testing/selftests/bpf/config
+++ b/tools/testing/selftests/bpf/config
@@ -143,3 +143,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
diff --git a/tools/testing/selftests/bpf/prog_tests/iocost_model.c b/tools/testing/selftests/bpf/prog_tests/iocost_model.c
new file mode 100644
index 000000000000..11bcb33a1eb5
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/iocost_model.c
@@ -0,0 +1,1021 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (C) 2026 KylinSoft Corporation. */
+
+#define _GNU_SOURCE
+#include <test_progs.h>
+#include <fcntl.h>
+#include <malloc.h>
+#include <sched.h>
+#include <sys/statfs.h>
+#include <linux/magic.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <sys/sysmacros.h>
+#include <unistd.h>
+#include "iocost_model.skel.h"
+#include "iocost_ms.skel.h"
+#include "cgroup_helpers.h"
+
+/*
+ * Write val to the file at path (configfs or cgroupfs), returning the
+ * errno of the write negated (0 on success).
+ */
+static int write_file(const char *path, const char *val)
+{
+ FILE *fp;
+ int err = 0;
+
+ fp = fopen(path, "w");
+ if (!fp)
+ return -errno;
+ if (fwrite(val, 1, strlen(val), fp) != strlen(val))
+ err = ferror(fp) ? (errno ? -errno : -EIO) : -EIO;
+ if (fclose(fp) && !err)
+ err = -errno;
+ return err;
+}
+
+/*
+ * Read the first token of the file at path, for the dev attribute.
+ */
+static int read_file_token(const char *path, char *tok, size_t tok_sz)
+{
+ char fmt[16];
+ FILE *fp;
+
+ fp = fopen(path, "r");
+ if (!fp)
+ return -errno;
+ snprintf(fmt, sizeof(fmt), "%%%zus", tok_sz - 1);
+ if (fscanf(fp, fmt, tok) != 1) {
+ fclose(fp);
+ return -EIO;
+ }
+ fclose(fp);
+ return 0;
+}
+
+/*
+ * Create a null_blk instance through configfs and copy its maj:min
+ * into @dev. The device appears only once power is written, and is
+ * removed by rmdir of the instance directory; the maj:min comes from
+ * the sysfs directory of the created disk, which is named after the
+ * instance.
+ */
+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)) {
+ if (errno != EEXIST)
+ return -errno;
+ /*
+ * a leftover instance from an earlier crashed run may
+ * still be powered: tear it down before reusing the
+ * name
+ */
+ snprintf(p2, sizeof(p2),
+ "/sys/kernel/config/nullb/%s/power", name);
+ write_file(p2, "0");
+ if (rmdir(path) && errno != ENOENT)
+ return -errno;
+ if (mkdir(path, 0755) && errno != EEXIST)
+ return -errno;
+ }
+
+ snprintf(path, sizeof(path), "/sys/kernel/config/nullb/%s/size", name);
+ err = write_file(path, "128");
+ if (err)
+ goto err_rmdir;
+
+ snprintf(path, sizeof(path), "/sys/kernel/config/nullb/%s/power", name);
+ err = write_file(path, "1");
+ if (err)
+ goto err_rmdir;
+
+ snprintf(path, sizeof(path), "/sys/block/%s/dev", name);
+ err = read_file_token(path, dev, dev_sz);
+ if (err) {
+ /* do not leave a powered instance behind */
+ snprintf(path, sizeof(path),
+ "/sys/kernel/config/nullb/%s/power", name);
+ write_file(path, "0");
+ snprintf(path, sizeof(path),
+ "/sys/kernel/config/nullb/%s", name);
+ rmdir(path);
+ }
+ return err;
+
+ /*
+ * roll the half-created instance back: power it off in case the
+ * failure left it on, then remove the directory
+ */
+err_rmdir:
+ snprintf(p2, sizeof(p2), "/sys/kernel/config/nullb/%s/power", name);
+ write_file(p2, "0");
+ snprintf(path, sizeof(path), "/sys/kernel/config/nullb/%s", name);
+ rmdir(path);
+ return err;
+}
+
+static int nullb_remove(const char *name)
+{
+ char path[128];
+
+ /* a powered instance cannot be removed */
+ snprintf(path, sizeof(path), "/sys/kernel/config/nullb/%s/power", name);
+ write_file(path, "0");
+ snprintf(path, sizeof(path), "/sys/kernel/config/nullb/%s", name);
+ if (rmdir(path))
+ return -errno;
+ return 0;
+}
+
+#define IOCOST_NULLB "iocost_model_test"
+#define IOCOST_NULLB2 "iocost_model_test2"
+
+/*
+ * Probe a file for a substring. Returns 1 if found, 0 if definitively
+ * not, -1 on probe errors (transient: callers that cache don't cache
+ * errors).
+ *
+ * Reads until EOF instead of trusting st_size: /proc files report
+ * st_size 0.
+ */
+static int file_contains(const char *path, const char *needle)
+{
+ char *buf = NULL, *tmp;
+ size_t cap = 0;
+ ssize_t got;
+ size_t total = 0;
+ bool on;
+ int fd;
+
+ fd = open(path, O_RDONLY);
+ if (fd < 0)
+ return -1;
+
+ /* reads may come up short; keep going until EOF */
+ while (true) {
+ if (total == cap) {
+ cap = cap ? cap * 2 : 1 << 16;
+ tmp = realloc(buf, cap);
+ if (!tmp) {
+ free(buf);
+ close(fd);
+ return -1;
+ }
+ buf = tmp;
+ }
+ got = read(fd, buf + total, cap - total);
+ if (got < 0) {
+ free(buf);
+ close(fd);
+ return -1;
+ }
+ if (!got)
+ break;
+ total += got;
+ }
+ close(fd);
+
+ if (!buf)
+ return -1;
+
+ on = memmem(buf, total, needle, strlen(needle)) != NULL;
+ free(buf);
+ return on;
+}
+
+/*
+ * register_bpf_struct_ops() emits the "bpf_struct_ops_iocost_model_ops"
+ * wrapper type into /sys/kernel/btf/vmlinux only when the struct_ops
+ * registration is compiled in. The bare "iocost_model_ops" struct is
+ * no such signal: blk-iocost.c defines it outside the config guard and
+ * its name lands in the BTF whenever the file is built, even if the
+ * registration itself is compiled out. Probing the wrapper name is
+ * what makes this definitive.
+ */
+static int iocost_bpf_supported(void)
+{
+ static int cached = -1;
+
+ if (cached >= 0)
+ return cached;
+
+ cached = file_contains("/sys/kernel/btf/vmlinux",
+ "bpf_struct_ops_iocost_model_ops");
+ return cached;
+}
+
+
+/* open the nullb device node, creating it manually when udev hasn't */
+static int open_nullb_dev(const char *name, int flags)
+{
+ char path[32], syspath[64], devtok[32];
+ unsigned int maj, min;
+ dev_t dev;
+ struct stat st;
+ int fd;
+
+ snprintf(syspath, sizeof(syspath), "/sys/block/%s/dev", name);
+ if (read_file_token(syspath, devtok, sizeof(devtok)) ||
+ sscanf(devtok, "%u:%u", &maj, &min) != 2)
+ return errno ? -errno : -ENOENT;
+ dev = makedev(maj, min);
+
+ snprintf(path, sizeof(path), "/dev/%s", name);
+ fd = open(path, flags);
+ if (fd >= 0 && fstat(fd, &st) == 0 && S_ISBLK(st.st_mode) &&
+ st.st_rdev == dev)
+ return fd;
+ if (fd >= 0) {
+ /* a stale node from a previous run, drop and recreate */
+ close(fd);
+ fd = -1;
+ }
+ if (unlink(path) && errno != ENOENT)
+ return -errno;
+ if (mknod(path, S_IFBLK | 0600, dev))
+ return -errno;
+ fd = open(path, flags);
+ if (fd < 0)
+ unlink(path);
+ return fd;
+}
+
+/*
+ * True if the named controller is available on the cgroup2 hierarchy
+ * mounted at /sys/fs/cgroup, that is, it shows up in the root
+ * cgroup.controllers list. Tokens are compared whole so that "io"
+ * does not match inside another controller's name.
+ */
+static bool cgroupfs_has_controller(const char *name)
+{
+ char line[512], *tok;
+ FILE *fp;
+ bool found = false;
+
+ fp = fopen("/sys/fs/cgroup/cgroup.controllers", "r");
+ if (!fp)
+ return false;
+ while (!found && fgets(line, sizeof(line), fp)) {
+ for (tok = strtok(line, " \t\n"); tok;
+ tok = strtok(NULL, " \t\n")) {
+ if (!strcmp(tok, name)) {
+ found = true;
+ break;
+ }
+ }
+ }
+ fclose(fp);
+ return found;
+}
+
+/*
+ * The tests run against their own null_blk instance created through
+ * configfs, so they need root, configfs and the null_blk driver. The
+ * BPF cost model further needs cgroup v2 at /sys/fs/cgroup and
+ * CONFIG_BLK_CGROUP_IOCOST_BPF in the running kernel; both are
+ * environment properties, so their absence is a skip.
+ */
+static bool iocost_test_env(void)
+{
+ static bool ready;
+ struct statfs sf;
+ int orig_ns = -1, orig_cwd = -1, supported;
+ bool ok = false;
+
+ if (geteuid() != 0) {
+ printf("%s:SKIP:needs root\n", __func__);
+ test__skip();
+ return false;
+ }
+
+ /*
+ * The private mount namespace and the configfs and cgroup2
+ * mounts are process-wide: set them up once so serial tests do
+ * not stack namespaces and pile mounts on top of each other.
+ * Mounting cgroup2 in the namespace shadows whatever the host
+ * or an earlier test left at /sys/fs/cgroup (tmpfs, cgroup v1),
+ * so the checks below run against a clean hierarchy regardless
+ * of the mount state the process inherited.
+ */
+ if (!ready) {
+ orig_cwd = open(".", O_RDONLY | O_DIRECTORY);
+ orig_ns = open("/proc/self/ns/mnt", O_RDONLY);
+ if (unshare(CLONE_NEWNS) ||
+ mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL)) {
+ printf("%s:SKIP:cannot make mounts private: %s\n",
+ __func__, strerror(errno));
+ test__skip();
+ goto out;
+ }
+ mkdir("/sys/kernel/config", 0755);
+ (void)mount("none", "/sys/kernel/config", "configfs", 0, NULL);
+ if (mount("none", "/sys/fs/cgroup", "cgroup2", 0, NULL)) {
+ /*
+ * EBUSY means a cgroup2 mount is already there: that
+ * is the common case and the inherited mount is fine
+ * to use. Any other failure, or an underlying mount
+ * that is not cgroup2 (tmpfs, cgroup v1 left by an
+ * earlier test), is handled by dropping what is there
+ * in the private namespace and trying once more.
+ */
+ if (!(errno == EBUSY &&
+ statfs("/sys/fs/cgroup", &sf) == 0 &&
+ sf.f_type == CGROUP2_SUPER_MAGIC) &&
+ (umount("/sys/fs/cgroup") ||
+ mount("none", "/sys/fs/cgroup",
+ "cgroup2", 0, NULL))) {
+ printf("%s:SKIP:cannot mount cgroup2: %s\n",
+ __func__, strerror(errno));
+ test__skip();
+ goto out;
+ }
+ }
+ }
+
+ if (statfs("/sys/fs/cgroup", &sf) ||
+ sf.f_type != CGROUP2_SUPER_MAGIC) {
+ printf("%s:SKIP:needs cgroup v2 at /sys/fs/cgroup\n",
+ __func__);
+ test__skip();
+ goto out;
+ }
+
+ /*
+ * The io controller can be missing from cgroup.controllers even
+ * with cgroup2 mounted: cgroup_disable=io leaves it out, and so
+ * does a cgroup v1 hierarchy claiming it. The io.* files the
+ * tests write do not exist then, so skip with a clear reason
+ * instead of failing on the first io.weight write.
+ */
+ if (!cgroupfs_has_controller("io")) {
+ printf("%s:SKIP:needs the io controller in cgroup.controllers\n",
+ __func__);
+ test__skip();
+ goto out;
+ }
+
+ supported = iocost_bpf_supported();
+ if (supported < 0) {
+ printf("%s:SKIP:cannot probe /sys/kernel/btf/vmlinux: %s\n",
+ __func__, strerror(errno));
+ test__skip();
+ goto out;
+ }
+ if (!supported) {
+ printf("%s:SKIP:needs CONFIG_BLK_CGROUP_IOCOST_BPF\n",
+ __func__);
+ test__skip();
+ goto out;
+ }
+
+ /*
+ * the tp_btf attach goes through the raw-tracepoint syscall and
+ * needs no tracefs mount; probe the tracepoint by its kallsyms
+ * entry instead. A probe error skips like an absent tracepoint:
+ * transient failures are retried on the next run.
+ */
+ if (file_contains("/proc/kallsyms",
+ "__tracepoint_iocost_ioc_tick") <= 0) {
+ printf("%s:SKIP:needs the iocost_ioc_tick tracepoint\n",
+ __func__);
+ test__skip();
+ goto out;
+ }
+ SYS_NOFAIL("modprobe null_blk nr_devices=0");
+ if (access("/sys/kernel/config/nullb", W_OK)) {
+ printf("%s:SKIP:needs null_blk with configfs support\n",
+ __func__);
+ test__skip();
+ goto out;
+ }
+
+ ok = true;
+ ready = true;
+
+out:
+ if (!ok)
+ ready = false;
+ if (orig_ns >= 0) {
+ if (!ok)
+ setns(orig_ns, CLONE_NEWNS);
+ close(orig_ns);
+ }
+ if (orig_cwd >= 0)
+ fchdir(orig_cwd);
+ close(orig_cwd);
+ return ok;
+}
+
+/*
+ * Read back the io.cost.model line of dev and copy the model= value into
+ * @model. Returns 0 on success.
+ */
+static int readback_model(const char *dev, char *model, size_t model_sz)
+{
+ char line[256], word[256], *m, *end;
+ FILE *fp;
+ int found = 0;
+
+ fp = fopen("/sys/fs/cgroup/io.cost.model", "r");
+ if (!fp)
+ return -1;
+ while (fgets(line, sizeof(line), fp)) {
+ if (sscanf(line, "%255s", word) == 1 && !strcmp(word, dev)) {
+ found = 1;
+ break;
+ }
+ }
+ fclose(fp);
+ if (!found)
+ return -1;
+
+ m = strstr(line, "model=");
+ if (!m)
+ return -1;
+ m += strlen("model=");
+ end = m;
+ while (*end && *end != ' ')
+ end++;
+ snprintf(model, model_sz, "%.*s", (int)(end - m), m);
+ return 0;
+}
+
+/*
+ * Read the cost.usage accumulator of dev from the cgroup's io.stat. Returns 0
+ * on success, -ENODEV when the device has no line yet (no charge recorded).
+ */
+static int read_cost_usage(const char *cgroup, const char *dev,
+ unsigned long long *usage)
+{
+ char buf[4096], *save = NULL, *linep, *tok, *word;
+ int found = 0, ret;
+
+ ret = read_cgroup_file(cgroup, "io.stat", buf, sizeof(buf));
+ if (ret)
+ return ret;
+ for (linep = strtok_r(buf, "\n", &save); linep;
+ linep = strtok_r(NULL, "\n", &save)) {
+ char *wsave = NULL;
+
+ tok = strtok_r(linep, " \t", &wsave);
+ if (!tok || strcmp(tok, dev))
+ continue;
+ found = 1;
+ while ((word = strtok_r(NULL, " \t", &wsave))) {
+ if (!strncmp(word, "cost.usage=", 11)) {
+ *usage = strtoull(word + 11, NULL, 0);
+ return 0;
+ }
+ }
+ }
+ return found ? -ENOENT : -ENODEV;
+}
+
+/*
+ * Write a line to io.cost.model for dev and return the errno of the write
+ * negated (0 on success), as ASSERT_ERR() expects.
+ */
+static int write_cost_model(const char *dev, const char *what)
+{
+ char buf[128];
+ FILE *fp;
+ int err = 0;
+
+ snprintf(buf, sizeof(buf), "%s %s", dev, what);
+ fp = fopen("/sys/fs/cgroup/io.cost.model", "w");
+ if (!fp)
+ return errno ? -errno : -EACCES;
+ if (fwrite(buf, 1, strlen(buf), fp) != strlen(buf))
+ err = ferror(fp) ? (errno ? -errno : -EIO) : -EIO;
+ if (fclose(fp) && !err)
+ err = -errno;
+ return err;
+}
+
+/*
+ * Attach the example model to the null_blk instance the test creates: the dev
+ * member is written through the struct_ops map's initial value before load,
+ * and attaching the struct_ops attaches the model to the device. Detaching the
+ * struct_ops restores the builtin model.
+ *
+ * Requires root, cgroup v2 and null_blk with configfs support.
+ */
+void serial_test_iocost_model(void)
+{
+ struct iocost_model *skel, *second, *bad;
+ unsigned int maj, min;
+ char buf[4096], qbuf[160], dev2[32];
+ int devfd, i, err, cg;
+ char model[32], dev[32];
+ unsigned long long u1 = 0, u2 = 0;
+
+ if (!iocost_test_env())
+ return;
+ if (!ASSERT_OK(nullb_create(IOCOST_NULLB, dev, sizeof(dev)),
+ "nullb_create"))
+ return;
+ if (sscanf(dev, "%u:%u", &maj, &min) != 2) {
+ ASSERT_TRUE(false, "dev_parse");
+ nullb_remove(IOCOST_NULLB);
+ return;
+ }
+
+ skel = iocost_model__open();
+ if (!ASSERT_OK_PTR(skel, "skel_open")) {
+ nullb_remove(IOCOST_NULLB);
+ return;
+ }
+
+ /*
+ * a model with a zero coefficient must fail to attach instead of
+ * silently zeroing the completion sizing (validate rejects it on
+ * the map update the attach performs; the link form of the
+ * struct_ops only reaches it there)
+ */
+ bad = iocost_model__open();
+ if (!ASSERT_OK_PTR(bad, "bad_open")) {
+ iocost_model__destroy(skel);
+ nullb_remove(IOCOST_NULLB);
+ return;
+ }
+ bad->struct_ops.iocost_2x->dev = (__u32)makedev(maj, min);
+ bad->struct_ops.iocost_2x->write_vtime_per_page = 0;
+ if (ASSERT_OK(iocost_model__load(bad), "bad_load"))
+ ASSERT_EQ(iocost_model__attach(bad), -EINVAL,
+ "attach_rejects_zero_coeff");
+ iocost_model__destroy(bad);
+
+ /* same for the read-side transfer coefficient */
+ bad = iocost_model__open();
+ if (!ASSERT_OK_PTR(bad, "bad_read_open")) {
+ iocost_model__destroy(skel);
+ nullb_remove(IOCOST_NULLB);
+ return;
+ }
+ bad->struct_ops.iocost_2x->dev = (__u32)makedev(maj, min);
+ bad->struct_ops.iocost_2x->read_vtime_per_page = 0;
+ if (ASSERT_OK(iocost_model__load(bad), "bad_read_load"))
+ ASSERT_EQ(iocost_model__attach(bad), -EINVAL,
+ "attach_rejects_zero_read");
+ iocost_model__destroy(bad);
+
+ /* and the upper bound of the transfer coefficient range */
+ bad = iocost_model__open();
+ if (!ASSERT_OK_PTR(bad, "bad_bound_open")) {
+ iocost_model__destroy(skel);
+ nullb_remove(IOCOST_NULLB);
+ return;
+ }
+ bad->struct_ops.iocost_2x->dev = (__u32)makedev(maj, min);
+ bad->struct_ops.iocost_2x->write_vtime_per_page = ~0ULL;
+ if (ASSERT_OK(iocost_model__load(bad), "bad_bound_load"))
+ ASSERT_EQ(iocost_model__attach(bad), -EINVAL,
+ "attach_rejects_upper_bound");
+ iocost_model__destroy(bad);
+
+ skel->struct_ops.iocost_2x->dev = (__u32)makedev(maj, min);
+ /*
+ * cgroup_setup_and_join() creates the priced-IO cgroup with the
+ * available controllers enabled, so the cgroup has
+ * io.weight/io.stat and the iocg activates.
+ * cleanup_cgroup_environment() removes it from every exit path
+ * below. io.cost.qos and io.cost.model are root-only cgroupfs
+ * files: they are written at the hierarchy root and reverted on
+ * exit.
+ */
+ cg = cgroup_setup_and_join("/iocost_pairing");
+ if (!ASSERT_GE(cg, 0, "setup_cg")) {
+ iocost_model__destroy(skel);
+ nullb_remove(IOCOST_NULLB);
+ return;
+ }
+ close(cg);
+ devfd = open_nullb_dev(IOCOST_NULLB, O_RDONLY);
+ if (!ASSERT_GE(devfd, 0, "open_dev")) {
+ cleanup_cgroup_environment();
+ iocost_model__destroy(skel);
+ nullb_remove(IOCOST_NULLB);
+ return;
+ }
+ /* drop stale page cache so that the warm reads issue real bios */
+ (void)posix_fadvise(devfd, 0, 0, POSIX_FADV_DONTNEED);
+ for (i = 0; i < 32; i++)
+ (void)read(devfd, buf, sizeof(buf));
+ close(devfd);
+
+ err = iocost_model__load(skel);
+ if (!ASSERT_OK(err, "skel_load")) {
+ iocost_model__destroy(skel);
+ cleanup_cgroup_environment();
+ nullb_remove(IOCOST_NULLB);
+ return;
+ }
+
+ err = iocost_model__attach(skel);
+ if (ASSERT_OK(err, "attach")) {
+ /*
+ * attached: the read path reports model=bpf until the
+ * struct_ops is detached; ctrl keeps describing the
+ * builtin coefficients
+ */
+ err = readback_model(dev, model, sizeof(model));
+ if (ASSERT_OK(err, "readback"))
+ ASSERT_STREQ(model, "bpf", "model_bpf");
+
+ /* a second model on the same device fails with -EBUSY */
+ second = iocost_model__open();
+ if (ASSERT_OK_PTR(second, "second_open")) {
+ second->struct_ops.iocost_2x->dev =
+ (__u32)makedev(maj, min);
+ err = iocost_model__load(second);
+ if (ASSERT_OK(err, "second_load")) {
+ struct bpf_link *l2;
+
+ /*
+ * the kernel rejects attaching a second
+ * model to the device with EBUSY
+ */
+ l2 = bpf_map__attach_struct_ops(
+ second->maps.iocost_2x);
+ if (!ASSERT_ERR_PTR(l2, "second_ebusy"))
+ bpf_link__destroy(l2);
+ else
+ ASSERT_EQ(libbpf_get_error(l2), -EBUSY,
+ "second_ebusy_errno");
+ }
+ iocost_model__destroy(second);
+ }
+
+ /*
+ * pricing coverage: root cgroup IOs bypass the model, so
+ * move into the pairing cgroup, enable the controller
+ * and verify IOs actually go through calc_cost() and get
+ * charged
+ */
+ ASSERT_OK(join_cgroup("/iocost_pairing"), "join_pairing");
+ snprintf(qbuf, sizeof(qbuf), "%s 1000", dev);
+ ASSERT_OK(write_cgroup_file("/iocost_pairing", "io.weight",
+ qbuf), "weight_pairing");
+ snprintf(qbuf, sizeof(qbuf),
+ "%s enable=1 ctrl=user min=100.00 max=100.00", dev);
+ ASSERT_OK(write_file("/sys/fs/cgroup/io.cost.qos", qbuf),
+ "qos_enable");
+
+ devfd = open_nullb_dev(IOCOST_NULLB, O_RDONLY);
+ if (!ASSERT_GE(devfd, 0, "open_dev_priced")) {
+ iocost_model__destroy(skel);
+ snprintf(qbuf, sizeof(qbuf), "%s enable=0", dev);
+ (void)write_file("/sys/fs/cgroup/io.cost.qos", qbuf);
+ nullb_remove(IOCOST_NULLB);
+ ASSERT_OK(join_root_cgroup(), "join_root_fail");
+ cleanup_cgroup_environment();
+ return;
+ }
+ ASSERT_OK(read_cost_usage("/iocost_pairing",
+ dev, &u1), "cost_usage_pre");
+ /* drop stale page cache so that the reads issue real bios */
+ (void)posix_fadvise(devfd, 0, 0, POSIX_FADV_DONTNEED);
+ for (i = 0; i < 500; i++)
+ (void)read(devfd, buf, sizeof(buf));
+ close(devfd);
+ ASSERT_GT(skel->bss->calc_costs, 0, "model_priced");
+ /*
+ * the usage stat is flushed by the iocost timer, give
+ * the current period a chance to end before reading
+ */
+ sleep(3);
+ ASSERT_OK(read_cost_usage("/iocost_pairing",
+ dev, &u2), "cost_usage_post");
+ ASSERT_GT(u2, u1, "cost_charged");
+ ASSERT_GT(skel->bss->ioc_ticks, 0, "tick_seen");
+
+ /*
+ * a second device is independent: enabling it shows
+ * the builtin model, not the one attached to the
+ * first
+ */
+ if (ASSERT_OK(nullb_create(IOCOST_NULLB2, dev2,
+ sizeof(dev2)), "nullb_create2")) {
+ snprintf(qbuf, sizeof(qbuf),
+ "%s enable=1 ctrl=auto", dev2);
+ ASSERT_OK(write_file(
+ "/sys/fs/cgroup/io.cost.qos", qbuf),
+ "qos_nullb2");
+ err = readback_model(dev2, model, sizeof(model));
+ if (ASSERT_OK(err, "readback_nullb2"))
+ ASSERT_STREQ(model, "linear",
+ "model_linear_nullb2");
+ snprintf(qbuf, sizeof(qbuf), "%s enable=0", dev2);
+ ASSERT_OK(write_file(
+ "/sys/fs/cgroup/io.cost.qos", qbuf),
+ "qos_nullb2_off");
+ }
+ nullb_remove(IOCOST_NULLB2);
+
+ /*
+ * attachment and model selection are independent:
+ * ctrl=bpf is never accepted, model=linear switches
+ * back to the builtin without detaching, model=bpf
+ * switches to the attached model again
+ */
+ err = write_cost_model(dev, "ctrl=bpf");
+ ASSERT_ERR(err, "ctrl_bpf_rejected");
+
+ err = write_cost_model(dev, "model=linear");
+ ASSERT_OK(err, "model_linear_write");
+ err = readback_model(dev, model, sizeof(model));
+ if (ASSERT_OK(err, "readback_linear"))
+ ASSERT_STREQ(model, "linear", "model_linear");
+
+ /* still attached: the switch must not free the slot */
+ second = iocost_model__open();
+ if (ASSERT_OK_PTR(second, "second_open2")) {
+ second->struct_ops.iocost_2x->dev =
+ (__u32)makedev(maj, min);
+ err = iocost_model__load(second);
+ if (ASSERT_OK(err, "second_load2")) {
+ struct bpf_link *l2;
+
+ l2 = bpf_map__attach_struct_ops(
+ second->maps.iocost_2x);
+ if (!ASSERT_ERR_PTR(l2, "second_ebusy2"))
+ bpf_link__destroy(l2);
+ else
+ ASSERT_EQ(libbpf_get_error(l2), -EBUSY,
+ "second_ebusy2_errno");
+ }
+ iocost_model__destroy(second);
+ }
+
+ /* still attached: switching back to the model works */
+ err = write_cost_model(dev, "model=bpf");
+ ASSERT_OK(err, "model_bpf_write");
+ err = readback_model(dev, model, sizeof(model));
+ if (ASSERT_OK(err, "readback_bpf"))
+ ASSERT_STREQ(model, "bpf", "model_bpf");
+
+ bpf_link__destroy(skel->links.iocost_2x);
+ skel->links.iocost_2x = NULL;
+
+ /* after detach, model=bpf fails: nothing is attached */
+ err = write_cost_model(dev, "model=bpf");
+ ASSERT_ERR(err, "model_bpf_after_detach");
+
+ err = readback_model(dev, model, sizeof(model));
+ if (ASSERT_OK(err, "readback_after_detach"))
+ ASSERT_STREQ(model, "linear", "model_linear");
+
+ }
+
+ iocost_model__destroy(skel);
+ snprintf(qbuf, sizeof(qbuf), "%s enable=0", dev);
+ (void)write_file("/sys/fs/cgroup/io.cost.qos", qbuf);
+ nullb_remove(IOCOST_NULLB);
+ ASSERT_OK(join_root_cgroup(), "procs_back");
+ cleanup_cgroup_environment();
+}
+/*
+ * Same check for the multi-stream example model. Only one model can be
+ * attached to a device at a time and the tests run serially: they reuse
+ * the same configfs instance name (with stale instances torn down on
+ * entry) except for the removal test, which uses a second device.
+ */
+void serial_test_iocost_model_streams(void)
+{
+ struct iocost_ms *skel;
+ unsigned int maj, min;
+ int devfd, i, err, cg;
+ char model[32], dev[32], qbuf[160];
+
+ if (!iocost_test_env())
+ return;
+ if (!ASSERT_OK(nullb_create(IOCOST_NULLB, dev, sizeof(dev)),
+ "nullb_create"))
+ return;
+ if (sscanf(dev, "%u:%u", &maj, &min) != 2) {
+ ASSERT_TRUE(false, "dev_parse");
+ nullb_remove(IOCOST_NULLB);
+ return;
+ }
+
+ skel = iocost_ms__open();
+ if (!ASSERT_OK_PTR(skel, "skel_open")) {
+ nullb_remove(IOCOST_NULLB);
+ return;
+ }
+
+ skel->struct_ops.iocost_ms->dev = (__u32)makedev(maj, min);
+
+ err = iocost_ms__load(skel);
+ if (!ASSERT_OK(err, "skel_load")) {
+ iocost_ms__destroy(skel);
+ nullb_remove(IOCOST_NULLB);
+ return;
+ }
+
+ err = iocost_ms__attach(skel);
+ if (ASSERT_OK(err, "attach")) {
+ err = readback_model(dev, model, sizeof(model));
+ if (ASSERT_OK(err, "readback"))
+ ASSERT_STREQ(model, "bpf", "model_bpf");
+
+ /*
+ * drive IO through the model: enable the controller, price
+ * from a cgroup, and check the model actually charged them
+ */
+ cg = cgroup_setup_and_join("/iocost_ms");
+ if (!ASSERT_GE(cg, 0, "setup_cg_ms")) {
+ iocost_ms__destroy(skel);
+ nullb_remove(IOCOST_NULLB);
+ cleanup_cgroup_environment();
+ return;
+ }
+ close(cg);
+ snprintf(qbuf, sizeof(qbuf), "%s 1000", dev);
+ ASSERT_OK(write_cgroup_file("/iocost_ms", "io.weight", qbuf),
+ "weight_ms");
+ snprintf(qbuf, sizeof(qbuf),
+ "%s enable=1 ctrl=user min=100.00 max=100.00", dev);
+ ASSERT_OK(write_file("/sys/fs/cgroup/io.cost.qos", qbuf),
+ "qos_enable");
+ devfd = open_nullb_dev(IOCOST_NULLB, O_RDONLY | O_DIRECT);
+ if (ASSERT_GE(devfd, 0, "open_dev_ms")) {
+ void *iobuf = NULL;
+ unsigned long long u1 = 0, u2 = 0;
+ __u64 seq0, rand0;
+
+ /*
+ * O_DIRECT so every read issues real bios: cached
+ * reads would never reach iocost_ms_calc_cost().
+ */
+ if (!ASSERT_OK(posix_memalign(&iobuf, 4096, 4096),
+ "memalign_iobuf")) {
+ printf("%s:SKIP:cannot allocate the aligned IO buffer\n",
+ __func__);
+ test__skip();
+ } else {
+ ASSERT_OK(read_cost_usage("/iocost_ms",
+ dev, &u1), "cost_usage_pre");
+ for (i = 0; i < 500; i++)
+ (void)read(devfd, iobuf, 4096);
+ /*
+ * Two interleaved sequential streams: exercise
+ * the stream table, not just a single cursor.
+ * Snapshot the decision counters first: the
+ * single-stream loop above already moved both
+ * off zero, so the assertions must cover this
+ * phase alone.
+ */
+ seq0 = skel->bss->seq_hits;
+ rand0 = skel->bss->rand_allocs;
+ for (i = 0; i < 200; i++) {
+ (void)pread(devfd, iobuf, 4096,
+ (i + 1) * 4096);
+ (void)pread(devfd, iobuf, 4096,
+ (1 << 20) +
+ (i + 1) * 4096);
+ }
+ free(iobuf);
+ sleep(3);
+ ASSERT_OK(read_cost_usage("/iocost_ms",
+ dev, &u2), "cost_usage_post");
+ ASSERT_GT(u2, u1, "ms_cost_charged");
+ ASSERT_GT(skel->bss->calc_costs, 0,
+ "ms_model_priced");
+ /*
+ * the interleaved pattern must exercise
+ * both stream-table decisions: regressions
+ * that price everything as one class leave
+ * one counter at its snapshot
+ */
+ ASSERT_GT(skel->bss->seq_hits, seq0,
+ "ms_stream_seq");
+ ASSERT_GT(skel->bss->rand_allocs, rand0,
+ "ms_stream_rand");
+ }
+ close(devfd);
+ }
+ ASSERT_OK(join_root_cgroup(), "procs_back");
+ snprintf(qbuf, sizeof(qbuf), "%s enable=0", dev);
+ (void)write_file("/sys/fs/cgroup/io.cost.qos", qbuf);
+ bpf_link__destroy(skel->links.iocost_ms);
+ skel->links.iocost_ms = NULL;
+
+ err = readback_model(dev, model, sizeof(model));
+ if (ASSERT_OK(err, "readback_after_detach"))
+ ASSERT_STREQ(model, "linear", "model_linear");
+
+ cleanup_cgroup_environment();
+ }
+
+ iocost_ms__destroy(skel);
+ nullb_remove(IOCOST_NULLB);
+}
+
+/*
+ * Removal of the device while a model is attached: the test builds
+ * its own null_blk instance through configfs like the other tests,
+ * attaches to it, then removes the device out from under the model.
+ * The ejection must drop the device from the cgroup interface,
+ * down, and a recreated device must be attachable again.
+ */
+void serial_test_iocost_model_removal(void)
+{
+ struct iocost_model *skel, *skel2;
+ unsigned int maj, min;
+ char dev[32], model[32];
+ int err;
+
+ if (!iocost_test_env())
+ return;
+
+ skel = iocost_model__open();
+ if (!ASSERT_OK_PTR(skel, "skel_open"))
+ return;
+
+ err = nullb_create("iocost_removal", dev, sizeof(dev));
+ if (!ASSERT_OK(err, "nullb_create"))
+ goto out;
+ if (sscanf(dev, "%u:%u", &maj, &min) != 2) {
+ ASSERT_TRUE(false, "dev_parse");
+ goto out;
+ }
+
+ skel->struct_ops.iocost_2x->dev = (__u32)makedev(maj, min);
+ err = iocost_model__load(skel);
+ if (!ASSERT_OK(err, "skel_load"))
+ goto out;
+
+ err = iocost_model__attach(skel);
+ if (!ASSERT_OK(err, "attach"))
+ goto out;
+
+ err = readback_model(dev, model, sizeof(model));
+ if (ASSERT_OK(err, "readback"))
+ ASSERT_STREQ(model, "bpf", "model_bpf");
+
+ /* remove the device out from under the attached model */
+ if (!ASSERT_OK(nullb_remove("iocost_removal"), "nullb_remove"))
+ goto detach;
+
+ /* the ejection drops the device from the cgroup files */
+ err = readback_model(dev, model, sizeof(model));
+ ASSERT_ERR(err, "readback_after_removal");
+
+ err = write_cost_model(dev, "model=bpf");
+ ASSERT_ERR(err, "model_bpf_after_removal");
+
+detach:
+ /*
+ * detaching after the device is gone must be a clean no-op;
+ * this exercises the eject-then-detach ordering in the kernel
+ */
+ bpf_link__destroy(skel->links.iocost_2x);
+ skel->links.iocost_2x = NULL;
+
+ /* the same attach and detach against a recreated device */
+ skel2 = iocost_model__open();
+ if (!ASSERT_OK_PTR(skel2, "skel2_open"))
+ goto out;
+
+ err = nullb_create("iocost_removal", dev, sizeof(dev));
+ if (!ASSERT_OK(err, "nullb_create_again"))
+ goto out2;
+ if (sscanf(dev, "%u:%u", &maj, &min) != 2) {
+ ASSERT_TRUE(false, "dev_parse_again");
+ goto out2;
+ }
+
+ skel2->struct_ops.iocost_2x->dev = (__u32)makedev(maj, min);
+ err = iocost_model__load(skel2);
+ if (!ASSERT_OK(err, "skel2_load"))
+ goto out2;
+
+ 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");
+
+ 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");
+
+out2:
+ iocost_model__destroy(skel2);
+out:
+ nullb_remove("iocost_removal");
+ iocost_model__destroy(skel);
+}
diff --git a/tools/testing/selftests/bpf/progs/iocost_model.c b/tools/testing/selftests/bpf/progs/iocost_model.c
new file mode 100644
index 000000000000..68b459404fbd
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/iocost_model.c
@@ -0,0 +1,189 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (C) 2026 KylinSoft Corporation. */
+/*
+ * Example iocost cost model: the builtin linear HDD formula with all costs
+ * doubled, for one device given by the dev member of the struct_ops.
+ *
+ * The constants mirror what calc_lcoefs() derives from the AUTOP_HDD defaults
+ * (rbps=174019176 rseqiops=41708 rrandiops=370, w-side analog) in vtime units
+ * where 1s == 2^37. On a rotational device still on ctrl=auto, a device with
+ * this model attached charges twice the builtin model under the same
+ * read/write workload (the builtin prices flushes as zero and adds a fixed
+ * flush term to data-bearing preflushes and to FUA writes on devices without
+ * native FUA support, which this model omits; this model prices flushes as
+ * one-page writes). The tests assert that charges flow through this model
+ * while it is attached, not the charge ratio to the builtin one; on a
+ * non-rotational device, or one with user-pinned coefficients, the ratio
+ * is arbitrary.
+ *
+ * The cursor handling follows the builtin: a zero cursor means "no previous
+ * IO", and the cursor is advanced for the bios the builtin prices
+ * (READ/WRITE/ZONE_APPEND with a non-zero size), so flushes and discards leave
+ * it alone and long merged streams do not drift past the 16MB seek threshold.
+ * One known deviation, mispricing only: the builtin does not move its cursor
+ * for an IO whose cgroup fails to activate; this model does not see the
+ * activation result.
+ *
+ * The model implements the full linear formula itself, including flushes:
+ * there is no fallback to the builtin model, which prices a dataless
+ * WRITE|REQ_PREFLUSH as zero unless flushiops is configured; this model prices
+ * it as a one-page sequential write. What a flush actually costs depends on
+ * the IOs before it, which a static formula cannot express; pricing it as a
+ * small constant is a crude penalty for unnecessarily frequent flushes, and a
+ * stateful model would be the way to do better. Discards and other unpriced
+ * operations pass through at zero cost, like the builtin.
+ */
+
+#include "vmlinux.h"
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+
+/*
+ * VTIME_PER_SEC, IOC_PAGE_SIZE/SHIFT, IOC_SECT_TO_PAGE_SHIFT,
+ * LCOEF_RANDIO_PAGES (the 16MB seek threshold) and IOCOST_CALC_MERGE
+ * come from vmlinux.h (BTF constants; the enum64 ones need pahole
+ * >= 1.23 to be emitted)
+ */
+#define IOCOST_REQ_OP_MASK 0xff /* REQ_OP_MASK, not in BTF */
+
+/*
+ * DIV64_U64_ROUND_UP / DIV_ROUND_UP_ULL equivalents, folded at
+ * compile time
+ */
+#define RU(x, y) ((x) / (y) + (((x) % (y)) ? 1 : 0))
+
+#define RBPS 174019176ULL
+#define RSEQIOPS 41708ULL
+#define RRANDIOPS 370ULL
+#define WBPS 178075866ULL
+#define WSEQIOPS 42705ULL
+#define WRANDIOPS 378ULL
+
+#define RPAGE (RU(VTIME_PER_SEC, RU(RBPS, IOC_PAGE_SIZE)))
+#define RSEQIO (RU(VTIME_PER_SEC, RSEQIOPS) - RPAGE)
+#define RRANDIO (RU(VTIME_PER_SEC, RRANDIOPS) - RPAGE)
+#define WPAGE (RU(VTIME_PER_SEC, RU(WBPS, IOC_PAGE_SIZE)))
+#define WSEQIO (RU(VTIME_PER_SEC, WSEQIOPS) - WPAGE)
+#define WRANDIO (RU(VTIME_PER_SEC, WRANDIOPS) - WPAGE)
+
+/*
+ * per-cgroup cursor storage: keyed by the cgroup and freed with it,
+ * so a cgroup that comes back starts with no cursor. A struct_ops
+ * map attaches to at most one device (a second attach to the same
+ * device fails with -EBUSY), and this example uses one map, so
+ * per-cgroup keys are per (cgroup, device) in effect
+ */
+struct {
+ __uint(type, BPF_MAP_TYPE_CGRP_STORAGE);
+ __uint(map_flags, BPF_F_NO_PREALLOC);
+ __type(key, int);
+ __type(value, __u64);
+} cursor_store SEC(".maps");
+
+/*
+ * incremented by calc_cost(): the test asserts pricing went
+ * through the model while it is attached and the controller is
+ * enabled
+ */
+__u64 calc_costs;
+
+/* counts iocost_ioc_tick emissions observed from BPF side */
+__u64 ioc_ticks;
+
+SEC("struct_ops")
+u64 BPF_PROG(iocost_2x_calc_cost, struct bio *bio, u64 calc_flags)
+{
+ u64 opf = bio->bi_opf, nbytes = bio->bi_iter.bi_size;
+ u64 sector = bio->bi_iter.bi_sector;
+ struct blkcg *blkcg = bio->bi_blkg->blkcg;
+ u64 pages, seek_pages = 0, base, coef_page, randio, cost;
+ __u64 *cursor, cur;
+
+ calc_costs++;
+
+ /* builtin truncates: max(sectors >> IOC_SECT_TO_PAGE_SHIFT, 1) */
+ pages = nbytes >> IOC_PAGE_SHIFT;
+ if (!pages)
+ pages = 1;
+
+ if ((opf & IOCOST_REQ_OP_MASK) == REQ_OP_READ) {
+ base = RSEQIO; coef_page = RPAGE; randio = RRANDIO;
+ } else if ((opf & IOCOST_REQ_OP_MASK) == REQ_OP_WRITE ||
+ (opf & IOCOST_REQ_OP_MASK) == REQ_OP_ZONE_APPEND) {
+ base = WSEQIO; coef_page = WPAGE; randio = WRANDIO;
+ } else {
+ /*
+ * the builtin prices other operations at zero and
+ * leaves them unthrottled; pass them through the same
+ * way instead of inventing costs
+ */
+ return 0;
+ }
+
+ /* mirror the builtin cursor semantics described above */
+ cursor = bpf_cgrp_storage_get(&cursor_store,
+ blkcg->css.cgroup, NULL,
+ BPF_LOCAL_STORAGE_GET_F_CREATE);
+ if (!cursor) {
+ /*
+ * the cursor table is unavailable (storage lookup
+ * failure): fall back to unconditional sequential
+ * pricing without the randio determination; a known
+ * deviation, mispricing only and unreachable short of
+ * a storage allocation failure
+ */
+ if (calc_flags & IOCOST_CALC_MERGE)
+ base = 0;
+ return 2 * (base + pages * coef_page);
+ }
+ cur = *cursor;
+ /*
+ * a size-zero IO never moves the cursor, so it must not be
+ * judged against it either; the builtin skips it entirely,
+ * this model prices it as a one-page sequential write
+ */
+ if (cur && nbytes) {
+ seek_pages = sector > cur ? sector - cur
+ : cur - sector;
+ seek_pages >>= IOC_SECT_TO_PAGE_SHIFT;
+ if (seek_pages > LCOEF_RANDIO_PAGES)
+ base = randio;
+ }
+ /*
+ * the builtin moves the cursor unconditionally on submit, but
+ * on a merge only when the merged request ends at the cursor,
+ * a test on the request extent that both merge directions can
+ * satisfy; this model advances only when the merged bio itself
+ * starts right at the cursor, so the two can disagree on a
+ * front merge, a known deviation, mispricing only. a zero
+ * cursor means no history so it never matches
+ */
+ if (nbytes &&
+ (!(calc_flags & IOCOST_CALC_MERGE) || (cur && cur == sector)))
+ *cursor = sector + (nbytes >> 9);
+
+ if (calc_flags & IOCOST_CALC_MERGE)
+ base = 0;
+
+ cost = 2 * (base + pages * coef_page);
+ return cost;
+}
+
+/* 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;
+}
+
+SEC(".struct_ops.link") /* detach on close */
+struct iocost_model_ops iocost_2x = {
+ .read_vtime_per_page = 2 * RPAGE,
+ .write_vtime_per_page = 2 * WPAGE,
+ .name = "iocost_2x",
+ .calc_cost = (void *)iocost_2x_calc_cost,
+};
+
+char LICENSE[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/progs/iocost_ms.c b/tools/testing/selftests/bpf/progs/iocost_ms.c
new file mode 100644
index 000000000000..bfa6f79003d3
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/iocost_ms.c
@@ -0,0 +1,206 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (C) 2026 KylinSoft Corporation. */
+/*
+ * Example multi-stream sequentiality detection cost model.
+ *
+ * The builtin model keeps a single cursor per cgroup, so two interleaved
+ * sequential readers in one cgroup are all priced random (measured 89x
+ * overcharge, 12.9x throughput collapse), while random IO inside a hot window
+ * smaller than the 16MB seek threshold is priced sequential (measured 107x
+ * undercharge). This model replaces the single cursor with a per-cgroup table
+ * of stream slots: an IO is sequential iff its sector matches the expected
+ * next sector of any tracked stream. Interleaved streams keep their own slots,
+ * and windowed random IO rarely matches a moving expectation.
+ *
+ * Stream state lives in a CGRP_STORAGE map, so it is created and freed with
+ * the cgroup. The model implements the builtin linear formula itself; unlike
+ * the builtin it has no flush term, so preflushed IOs are priced as plain
+ * writes (mispricing only, the test never issues flushes). A
+ * struct_ops map attaches to at most one device (a second attach
+ * to the same device fails with -EBUSY), and this example uses one
+ * map, so the per-cgroup keys are per (cgroup, device) in effect.
+ * Two more known deviations:
+ * a flush-flagged size-zero WRITE is priced as a one-page
+ * sequential write
+ * (the builtin prices it zero at flushiops=0), and discards do not
+ * advance the stream expectation; the builtin cursor does not move
+ * for them either.
+ */
+#include "vmlinux.h"
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+
+/*
+ * VTIME_PER_SEC, IOC_PAGE_SIZE/SHIFT, IOC_SECT_TO_PAGE_SHIFT and
+ * IOCOST_CALC_MERGE comes from vmlinux.h (BTF enum constants)
+ */
+#define IOCOST_REQ_OP_MASK 0xff /* REQ_OP_MASK, not in BTF */
+
+/*
+ * DIV64_U64_ROUND_UP / DIV_ROUND_UP_ULL equivalents, folded at
+ * compile time
+ */
+#define RU(x, y) ((x) / (y) + (((x) % (y)) ? 1 : 0))
+
+#define RBPS 174019176ULL
+#define RSEQIOPS 41708ULL
+#define RRANDIOPS 370ULL
+#define WBPS 178075866ULL
+#define WSEQIOPS 42705ULL
+#define WRANDIOPS 378ULL
+
+#define RPAGE (RU(VTIME_PER_SEC, RU(RBPS, IOC_PAGE_SIZE)))
+#define RSEQIO (RU(VTIME_PER_SEC, RSEQIOPS) - RPAGE)
+#define RRANDIO (RU(VTIME_PER_SEC, RRANDIOPS) - RPAGE)
+#define WPAGE (RU(VTIME_PER_SEC, RU(WBPS, IOC_PAGE_SIZE)))
+#define WSEQIO (RU(VTIME_PER_SEC, WSEQIOPS) - WPAGE)
+#define WRANDIO (RU(VTIME_PER_SEC, WRANDIOPS) - WPAGE)
+
+#define NSLOTS 4
+
+struct streams {
+ __u64 expected[NSLOTS]; /* next expected sector, per stream */
+ __u64 stamp[NSLOTS]; /* LRU stamp, 0 = empty */
+};
+
+/*
+ * per-cgroup stream table: keyed by the cgroup, freed with it
+ */
+struct {
+ __uint(type, BPF_MAP_TYPE_CGRP_STORAGE);
+ __uint(map_flags, BPF_F_NO_PREALLOC);
+ __type(key, int);
+ __type(value, struct streams);
+} stream_tab SEC(".maps");
+
+/*
+ * incremented by calc_cost(): the streams test asserts pricing went
+ * through the model while it is attached
+ */
+__u64 calc_costs;
+
+/*
+ * stream-table decisions: the streams test asserts both classes occur,
+ * so the interleaved-stream pattern really exercises the table instead
+ * of collapsing to a single behavior
+ */
+__u64 seq_hits;
+__u64 rand_allocs;
+
+SEC("struct_ops")
+u64 BPF_PROG(iocost_ms_calc_cost, struct bio *bio, u64 calc_flags)
+{
+ u64 opf = bio->bi_opf, nbytes = bio->bi_iter.bi_size;
+ u64 sector = bio->bi_iter.bi_sector;
+ struct blkcg *blkcg = bio->bi_blkg->blkcg;
+ struct streams *s;
+ u64 pages, base, coef_page, randio, advance, now;
+ u32 i, victim = 0, found = 0xFFFFFFFF;
+
+ calc_costs++;
+
+ if ((opf & IOCOST_REQ_OP_MASK) == REQ_OP_READ) {
+ base = RSEQIO; coef_page = RPAGE; randio = RRANDIO;
+ } else if ((opf & IOCOST_REQ_OP_MASK) == REQ_OP_WRITE ||
+ (opf & IOCOST_REQ_OP_MASK) == REQ_OP_ZONE_APPEND) {
+ base = WSEQIO; coef_page = WPAGE; randio = WRANDIO;
+ } else {
+ /*
+ * the builtin prices other operations at zero and
+ * leaves them unthrottled; pass them through the same
+ * way instead of inventing costs
+ */
+ return 0;
+ }
+ advance = nbytes >> 9; /* sectors, truncated like the builtin */
+
+ /*
+ * only sized bios participate in stream tracking; the early
+ * return below skips the merge discount, which only applies
+ * to tracked data bios
+ */
+ if (!nbytes) {
+ pages = nbytes >> IOC_PAGE_SHIFT;
+ if (!pages)
+ pages = 1;
+ return base + pages * coef_page;
+ }
+
+ s = bpf_cgrp_storage_get(&stream_tab, blkcg->css.cgroup, NULL,
+ BPF_LOCAL_STORAGE_GET_F_CREATE);
+ if (!s) {
+ /*
+ * no storage: price per page, truncating like the
+ * builtin; merges skip the base like the main path
+ */
+ if (calc_flags & IOCOST_CALC_MERGE)
+ base = 0;
+ pages = nbytes >> IOC_PAGE_SHIFT;
+ if (!pages)
+ pages = 1;
+ return base + pages * coef_page;
+ }
+
+ /*
+ * Slot access is lockless, mirroring the builtin single-cursor
+ * update in ioc_rqos_throttle(): concurrent CPUs submitting for
+ * the same cgroup can race on slot updates; mispricing is
+ * bounded and acceptable for an example model.
+ */
+ now = bpf_ktime_get_ns();
+ for (i = 0; i < NSLOTS; i++) {
+ if (s->expected[i] == sector && s->stamp[i]) {
+ found = i;
+ break;
+ }
+ }
+ if (found != 0xFFFFFFFF) {
+ /* sequential: keep the seq base from the op branch */
+ seq_hits++;
+ s->expected[found] = sector + advance;
+ s->stamp[found] = now;
+ } else {
+ /*
+ * a merge which matches no slot is not a new stream:
+ * replacing a slot could evict a live stream, so merged
+ * bios are priced without touching the table (and skip
+ * the base cost below)
+ */
+ if (!(calc_flags & IOCOST_CALC_MERGE)) {
+ rand_allocs++;
+ base = randio;
+ for (i = 1; i < NSLOTS; i++) {
+ if (s->stamp[i] < s->stamp[victim])
+ victim = i;
+ }
+ s->expected[victim] = sector + advance;
+ s->stamp[victim] = now;
+ }
+ }
+
+ /* builtin truncates: max(sectors >> IOC_SECT_TO_PAGE_SHIFT, 1) */
+ pages = nbytes >> IOC_PAGE_SHIFT;
+ if (!pages)
+ pages = 1;
+ if (calc_flags & IOCOST_CALC_MERGE) {
+ /*
+ * merged bios skip the base cost but still advance
+ * the stream position above, so a merge at the
+ * expected sector does not make the following new IO
+ * look random
+ */
+ base = 0;
+ }
+
+ return base + pages * coef_page;
+}
+
+SEC(".struct_ops.link") /* detach on close */
+struct iocost_model_ops iocost_ms = {
+ .read_vtime_per_page = RPAGE,
+ .write_vtime_per_page = WPAGE,
+ .name = "iocost_ms",
+ .calc_cost = (void *)iocost_ms_calc_cost,
+};
+
+char LICENSE[] SEC("license") = "GPL";
--
2.43.0
^ permalink raw reply related [flat|nested] 7+ messages in thread