AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/09/20 09:39 flow patch-triage
2m Args:
null

Results:
{
  "EnableConfigs": [
    "BLK_CGROUP_IOCOST_BPF",
    "BLK_CGROUP_IOCOST",
    "BLK_CGROUP",
    "BPF_SYSCALL",
    "BPF_JIT",
    "DEBUG_INFO_BTF"
  ],
  "FocusSymbols": [
    "ioc_cost_model_write",
    "iocost_bpf_model_get",
    "iocost_bpf_model_put",
    "bpf_iocost_reg",
    "bpf_iocost_unreg",
    "bpf_iocost_validate",
    "calc_vtime_cost",
    "calc_size_vtime_cost",
    "iocost_notify_blkcg_online",
    "iocost_notify_blkcg_offline"
  ],
  "KMSANReasoning": "The patch introduces BPF struct_ops support (`iocost_model_ops`) for the block iocost controller, allowing BPF programs to provide custom cost models bound to devices via cgroup v2 `io.cost.model`. It also introduces lifecycle notifications (`blkcg_online`/`blkcg_offline`) and a new tracepoint (`iocost_ioc_tick`).\n\nAnalysis of uninitialized memory risks:\n1. All heap allocations (specifically `struct iocost_bpf_model`) use `kzalloc_obj`, ensuring zero-initialization.\n2. String buffers on the stack (such as `bpf_model` in `ioc_cost_model_write`) are properly initialized and bounded using `strscpy`, `match_strlcpy`, and `bpf_obj_name_cpy` (which memsets the target buffer to zero before copying).\n3. The new tracepoint `trace_iocost_ioc_tick` explicitly snapshots all variables (`tick_period_us`, `tick_vrate`, `tick_busy`, `tick_running`, `tick_dur`) and assigns each field in `TP_fast_assign`.\n4. Kernel-to-userspace data flow occurs only through text formatting via `seq_printf` in `ioc_cost_model_prfill`; no binary structures or padded buffers are copied to user space.\n\nKASAN vs KMSAN applicability:\nAny potential risks introduced by this change involve concurrency, lock ordering (between `ioc-\u003elock` and `iocost_bpf_reg_lock`), RCU synchronization, and reference count management (`refcount_t`, `bpf_struct_ops_get`/`put`), which could manifest as use-after-free, double-free, or deadlocks. These bugs are fully covered by standard debugging tools (KASAN, LOCKDEP, and refcount checks). There is no risk of uninitialized memory reads or information leaks that would uniquely require KMSAN. Therefore, running a dedicated KMSAN session is not justified.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch introduces pluggable BPF struct_ops cost model support (iocost_model_ops) for the cgroup iocost controller, bound via cgroup v2's io.cost.model interface. It modifies core block cgroup and iocost pricing logic, introduces complex refcounting and lifecycle state machines between BPF struct_ops map/link lifetime and bound block devices, hooks into blkcg css online/offline callbacks, and accesses the BPF model under RCU during I/O dispatch. This code is fully reachable in standard virtualized environments via BPF and cgroup syscalls and warrants fuzzing for concurrency, refcounting, and synchronization issues.",
  "WorthFuzzing": true
}

1/1 2026/09/20 09:39 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit 8b534faffc0c4eb3a498186f6484e9fc42190b59\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Sun Sep 20 09:39:48 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/Documentation/admin-guide/cgroup-v2.rst b/Documentation/admin-guide/cgroup-v2.rst\nindex 8d2603751c51a..d9d82559e2bc6 100644\n--- a/Documentation/admin-guide/cgroup-v2.rst\n+++ b/Documentation/admin-guide/cgroup-v2.rst\n@@ -2115,8 +2115,10 @@ IO Interface Files\n \tare defined.\n \n \t  =====\t\t================================\n-\t  ctrl\t\t\"auto\" or \"user\"\n+\t  ctrl\t\t\"auto\", \"user\" or \"bpf\"\n \t  model\t\tThe cost model in use - \"linear\"\n+\t\t\tor the name of the bound\n+\t\t\tmodel\n \t  =====\t\t================================\n \n \tWhen \"ctrl\" is \"auto\", the kernel may change all parameters\n@@ -2124,6 +2126,23 @@ IO Interface Files\n \tparameters are written to, \"ctrl\" become \"user\" and the\n \tautomatic changes are disabled.\n \n+\tWhen CONFIG_BLK_CGROUP_IOCOST_BPF is enabled, a bound model is\n+\tread back as \"ctrl=bpf model=\u003cname\u003e\", and writing \"ctrl=bpf\" is\n+\taccepted as a no-op so a saved configuration can be restored as-is.\n+\t\"model\" also accepts\n+\tthe name of a registered iocost_model_ops BPF struct_ops model:\n+\t\"model=\u003cname\u003e\" binds the model to the device and the model fully\n+\treplaces the builtin linear pricing, for every operation including\n+\tflushes; \"model=linear\" (or \"ctrl=auto/user\") restores the builtin\n+\tmodel.  Writing an unknown name fails with ENOENT and nothing is\n+\tapplied.  Unregistering a model removes its name from the\n+\tregistry; devices already bound keep using it, and keep receiving\n+\tcgroup lifecycle notifications, until switched back to the builtin\n+\tmodel, and its name keeps working for writes (so a coefficient-only\n+\twrite does not disturb the binding) until the last device unbinds.\n+\tSee\n+\tinclude/linux/blk-iocost.h for the model interface.\n+\n \tWhen \"model\" is \"linear\", the following model parameters are\n \tdefined.\n \ndiff --git a/block/Kconfig b/block/Kconfig\nindex 70e4a66d941ff..91e808f86d28d 100644\n--- a/block/Kconfig\n+++ b/block/Kconfig\n@@ -231,4 +231,13 @@ config BLK_ERROR_INJECTION\n \n source \"block/Kconfig.iosched\"\n \n+config BLK_CGROUP_IOCOST_BPF\n+\tbool \"Enable BPF pluggable cost model support for the cost IO controller\"\n+\tdepends on BLK_CGROUP_IOCOST \u0026\u0026 BPF_SYSCALL \u0026\u0026 BPF_JIT \u0026\u0026 DEBUG_INFO_BTF\n+\thelp\n+\t Enabling this option registers the \"iocost_model_ops\" BPF\n+\t struct_ops type, which allows a BPF program to fully replace\n+\t the builtin linear cost model on a device it is bound to\n+\t through io.cost.model.\n+\n endif # BLOCK\ndiff --git a/block/Makefile b/block/Makefile\nindex e7bd320e3d697..ee5cebeea006f 100644\n--- a/block/Makefile\n+++ b/block/Makefile\n@@ -39,3 +39,4 @@ obj-$(CONFIG_BLK_INLINE_ENCRYPTION)\t+= blk-crypto.o blk-crypto-profile.o \\\n \t\t\t\t\t   blk-crypto-sysfs.o\n obj-$(CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK)\t+= blk-crypto-fallback.o\n obj-$(CONFIG_BLOCK_HOLDER_DEPRECATED)\t+= holder.o\n+obj-$(CONFIG_BLK_CGROUP_IOCOST_BPF)\t+= blk-iocost-bpf.o\ndiff --git a/block/blk-cgroup.c b/block/blk-cgroup.c\nindex b56db1cc6778f..b08ceb94a281b 100644\n--- a/block/blk-cgroup.c\n+++ b/block/blk-cgroup.c\n@@ -32,6 +32,7 @@\n #include \u003clinux/part_stat.h\u003e\n #include \"blk.h\"\n #include \"blk-cgroup.h\"\n+#include \u003clinux/blk-iocost.h\u003e\n #include \"blk-ioprio.h\"\n #include \"blk-throttle.h\"\n \n@@ -1341,6 +1342,7 @@ void blkcg_unpin_online(struct cgroup_subsys_state *blkcg_css)\n  */\n static void blkcg_css_offline(struct cgroup_subsys_state *css)\n {\n+\tiocost_notify_blkcg_offline(css_to_blkcg(css));\n \t/* this prevents anyone from attaching or migrating to this blkcg */\n \twb_blkcg_offline(css);\n \n@@ -1447,6 +1449,8 @@ static int blkcg_css_online(struct cgroup_subsys_state *css)\n {\n \tstruct blkcg *parent = blkcg_parent(css_to_blkcg(css));\n \n+\tiocost_notify_blkcg_online(css_to_blkcg(css));\n+\n \t/*\n \t * blkcg_pin_online() is used to delay blkcg offline so that blkgs\n \t * don't go offline while cgwbs are still active on them.  Pin the\ndiff --git a/block/blk-iocost-bpf.c b/block/blk-iocost-bpf.c\nnew file mode 100644\nindex 0000000000000..444ca52ed0b08\n--- /dev/null\n+++ b/block/blk-iocost-bpf.c\n@@ -0,0 +1,321 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/*\n+ * blk-iocost: BPF struct_ops plumbing for pluggable cost models.\n+ *\n+ * Registers the \"iocost_model_ops\" struct_ops type and maintains the\n+ * name registry of registered models.  A registered model is bound to\n+ * a device through io.cost.model; see include/linux/blk-iocost.h.\n+ */\n+#include \u003clinux/init.h\u003e\n+#include \u003clinux/kernel.h\u003e\n+#include \u003clinux/module.h\u003e\n+#include \u003clinux/mutex.h\u003e\n+#include \u003clinux/slab.h\u003e\n+#include \u003clinux/bpf.h\u003e\n+#include \u003clinux/bpf_verifier.h\u003e\n+#include \u003clinux/btf.h\u003e\n+#include \u003clinux/blk-iocost.h\u003e\n+\n+static DEFINE_MUTEX(iocost_bpf_reg_lock);\n+static LIST_HEAD(iocost_bpf_models);\n+static LIST_HEAD(iocost_bpf_lifecycle);\n+\n+/*\n+ * One node per registered model.  refcount: 1 while registered\n+ * (dropped in .unreg) plus one per bound device (dropped in\n+ * iocost_bpf_model_put(), which pairs its bpf_struct_ops_get(), so the\n+ * kdata of an unregistered model stays alive while any device is still\n+ * bound to it).  The node sits on the lifecycle notify list exactly\n+ * while at least one device has the model bound.\n+ */\n+struct iocost_bpf_model {\n+\tstruct list_head\tlist;\t\t/* name registry */\n+\tstruct list_head\tlifecycle;\t/* lifecycle notify list */\n+\tconst struct iocost_model_ops *ops;\n+\trefcount_t\t\trefs;\n+};\n+\n+/*\n+ * Take a name and acquire a binding reference on the model it selects.\n+ * The registry is searched first; a model which is unregistered but\n+ * still bound to a device remains selectable by name until the last\n+ * device unbinds, so a coefficient-only write on such a device keeps\n+ * the model bound instead of failing with ENOENT.  The registry lock\n+ * is held across the lookup and bpf_struct_ops_get() so the model\n+ * cannot be unregistered in between.  Returns the ops or an ERR_PTR.\n+ */\n+const struct iocost_model_ops *iocost_bpf_model_get(const char *name)\n+{\n+\tstruct iocost_bpf_model *m;\n+\tconst struct iocost_model_ops *ops = ERR_PTR(-ENOENT);\n+\n+\tmutex_lock(\u0026iocost_bpf_reg_lock);\n+\tlist_for_each_entry(m, \u0026iocost_bpf_models, list) {\n+\t\tif (!strcmp(m-\u003eops-\u003ename, name))\n+\t\t\tgoto found;\n+\t}\n+\tlist_for_each_entry(m, \u0026iocost_bpf_lifecycle, lifecycle) {\n+\t\tif (!strcmp(m-\u003eops-\u003ename, name))\n+\t\t\tgoto found;\n+\t}\n+\tmutex_unlock(\u0026iocost_bpf_reg_lock);\n+\treturn ops;\n+found:\n+\tif (bpf_struct_ops_get(m-\u003eops)) {\n+\t\trefcount_inc(\u0026m-\u003erefs);\n+\t\t/* first bind: join the notify list */\n+\t\tif (refcount_read(\u0026m-\u003erefs) == 2 \u0026\u0026\n+\t\t    list_empty(\u0026m-\u003elifecycle))\n+\t\t\tlist_add(\u0026m-\u003elifecycle, \u0026iocost_bpf_lifecycle);\n+\t\tops = m-\u003eops;\n+\t}\n+\tmutex_unlock(\u0026iocost_bpf_reg_lock);\n+\treturn ops;\n+}\n+\n+static struct iocost_bpf_model *\n+iocost_bpf_model_lookup(const struct iocost_model_ops *ops)\n+{\n+\tstruct iocost_bpf_model *m;\n+\n+\tlist_for_each_entry(m, \u0026iocost_bpf_models, list) {\n+\t\tif (m-\u003eops == ops)\n+\t\t\treturn m;\n+\t}\n+\treturn NULL;\n+}\n+\n+/*\n+ * Lifecycle notifications walk the lifecycle list, which keeps a node\n+ * for as long as any device has the model bound, so an unregistered\n+ * but still-bound model keeps receiving blkcg online/offline.\n+ */\n+void iocost_notify_blkcg_online(struct blkcg *blkcg)\n+{\n+\tstruct iocost_bpf_model *m;\n+\n+\tguard(mutex)(\u0026iocost_bpf_reg_lock);\n+\tlist_for_each_entry(m, \u0026iocost_bpf_lifecycle, lifecycle) {\n+\t\tif (m-\u003eops-\u003eblkcg_online)\n+\t\t\tm-\u003eops-\u003eblkcg_online(blkcg);\n+\t}\n+}\n+\n+void iocost_notify_blkcg_offline(struct blkcg *blkcg)\n+{\n+\tstruct iocost_bpf_model *m;\n+\n+\tguard(mutex)(\u0026iocost_bpf_reg_lock);\n+\tlist_for_each_entry(m, \u0026iocost_bpf_lifecycle, lifecycle) {\n+\t\tif (m-\u003eops-\u003eblkcg_offline)\n+\t\t\tm-\u003eops-\u003eblkcg_offline(blkcg);\n+\t}\n+}\n+\n+static int bpf_iocost_model_init(struct btf *btf)\n+{\n+\ts32 type_id;\n+\n+\ttype_id = btf_find_by_name_kind(btf, \"iocost_model_ops\", BTF_KIND_STRUCT);\n+\tif (type_id \u003c 0)\n+\t\treturn -EINVAL;\n+\treturn 0;\n+}\n+\n+static bool bpf_iocost_is_valid_access(int off, int size,\n+\t\t\t\t       enum bpf_access_type type,\n+\t\t\t\t       const struct bpf_prog *prog,\n+\t\t\t\t       struct bpf_insn_access_aux *info)\n+{\n+\treturn bpf_tracing_btf_ctx_access(off, size, type, prog, info);\n+}\n+\n+/*\n+ * No iocost-specific helpers; bpf_base_func_proto already covers the\n+ * cgroup storage helpers under CONFIG_CGROUPS.\n+ */\n+static const struct bpf_func_proto *\n+bpf_iocost_get_func_proto(enum bpf_func_id func_id,\n+\t\t\t  const struct bpf_prog *prog)\n+{\n+\treturn bpf_base_func_proto(func_id, prog);\n+}\n+\n+static int bpf_iocost_check_member(const struct btf_type *t,\n+\t\t\t\t   const struct btf_member *member,\n+\t\t\t\t   const struct bpf_prog *prog)\n+{\n+\t/* calc_cost() is called with RCU read lock held */\n+\tif (prog-\u003esleepable)\n+\t\treturn -EINVAL;\n+\treturn 0;\n+}\n+\n+static int bpf_iocost_init_member(const struct btf_type *t,\n+\t\t\t\t  const struct btf_member *member,\n+\t\t\t\t  void *kdata, const void *udata)\n+{\n+\tstruct iocost_model_ops *ops = kdata;\n+\tconst struct iocost_model_ops *uops = udata;\n+\tu32 moff = __btf_member_bit_offset(t, member) / 8;\n+\n+\tswitch (moff) {\n+\tcase offsetof(struct iocost_model_ops, name):\n+\t\tif (bpf_obj_name_cpy(ops-\u003ename, uops-\u003ename,\n+\t\t\t\t     sizeof(ops-\u003ename)) \u003c= 0)\n+\t\t\treturn -EINVAL;\n+\t\treturn 1;\n+\t}\n+\n+\treturn 0;\n+}\n+\n+/*\n+ * kvalue is zeroed at map allocation and function members are only\n+ * written when the BPF side provides a prog, so a model which did\n+ * not implement calc_cost leaves it NULL.  The dispatch would call\n+ * it on every bio, so reject it here.\n+ */\n+static int bpf_iocost_validate(void *kdata)\n+{\n+\tstruct iocost_model_ops *ops = kdata;\n+\n+\tif (!ops-\u003ecalc_cost)\n+\t\treturn -EINVAL;\n+\t/* \"linear\" is the builtin model; model=linear unbinds */\n+\tif (!strcmp(ops-\u003ename, \"linear\"))\n+\t\treturn -EINVAL;\n+\treturn 0;\n+}\n+\n+/*\n+ * The struct_ops core holds a reference on the map while the model is\n+ * registered, so kdata stays valid until .unreg returns; no extra\n+ * reference is needed here.\n+ */\n+static int bpf_iocost_reg(void *kdata, struct bpf_link *link)\n+{\n+\tstruct iocost_model_ops *ops = kdata;\n+\tstruct iocost_bpf_model *m;\n+\tint ret = 0;\n+\n+\tm = kzalloc_obj(struct iocost_bpf_model, GFP_KERNEL);\n+\tif (!m)\n+\t\treturn -ENOMEM;\n+\trefcount_set(\u0026m-\u003erefs, 1);\n+\tINIT_LIST_HEAD(\u0026m-\u003elifecycle);\n+\n+\tmutex_lock(\u0026iocost_bpf_reg_lock);\n+\t{\n+\t\tstruct iocost_bpf_model *other;\n+\n+\t\tlist_for_each_entry(other, \u0026iocost_bpf_models, list) {\n+\t\t\tif (!strcmp(other-\u003eops-\u003ename, ops-\u003ename)) {\n+\t\t\t\tret = -EEXIST;\n+\t\t\t\tbreak;\n+\t\t\t}\n+\t\t}\n+\t}\n+\tif (!ret) {\n+\t\tm-\u003eops = ops;\n+\t\tlist_add(\u0026m-\u003elist, \u0026iocost_bpf_models);\n+\t}\n+\tmutex_unlock(\u0026iocost_bpf_reg_lock);\n+\n+\tif (ret)\n+\t\tkfree(m);\n+\treturn ret;\n+}\n+\n+/*\n+ * Unregistering drops the registration reference.  If a device is\n+ * still bound, the binding references keep the node (and the kdata,\n+ * through their bpf_struct_ops_get()) alive and it keeps receiving\n+ * blkcg online/offline notifications; otherwise the node is freed.\n+ */\n+static void bpf_iocost_unreg(void *kdata, struct bpf_link *link)\n+{\n+\tstruct iocost_model_ops *ops = kdata;\n+\tstruct iocost_bpf_model *m;\n+\n+\tmutex_lock(\u0026iocost_bpf_reg_lock);\n+\tm = iocost_bpf_model_lookup(ops);\n+\tif (m) {\n+\t\t/*\n+\t\t * keep the linkage queryable so model_put() can tell a\n+\t\t * still-registered node (one ref held by the registry)\n+\t\t * from one kept alive only by device bindings\n+\t\t */\n+\t\tlist_del_init(\u0026m-\u003elist);\n+\t\tif (refcount_dec_and_test(\u0026m-\u003erefs))\n+\t\t\tkfree(m);\n+\t}\n+\tmutex_unlock(\u0026iocost_bpf_reg_lock);\n+}\n+\n+void iocost_bpf_model_put(const struct iocost_model_ops *ops)\n+{\n+\tstruct iocost_bpf_model *m;\n+\n+\tmutex_lock(\u0026iocost_bpf_reg_lock);\n+\tlist_for_each_entry(m, \u0026iocost_bpf_lifecycle, lifecycle) {\n+\t\tif (m-\u003eops == ops)\n+\t\t\tbreak;\n+\t}\n+\tif (\u0026m-\u003elifecycle != \u0026iocost_bpf_lifecycle) {\n+\t\tbool freed = refcount_dec_and_test(\u0026m-\u003erefs);\n+\n+\t\t/*\n+\t\t * leave the notify list with the last binding: refs is\n+\t\t * now zero (node freed) or the registry's single one\n+\t\t */\n+\t\tif (freed || (!list_empty(\u0026m-\u003elist) \u0026\u0026\n+\t\t\t      refcount_read(\u0026m-\u003erefs) == 1))\n+\t\t\tlist_del_init(\u0026m-\u003elifecycle);\n+\t\tmutex_unlock(\u0026iocost_bpf_reg_lock);\n+\t\tbpf_struct_ops_put(ops);\n+\t\tif (freed)\n+\t\t\tkfree(m);\n+\t\treturn;\n+\t}\n+\tmutex_unlock(\u0026iocost_bpf_reg_lock);\n+}\n+\n+static const struct bpf_verifier_ops bpf_iocost_verifier_ops = {\n+\t.get_func_proto = bpf_iocost_get_func_proto,\n+\t.is_valid_access = bpf_iocost_is_valid_access,\n+};\n+\n+static u64 bpf_iocost_calc_cost_stub(u64 opf, u64 nbytes, u64 sector,\n+\t\t\t\t     struct blkcg *blkcg, u64 flags)\n+{\n+\treturn 0;\n+}\n+\n+static void bpf_iocost_blkcg_online_stub(struct blkcg *blkcg) { }\n+static void bpf_iocost_blkcg_offline_stub(struct blkcg *blkcg) { }\n+\n+static struct iocost_model_ops __bpf_ops_iocost_model_ops = {\n+\t.calc_cost = bpf_iocost_calc_cost_stub,\n+\t.blkcg_online = bpf_iocost_blkcg_online_stub,\n+\t.blkcg_offline = bpf_iocost_blkcg_offline_stub,\n+};\n+\n+static struct bpf_struct_ops bpf_iocost_model_ops = {\n+\t.verifier_ops = \u0026bpf_iocost_verifier_ops,\n+\t.init = bpf_iocost_model_init,\n+\t.check_member = bpf_iocost_check_member,\n+\t.init_member = bpf_iocost_init_member,\n+\t.validate = bpf_iocost_validate,\n+\t.reg = bpf_iocost_reg,\n+\t.unreg = bpf_iocost_unreg,\n+\t.name = \"iocost_model_ops\",\n+\t.cfi_stubs = \u0026__bpf_ops_iocost_model_ops,\n+\t.owner = THIS_MODULE,\n+};\n+\n+static int __init bpf_iocost_init(void)\n+{\n+\treturn register_bpf_struct_ops(\u0026bpf_iocost_model_ops, iocost_model_ops);\n+}\n+late_initcall(bpf_iocost_init);\ndiff --git a/block/blk-iocost.c b/block/blk-iocost.c\nindex 2745bffcd5eef..9eb97f38a39cf 100644\n--- a/block/blk-iocost.c\n+++ b/block/blk-iocost.c\n@@ -177,6 +177,7 @@\n #include \u003clinux/timer.h\u003e\n #include \u003clinux/time64.h\u003e\n #include \u003clinux/parser.h\u003e\n+#include \u003clinux/blk-iocost.h\u003e\n #include \u003clinux/sched/signal.h\u003e\n #include \u003casm/local.h\u003e\n #include \u003casm/local64.h\u003e\n@@ -445,6 +446,11 @@ struct ioc {\n \tint\t\t\t\tautop_idx;\n \tbool\t\t\t\tuser_qos_params:1;\n \tbool\t\t\t\tuser_cost_model:1;\n+\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\t/* bound BPF cost model, NULL = builtin linear model */\n+\tconst struct iocost_model_ops\t__rcu *model;\n+#endif\n };\n \n struct iocg_pcpu_stat {\n@@ -2238,6 +2244,10 @@ static void ioc_timer_fn(struct timer_list *timer)\n \tstruct ioc_now now;\n \tLIST_HEAD(surpluses);\n \tint nr_debtors, nr_shortages = 0, nr_lagging = 0;\n+\tint nr_active = 0;\n+\tu32 tick_period_us;\n+\tu64 tick_vrate, tick_dur;\n+\tint tick_busy, tick_running;\n \tu64 usage_us_sum = 0;\n \tu32 ppm_rthr;\n \tu32 ppm_wthr;\n@@ -2274,6 +2284,8 @@ static void ioc_timer_fn(struct timer_list *timer)\n \t\tu64 vdone, vtime, usage_us;\n \t\tu32 hw_active, hw_inuse;\n \n+\t\tnr_active++;\n+\n \t\t/*\n \t\t * Collect unused and wind vtime closer to vnow to prevent\n \t\t * iocgs from accumulating a large amount of budget.\n@@ -2435,6 +2447,14 @@ static void ioc_timer_fn(struct timer_list *timer)\n \n \tioc-\u003ebusy_level = clamp(ioc-\u003ebusy_level, -1000, 1000);\n \n+\t/*\n+\t * vrate and period_us change right below; snapshot the values\n+\t * this period ran in so the tick below reports the period's own\n+\t * parameters instead of the next period's.\n+\t */\n+\ttick_period_us = ioc-\u003eperiod_us;\n+\ttick_vrate = ioc-\u003evtime_base_rate;\n+\n \tioc_adjust_base_vrate(ioc, rq_wait_pct, nr_lagging, nr_shortages,\n \t\t\t      prev_busy_level, missed_ppm);\n \n@@ -2442,6 +2462,24 @@ static void ioc_timer_fn(struct timer_list *timer)\n \n \tioc_forgive_debts(ioc, usage_us_sum, nr_debtors, \u0026now);\n \n+\t/*\n+\t * Snapshot the state this period ran in before the idle\n+\t * transition below wipes it, so the final tick reports the period's\n+\t * own busy level (e.g. the saturation that drove the controller\n+\t * idle) instead of the cleared one.  usage is normalized by the\n+\t * measured period length, captured before ioc_start_period()\n+\t * overwrites period_at, the same way the donation loop does.\n+\t * Emitted before cur_period is bumped, so the tick carries the\n+\t * number of the period it describes.\n+\t */\n+\ttick_busy = ioc-\u003ebusy_level;\n+\ttick_running = ioc-\u003erunning;\n+\ttick_dur = now.now - ioc-\u003eperiod_at;\n+\n+\ttrace_iocost_ioc_tick(ioc, nr_active, usage_us_sum,\n+\t\t\t      tick_period_us, tick_vrate,\n+\t\t\t      tick_busy, tick_running, tick_dur);\n+\n \t/*\n \t * This period is done.  Move onto the next one.  If nothing's\n \t * going on with the device, stop the timer.\n@@ -2571,10 +2609,28 @@ static void calc_vtime_cost_builtin(struct bio *bio, struct ioc_gq *iocg,\n \n static u64 calc_vtime_cost(struct bio *bio, struct ioc_gq *iocg, bool is_merge)\n {\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\tconst struct iocost_model_ops *model;\n \tu64 cost;\n \n-\tcalc_vtime_cost_builtin(bio, iocg, is_merge, \u0026cost);\n-\treturn cost;\n+\trcu_read_lock();\n+\tmodel = rcu_dereference(iocg-\u003eioc-\u003emodel);\n+\tif (model) {\n+\t\tcost = model-\u003ecalc_cost(bio-\u003ebi_opf, bio-\u003ebi_iter.bi_size,\n+\t\t\t\t\tbio-\u003ebi_iter.bi_sector,\n+\t\t\t\t\tiocg_to_blkg(iocg)-\u003eblkcg,\n+\t\t\t\t\tis_merge ? IOCOST_COST_F_MERGE : 0);\n+\t\trcu_read_unlock();\n+\t\treturn min(cost, VTIME_PER_SEC);\n+\t}\n+\trcu_read_unlock();\n+#endif\n+\t{\n+\t\tu64 cost;\n+\n+\t\tcalc_vtime_cost_builtin(bio, iocg, is_merge, \u0026cost);\n+\t\treturn cost;\n+\t}\n }\n \n static void calc_size_vtime_cost_builtin(struct request *rq, struct ioc *ioc,\n@@ -2596,10 +2652,28 @@ static void calc_size_vtime_cost_builtin(struct request *rq, struct ioc *ioc,\n \n static u64 calc_size_vtime_cost(struct request *rq, struct ioc *ioc)\n {\n-\tu64 cost;\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\tconst struct iocost_model_ops *model;\n \n-\tcalc_size_vtime_cost_builtin(rq, ioc, \u0026cost);\n-\treturn cost;\n+\trcu_read_lock();\n+\tmodel = rcu_dereference(ioc-\u003emodel);\n+\tif (model \u0026\u0026 rq-\u003ebio \u0026\u0026 rq-\u003ebio-\u003ebi_blkg) {\n+\t\tu64 cost;\n+\n+\t\tcost = model-\u003ecalc_cost(rq-\u003ecmd_flags, blk_rq_bytes(rq),\n+\t\t\t\t\tblk_rq_pos(rq),\n+\t\t\t\t\trq-\u003ebio-\u003ebi_blkg-\u003eblkcg, 0);\n+\t\trcu_read_unlock();\n+\t\treturn min(cost, VTIME_PER_SEC);\n+\t}\n+\trcu_read_unlock();\n+#endif\n+\t{\n+\t\tu64 cost;\n+\n+\t\tcalc_size_vtime_cost_builtin(rq, ioc, \u0026cost);\n+\t\treturn cost;\n+\t}\n }\n \n enum over_budget_action {\n@@ -2900,6 +2974,19 @@ static void ioc_rqos_exit(struct rq_qos *rqos)\n \n \ttimer_shutdown_sync(\u0026ioc-\u003etimer);\n \tfree_percpu(ioc-\u003epcpu_stat);\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\t{\n+\t\tconst struct iocost_model_ops *model;\n+\n+\t\tspin_lock_irq(\u0026ioc-\u003elock);\n+\t\tmodel = rcu_dereference_protected(ioc-\u003emodel,\n+\t\t\t\t\tlockdep_is_held(\u0026ioc-\u003elock));\n+\t\trcu_assign_pointer(ioc-\u003emodel, NULL);\n+\t\tspin_unlock_irq(\u0026ioc-\u003elock);\n+\t\tif (model)\n+\t\t\tiocost_bpf_model_put(model);\n+\t}\n+#endif\n \tkfree(ioc);\n }\n \n@@ -3438,12 +3525,30 @@ static u64 ioc_cost_model_prfill(struct seq_file *sf,\n \t\treturn 0;\n \n \tspin_lock_irq(\u0026ioc-\u003elock);\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\t{\n+\t\tconst struct iocost_model_ops *model =\n+\t\t\trcu_dereference_protected(ioc-\u003emodel,\n+\t\t\t\t\tlockdep_is_held(\u0026ioc-\u003elock));\n+\n+\t\tseq_printf(sf, \"%s ctrl=%s model=%s \"\n+\t\t\t   \"rbps=%llu rseqiops=%llu rrandiops=%llu \"\n+\t\t\t   \"wbps=%llu wseqiops=%llu wrandiops=%llu\\n\",\n+\t\t\t   dname, model ? \"bpf\" :\n+\t\t\t\t   ioc-\u003euser_cost_model ? \"user\" : \"auto\",\n+\t\t\t   model ? model-\u003ename : \"linear\",\n+\t\t\t   u[I_LCOEF_RBPS], u[I_LCOEF_RSEQIOPS],\n+\t\t\t   u[I_LCOEF_RRANDIOPS], u[I_LCOEF_WBPS],\n+\t\t\t   u[I_LCOEF_WSEQIOPS], u[I_LCOEF_WRANDIOPS]);\n+\t}\n+#else\n \tseq_printf(sf, \"%s ctrl=%s model=linear \"\n \t\t   \"rbps=%llu rseqiops=%llu rrandiops=%llu \"\n \t\t   \"wbps=%llu wseqiops=%llu wrandiops=%llu\\n\",\n \t\t   dname, ioc-\u003euser_cost_model ? \"user\" : \"auto\",\n \t\t   u[I_LCOEF_RBPS], u[I_LCOEF_RSEQIOPS], u[I_LCOEF_RRANDIOPS],\n \t\t   u[I_LCOEF_WBPS], u[I_LCOEF_WSEQIOPS], u[I_LCOEF_WRANDIOPS]);\n+#endif\n \tspin_unlock_irq(\u0026ioc-\u003elock);\n \treturn 0;\n }\n@@ -3457,6 +3562,48 @@ static int ioc_cost_model_show(struct seq_file *sf, void *v)\n \treturn 0;\n }\n \n+/*\n+ * Resolve the model name and take a reference on the new model before\n+ * anything is applied, so a bad name rejects the whole write.  The\n+ * registry lookup takes the registration mutex and must stay outside\n+ * ioc-\u003elock.  The returned model is per-write state passed back into\n+ * ioc_bpf_model_commit(), which performs the pointer swap under\n+ * ioc-\u003elock so concurrent writers cannot interleave a half-applied\n+ * configuration, and the caller drops the old model's reference\n+ * afterwards.\n+ */\n+static const struct iocost_model_ops *\n+ioc_bpf_model_prepare(const char *name)\n+{\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\tif (!name[0])\n+\t\treturn NULL;\n+\treturn iocost_bpf_model_get(name);\n+#else\n+\treturn name[0] ? ERR_PTR(-ENOENT) : NULL;\n+#endif\n+}\n+\n+/*\n+ * Swap in the model returned by ioc_bpf_model_prepare().  Called with\n+ * ioc-\u003elock held; dropping the old model's reference may sleep, so\n+ * the caller does it after releasing the lock.\n+ */\n+static const struct iocost_model_ops *\n+ioc_bpf_model_commit(struct ioc *ioc, const struct iocost_model_ops *new)\n+{\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\tconst struct iocost_model_ops *old;\n+\n+\told = rcu_dereference_protected(ioc-\u003emodel,\n+\t\t\t\t\tlockdep_is_held(\u0026ioc-\u003elock));\n+\trcu_assign_pointer(ioc-\u003emodel, new);\n+\treturn old;\n+#else\n+\treturn NULL;\n+#endif\n+}\n+\n static const match_table_t cost_ctrl_tokens = {\n \t{ COST_CTRL,\t\t\"ctrl=%s\"\t},\n \t{ COST_MODEL,\t\t\"model=%s\"\t},\n@@ -3482,6 +3629,7 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,\n \tstruct ioc *ioc;\n \tu64 u[NR_I_LCOEFS];\n \tbool user;\n+\tchar bpf_model[IOCOST_MODEL_NAME_LEN];\n \tchar *body, *p;\n \tint ret;\n \n@@ -3512,6 +3660,25 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,\n \tspin_lock_irq(\u0026ioc-\u003elock);\n \tmemcpy(u, ioc-\u003eparams.i_lcoefs, sizeof(u));\n \tuser = ioc-\u003euser_cost_model;\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\t{\n+\t\tconst struct iocost_model_ops *model =\n+\t\t\trcu_dereference_protected(ioc-\u003emodel,\n+\t\t\t\t\tlockdep_is_held(\u0026ioc-\u003elock));\n+\n+\t\t/*\n+\t\t * seed from the bound model so a coefficient-only write\n+\t\t * keeps it bound; ctrl=auto/user and model=linear are\n+\t\t * the explicit ways back to the builtin model\n+\t\t */\n+\t\tif (model)\n+\t\t\tstrscpy(bpf_model, model-\u003ename, sizeof(bpf_model));\n+\t\telse\n+\t\t\tbpf_model[0] = '\\0';\n+\t}\n+#else\n+\tbpf_model[0] = '\\0';\n+#endif\n \n \tret = -EINVAL;\n \n@@ -3527,17 +3694,27 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,\n \t\tswitch (match_token(p, cost_ctrl_tokens, args)) {\n \t\tcase COST_CTRL:\n \t\t\tmatch_strlcpy(buf, \u0026args[0], sizeof(buf));\n-\t\t\tif (!strcmp(buf, \"auto\"))\n+\t\t\tif (!strcmp(buf, \"auto\")) {\n \t\t\t\tuser = false;\n-\t\t\telse if (!strcmp(buf, \"user\"))\n+\t\t\t} else if (!strcmp(buf, \"user\")) {\n \t\t\t\tuser = true;\n-\t\t\telse\n+\t\t\t} else if (!strcmp(buf, \"bpf\")) {\n+\t\t\t\t/* readback value; keep the bound model */\n+\t\t\t\tcontinue;\n+\t\t\t} else {\n \t\t\t\tgoto unlock;\n+\t\t\t}\n+\t\t\t/* ctrl=auto/user: explicit return to builtin */\n+\t\t\tbpf_model[0] = '\\0';\n \t\t\tcontinue;\n \t\tcase COST_MODEL:\n \t\t\tmatch_strlcpy(buf, \u0026args[0], sizeof(buf));\n-\t\t\tif (strcmp(buf, \"linear\"))\n-\t\t\t\tgoto unlock;\n+\t\t\tif (!strcmp(buf, \"linear\")) {\n+\t\t\t\t/* back to the builtin linear model */\n+\t\t\t\tbpf_model[0] = '\\0';\n+\t\t\t\tcontinue;\n+\t\t\t}\n+\t\t\tmatch_strlcpy(bpf_model, \u0026args[0], sizeof(bpf_model));\n \t\t\tcontinue;\n \t\t}\n \n@@ -3550,19 +3727,34 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,\n \t\tuser = true;\n \t}\n \n-\tif (user) {\n-\t\tmemcpy(ioc-\u003eparams.i_lcoefs, u, sizeof(u));\n-\t\tioc-\u003euser_cost_model = true;\n-\t} else {\n-\t\tioc-\u003euser_cost_model = false;\n-\t}\n-\tioc_refresh_params(ioc, true);\n-\n \tret = 0;\n \n unlock:\n \tspin_unlock_irq(\u0026ioc-\u003elock);\n \n+\t/* resolve the name outside ioc-\u003elock; see ioc_bpf_model_prepare() */\n+\tif (!ret) {\n+\t\tconst struct iocost_model_ops *new, *old;\n+\n+\t\tnew = ioc_bpf_model_prepare(bpf_model);\n+\t\tif (IS_ERR(new)) {\n+\t\t\tret = PTR_ERR(new);\n+\t\t} else {\n+\t\t\tspin_lock_irq(\u0026ioc-\u003elock);\n+\t\t\tif (user) {\n+\t\t\t\tmemcpy(ioc-\u003eparams.i_lcoefs, u, sizeof(u));\n+\t\t\t\tioc-\u003euser_cost_model = true;\n+\t\t\t} else {\n+\t\t\t\tioc-\u003euser_cost_model = false;\n+\t\t\t}\n+\t\t\tioc_refresh_params(ioc, true);\n+\t\t\told = ioc_bpf_model_commit(ioc, new);\n+\t\t\tspin_unlock_irq(\u0026ioc-\u003elock);\n+\t\t\tif (IS_ENABLED(CONFIG_BLK_CGROUP_IOCOST_BPF) \u0026\u0026 old)\n+\t\t\t\tiocost_bpf_model_put(old);\n+\t\t}\n+\t}\n+\n \tblk_mq_unquiesce_queue(q);\n \tblk_mq_unfreeze_queue(q, memflags);\n \ndiff --git a/include/linux/blk-iocost.h b/include/linux/blk-iocost.h\nnew file mode 100644\nindex 0000000000000..e6dc6772ef5c9\n--- /dev/null\n+++ b/include/linux/blk-iocost.h\n@@ -0,0 +1,86 @@\n+/* SPDX-License-Identifier: GPL-2.0 */\n+#ifndef _LINUX_BLK_IOCOST_H\n+#define _LINUX_BLK_IOCOST_H\n+\n+#include \u003clinux/types.h\u003e\n+#include \u003clinux/blk_types.h\u003e\n+\n+#define IOCOST_MODEL_NAME_LEN\t16\n+\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\n+struct blkcg;\n+\n+/*\n+ * Pluggable cost model interface for blk-iocost.\n+ *\n+ * A BPF struct_ops implementation registered against \"iocost_model_ops\"\n+ * fully replaces the builtin linear model on the devices it is bound to\n+ * through io.cost.model.  The model owns pricing for every IO on a bound\n+ * device: it prices all operations, including flushes, and it is called\n+ * from the bio charging path.  The completion-time request sizing for\n+ * the latency met/missed accounting still uses the builtin coefficients\n+ * (the request's bio, and with it the issuing cgroup, is gone by then);\n+ * extending the model there is left open by this interface.\n+ *\n+ * calc_cost() is called from the IO submission path with RCU read lock\n+ * held and must not sleep.  It returns the cost of the IO in vtime\n+ * units, where 1 second of device time equals VTIME_PER_SEC (2^37,\n+ * available to BPF programs through vmlinux.h).  The returned value is\n+ * clamped to 1 second of device time per IO.\n+ *\n+ * The model is passed the blkcg of the issuing cgroup so it can keep\n+ * per-cgroup state.  State keyed by the blkcg alone is shared across\n+ * every device the model is bound to, unlike the builtin cursor which\n+ * is per (cgroup, device).  blkcg_online()/blkcg_offline() are optional\n+ * callbacks mirroring the blkcg css lifecycle: they are delivered\n+ * only while at least one device has the model bound, and state\n+ * created on online (or lazily on first use) must be released on\n+ * offline.\n+ *\n+ * The registration and binding model follows the TCP congestion\n+ * control framework: registering a struct_ops makes the model available\n+ * by its name, while io.cost.model binds one registered model to a\n+ * device.  Unregistering removes the name from the registry; devices\n+ * already bound keep using it until switched back to the builtin\n+ * model, and the name remains usable for io.cost.model writes (so a\n+ * coefficient-only write keeps such a model bound) until the last\n+ * device unbinds.\n+ */\n+\n+/*\n+ * iocost-specific call metadata for calc_cost()'s model_flags\n+ * argument; everything else, including REQ_PREFLUSH/REQ_FUA, is\n+ * already present in the opf argument.  An enum so the value is\n+ * exported through BTF and BPF models can use it from vmlinux.h.\n+ */\n+enum {\n+\tIOCOST_COST_F_MERGE\t= 1 \u003c\u003c 0,\t/* called from merge path */\n+};\n+\n+struct iocost_model_ops {\n+\tu64 (*calc_cost)(u64 opf, u64 nbytes, sector_t sector,\n+\t\t\t struct blkcg *blkcg, u64 model_flags);\n+\tvoid (*blkcg_online)(struct blkcg *blkcg);\n+\tvoid (*blkcg_offline)(struct blkcg *blkcg);\n+\n+\t/* model name, used to select the model through io.cost.model */\n+\tchar name[IOCOST_MODEL_NAME_LEN];\n+};\n+\n+const struct iocost_model_ops *iocost_bpf_model_get(const char *name);\n+void iocost_bpf_model_put(const struct iocost_model_ops *ops);\n+void iocost_notify_blkcg_online(struct blkcg *blkcg);\n+void iocost_notify_blkcg_offline(struct blkcg *blkcg);\n+\n+#else\t/* CONFIG_BLK_CGROUP_IOCOST_BPF */\n+\n+struct blkcg;\n+struct iocost_model_ops;\n+\n+static inline void iocost_bpf_model_put(const struct iocost_model_ops *ops) { }\n+static inline void iocost_notify_blkcg_online(struct blkcg *blkcg) { }\n+static inline void iocost_notify_blkcg_offline(struct blkcg *blkcg) { }\n+\n+#endif\t/* CONFIG_BLK_CGROUP_IOCOST_BPF */\n+#endif\t/* _LINUX_BLK_IOCOST_H */\ndiff --git a/include/trace/events/iocost.h b/include/trace/events/iocost.h\nindex e772b1bc60d60..32f19861a78fd 100644\n--- a/include/trace/events/iocost.h\n+++ b/include/trace/events/iocost.h\n@@ -178,6 +178,51 @@ TRACE_EVENT(iocost_ioc_vrate_adj,\n \t)\n );\n \n+/*\n+ * Periodic per-device summary, emitted once per period from the tail of\n+ * ioc_timer_fn().  Unlike the state-change events above, this fires every\n+ * period the controller is running, including steady states, and carries\n+ * the overall controller state so basic monitoring doesn't require drgn.\n+ */\n+TRACE_EVENT(iocost_ioc_tick,\n+\n+\tTP_PROTO(struct ioc *ioc, int nr_active, u64 usage_us_sum,\n+\t\t u32 tick_period_us, u64 tick_vrate,\n+\t\t int tick_busy, int tick_running, u64 tick_dur),\n+\n+\tTP_ARGS(ioc, nr_active, usage_us_sum, tick_period_us, tick_vrate,\n+\t\ttick_busy, tick_running, tick_dur),\n+\n+\tTP_STRUCT__entry (\n+\t\t__string(devname, ioc_name(ioc))\n+\t\t__field(u64, cur_period)\n+\t\t__field(u32, period_us)\n+\t\t__field(u64, vrate)\n+\t\t__field(int, busy_level)\n+\t\t__field(int, nr_active)\n+\t\t__field(u32, usage_pct)\n+\t\t__field(int, running)\n+\t),\n+\n+\tTP_fast_assign(\n+\t\t__assign_str(devname);\n+\t\t__entry-\u003ecur_period = atomic64_read(\u0026ioc-\u003ecur_period);\n+\t\t__entry-\u003eperiod_us = tick_period_us;\n+\t\t__entry-\u003evrate = tick_vrate;\n+\t\t__entry-\u003ebusy_level = tick_busy;\n+\t\t__entry-\u003enr_active = nr_active;\n+\t\t__entry-\u003eusage_pct = tick_dur ?\n+\t\t\tdiv64_u64(usage_us_sum * 100, tick_dur) : 0;\n+\t\t__entry-\u003erunning = tick_running;\n+\t),\n+\n+\tTP_printk(\"[%s] period=%llu:%uus vrate=%llu busy=%d active=%d usage=%u%% running=%d\",\n+\t\t__get_str(devname), __entry-\u003ecur_period, __entry-\u003eperiod_us,\n+\t\t__entry-\u003evrate, __entry-\u003ebusy_level, __entry-\u003enr_active,\n+\t\t__entry-\u003eusage_pct, __entry-\u003erunning\n+\t)\n+);\n+\n TRACE_EVENT(iocost_iocg_forgive_debt,\n \n \tTP_PROTO(struct ioc_gq *iocg, const char *path, struct ioc_now *now,\ndiff --git a/tools/testing/selftests/bpf/config b/tools/testing/selftests/bpf/config\nindex 2f79688dcf7ce..67a630cb56148 100644\n--- a/tools/testing/selftests/bpf/config\n+++ b/tools/testing/selftests/bpf/config\n@@ -138,3 +138,5 @@ CONFIG_SMC_HS_CTRL_BPF=y\n CONFIG_DIBS=y\n CONFIG_DIBS_LO=y\n CONFIG_PM_WAKELOCKS=y\n+CONFIG_BLK_CGROUP_IOCOST=y\n+CONFIG_BLK_CGROUP_IOCOST_BPF=y\ndiff --git a/tools/testing/selftests/bpf/prog_tests/iocost_model.c b/tools/testing/selftests/bpf/prog_tests/iocost_model.c\nnew file mode 100644\nindex 0000000000000..ac734c0e09cb0\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/prog_tests/iocost_model.c\n@@ -0,0 +1,200 @@\n+// SPDX-License-Identifier: GPL-2.0\n+#include \u003ctest_progs.h\u003e\n+#include \u003cctype.h\u003e\n+#include \u003cfcntl.h\u003e\n+#include \u003cunistd.h\u003e\n+#include \"iocost_model.skel.h\"\n+#include \"iocost_ms.skel.h\"\n+\n+/*\n+ * Write a line to io.cost.model with write(2) and return the errno of\n+ * the failed write, or 0 on success.  stdio is not used here on\n+ * purpose: the kernel's rejection happens in the write() syscall,\n+ * not in the userspace buffer copy, and every write, including\n+ * the error paths of the callers below, is checked.\n+ */\n+static int write_cost_model(const char *buf)\n+{\n+\tint fd, err = 0;\n+\tssize_t n;\n+\n+\tfd = open(\"/sys/fs/cgroup/io.cost.model\", O_WRONLY);\n+\tif (fd \u003c 0)\n+\t\treturn -errno;\t/* negative: the file is not there */\n+\tn = write(fd, buf, strlen(buf));\n+\tif (n \u003c 0)\n+\t\terr = errno;\n+\tclose(fd);\n+\treturn err;\n+}\n+\n+/*\n+ * Read back the io.cost.model line of dev and copy the model= value\n+ * into @model.  Returns 0 on success.\n+ */\n+static int readback_model(const char *dev, char *model, size_t model_sz)\n+{\n+\tchar line[256], word[256], *m, *end;\n+\tFILE *fp;\n+\tint found = 0;\n+\n+\tfp = fopen(\"/sys/fs/cgroup/io.cost.model\", \"r\");\n+\tif (!fp)\n+\t\treturn -1;\n+\twhile (fgets(line, sizeof(line), fp)) {\n+\t\tif (sscanf(line, \"%255s\", word) == 1 \u0026\u0026 !strcmp(word, dev)) {\n+\t\t\tfound = 1;\n+\t\t\tbreak;\n+\t\t}\n+\t}\n+\tfclose(fp);\n+\tif (!found)\n+\t\treturn -1;\n+\n+\tm = strstr(line, \"model=\");\n+\tif (!m)\n+\t\treturn -1;\n+\tm += strlen(\"model=\");\n+\tend = m;\n+\twhile (*end \u0026\u0026 !isspace(*end))\n+\t\tend++;\n+\tsnprintf(model, model_sz, \"%.*s\", (int)(end - m), m);\n+\treturn 0;\n+}\n+\n+/*\n+ * Bind the named model to a device with \"model=\u003cname\u003e\", verify the\n+ * readback and restore the builtin model.  Returns 0 on success.\n+ */\n+static int bind_model(const char *dev, const char *name)\n+{\n+\tchar buf[300], got[64];\n+\tint err;\n+\n+\tsnprintf(buf, sizeof(buf), \"%s model=%s\\n\", dev, name);\n+\terr = write_cost_model(buf);\n+\tif (err)\n+\t\treturn err \u003e 0 ? -err : -EIO;\n+\terr = readback_model(dev, got, sizeof(got));\n+\tif (!err \u0026\u0026 !strcmp(got, name)) {\n+\t\t/*\n+\t\t * restore the builtin linear model on every path so\n+\t\t * the device is not left bound to a model the caller\n+\t\t * may unregister right after; the write is checked too\n+\t\t */\n+\t\tsnprintf(buf, sizeof(buf), \"%s model=linear\\n\", dev);\n+\t\terr = write_cost_model(buf);\n+\t\treturn err \u003e 0 ? -err : (err ? -EIO : 0);\n+\t}\n+\n+\t/*\n+\t * bind failed or does not read back: still restore, but report\n+\t * the original failure rather than the restore result\n+\t */\n+\tsnprintf(buf, sizeof(buf), \"%s model=linear\\n\", dev);\n+\twrite_cost_model(buf);\n+\treturn err ? -EIO : -EINVAL;\n+}\n+\n+/*\n+ * True when the device line exists in io.cost.qos and iocost is\n+ * enabled on it.\n+ */\n+static int dev_has_iocost(const char *dev)\n+{\n+\tchar line[256], word[256];\n+\tFILE *fp;\n+\tint found = 0;\n+\n+\tfp = fopen(\"/sys/fs/cgroup/io.cost.qos\", \"r\");\n+\tif (!fp)\n+\t\treturn 0;\n+\twhile (fgets(line, sizeof(line), fp)) {\n+\t\tif (sscanf(line, \"%255s\", word) == 1 \u0026\u0026 !strcmp(word, dev)) {\n+\t\t\tfound = strstr(line, \"enable=1\") != NULL;\n+\t\t\tbreak;\n+\t\t}\n+\t}\n+\tfclose(fp);\n+\treturn found;\n+}\n+\n+/*\n+ * Bind the 2x example model and verify the io.cost.model readback.\n+ * IO accounting itself is not checked here; it needs a device doing\n+ * real IO under iocost and is covered by the kernel-side validation\n+ * described in the cover letter.\n+ *\n+ * Requires root, cgroup v2 and a device with iocost support.  The\n+ * device must be given as major:minor in $IOCOST_TEST_DEV, otherwise\n+ * the test is skipped.\n+ */\n+void serial_test_iocost_model(void)\n+{\n+\tstruct iocost_model *skel;\n+\tchar buf[300], *dev;\n+\tint err;\n+\n+\tdev = getenv(\"IOCOST_TEST_DEV\");\n+\tif (!dev || geteuid() != 0) {\n+\t\ttest__skip();\n+\t\treturn;\n+\t}\n+\tif (!dev_has_iocost(dev)) {\n+\t\tprintf(\"skip: %s has no iocost enabled\\n\", dev);\n+\t\ttest__skip();\n+\t\treturn;\n+\t}\n+\n+\t/*\n+\t * negative: binding an unknown model name must be rejected,\n+\t * so a typo cannot silently disable cost model updates\n+\t */\n+\tsnprintf(buf, sizeof(buf), \"%s model=no_such_model\\n\", dev);\n+\terr = write_cost_model(buf);\n+\tASSERT_EQ(err \u003e 0 ? err : 0, ENOENT, \"unknown_model_rejected\");\n+\n+\tskel = iocost_model__open_and_load();\n+\tif (!ASSERT_OK_PTR(skel, \"skel_open_load\"))\n+\t\treturn;\n+\n+\t/* attaching the struct_ops registers the model by name */\n+\terr = iocost_model__attach(skel);\n+\tif (ASSERT_OK(err, \"attach\"))\n+\t\tASSERT_OK(bind_model(dev, \"iocost_2x\"), \"bind_and_readback\");\n+\n+\tiocost_model__destroy(skel);\n+}\n+\n+/*\n+ * Same check for the multi-stream example model.  Only one model can\n+ * be bound to a device at a time; both tests bind and restore, so\n+ * they are serial and independent.\n+ */\n+void serial_test_iocost_model_streams(void)\n+{\n+\tstruct iocost_ms *skel;\n+\tchar *dev;\n+\tint err;\n+\n+\tdev = getenv(\"IOCOST_TEST_DEV\");\n+\tif (!dev || geteuid() != 0) {\n+\t\ttest__skip();\n+\t\treturn;\n+\t}\n+\tif (!dev_has_iocost(dev)) {\n+\t\tprintf(\"skip: %s has no iocost enabled\\n\", dev);\n+\t\ttest__skip();\n+\t\treturn;\n+\t}\n+\n+\tskel = iocost_ms__open_and_load();\n+\tif (!ASSERT_OK_PTR(skel, \"skel_open_load\"))\n+\t\treturn;\n+\n+\terr = iocost_ms__attach(skel);\n+\tif (ASSERT_OK(err, \"attach\"))\n+\t\tASSERT_OK(bind_model(dev, \"iocost_ms\"), \"bind_and_readback\");\n+\n+\tiocost_ms__destroy(skel);\n+}\ndiff --git a/tools/testing/selftests/bpf/progs/iocost_model.c b/tools/testing/selftests/bpf/progs/iocost_model.c\nnew file mode 100644\nindex 0000000000000..66fab4711c0b5\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/progs/iocost_model.c\n@@ -0,0 +1,136 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/*\n+ * Example iocost cost model: the builtin linear HDD formula with all\n+ * costs doubled.\n+ *\n+ * The constants mirror what calc_lcoefs() derives from the AUTOP_HDD\n+ * defaults (rbps=174019176 rseqiops=41708 rrandiops=370, w-side\n+ * analog) in vtime units where 1s == 2^37.  On a rotational device\n+ * still on ctrl=auto, a device bound to this model through\n+ * io.cost.model charges exactly twice the builtin model under the\n+ * same workload, so the doubled cost is a direct check that\n+ * accounting goes through the BPF path.  On a non-rotational device,\n+ * or one with user-pinned coefficients, the ratio to the builtin\n+ * model is arbitrary.\n+ *\n+ * The cursor handling mirrors the builtin: a zero cursor means \"no\n+ * previous IO\", and the cursor is only advanced for READ and WRITE\n+ * bios the builtin prices, so flushes and discards leave it alone.\n+ *\n+ * The model implements the full linear formula itself, including\n+ * flushes: there is no fallback to the builtin model, a dataless\n+ * WRITE|REQ_PREFLUSH is priced as a one-page write.\n+ */\n+\n+#include \"vmlinux.h\"\n+#include \u003cbpf/bpf_helpers.h\u003e\n+#include \u003cbpf/bpf_tracing.h\u003e\n+\n+/*\n+ * VTIME_PER_SEC, IOC_PAGE_SIZE/SHIFT, IOC_SECT_TO_PAGE_SHIFT and\n+ * IOCOST_COST_F_MERGE come from vmlinux.h (BTF enum constants)\n+ */\n+#define LCOEF_RANDIO_PAGES\t4096\t/* 16MB seek threshold */\n+#define IOCOST_REQ_OP_MASK\t0xff\t\t/* REQ_OP_MASK, not in BTF */\n+\n+/*\n+ * DIV64_U64_ROUND_UP / DIV_ROUND_UP_ULL equivalents, folded at\n+ * compile time\n+ */\n+#define RU(x, y)\t\t((x) / (y) + (((x) % (y)) ? 1 : 0))\n+\n+#define RBPS\t174019176ULL\n+#define RSEQIOPS\t41708ULL\n+#define RRANDIOPS\t370ULL\n+#define WBPS\t178075866ULL\n+#define WSEQIOPS\t42705ULL\n+#define WRANDIOPS\t378ULL\n+\n+#define RPAGE\t(RU(VTIME_PER_SEC, RU(RBPS, IOC_PAGE_SIZE)))\n+#define RSEQIO\t(RU(VTIME_PER_SEC, RSEQIOPS) - RPAGE)\n+#define RRANDIO\t(RU(VTIME_PER_SEC, RRANDIOPS) - RPAGE)\n+#define WPAGE\t(RU(VTIME_PER_SEC, RU(WBPS, IOC_PAGE_SIZE)))\n+#define WSEQIO\t(RU(VTIME_PER_SEC, WSEQIOPS) - WPAGE)\n+#define WRANDIO\t(RU(VTIME_PER_SEC, WRANDIOPS) - WPAGE)\n+\n+/*\n+ * per-cgroup cursor storage: keyed by the cgroup, freed with it, so\n+ * the model never leaks or reuses stale per-cgroup state\n+ */\n+struct {\n+\t__uint(type, BPF_MAP_TYPE_CGRP_STORAGE);\n+\t__uint(map_flags, BPF_F_NO_PREALLOC);\n+\t__type(key, int);\n+\t__type(value, __u64);\n+} cursor_store SEC(\".maps\");\n+\n+SEC(\"struct_ops\")\n+u64 BPF_PROG(iocost_2x_calc_cost, u64 opf, u64 nbytes, u64 sector,\n+\t     struct blkcg *blkcg, u64 model_flags)\n+{\n+\tu64 pages, seek_pages = 0, base, coef_page, randio, cost;\n+\n+\t/* builtin truncates: max(sectors \u003e\u003e IOC_SECT_TO_PAGE_SHIFT, 1) */\n+\tpages = nbytes \u003e\u003e IOC_PAGE_SHIFT;\n+\tif (!pages)\n+\t\tpages = 1;\n+\n+\tif ((opf \u0026 IOCOST_REQ_OP_MASK) == REQ_OP_READ) {\n+\t\tbase = RSEQIO; coef_page = RPAGE; randio = RRANDIO;\n+\t} else if ((opf \u0026 IOCOST_REQ_OP_MASK) == REQ_OP_WRITE) {\n+\t\tbase = WSEQIO; coef_page = WPAGE; randio = WRANDIO;\n+\t} else {\n+\t\t/*\n+\t\t * a fully owning model must price every op; unknown\n+\t\t * ops are priced as a single page write\n+\t\t */\n+\t\tbase = 0; coef_page = WPAGE; randio = 0;\n+\t}\n+\n+\t/*\n+\t * mirror the builtin cursor semantics: seek distance is only\n+\t * computed against a non-zero cursor, and the cursor is\n+\t * advanced for bios the builtin prices (READ/WRITE with a\n+\t * non-zero size), merged ones included, so flushes and\n+\t * discards leave it alone and long merged streams do not\n+\t * drift past the 16MB seek threshold\n+\t */\n+\t{\n+\t\t__u64 *cursor, cur;\n+\t\tint priced = (opf \u0026 IOCOST_REQ_OP_MASK) == REQ_OP_READ ||\n+\t\t\t     (opf \u0026 IOCOST_REQ_OP_MASK) == REQ_OP_WRITE;\n+\n+\t\tcursor = bpf_cgrp_storage_get(\u0026cursor_store,\n+\t\t\t\t\t      blkcg-\u003ecss.cgroup, NULL,\n+\t\t\t\t\t      BPF_LOCAL_STORAGE_GET_F_CREATE);\n+\t\tif (!cursor) {\n+\t\t\tif (model_flags \u0026 IOCOST_COST_F_MERGE)\n+\t\t\t\tbase = 0;\n+\t\t\treturn 2 * (base + pages * coef_page);\n+\t\t}\n+\t\tcur = *cursor;\n+\t\tif (cur \u0026\u0026 priced) {\n+\t\t\tseek_pages = sector \u003e cur ? sector - cur\n+\t\t\t\t\t\t   : cur - sector;\n+\t\t\tseek_pages \u003e\u003e= IOC_SECT_TO_PAGE_SHIFT;\n+\t\t\tif (seek_pages \u003e LCOEF_RANDIO_PAGES)\n+\t\t\t\tbase = randio;\n+\t\t}\n+\t\tif (priced \u0026\u0026 nbytes)\n+\t\t\t*cursor = sector + RU(nbytes, 512);\n+\t}\n+\n+\tif (model_flags \u0026 IOCOST_COST_F_MERGE)\n+\t\tbase = 0;\n+\n+\tcost = 2 * (base + pages * coef_page);\n+\treturn cost;\n+}\n+\n+SEC(\".struct_ops\")\n+struct iocost_model_ops iocost_2x = {\n+\t.calc_cost = (void *)iocost_2x_calc_cost,\n+\t.name = \"iocost_2x\",\n+};\n+\n+char LICENSE[] SEC(\"license\") = \"GPL\";\ndiff --git a/tools/testing/selftests/bpf/progs/iocost_ms.c b/tools/testing/selftests/bpf/progs/iocost_ms.c\nnew file mode 100644\nindex 0000000000000..70019db0fd790\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/progs/iocost_ms.c\n@@ -0,0 +1,156 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/*\n+ * Example multi-stream sequentiality detection cost model.\n+ *\n+ * The builtin model keeps a single cursor per cgroup, so two\n+ * interleaved sequential readers in one cgroup are all priced random\n+ * (measured 89x overcharge, 12.9x throughput collapse), while random\n+ * IO inside a hot window smaller than the 16MB seek threshold is\n+ * priced sequential (measured 107x undercharge).  This model replaces\n+ * the single cursor with a per-cgroup table of stream slots: an IO is\n+ * sequential iff its sector matches the expected next sector of any\n+ * tracked stream.  Interleaved streams keep their own slots, and\n+ * windowed random IO rarely matches a moving expectation.\n+ *\n+ * Stream state lives in a CGRP_STORAGE map, so it is created and\n+ * freed with the cgroup.  The model implements the full builtin\n+ * linear formula itself, including flush pricing.\n+ */\n+#include \"vmlinux.h\"\n+#include \u003cbpf/bpf_helpers.h\u003e\n+#include \u003cbpf/bpf_tracing.h\u003e\n+\n+/*\n+ * VTIME_PER_SEC, IOC_PAGE_SIZE/SHIFT, IOC_SECT_TO_PAGE_SHIFT and\n+ * IOCOST_COST_F_MERGE come from vmlinux.h (BTF enum constants)\n+ */\n+#define IOCOST_REQ_OP_MASK\t0xff\t\t/* REQ_OP_MASK, not in BTF */\n+\n+/*\n+ * DIV64_U64_ROUND_UP / DIV_ROUND_UP_ULL equivalents, folded at\n+ * compile time\n+ */\n+#define RU(x, y)\t\t((x) / (y) + (((x) % (y)) ? 1 : 0))\n+\n+#define RBPS\t174019176ULL\n+#define RSEQIOPS\t41708ULL\n+#define RRANDIOPS\t370ULL\n+#define WBPS\t178075866ULL\n+#define WSEQIOPS\t42705ULL\n+#define WRANDIOPS\t378ULL\n+\n+#define RPAGE\t(RU(VTIME_PER_SEC, RU(RBPS, IOC_PAGE_SIZE)))\n+#define RSEQIO\t(RU(VTIME_PER_SEC, RSEQIOPS) - RPAGE)\n+#define RRANDIO\t(RU(VTIME_PER_SEC, RRANDIOPS) - RPAGE)\n+#define WPAGE\t(RU(VTIME_PER_SEC, RU(WBPS, IOC_PAGE_SIZE)))\n+#define WSEQIO\t(RU(VTIME_PER_SEC, WSEQIOPS) - WPAGE)\n+#define WRANDIO\t(RU(VTIME_PER_SEC, WRANDIOPS) - WPAGE)\n+\n+#define NSLOTS\t4\n+\n+struct streams {\n+\t__u64 expected[NSLOTS];\t/* next expected sector, per stream */\n+\t__u64 stamp[NSLOTS];\t/* LRU stamp, 0 = empty */\n+};\n+\n+/*\n+ * per-cgroup stream table: keyed by the cgroup, freed with it\n+ */\n+struct {\n+\t__uint(type, BPF_MAP_TYPE_CGRP_STORAGE);\n+\t__uint(map_flags, BPF_F_NO_PREALLOC);\n+\t__type(key, int);\n+\t__type(value, struct streams);\n+} stream_tab SEC(\".maps\");\n+\n+SEC(\"struct_ops\")\n+u64 BPF_PROG(iocost_ms_calc_cost, u64 opf, u64 nbytes, u64 sector,\n+\t     struct blkcg *blkcg, u64 model_flags)\n+{\n+\tstruct streams *s;\n+\tu64 pages, base, coef_page, randio, advance, now;\n+\tu32 i, victim = 0, found = 0xFFFFFFFF;\n+\n+\tif ((opf \u0026 IOCOST_REQ_OP_MASK) == REQ_OP_READ) {\n+\t\tbase = RSEQIO; coef_page = RPAGE; randio = RRANDIO;\n+\t} else if ((opf \u0026 IOCOST_REQ_OP_MASK) == REQ_OP_WRITE) {\n+\t\tbase = WSEQIO; coef_page = WPAGE; randio = WRANDIO;\n+\t} else {\n+\t\t/*\n+\t\t * a fully owning model must price every op; unknown\n+\t\t * ops are priced as per-page writes\n+\t\t */\n+\t\tbase = 0; coef_page = WPAGE; randio = 0;\n+\t}\n+\tadvance = RU(nbytes, 512);\t/* sectors */\n+\n+\t/* only bios the builtin prices participate in stream tracking */\n+\tif (!(((opf \u0026 IOCOST_REQ_OP_MASK) == REQ_OP_READ ||\n+\t       (opf \u0026 IOCOST_REQ_OP_MASK) == REQ_OP_WRITE) \u0026\u0026 nbytes)) {\n+\t\tpages = nbytes \u003e\u003e IOC_PAGE_SHIFT;\n+\t\tif (!pages)\n+\t\t\tpages = 1;\n+\t\treturn base + pages * coef_page;\n+\t}\n+\n+\ts = bpf_cgrp_storage_get(\u0026stream_tab, blkcg-\u003ecss.cgroup, NULL,\n+\t\t\t\t BPF_LOCAL_STORAGE_GET_F_CREATE);\n+\tif (!s) {\n+\t\t/* no storage: price per page, truncating like the builtin */\n+\t\tpages = nbytes \u003e\u003e IOC_PAGE_SHIFT;\n+\t\tif (!pages)\n+\t\t\tpages = 1;\n+\t\treturn base + pages * coef_page;\n+\t}\n+\n+\t/*\n+\t * Slot access is lockless, mirroring the builtin single-cursor\n+\t * update in ioc_rqos_throttle(): concurrent CPUs submitting for\n+\t * the same cgroup can race on slot updates; mispricing is\n+\t * bounded and acceptable for an example model.\n+\t */\n+\tnow = bpf_ktime_get_ns();\n+\tfor (i = 0; i \u003c NSLOTS; i++) {\n+\t\tif (s-\u003eexpected[i] == sector \u0026\u0026 s-\u003estamp[i]) {\n+\t\t\tfound = i;\n+\t\t\tbreak;\n+\t\t}\n+\t}\n+\tif (found != 0xFFFFFFFF) {\n+\t\t/* sequential: keep the seq base from the op branch */\n+\t\ts-\u003eexpected[found] = sector + advance;\n+\t\ts-\u003estamp[found] = now;\n+\t} else {\n+\t\tbase = randio;\n+\t\tfor (i = 1; i \u003c NSLOTS; i++) {\n+\t\t\tif (s-\u003estamp[i] \u003c s-\u003estamp[victim])\n+\t\t\t\tvictim = i;\n+\t\t}\n+\t\ts-\u003eexpected[victim] = sector + advance;\n+\t\ts-\u003estamp[victim] = now;\n+\t}\n+\n+\t/* builtin truncates: max(sectors \u003e\u003e IOC_SECT_TO_PAGE_SHIFT, 1) */\n+\tpages = nbytes \u003e\u003e IOC_PAGE_SHIFT;\n+\tif (!pages)\n+\t\tpages = 1;\n+\tif (model_flags \u0026 IOCOST_COST_F_MERGE) {\n+\t\t/*\n+\t\t * merged bios skip the base cost but still advance\n+\t\t * the stream position above, so a merge at the\n+\t\t * expected sector does not make the following new IO\n+\t\t * look random\n+\t\t */\n+\t\tbase = 0;\n+\t}\n+\n+\treturn base + pages * coef_page;\n+}\n+\n+SEC(\".struct_ops\")\n+struct iocost_model_ops iocost_ms = {\n+\t.calc_cost = (void *)iocost_ms_calc_cost,\n+\t.name = \"iocost_ms\",\n+};\n+\n+char LICENSE[] SEC(\"license\") = \"GPL\";\n"
}

2/1 2026/09/20 09:39 agent patch-evaluator
1m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "BLK_CGROUP_IOCOST_BPF",
    "BLK_CGROUP_IOCOST",
    "BLK_CGROUP",
    "BPF_SYSCALL",
    "BPF_JIT",
    "DEBUG_INFO_BTF"
  ],
  "FocusSymbols": [
    "ioc_cost_model_write",
    "iocost_bpf_model_get",
    "iocost_bpf_model_put",
    "bpf_iocost_reg",
    "bpf_iocost_unreg",
    "bpf_iocost_validate",
    "calc_vtime_cost",
    "calc_size_vtime_cost",
    "iocost_notify_blkcg_online",
    "iocost_notify_blkcg_offline"
  ],
  "Reasoning": "The patch introduces pluggable BPF struct_ops cost model support (iocost_model_ops) for the cgroup iocost controller, bound via cgroup v2's io.cost.model interface. It modifies core block cgroup and iocost pricing logic, introduces complex refcounting and lifecycle state machines between BPF struct_ops map/link lifetime and bound block devices, hooks into blkcg css online/offline callbacks, and accesses the BPF model under RCU during I/O dispatch. This code is fully reachable in standard virtualized environments via BPF and cgroup syscalls and warrants fuzzing for concurrency, refcounting, and synchronization issues.",
  "WorthFuzzing": true
}

Instruction:
You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.

IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.

================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.

- REACHABILITY IS THE PRIMARY GATE:
  Fuzzing can only discover bugs in code that can actually execute in standard virtualized
  environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
  If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
  regardless of whether it adds assertions or complex logic.

- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
  Patch authors routinely label changes as "cleanups", "refactorings", or state
  "No functional change intended". Do NOT take these claims at face value.
  Code refactorings that rearrange logic, introduce helper functions, or alter state management
  in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
  If reachable executable code is modified or refactored, it MUST be fuzzed.

- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
  When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
  BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
  Even if the author believes the invariant always holds, fuzzing is essential to verify whether
  an unusual sequence of operations can violate it.

================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:

- Non-kernel and non-executable changes:
  * Modifications to Documentation/, comments, or spelling fixes.
  * User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
    that do not affect the compiled kernel image (vmlinux) or kernel modules.
  * Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
    that do not alter control flow or data structures.
  * Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
  * Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
    ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
  * Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
    physical PCI hot-unplug or manual sysfs driver unbinding.
  * Code paths exclusive to architectures other than the target architecture.

================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
  * Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
    BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
  * Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
  * Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
  * Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).

================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:

- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
  Do NOT list generic, ubiquitous functions called by almost every program in the corpus
  (including, but not limited to: general memory allocators and deallocators, page fault
  and trap handlers, or core synchronization primitives; this is not an exhaustive list).
  Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
  which severely dilutes fuzzing effort away from the actual changes.

- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
  List functions that specifically implement the logic being added or altered, or direct API entrypoints
  for the subsystem feature under review.

- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
  Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
  distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
  If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
  functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).

================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit 8b534faffc0c4eb3a498186f6484e9fc42190b59
Author: syz-cluster <triage@syzkaller.com>
Date:   Sun Sep 20 09:39:48 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/admin-guide/cgroup-v2.rst b/Documentation/admin-guide/cgroup-v2.rst
index 8d2603751c51a..d9d82559e2bc6 100644
--- a/Documentation/admin-guide/cgroup-v2.rst
+++ b/Documentation/admin-guide/cgroup-v2.rst
@@ -2115,8 +2115,10 @@ IO Interface Files
 	are defined.
 
 	  =====		================================
-	  ctrl		"auto" or "user"
+	  ctrl		"auto", "user" or "bpf"
 	  model		The cost model in use - "linear"
+			or the name of the bound
+			model
 	  =====		================================
 
 	When "ctrl" is "auto", the kernel may change all parameters
@@ -2124,6 +2126,23 @@ IO Interface Files
 	parameters are written to, "ctrl" become "user" and the
 	automatic changes are disabled.
 
+	When CONFIG_BLK_CGROUP_IOCOST_BPF is enabled, a bound model is
+	read back as "ctrl=bpf model=<name>", and writing "ctrl=bpf" is
+	accepted as a no-op so a saved configuration can be restored as-is.
+	"model" also accepts
+	the name of a registered iocost_model_ops BPF struct_ops model:
+	"model=<name>" binds the model to the device and the model fully
+	replaces the builtin linear pricing, for every operation including
+	flushes; "model=linear" (or "ctrl=auto/user") restores the builtin
+	model.  Writing an unknown name fails with ENOENT and nothing is
+	applied.  Unregistering a model removes its name from the
+	registry; devices already bound keep using it, and keep receiving
+	cgroup lifecycle notifications, until switched back to the builtin
+	model, and its name keeps working for writes (so a coefficient-only
+	write does not disturb the binding) until the last device unbinds.
+	See
+	include/linux/blk-iocost.h for the model interface.
+
 	When "model" is "linear", the following model parameters are
 	defined.
 
diff --git a/block/Kconfig b/block/Kconfig
index 70e4a66d941ff..91e808f86d28d 100644
--- a/block/Kconfig
+++ b/block/Kconfig
@@ -231,4 +231,13 @@ config BLK_ERROR_INJECTION
 
 source "block/Kconfig.iosched"
 
+config BLK_CGROUP_IOCOST_BPF
+	bool "Enable BPF pluggable cost model support for the cost IO controller"
+	depends on BLK_CGROUP_IOCOST && BPF_SYSCALL && BPF_JIT && DEBUG_INFO_BTF
+	help
+	 Enabling this option registers the "iocost_model_ops" BPF
+	 struct_ops type, which allows a BPF program to fully replace
+	 the builtin linear cost model on a device it is bound to
+	 through io.cost.model.
+
 endif # BLOCK
diff --git a/block/Makefile b/block/Makefile
index e7bd320e3d697..ee5cebeea006f 100644
--- a/block/Makefile
+++ b/block/Makefile
@@ -39,3 +39,4 @@ obj-$(CONFIG_BLK_INLINE_ENCRYPTION)	+= blk-crypto.o blk-crypto-profile.o \
 					   blk-crypto-sysfs.o
 obj-$(CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK)	+= blk-crypto-fallback.o
 obj-$(CONFIG_BLOCK_HOLDER_DEPRECATED)	+= holder.o
+obj-$(CONFIG_BLK_CGROUP_IOCOST_BPF)	+= blk-iocost-bpf.o
diff --git a/block/blk-cgroup.c b/block/blk-cgroup.c
index b56db1cc6778f..b08ceb94a281b 100644
--- a/block/blk-cgroup.c
+++ b/block/blk-cgroup.c
@@ -32,6 +32,7 @@
 #include <linux/part_stat.h>
 #include "blk.h"
 #include "blk-cgroup.h"
+#include <linux/blk-iocost.h>
 #include "blk-ioprio.h"
 #include "blk-throttle.h"
 
@@ -1341,6 +1342,7 @@ void blkcg_unpin_online(struct cgroup_subsys_state *blkcg_css)
  */
 static void blkcg_css_offline(struct cgroup_subsys_state *css)
 {
+	iocost_notify_blkcg_offline(css_to_blkcg(css));
 	/* this prevents anyone from attaching or migrating to this blkcg */
 	wb_blkcg_offline(css);
 
@@ -1447,6 +1449,8 @@ static int blkcg_css_online(struct cgroup_subsys_state *css)
 {
 	struct blkcg *parent = blkcg_parent(css_to_blkcg(css));
 
+	iocost_notify_blkcg_online(css_to_blkcg(css));
+
 	/*
 	 * blkcg_pin_online() is used to delay blkcg offline so that blkgs
 	 * don't go offline while cgwbs are still active on them.  Pin the
diff --git a/block/blk-iocost-bpf.c b/block/blk-iocost-bpf.c
new file mode 100644
index 0000000000000..444ca52ed0b08
--- /dev/null
+++ b/block/blk-iocost-bpf.c
@@ -0,0 +1,321 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * blk-iocost: BPF struct_ops plumbing for pluggable cost models.
+ *
+ * Registers the "iocost_model_ops" struct_ops type and maintains the
+ * name registry of registered models.  A registered model is bound to
+ * a device through io.cost.model; see include/linux/blk-iocost.h.
+ */
+#include <linux/init.h>
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/mutex.h>
+#include <linux/slab.h>
+#include <linux/bpf.h>
+#include <linux/bpf_verifier.h>
+#include <linux/btf.h>
+#include <linux/blk-iocost.h>
+
+static DEFINE_MUTEX(iocost_bpf_reg_lock);
+static LIST_HEAD(iocost_bpf_models);
+static LIST_HEAD(iocost_bpf_lifecycle);
+
+/*
+ * One node per registered model.  refcount: 1 while registered
+ * (dropped in .unreg) plus one per bound device (dropped in
+ * iocost_bpf_model_put(), which pairs its bpf_struct_ops_get(), so the
+ * kdata of an unregistered model stays alive while any device is still
+ * bound to it).  The node sits on the lifecycle notify list exactly
+ * while at least one device has the model bound.
+ */
+struct iocost_bpf_model {
+	struct list_head	list;		/* name registry */
+	struct list_head	lifecycle;	/* lifecycle notify list */
+	const struct iocost_model_ops *ops;
+	refcount_t		refs;
+};
+
+/*
+ * Take a name and acquire a binding reference on the model it selects.
+ * The registry is searched first; a model which is unregistered but
+ * still bound to a device remains selectable by name until the last
+ * device unbinds, so a coefficient-only write on such a device keeps
+ * the model bound instead of failing with ENOENT.  The registry lock
+ * is held across the lookup and bpf_struct_ops_get() so the model
+ * cannot be unregistered in between.  Returns the ops or an ERR_PTR.
+ */
+const struct iocost_model_ops *iocost_bpf_model_get(const char *name)
+{
+	struct iocost_bpf_model *m;
+	const struct iocost_model_ops *ops = ERR_PTR(-ENOENT);
+
+	mutex_lock(&iocost_bpf_reg_lock);
+	list_for_each_entry(m, &iocost_bpf_models, list) {
+		if (!strcmp(m->ops->name, name))
+			goto found;
+	}
+	list_for_each_entry(m, &iocost_bpf_lifecycle, lifecycle) {
+		if (!strcmp(m->ops->name, name))
+			goto found;
+	}
+	mutex_unlock(&iocost_bpf_reg_lock);
+	return ops;
+found:
+	if (bpf_struct_ops_get(m->ops)) {
+		refcount_inc(&m->refs);
+		/* first bind: join the notify list */
+		if (refcount_read(&m->refs) == 2 &&
+		    list_empty(&m->lifecycle))
+			list_add(&m->lifecycle, &iocost_bpf_lifecycle);
+		ops = m->ops;
+	}
+	mutex_unlock(&iocost_bpf_reg_lock);
+	return ops;
+}
+
+static struct iocost_bpf_model *
+iocost_bpf_model_lookup(const struct iocost_model_ops *ops)
+{
+	struct iocost_bpf_model *m;
+
+	list_for_each_entry(m, &iocost_bpf_models, list) {
+		if (m->ops == ops)
+			return m;
+	}
+	return NULL;
+}
+
+/*
+ * Lifecycle notifications walk the lifecycle list, which keeps a node
+ * for as long as any device has the model bound, so an unregistered
+ * but still-bound model keeps receiving blkcg online/offline.
+ */
+void iocost_notify_blkcg_online(struct blkcg *blkcg)
+{
+	struct iocost_bpf_model *m;
+
+	guard(mutex)(&iocost_bpf_reg_lock);
+	list_for_each_entry(m, &iocost_bpf_lifecycle, lifecycle) {
+		if (m->ops->blkcg_online)
+			m->ops->blkcg_online(blkcg);
+	}
+}
+
+void iocost_notify_blkcg_offline(struct blkcg *blkcg)
+{
+	struct iocost_bpf_model *m;
+
+	guard(mutex)(&iocost_bpf_reg_lock);
+	list_for_each_entry(m, &iocost_bpf_lifecycle, lifecycle) {
+		if (m->ops->blkcg_offline)
+			m->ops->blkcg_offline(blkcg);
+	}
+}
+
+static int bpf_iocost_model_init(struct btf *btf)
+{
+	s32 type_id;
+
+	type_id = btf_find_by_name_kind(btf, "iocost_model_ops", BTF_KIND_STRUCT);
+	if (type_id < 0)
+		return -EINVAL;
+	return 0;
+}
+
+static bool bpf_iocost_is_valid_access(int off, int size,
+				       enum bpf_access_type type,
+				       const struct bpf_prog *prog,
+				       struct bpf_insn_access_aux *info)
+{
+	return bpf_tracing_btf_ctx_access(off, size, type, prog, info);
+}
+
+/*
+ * No iocost-specific helpers; bpf_base_func_proto already covers the
+ * cgroup storage helpers under CONFIG_CGROUPS.
+ */
+static const struct bpf_func_proto *
+bpf_iocost_get_func_proto(enum bpf_func_id func_id,
+			  const struct bpf_prog *prog)
+{
+	return bpf_base_func_proto(func_id, prog);
+}
+
+static int bpf_iocost_check_member(const struct btf_type *t,
+				   const struct btf_member *member,
+				   const struct bpf_prog *prog)
+{
+	/* calc_cost() is called with RCU read lock held */
+	if (prog->sleepable)
+		return -EINVAL;
+	return 0;
+}
+
+static int bpf_iocost_init_member(const struct btf_type *t,
+				  const struct btf_member *member,
+				  void *kdata, const void *udata)
+{
+	struct iocost_model_ops *ops = kdata;
+	const struct iocost_model_ops *uops = udata;
+	u32 moff = __btf_member_bit_offset(t, member) / 8;
+
+	switch (moff) {
+	case offsetof(struct iocost_model_ops, name):
+		if (bpf_obj_name_cpy(ops->name, uops->name,
+				     sizeof(ops->name)) <= 0)
+			return -EINVAL;
+		return 1;
+	}
+
+	return 0;
+}
+
+/*
+ * kvalue is zeroed at map allocation and function members are only
+ * written when the BPF side provides a prog, so a model which did
+ * not implement calc_cost leaves it NULL.  The dispatch would call
+ * it on every bio, so reject it here.
+ */
+static int bpf_iocost_validate(void *kdata)
+{
+	struct iocost_model_ops *ops = kdata;
+
+	if (!ops->calc_cost)
+		return -EINVAL;
+	/* "linear" is the builtin model; model=linear unbinds */
+	if (!strcmp(ops->name, "linear"))
+		return -EINVAL;
+	return 0;
+}
+
+/*
+ * The struct_ops core holds a reference on the map while the model is
+ * registered, so kdata stays valid until .unreg returns; no extra
+ * reference is needed here.
+ */
+static int bpf_iocost_reg(void *kdata, struct bpf_link *link)
+{
+	struct iocost_model_ops *ops = kdata;
+	struct iocost_bpf_model *m;
+	int ret = 0;
+
+	m = kzalloc_obj(struct iocost_bpf_model, GFP_KERNEL);
+	if (!m)
+		return -ENOMEM;
+	refcount_set(&m->refs, 1);
+	INIT_LIST_HEAD(&m->lifecycle);
+
+	mutex_lock(&iocost_bpf_reg_lock);
+	{
+		struct iocost_bpf_model *other;
+
+		list_for_each_entry(other, &iocost_bpf_models, list) {
+			if (!strcmp(other->ops->name, ops->name)) {
+				ret = -EEXIST;
+				break;
+			}
+		}
+	}
+	if (!ret) {
+		m->ops = ops;
+		list_add(&m->list, &iocost_bpf_models);
+	}
+	mutex_unlock(&iocost_bpf_reg_lock);
+
+	if (ret)
+		kfree(m);
+	return ret;
+}
+
+/*
+ * Unregistering drops the registration reference.  If a device is
+ * still bound, the binding references keep the node (and the kdata,
+ * through their bpf_struct_ops_get()) alive and it keeps receiving
+ * blkcg online/offline notifications; otherwise the node is freed.
+ */
+static void bpf_iocost_unreg(void *kdata, struct bpf_link *link)
+{
+	struct iocost_model_ops *ops = kdata;
+	struct iocost_bpf_model *m;
+
+	mutex_lock(&iocost_bpf_reg_lock);
+	m = iocost_bpf_model_lookup(ops);
+	if (m) {
+		/*
+		 * keep the linkage queryable so model_put() can tell a
+		 * still-registered node (one ref held by the registry)
+		 * from one kept alive only by device bindings
+		 */
+		list_del_init(&m->list);
+		if (refcount_dec_and_test(&m->refs))
+			kfree(m);
+	}
+	mutex_unlock(&iocost_bpf_reg_lock);
+}
+
+void iocost_bpf_model_put(const struct iocost_model_ops *ops)
+{
+	struct iocost_bpf_model *m;
+
+	mutex_lock(&iocost_bpf_reg_lock);
+	list_for_each_entry(m, &iocost_bpf_lifecycle, lifecycle) {
+		if (m->ops == ops)
+			break;
+	}
+	if (&m->lifecycle != &iocost_bpf_lifecycle) {
+		bool freed = refcount_dec_and_test(&m->refs);
+
+		/*
+		 * leave the notify list with the last binding: refs is
+		 * now zero (node freed) or the registry's single one
+		 */
+		if (freed || (!list_empty(&m->list) &&
+			      refcount_read(&m->refs) == 1))
+			list_del_init(&m->lifecycle);
+		mutex_unlock(&iocost_bpf_reg_lock);
+		bpf_struct_ops_put(ops);
+		if (freed)
+			kfree(m);
+		return;
+	}
+	mutex_unlock(&iocost_bpf_reg_lock);
+}
+
+static const struct bpf_verifier_ops bpf_iocost_verifier_ops = {
+	.get_func_proto = bpf_iocost_get_func_proto,
+	.is_valid_access = bpf_iocost_is_valid_access,
+};
+
+static u64 bpf_iocost_calc_cost_stub(u64 opf, u64 nbytes, u64 sector,
+				     struct blkcg *blkcg, u64 flags)
+{
+	return 0;
+}
+
+static void bpf_iocost_blkcg_online_stub(struct blkcg *blkcg) { }
+static void bpf_iocost_blkcg_offline_stub(struct blkcg *blkcg) { }
+
+static struct iocost_model_ops __bpf_ops_iocost_model_ops = {
+	.calc_cost = bpf_iocost_calc_cost_stub,
+	.blkcg_online = bpf_iocost_blkcg_online_stub,
+	.blkcg_offline = bpf_iocost_blkcg_offline_stub,
+};
+
+static struct bpf_struct_ops bpf_iocost_model_ops = {
+	.verifier_ops = &bpf_iocost_verifier_ops,
+	.init = bpf_iocost_model_init,
+	.check_member = bpf_iocost_check_member,
+	.init_member = bpf_iocost_init_member,
+	.validate = bpf_iocost_validate,
+	.reg = bpf_iocost_reg,
+	.unreg = bpf_iocost_unreg,
+	.name = "iocost_model_ops",
+	.cfi_stubs = &__bpf_ops_iocost_model_ops,
+	.owner = THIS_MODULE,
+};
+
+static int __init bpf_iocost_init(void)
+{
+	return register_bpf_struct_ops(&bpf_iocost_model_ops, iocost_model_ops);
+}
+late_initcall(bpf_iocost_init);
diff --git a/block/blk-iocost.c b/block/blk-iocost.c
index 2745bffcd5eef..9eb97f38a39cf 100644
--- a/block/blk-iocost.c
+++ b/block/blk-iocost.c
@@ -177,6 +177,7 @@
 #include <linux/timer.h>
 #include <linux/time64.h>
 #include <linux/parser.h>
+#include <linux/blk-iocost.h>
 #include <linux/sched/signal.h>
 #include <asm/local.h>
 #include <asm/local64.h>
@@ -445,6 +446,11 @@ struct ioc {
 	int				autop_idx;
 	bool				user_qos_params:1;
 	bool				user_cost_model:1;
+
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	/* bound BPF cost model, NULL = builtin linear model */
+	const struct iocost_model_ops	__rcu *model;
+#endif
 };
 
 struct iocg_pcpu_stat {
@@ -2238,6 +2244,10 @@ static void ioc_timer_fn(struct timer_list *timer)
 	struct ioc_now now;
 	LIST_HEAD(surpluses);
 	int nr_debtors, nr_shortages = 0, nr_lagging = 0;
+	int nr_active = 0;
+	u32 tick_period_us;
+	u64 tick_vrate, tick_dur;
+	int tick_busy, tick_running;
 	u64 usage_us_sum = 0;
 	u32 ppm_rthr;
 	u32 ppm_wthr;
@@ -2274,6 +2284,8 @@ static void ioc_timer_fn(struct timer_list *timer)
 		u64 vdone, vtime, usage_us;
 		u32 hw_active, hw_inuse;
 
+		nr_active++;
+
 		/*
 		 * Collect unused and wind vtime closer to vnow to prevent
 		 * iocgs from accumulating a large amount of budget.
@@ -2435,6 +2447,14 @@ static void ioc_timer_fn(struct timer_list *timer)
 
 	ioc->busy_level = clamp(ioc->busy_level, -1000, 1000);
 
+	/*
+	 * vrate and period_us change right below; snapshot the values
+	 * this period ran in so the tick below reports the period's own
+	 * parameters instead of the next period's.
+	 */
+	tick_period_us = ioc->period_us;
+	tick_vrate = ioc->vtime_base_rate;
+
 	ioc_adjust_base_vrate(ioc, rq_wait_pct, nr_lagging, nr_shortages,
 			      prev_busy_level, missed_ppm);
 
@@ -2442,6 +2462,24 @@ static void ioc_timer_fn(struct timer_list *timer)
 
 	ioc_forgive_debts(ioc, usage_us_sum, nr_debtors, &now);
 
+	/*
+	 * Snapshot the state this period ran in before the idle
+	 * transition below wipes it, so the final tick reports the period's
+	 * own busy level (e.g. the saturation that drove the controller
+	 * idle) instead of the cleared one.  usage is normalized by the
+	 * measured period length, captured before ioc_start_period()
+	 * overwrites period_at, the same way the donation loop does.
+	 * Emitted before cur_period is bumped, so the tick carries the
+	 * number of the period it describes.
+	 */
+	tick_busy = ioc->busy_level;
+	tick_running = ioc->running;
+	tick_dur = now.now - ioc->period_at;
+
+	trace_iocost_ioc_tick(ioc, nr_active, usage_us_sum,
+			      tick_period_us, tick_vrate,
+			      tick_busy, tick_running, tick_dur);
+
 	/*
 	 * This period is done.  Move onto the next one.  If nothing's
 	 * going on with the device, stop the timer.
@@ -2571,10 +2609,28 @@ static void calc_vtime_cost_builtin(struct bio *bio, struct ioc_gq *iocg,
 
 static u64 calc_vtime_cost(struct bio *bio, struct ioc_gq *iocg, bool is_merge)
 {
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	const struct iocost_model_ops *model;
 	u64 cost;
 
-	calc_vtime_cost_builtin(bio, iocg, is_merge, &cost);
-	return cost;
+	rcu_read_lock();
+	model = rcu_dereference(iocg->ioc->model);
+	if (model) {
+		cost = model->calc_cost(bio->bi_opf, bio->bi_iter.bi_size,
+					bio->bi_iter.bi_sector,
+					iocg_to_blkg(iocg)->blkcg,
+					is_merge ? IOCOST_COST_F_MERGE : 0);
+		rcu_read_unlock();
+		return min(cost, VTIME_PER_SEC);
+	}
+	rcu_read_unlock();
+#endif
+	{
+		u64 cost;
+
+		calc_vtime_cost_builtin(bio, iocg, is_merge, &cost);
+		return cost;
+	}
 }
 
 static void calc_size_vtime_cost_builtin(struct request *rq, struct ioc *ioc,
@@ -2596,10 +2652,28 @@ static void calc_size_vtime_cost_builtin(struct request *rq, struct ioc *ioc,
 
 static u64 calc_size_vtime_cost(struct request *rq, struct ioc *ioc)
 {
-	u64 cost;
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	const struct iocost_model_ops *model;
 
-	calc_size_vtime_cost_builtin(rq, ioc, &cost);
-	return cost;
+	rcu_read_lock();
+	model = rcu_dereference(ioc->model);
+	if (model && rq->bio && rq->bio->bi_blkg) {
+		u64 cost;
+
+		cost = model->calc_cost(rq->cmd_flags, blk_rq_bytes(rq),
+					blk_rq_pos(rq),
+					rq->bio->bi_blkg->blkcg, 0);
+		rcu_read_unlock();
+		return min(cost, VTIME_PER_SEC);
+	}
+	rcu_read_unlock();
+#endif
+	{
+		u64 cost;
+
+		calc_size_vtime_cost_builtin(rq, ioc, &cost);
+		return cost;
+	}
 }
 
 enum over_budget_action {
@@ -2900,6 +2974,19 @@ static void ioc_rqos_exit(struct rq_qos *rqos)
 
 	timer_shutdown_sync(&ioc->timer);
 	free_percpu(ioc->pcpu_stat);
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	{
+		const struct iocost_model_ops *model;
+
+		spin_lock_irq(&ioc->lock);
+		model = rcu_dereference_protected(ioc->model,
+					lockdep_is_held(&ioc->lock));
+		rcu_assign_pointer(ioc->model, NULL);
+		spin_unlock_irq(&ioc->lock);
+		if (model)
+			iocost_bpf_model_put(model);
+	}
+#endif
 	kfree(ioc);
 }
 
@@ -3438,12 +3525,30 @@ static u64 ioc_cost_model_prfill(struct seq_file *sf,
 		return 0;
 
 	spin_lock_irq(&ioc->lock);
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	{
+		const struct iocost_model_ops *model =
+			rcu_dereference_protected(ioc->model,
+					lockdep_is_held(&ioc->lock));
+
+		seq_printf(sf, "%s ctrl=%s model=%s "
+			   "rbps=%llu rseqiops=%llu rrandiops=%llu "
+			   "wbps=%llu wseqiops=%llu wrandiops=%llu\n",
+			   dname, model ? "bpf" :
+				   ioc->user_cost_model ? "user" : "auto",
+			   model ? model->name : "linear",
+			   u[I_LCOEF_RBPS], u[I_LCOEF_RSEQIOPS],
+			   u[I_LCOEF_RRANDIOPS], u[I_LCOEF_WBPS],
+			   u[I_LCOEF_WSEQIOPS], u[I_LCOEF_WRANDIOPS]);
+	}
+#else
 	seq_printf(sf, "%s ctrl=%s model=linear "
 		   "rbps=%llu rseqiops=%llu rrandiops=%llu "
 		   "wbps=%llu wseqiops=%llu wrandiops=%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]);
+#endif
 	spin_unlock_irq(&ioc->lock);
 	return 0;
 }
@@ -3457,6 +3562,48 @@ static int ioc_cost_model_show(struct seq_file *sf, void *v)
 	return 0;
 }
 
+/*
+ * Resolve the model name and take a reference on the new model before
+ * anything is applied, so a bad name rejects the whole write.  The
+ * registry lookup takes the registration mutex and must stay outside
+ * ioc->lock.  The returned model is per-write state passed back into
+ * ioc_bpf_model_commit(), which performs the pointer swap under
+ * ioc->lock so concurrent writers cannot interleave a half-applied
+ * configuration, and the caller drops the old model's reference
+ * afterwards.
+ */
+static const struct iocost_model_ops *
+ioc_bpf_model_prepare(const char *name)
+{
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	if (!name[0])
+		return NULL;
+	return iocost_bpf_model_get(name);
+#else
+	return name[0] ? ERR_PTR(-ENOENT) : NULL;
+#endif
+}
+
+/*
+ * Swap in the model returned by ioc_bpf_model_prepare().  Called with
+ * ioc->lock held; dropping the old model's reference may sleep, so
+ * the caller does it after releasing the lock.
+ */
+static const struct iocost_model_ops *
+ioc_bpf_model_commit(struct ioc *ioc, const struct iocost_model_ops *new)
+{
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	const struct iocost_model_ops *old;
+
+	old = rcu_dereference_protected(ioc->model,
+					lockdep_is_held(&ioc->lock));
+	rcu_assign_pointer(ioc->model, new);
+	return old;
+#else
+	return NULL;
+#endif
+}
+
 static const match_table_t cost_ctrl_tokens = {
 	{ COST_CTRL,		"ctrl=%s"	},
 	{ COST_MODEL,		"model=%s"	},
@@ -3482,6 +3629,7 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 	struct ioc *ioc;
 	u64 u[NR_I_LCOEFS];
 	bool user;
+	char bpf_model[IOCOST_MODEL_NAME_LEN];
 	char *body, *p;
 	int ret;
 
@@ -3512,6 +3660,25 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 	spin_lock_irq(&ioc->lock);
 	memcpy(u, ioc->params.i_lcoefs, sizeof(u));
 	user = ioc->user_cost_model;
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	{
+		const struct iocost_model_ops *model =
+			rcu_dereference_protected(ioc->model,
+					lockdep_is_held(&ioc->lock));
+
+		/*
+		 * seed from the bound model so a coefficient-only write
+		 * keeps it bound; ctrl=auto/user and model=linear are
+		 * the explicit ways back to the builtin model
+		 */
+		if (model)
+			strscpy(bpf_model, model->name, sizeof(bpf_model));
+		else
+			bpf_model[0] = '\0';
+	}
+#else
+	bpf_model[0] = '\0';
+#endif
 
 	ret = -EINVAL;
 
@@ -3527,17 +3694,27 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 		switch (match_token(p, cost_ctrl_tokens, args)) {
 		case COST_CTRL:
 			match_strlcpy(buf, &args[0], sizeof(buf));
-			if (!strcmp(buf, "auto"))
+			if (!strcmp(buf, "auto")) {
 				user = false;
-			else if (!strcmp(buf, "user"))
+			} else if (!strcmp(buf, "user")) {
 				user = true;
-			else
+			} else if (!strcmp(buf, "bpf")) {
+				/* readback value; keep the bound model */
+				continue;
+			} else {
 				goto unlock;
+			}
+			/* ctrl=auto/user: explicit return to builtin */
+			bpf_model[0] = '\0';
 			continue;
 		case COST_MODEL:
 			match_strlcpy(buf, &args[0], sizeof(buf));
-			if (strcmp(buf, "linear"))
-				goto unlock;
+			if (!strcmp(buf, "linear")) {
+				/* back to the builtin linear model */
+				bpf_model[0] = '\0';
+				continue;
+			}
+			match_strlcpy(bpf_model, &args[0], sizeof(bpf_model));
 			continue;
 		}
 
@@ -3550,19 +3727,34 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 		user = true;
 	}
 
-	if (user) {
-		memcpy(ioc->params.i_lcoefs, u, sizeof(u));
-		ioc->user_cost_model = true;
-	} else {
-		ioc->user_cost_model = false;
-	}
-	ioc_refresh_params(ioc, true);
-
 	ret = 0;
 
 unlock:
 	spin_unlock_irq(&ioc->lock);
 
+	/* resolve the name outside ioc->lock; see ioc_bpf_model_prepare() */
+	if (!ret) {
+		const struct iocost_model_ops *new, *old;
+
+		new = ioc_bpf_model_prepare(bpf_model);
+		if (IS_ERR(new)) {
+			ret = PTR_ERR(new);
+		} else {
+			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;
+			}
+			ioc_refresh_params(ioc, true);
+			old = ioc_bpf_model_commit(ioc, new);
+			spin_unlock_irq(&ioc->lock);
+			if (IS_ENABLED(CONFIG_BLK_CGROUP_IOCOST_BPF) && old)
+				iocost_bpf_model_put(old);
+		}
+	}
+
 	blk_mq_unquiesce_queue(q);
 	blk_mq_unfreeze_queue(q, memflags);
 
diff --git a/include/linux/blk-iocost.h b/include/linux/blk-iocost.h
new file mode 100644
index 0000000000000..e6dc6772ef5c9
--- /dev/null
+++ b/include/linux/blk-iocost.h
@@ -0,0 +1,86 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _LINUX_BLK_IOCOST_H
+#define _LINUX_BLK_IOCOST_H
+
+#include <linux/types.h>
+#include <linux/blk_types.h>
+
+#define IOCOST_MODEL_NAME_LEN	16
+
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+
+struct blkcg;
+
+/*
+ * Pluggable cost model interface for blk-iocost.
+ *
+ * A BPF struct_ops implementation registered against "iocost_model_ops"
+ * fully replaces the builtin linear model on the devices it is bound to
+ * through io.cost.model.  The model owns pricing for every IO on a bound
+ * device: it prices all operations, including flushes, and it is called
+ * from the bio charging path.  The completion-time request sizing for
+ * the latency met/missed accounting still uses the builtin coefficients
+ * (the request's bio, and with it the issuing cgroup, is gone by then);
+ * extending the model there is left open by this interface.
+ *
+ * calc_cost() is called from the IO submission path with RCU read lock
+ * held and must not sleep.  It returns the cost of the IO in vtime
+ * units, where 1 second of device time equals VTIME_PER_SEC (2^37,
+ * available to BPF programs through vmlinux.h).  The returned value is
+ * clamped to 1 second of device time per IO.
+ *
+ * The model is passed the blkcg of the issuing cgroup so it can keep
+ * per-cgroup state.  State keyed by the blkcg alone is shared across
+ * every device the model is bound to, unlike the builtin cursor which
+ * is per (cgroup, device).  blkcg_online()/blkcg_offline() are optional
+ * callbacks mirroring the blkcg css lifecycle: they are delivered
+ * only while at least one device has the model bound, and state
+ * created on online (or lazily on first use) must be released on
+ * offline.
+ *
+ * The registration and binding model follows the TCP congestion
+ * control framework: registering a struct_ops makes the model available
+ * by its name, while io.cost.model binds one registered model to a
+ * device.  Unregistering removes the name from the registry; devices
+ * already bound keep using it until switched back to the builtin
+ * model, and the name remains usable for io.cost.model writes (so a
+ * coefficient-only write keeps such a model bound) until the last
+ * device unbinds.
+ */
+
+/*
+ * iocost-specific call metadata for calc_cost()'s model_flags
+ * argument; everything else, including REQ_PREFLUSH/REQ_FUA, is
+ * already present in the opf argument.  An enum so the value is
+ * exported through BTF and BPF models can use it from vmlinux.h.
+ */
+enum {
+	IOCOST_COST_F_MERGE	= 1 << 0,	/* called from merge path */
+};
+
+struct iocost_model_ops {
+	u64 (*calc_cost)(u64 opf, u64 nbytes, sector_t sector,
+			 struct blkcg *blkcg, u64 model_flags);
+	void (*blkcg_online)(struct blkcg *blkcg);
+	void (*blkcg_offline)(struct blkcg *blkcg);
+
+	/* model name, used to select the model through io.cost.model */
+	char name[IOCOST_MODEL_NAME_LEN];
+};
+
+const struct iocost_model_ops *iocost_bpf_model_get(const char *name);
+void iocost_bpf_model_put(const struct iocost_model_ops *ops);
+void iocost_notify_blkcg_online(struct blkcg *blkcg);
+void iocost_notify_blkcg_offline(struct blkcg *blkcg);
+
+#else	/* CONFIG_BLK_CGROUP_IOCOST_BPF */
+
+struct blkcg;
+struct iocost_model_ops;
+
+static inline void iocost_bpf_model_put(const struct iocost_model_ops *ops) { }
+static inline void iocost_notify_blkcg_online(struct blkcg *blkcg) { }
+static inline void iocost_notify_blkcg_offline(struct blkcg *blkcg) { }
+
+#endif	/* CONFIG_BLK_CGROUP_IOCOST_BPF */
+#endif	/* _LINUX_BLK_IOCOST_H */
diff --git a/include/trace/events/iocost.h b/include/trace/events/iocost.h
index e772b1bc60d60..32f19861a78fd 100644
--- a/include/trace/events/iocost.h
+++ b/include/trace/events/iocost.h
@@ -178,6 +178,51 @@ TRACE_EVENT(iocost_ioc_vrate_adj,
 	)
 );
 
+/*
+ * Periodic per-device summary, emitted once per period from the tail of
+ * ioc_timer_fn().  Unlike the state-change events above, this fires every
+ * period the controller is running, including steady states, and carries
+ * the overall controller state so basic monitoring doesn't require drgn.
+ */
+TRACE_EVENT(iocost_ioc_tick,
+
+	TP_PROTO(struct ioc *ioc, int nr_active, u64 usage_us_sum,
+		 u32 tick_period_us, u64 tick_vrate,
+		 int tick_busy, int tick_running, u64 tick_dur),
+
+	TP_ARGS(ioc, nr_active, usage_us_sum, tick_period_us, tick_vrate,
+		tick_busy, tick_running, tick_dur),
+
+	TP_STRUCT__entry (
+		__string(devname, ioc_name(ioc))
+		__field(u64, cur_period)
+		__field(u32, period_us)
+		__field(u64, vrate)
+		__field(int, busy_level)
+		__field(int, nr_active)
+		__field(u32, usage_pct)
+		__field(int, running)
+	),
+
+	TP_fast_assign(
+		__assign_str(devname);
+		__entry->cur_period = atomic64_read(&ioc->cur_period);
+		__entry->period_us = tick_period_us;
+		__entry->vrate = tick_vrate;
+		__entry->busy_level = tick_busy;
+		__entry->nr_active = nr_active;
+		__entry->usage_pct = tick_dur ?
+			div64_u64(usage_us_sum * 100, tick_dur) : 0;
+		__entry->running = tick_running;
+	),
+
+	TP_printk("[%s] period=%llu:%uus vrate=%llu busy=%d active=%d usage=%u%% running=%d",
+		__get_str(devname), __entry->cur_period, __entry->period_us,
+		__entry->vrate, __entry->busy_level, __entry->nr_active,
+		__entry->usage_pct, __entry->running
+	)
+);
+
 TRACE_EVENT(iocost_iocg_forgive_debt,
 
 	TP_PROTO(struct ioc_gq *iocg, const char *path, struct ioc_now *now,
diff --git a/tools/testing/selftests/bpf/config b/tools/testing/selftests/bpf/config
index 2f79688dcf7ce..67a630cb56148 100644
--- a/tools/testing/selftests/bpf/config
+++ b/tools/testing/selftests/bpf/config
@@ -138,3 +138,5 @@ CONFIG_SMC_HS_CTRL_BPF=y
 CONFIG_DIBS=y
 CONFIG_DIBS_LO=y
 CONFIG_PM_WAKELOCKS=y
+CONFIG_BLK_CGROUP_IOCOST=y
+CONFIG_BLK_CGROUP_IOCOST_BPF=y
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 0000000000000..ac734c0e09cb0
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/iocost_model.c
@@ -0,0 +1,200 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <test_progs.h>
+#include <ctype.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include "iocost_model.skel.h"
+#include "iocost_ms.skel.h"
+
+/*
+ * Write a line to io.cost.model with write(2) and return the errno of
+ * the failed write, or 0 on success.  stdio is not used here on
+ * purpose: the kernel's rejection happens in the write() syscall,
+ * not in the userspace buffer copy, and every write, including
+ * the error paths of the callers below, is checked.
+ */
+static int write_cost_model(const char *buf)
+{
+	int fd, err = 0;
+	ssize_t n;
+
+	fd = open("/sys/fs/cgroup/io.cost.model", O_WRONLY);
+	if (fd < 0)
+		return -errno;	/* negative: the file is not there */
+	n = write(fd, buf, strlen(buf));
+	if (n < 0)
+		err = errno;
+	close(fd);
+	return err;
+}
+
+/*
+ * 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 && !isspace(*end))
+		end++;
+	snprintf(model, model_sz, "%.*s", (int)(end - m), m);
+	return 0;
+}
+
+/*
+ * Bind the named model to a device with "model=<name>", verify the
+ * readback and restore the builtin model.  Returns 0 on success.
+ */
+static int bind_model(const char *dev, const char *name)
+{
+	char buf[300], got[64];
+	int err;
+
+	snprintf(buf, sizeof(buf), "%s model=%s\n", dev, name);
+	err = write_cost_model(buf);
+	if (err)
+		return err > 0 ? -err : -EIO;
+	err = readback_model(dev, got, sizeof(got));
+	if (!err && !strcmp(got, name)) {
+		/*
+		 * restore the builtin linear model on every path so
+		 * the device is not left bound to a model the caller
+		 * may unregister right after; the write is checked too
+		 */
+		snprintf(buf, sizeof(buf), "%s model=linear\n", dev);
+		err = write_cost_model(buf);
+		return err > 0 ? -err : (err ? -EIO : 0);
+	}
+
+	/*
+	 * bind failed or does not read back: still restore, but report
+	 * the original failure rather than the restore result
+	 */
+	snprintf(buf, sizeof(buf), "%s model=linear\n", dev);
+	write_cost_model(buf);
+	return err ? -EIO : -EINVAL;
+}
+
+/*
+ * True when the device line exists in io.cost.qos and iocost is
+ * enabled on it.
+ */
+static int dev_has_iocost(const char *dev)
+{
+	char line[256], word[256];
+	FILE *fp;
+	int found = 0;
+
+	fp = fopen("/sys/fs/cgroup/io.cost.qos", "r");
+	if (!fp)
+		return 0;
+	while (fgets(line, sizeof(line), fp)) {
+		if (sscanf(line, "%255s", word) == 1 && !strcmp(word, dev)) {
+			found = strstr(line, "enable=1") != NULL;
+			break;
+		}
+	}
+	fclose(fp);
+	return found;
+}
+
+/*
+ * Bind the 2x example model and verify the io.cost.model readback.
+ * IO accounting itself is not checked here; it needs a device doing
+ * real IO under iocost and is covered by the kernel-side validation
+ * described in the cover letter.
+ *
+ * Requires root, cgroup v2 and a device with iocost support.  The
+ * device must be given as major:minor in $IOCOST_TEST_DEV, otherwise
+ * the test is skipped.
+ */
+void serial_test_iocost_model(void)
+{
+	struct iocost_model *skel;
+	char buf[300], *dev;
+	int err;
+
+	dev = getenv("IOCOST_TEST_DEV");
+	if (!dev || geteuid() != 0) {
+		test__skip();
+		return;
+	}
+	if (!dev_has_iocost(dev)) {
+		printf("skip: %s has no iocost enabled\n", dev);
+		test__skip();
+		return;
+	}
+
+	/*
+	 * negative: binding an unknown model name must be rejected,
+	 * so a typo cannot silently disable cost model updates
+	 */
+	snprintf(buf, sizeof(buf), "%s model=no_such_model\n", dev);
+	err = write_cost_model(buf);
+	ASSERT_EQ(err > 0 ? err : 0, ENOENT, "unknown_model_rejected");
+
+	skel = iocost_model__open_and_load();
+	if (!ASSERT_OK_PTR(skel, "skel_open_load"))
+		return;
+
+	/* attaching the struct_ops registers the model by name */
+	err = iocost_model__attach(skel);
+	if (ASSERT_OK(err, "attach"))
+		ASSERT_OK(bind_model(dev, "iocost_2x"), "bind_and_readback");
+
+	iocost_model__destroy(skel);
+}
+
+/*
+ * Same check for the multi-stream example model.  Only one model can
+ * be bound to a device at a time; both tests bind and restore, so
+ * they are serial and independent.
+ */
+void serial_test_iocost_model_streams(void)
+{
+	struct iocost_ms *skel;
+	char *dev;
+	int err;
+
+	dev = getenv("IOCOST_TEST_DEV");
+	if (!dev || geteuid() != 0) {
+		test__skip();
+		return;
+	}
+	if (!dev_has_iocost(dev)) {
+		printf("skip: %s has no iocost enabled\n", dev);
+		test__skip();
+		return;
+	}
+
+	skel = iocost_ms__open_and_load();
+	if (!ASSERT_OK_PTR(skel, "skel_open_load"))
+		return;
+
+	err = iocost_ms__attach(skel);
+	if (ASSERT_OK(err, "attach"))
+		ASSERT_OK(bind_model(dev, "iocost_ms"), "bind_and_readback");
+
+	iocost_ms__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 0000000000000..66fab4711c0b5
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/iocost_model.c
@@ -0,0 +1,136 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Example iocost cost model: the builtin linear HDD formula with all
+ * costs doubled.
+ *
+ * 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 bound to this model through
+ * io.cost.model charges exactly twice the builtin model under the
+ * same workload, so the doubled cost is a direct check that
+ * accounting goes through the BPF path.  On a non-rotational device,
+ * or one with user-pinned coefficients, the ratio to the builtin
+ * model is arbitrary.
+ *
+ * The cursor handling mirrors the builtin: a zero cursor means "no
+ * previous IO", and the cursor is only advanced for READ and WRITE
+ * bios the builtin prices, so flushes and discards leave it alone.
+ *
+ * The model implements the full linear formula itself, including
+ * flushes: there is no fallback to the builtin model, a dataless
+ * WRITE|REQ_PREFLUSH is priced as a one-page write.
+ */
+
+#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_COST_F_MERGE come from vmlinux.h (BTF enum constants)
+ */
+#define LCOEF_RANDIO_PAGES	4096	/* 16MB seek threshold */
+#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, freed with it, so
+ * the model never leaks or reuses stale per-cgroup state
+ */
+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");
+
+SEC("struct_ops")
+u64 BPF_PROG(iocost_2x_calc_cost, u64 opf, u64 nbytes, u64 sector,
+	     struct blkcg *blkcg, u64 model_flags)
+{
+	u64 pages, seek_pages = 0, base, coef_page, randio, cost;
+
+	/* 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) {
+		base = WSEQIO; coef_page = WPAGE; randio = WRANDIO;
+	} else {
+		/*
+		 * a fully owning model must price every op; unknown
+		 * ops are priced as a single page write
+		 */
+		base = 0; coef_page = WPAGE; randio = 0;
+	}
+
+	/*
+	 * mirror the builtin cursor semantics: seek distance is only
+	 * computed against a non-zero cursor, and the cursor is
+	 * advanced for bios the builtin prices (READ/WRITE with a
+	 * non-zero size), merged ones included, so flushes and
+	 * discards leave it alone and long merged streams do not
+	 * drift past the 16MB seek threshold
+	 */
+	{
+		__u64 *cursor, cur;
+		int priced = (opf & IOCOST_REQ_OP_MASK) == REQ_OP_READ ||
+			     (opf & IOCOST_REQ_OP_MASK) == REQ_OP_WRITE;
+
+		cursor = bpf_cgrp_storage_get(&cursor_store,
+					      blkcg->css.cgroup, NULL,
+					      BPF_LOCAL_STORAGE_GET_F_CREATE);
+		if (!cursor) {
+			if (model_flags & IOCOST_COST_F_MERGE)
+				base = 0;
+			return 2 * (base + pages * coef_page);
+		}
+		cur = *cursor;
+		if (cur && priced) {
+			seek_pages = sector > cur ? sector - cur
+						   : cur - sector;
+			seek_pages >>= IOC_SECT_TO_PAGE_SHIFT;
+			if (seek_pages > LCOEF_RANDIO_PAGES)
+				base = randio;
+		}
+		if (priced && nbytes)
+			*cursor = sector + RU(nbytes, 512);
+	}
+
+	if (model_flags & IOCOST_COST_F_MERGE)
+		base = 0;
+
+	cost = 2 * (base + pages * coef_page);
+	return cost;
+}
+
+SEC(".struct_ops")
+struct iocost_model_ops iocost_2x = {
+	.calc_cost = (void *)iocost_2x_calc_cost,
+	.name = "iocost_2x",
+};
+
+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 0000000000000..70019db0fd790
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/iocost_ms.c
@@ -0,0 +1,156 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * 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 full builtin
+ * linear formula itself, including flush pricing.
+ */
+#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_COST_F_MERGE come 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");
+
+SEC("struct_ops")
+u64 BPF_PROG(iocost_ms_calc_cost, u64 opf, u64 nbytes, u64 sector,
+	     struct blkcg *blkcg, u64 model_flags)
+{
+	struct streams *s;
+	u64 pages, base, coef_page, randio, advance, now;
+	u32 i, victim = 0, found = 0xFFFFFFFF;
+
+	if ((opf & IOCOST_REQ_OP_MASK) == REQ_OP_READ) {
+		base = RSEQIO; coef_page = RPAGE; randio = RRANDIO;
+	} else if ((opf & IOCOST_REQ_OP_MASK) == REQ_OP_WRITE) {
+		base = WSEQIO; coef_page = WPAGE; randio = WRANDIO;
+	} else {
+		/*
+		 * a fully owning model must price every op; unknown
+		 * ops are priced as per-page writes
+		 */
+		base = 0; coef_page = WPAGE; randio = 0;
+	}
+	advance = RU(nbytes, 512);	/* sectors */
+
+	/* only bios the builtin prices participate in stream tracking */
+	if (!(((opf & IOCOST_REQ_OP_MASK) == REQ_OP_READ ||
+	       (opf & IOCOST_REQ_OP_MASK) == REQ_OP_WRITE) && 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 */
+		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 */
+		s->expected[found] = sector + advance;
+		s->stamp[found] = now;
+	} else {
+		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 (model_flags & IOCOST_COST_F_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")
+struct iocost_model_ops iocost_ms = {
+	.calc_cost = (void *)iocost_ms_calc_cost,
+	.name = "iocost_ms",
+};
+
+char LICENSE[] SEC("license") = "GPL";

3/2 2026/09/20 09:39 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 20666
							output: 32
							thoughts: 1228
						

Thoughts:
**Evaluation of the Patch for Syzkaller Fuzzing**

Alright, let's break this down. My goal is to determine if this patch warrants fuzzing with syzkaller. First, let's get an overview of the changes. It looks like we're introducing BPF-based pluggable cost models for the cgroup IO cost controller.

Key observations:

*   **Documentation:** Updates to the documentation in `Documentation/admin-guide/cgroup-v2.rst` specifically mention `ctrl=bpf` and `model=<name>` in `io.cost.model`. This is huge, as it highlights the user-facing interface, which is prime fuzzing material.
*   **Kconfig:** `CONFIG_BLK_CGROUP_IOCOST_BPF` is added, which *depends on* `BLK_CGROUP_IOCOST`, `BPF_SYSCALL`, `BPF_JIT`, and `DEBUG_INFO_BTF`. This is great; we have clear prerequisites for testing. I'll need to figure out how to configure these. I'll use `grepper` to see where `BLK_CGROUP_IOCOST` is used.
*   **Makefile:** The Makefile hooks in `blk-iocost-bpf.o`, so the new code is being compiled if the config is enabled.
*   **blk-cgroup.c:**  Hooks for online/offline events for blkcg.
*   **blk-iocost-bpf.c:** This is the heart of it – the new code!  A new `iocost_model_ops` struct is defined with associated functions. This includes getting/putting models, lifecycle management, and BPF validation.
*   **blk-iocost.c:** This is where the integration happens. The `struct ioc` now includes the `iocost_model_ops` pointer. Crucially, the code now *calls* `model->calc_cost` under an RCU read lock, which means there's a good chance for concurrency issues. We are also setting and committing the models through sysfs interfaces.
*   **Header and Tracepoint:** `iocost_model_ops` and `trace_iocost_ioc_tick` are defined.
*   **Selftests:**  There are also selftests in `tools/...`. This is a very good sign that the developers thought about the importance of testing.

Now, is this reachable? Absolutely! We have a few crucial paths here:

1.  **BPF syscall interface:**  We're talking about registering and using `struct_ops` maps and links via BPF.
2.  **cgroup v2 sysfs/cgroupfs interface:** This includes reading and writing to the `io.cost.model` cgroup file via the interfaces mentioned in documentation (`model=<name>`, `ctrl=...`).

Both of these are easily accessible in a standard QEMU/KVM environment. No special setup is needed, which is ideal.

**WorthFuzzing = TRUE!** This hits all the right notes:

*   We're dealing with core subsystems: block layer, cgroups, and BPF.
*   There's refcounting, locking (including RCU), list management, and cgroup-specific lifecycle (online/offline) involved.
*   Specifically, there's RCU pointer handling which is almost a guarantee for potential race conditions.
*   Writing to cgroup `io.cost.model` is definitely exploitable.

Now, what are the configurations needed? I'll re-check the `block/Kconfig`:
```
config BLK_CGROUP_IOCOST_BPF
	bool "Enable BPF pluggable cost model support for the cost IO controller"
	depends on BLK_CGROUP_IOCOST && BPF_SYSCALL && BPF_JIT && DEBUG_INFO_BTF
```

I'll check the dependencies of `BLK_CGROUP_IOCOST` via `grepper` to be sure. I'm confident that this is *definitely* a good target for syzkaller.



4/2 2026/09/20 09:40 tool grepper
0m Args:
{
  "Expression": "config BLK_CGROUP_IOCOST",
  "PathPrefix": "block/"
}

Results:
{
  "Output": "block/Kconfig=145=config BLK_CGROUP_FC_APPID\n--\nblock/Kconfig-153-\nblock/Kconfig:154:config BLK_CGROUP_IOCOST\nblock/Kconfig-155-\tbool \"Enable support for cost model based cgroup IO controller\"\n--\nblock/Kconfig=232=source \"block/Kconfig.iosched\"\nblock/Kconfig-233-\nblock/Kconfig:234:config BLK_CGROUP_IOCOST_BPF\nblock/Kconfig-235-\tbool \"Enable BPF pluggable cost model support for the cost IO controller\"\n"
}

5/2 2026/09/20 09:40 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 22996
							output: 32
							thoughts: 20
						

Thoughts:
Here's my take on those lines from `block/Kconfig`:

**Analyzing Block/Kconfig (Lines 150-165)**

Okay, let's dive into lines 150-165 of `block/Kconfig`. Right, the context here is likely configuration options related to block devices, and specifically, within the kernel's block layer. Hmm, judging from the surrounding lines, it seems we're dealing with features or drivers that are *conditionally* included based on other Kconfig symbols being set. My immediate suspicion is that we are looking at something advanced that is usually not selected unless the user knows what they are doing.

The indentation likely dictates the dependency structure. Let me see... If `BLK_DEV_RAM` is enabled (i.e. if the user has selected the "RAM disk" feature), then we *might* see a series of further sub-options or parameters. This is very standard Kconfig behavior. I wonder if there are any specific block size constraints, or possibly other low-level parameters being configured within this specific block device. Are they introducing a new driver or is it an alteration to the standard ramdisk?

It's almost certainly related to a specific block device implementation, since we're inside the `block/` directory. Are we looking at a specific block device, or a set of options that govern some more generic characteristics? Without looking at the code further, it's hard to be certain.



6/2 2026/09/20 09:40 tool read-file
0m Args:
{
  "File": "block/Kconfig",
  "FirstLine": 150,
  "LineCount": 20
}

Results:
{
  "Contents": " 150:\t\t  cgroup applications. It enables the Fabric and the storage targets to\n 151:\t\t  identify, monitor, and handle FC traffic based on VM tags by inserting\n 152:\t\t  application specific identification into the FC frame.\n 153:\t\n 154:\tconfig BLK_CGROUP_IOCOST\n 155:\t\tbool \"Enable support for cost model based cgroup IO controller\"\n 156:\t\tdepends on BLK_CGROUP\n 157:\t\tselect BLK_RQ_ALLOC_TIME\n 158:\t\thelp\n 159:\t\tEnabling this option enables the .weight interface for cost\n 160:\t\tmodel based proportional IO control.  The IO controller\n 161:\t\tdistributes IO capacity between different groups based on\n 162:\t\ttheir share of the overall weight distribution.\n 163:\t\n 164:\tconfig BLK_CGROUP_IOPRIO\n 165:\t\tbool \"Cgroup I/O controller for assigning an I/O priority class\"\n 166:\t\tdepends on BLK_CGROUP\n 167:\t\thelp\n 168:\t\tEnable the .prio interface for assigning an I/O priority class to\n 169:\t\trequests. The I/O priority class affects the order in which an I/O\n"
}

7/2 2026/09/20 09:40 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 23698
							output: 21
							thoughts: 117
						

Thoughts:
**Kernel Configuration Dependencies: A Quick Mental Audit**

Okay, so I'm looking at these kernel config options and the dependencies are starting to swim into view. My immediate thought is, right, `BLK_CGROUP_IOCOST` needs `BLK_CGROUP`. Makes sense, the IO cost accounting builds on the cgroup infrastructure. No surprises there.

But then things get a little more complex with `BLK_CGROUP_IOCOST_BPF`. It hinges on `BLK_CGROUP_IOCOST` – that's expected – and then a whole suite of BPF-related options: `BPF_SYSCALL`, `BPF_JIT`, and `DEBUG_INFO_BTF`. Clearly, to get the BPF functionality in io accounting, you need the underlying BPF machinery. That seems logical.

Now, hold on... what about `BPF_STRUCT_OPS`? Is that a straight-up config option I need to explicitly set, or is it automatically pulled in by something else? Or, does it depend on any of the others? I need to clarify that. Okay, time to dive into the `Kconfig` for `BPF_STRUCT_OPS` and see what it says. Gotta make sure the dependency tree is completely clear.



8/2 2026/09/20 09:40 tool grepper
0m Error:
no matches

Args:
{
  "Expression": "config BPF_STRUCT_OPS"
}

Results:
{
  "error": "no matches"
}

9/2 2026/09/20 09:40 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 24123
							output: 22
							thoughts: 29
						

Thoughts:
Here's my thought process, as requested:

**Investigating the Configuration Dependency of `register_bpf_struct_ops`**

Okay, so I need to figure out if `register_bpf_struct_ops` is tied to a specific kernel configuration option. My instinct is to dive directly into the kernel source code. I'll use a search tool—likely `grep` or `cscope` depending on the environment—to look for all instances of `register_bpf_struct_ops`. The goal is to see if any `#ifdef`, `#if`, or similar preprocessor directives surround its definition or usage. I'm expecting to find a conditional statement. It will probably be a config option like `CONFIG_BPF` or something more specific related to the functionality this function provides. Once I identify the guarding config option, I'll know under what conditions this functionality is compiled and enabled within the kernel. This is pretty standard debugging when dealing with build-time options and kernel features. Knowing the config is important for debugging issues or even enabling the functionality in a custom kernel build. Let's see what we find.



10/2 2026/09/20 09:40 tool grepper
0m Args:
{
  "Expression": "register_bpf_struct_ops"
}

Results:
{
  "Output": "block/blk-iocost-bpf.c=317=static int __init bpf_iocost_init(void)\nblock/blk-iocost-bpf.c-318-{\nblock/blk-iocost-bpf.c:319:\treturn register_bpf_struct_ops(\u0026bpf_iocost_model_ops, iocost_model_ops);\nblock/blk-iocost-bpf.c-320-}\n--\ndrivers/hid/bpf/hid_bpf_struct_ops.c=337=static int __init hid_bpf_struct_ops_init(void)\ndrivers/hid/bpf/hid_bpf_struct_ops.c-338-{\ndrivers/hid/bpf/hid_bpf_struct_ops.c:339:\treturn register_bpf_struct_ops(\u0026bpf_hid_bpf_ops, hid_bpf_ops);\ndrivers/hid/bpf/hid_bpf_struct_ops.c-340-}\n--\nfs/binfmt_misc_bpf.c=430=static int __init bm_bpf_struct_ops_init(void)\nfs/binfmt_misc_bpf.c-431-{\nfs/binfmt_misc_bpf.c:432:\treturn register_bpf_struct_ops(\u0026bpf_binfmt_misc_ops, binfmt_misc_ops);\nfs/binfmt_misc_bpf.c-433-}\n--\ninclude/linux/bpf.h=2232=static inline bool is_struct_ops_tramp(const struct bpf_tramp_nodes *fentry_nodes)\n--\ninclude/linux/bpf.h-2240- * type information correctly. Developers should use this macro to register\ninclude/linux/bpf.h:2241: * a struct_ops type instead of calling __register_bpf_struct_ops() directly.\ninclude/linux/bpf.h-2242- */\ninclude/linux/bpf.h:2243:#define register_bpf_struct_ops(st_ops, type)\t\t\t\t\\\ninclude/linux/bpf.h-2244-\t({\t\t\t\t\t\t\t\t\\\n--\ninclude/linux/bpf.h-2249-\t\tBTF_TYPE_EMIT(struct bpf_struct_ops_##type);\t\t\\\ninclude/linux/bpf.h:2250:\t\t__register_bpf_struct_ops(st_ops);\t\t\t\\\ninclude/linux/bpf.h-2251-\t})\n--\ninclude/linux/bpf.h=2308=void bpf_struct_ops_desc_release(struct bpf_struct_ops_desc *st_ops_desc);\ninclude/linux/bpf.h-2309-#else\ninclude/linux/bpf.h:2310:#define register_bpf_struct_ops(st_ops, type) ({ (void *)(st_ops); 0; })\ninclude/linux/bpf.h-2311-static inline bool bpf_try_module_get(const void *data, struct module *owner)\n--\ninclude/linux/btf.h=541=struct bpf_struct_ops;\ninclude/linux/btf.h:542:int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops);\ninclude/linux/btf.h-543-const struct bpf_struct_ops_desc *bpf_struct_ops_find_value(struct btf *btf, u32 value_id);\n--\nio_uring/bpf-ops.c=263=static int __init io_uring_bpf_init(void)\n--\nio_uring/bpf-ops.c-266-\nio_uring/bpf-ops.c:267:\tret = register_bpf_struct_ops(\u0026bpf_ring_ops, io_uring_bpf_ops);\nio_uring/bpf-ops.c-268-\tif (ret) {\n--\nkernel/bpf/btf.c=10055=bpf_struct_ops_find(struct btf *btf, u32 type_id)\n--\nkernel/bpf/btf.c-10075-\nkernel/bpf/btf.c:10076:int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)\nkernel/bpf/btf.c-10077-{\n--\nkernel/bpf/btf.c-10103-}\nkernel/bpf/btf.c:10104:EXPORT_SYMBOL_GPL(__register_bpf_struct_ops);\nkernel/bpf/btf.c-10105-#endif\n--\nkernel/sched/ext/ext.c=11017=static int __init scx_init(void)\n--\nkernel/sched/ext/ext.c-11137-\nkernel/sched/ext/ext.c:11138:\tret = register_bpf_struct_ops(\u0026bpf_sched_ext_ops, sched_ext_ops);\nkernel/sched/ext/ext.c-11139-\tif (ret) {\n--\nkernel/sched/ext/ext.c-11143-\nkernel/sched/ext/ext.c:11144:\tret = register_bpf_struct_ops(\u0026bpf_sched_ext_ops_cid, sched_ext_ops_cid);\nkernel/sched/ext/ext.c-11145-\tif (ret) {\n--\nnet/bpf/bpf_dummy_struct_ops.c=319=static int __init bpf_dummy_struct_ops_init(void)\nnet/bpf/bpf_dummy_struct_ops.c-320-{\nnet/bpf/bpf_dummy_struct_ops.c:321:\treturn register_bpf_struct_ops(\u0026bpf_bpf_dummy_ops, bpf_dummy_ops);\nnet/bpf/bpf_dummy_struct_ops.c-322-}\n--\nnet/ipv4/bpf_tcp_ca.c=346=static int __init bpf_tcp_ca_kfunc_init(void)\n--\nnet/ipv4/bpf_tcp_ca.c-350-\tret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, \u0026bpf_tcp_ca_kfunc_set);\nnet/ipv4/bpf_tcp_ca.c:351:\tret = ret ?: register_bpf_struct_ops(\u0026bpf_tcp_congestion_ops, tcp_congestion_ops);\nnet/ipv4/bpf_tcp_ca.c-352-\n--\nnet/sched/bpf_qdisc.c=460=static int __init bpf_qdisc_kfunc_init(void)\n--\nnet/sched/bpf_qdisc.c-473-\t\t\t\t\t\t THIS_MODULE);\nnet/sched/bpf_qdisc.c:474:\tret = ret ?: register_bpf_struct_ops(\u0026bpf_Qdisc_ops, Qdisc_ops);\nnet/sched/bpf_qdisc.c-475-\n--\nnet/smc/smc_hs_bpf.c=137=int bpf_smc_hs_ctrl_init(void)\nnet/smc/smc_hs_bpf.c-138-{\nnet/smc/smc_hs_bpf.c:139:\treturn register_bpf_struct_ops(\u0026bpf_smc_hs_ctrl_ops, smc_hs_ctrl);\nnet/smc/smc_hs_bpf.c-140-}\n--\ntools/testing/selftests/bpf/test_kmods/bpf_test_no_cfi.c=59=static int bpf_test_no_cfi_init(void)\n--\ntools/testing/selftests/bpf/test_kmods/bpf_test_no_cfi.c-62-\ntools/testing/selftests/bpf/test_kmods/bpf_test_no_cfi.c:63:\tret = register_bpf_struct_ops(\u0026test_no_cif_ops,\ntools/testing/selftests/bpf/test_kmods/bpf_test_no_cfi.c-64-\t\t\t\t      bpf_test_no_cfi_ops);\n--\ntools/testing/selftests/bpf/test_kmods/bpf_test_no_cfi.c-68-\ttest_no_cif_ops.cfi_stubs = \u0026__test_no_cif_ops;\ntools/testing/selftests/bpf/test_kmods/bpf_test_no_cfi.c:69:\tret = register_bpf_struct_ops(\u0026test_no_cif_ops,\ntools/testing/selftests/bpf/test_kmods/bpf_test_no_cfi.c-70-\t\t\t\t      bpf_test_no_cfi_ops);\n--\ntools/testing/selftests/bpf/test_kmods/bpf_testmod.c=2379=static int bpf_testmod_init(void)\n--\ntools/testing/selftests/bpf/test_kmods/bpf_testmod.c-2395-\tret = ret ?: register_btf_fmodret_id_set(\u0026bpf_testmod_trampoline_count_fmodret_set);\ntools/testing/selftests/bpf/test_kmods/bpf_testmod.c:2396:\tret = ret ?: register_bpf_struct_ops(\u0026bpf_bpf_testmod_ops, bpf_testmod_ops);\ntools/testing/selftests/bpf/test_kmods/bpf_testmod.c:2397:\tret = ret ?: register_bpf_struct_ops(\u0026bpf_testmod_ops2, bpf_testmod_ops2);\ntools/testing/selftests/bpf/test_kmods/bpf_testmod.c:2398:\tret = ret ?: register_bpf_struct_ops(\u0026bpf_testmod_ops3, bpf_testmod_ops3);\ntools/testing/selftests/bpf/test_kmods/bpf_testmod.c:2399:\tret = ret ?: register_bpf_struct_ops(\u0026testmod_st_ops, bpf_testmod_st_ops);\ntools/testing/selftests/bpf/test_kmods/bpf_testmod.c:2400:\tret = ret ?: register_bpf_struct_ops(\u0026testmod_multi_st_ops, bpf_testmod_multi_st_ops);\ntools/testing/selftests/bpf/test_kmods/bpf_testmod.c-2401-\tret = ret ?: register_btf_id_dtor_kfuncs(bpf_testmod_dtors,\n"
}

11/2 2026/09/20 09:40 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 27186
							output: 39
							thoughts: 62
						

Thoughts:
**Examining the BPF Structure Registration**

Okay, so I need to understand how `register_bpf_struct_ops` is handled. The code tells me it's defined in `kernel/bpf/btf.c`. Right, that's where I'd expect it to be. Now, let's zoom in on that file. I'm going to jump to around line 10076. I need to figure out which preprocessor directives, specifically `#ifdef` blocks, control whether this function gets compiled and what its effective implementation looks like. Knowing the conditional compilation logic is key to understanding its behavior in different kernel configurations. It's time to dig into those `#ifdef` statements and trace the different paths.



12/2 2026/09/20 09:40 tool read-file
0m Args:
{
  "File": "kernel/bpf/btf.c",
  "FirstLine": 10050,
  "LineCount": 40
}

Results:
{
  "Contents": "10050:\t\n10051:\t\treturn NULL;\n10052:\t}\n10053:\t\n10054:\tconst struct bpf_struct_ops_desc *\n10055:\tbpf_struct_ops_find(struct btf *btf, u32 type_id)\n10056:\t{\n10057:\t\tconst struct bpf_struct_ops_desc *st_ops_list;\n10058:\t\tunsigned int i;\n10059:\t\tu32 cnt;\n10060:\t\n10061:\t\tif (!type_id)\n10062:\t\t\treturn NULL;\n10063:\t\tif (!btf-\u003estruct_ops_tab)\n10064:\t\t\treturn NULL;\n10065:\t\n10066:\t\tcnt = btf-\u003estruct_ops_tab-\u003ecnt;\n10067:\t\tst_ops_list = btf-\u003estruct_ops_tab-\u003eops;\n10068:\t\tfor (i = 0; i \u003c cnt; i++) {\n10069:\t\t\tif (st_ops_list[i].type_id == type_id)\n10070:\t\t\t\treturn \u0026st_ops_list[i];\n10071:\t\t}\n10072:\t\n10073:\t\treturn NULL;\n10074:\t}\n10075:\t\n10076:\tint __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)\n10077:\t{\n10078:\t\tstruct bpf_verifier_log *log;\n10079:\t\tstruct btf *btf;\n10080:\t\tint err = 0;\n10081:\t\n10082:\t\tbtf = btf_get_module_btf(st_ops-\u003eowner);\n10083:\t\tif (!btf)\n10084:\t\t\treturn check_btf_kconfigs(st_ops-\u003eowner, \"struct_ops\");\n10085:\t\tif (IS_ERR(btf))\n10086:\t\t\treturn PTR_ERR(btf);\n10087:\t\n10088:\t\tlog = kzalloc_obj(*log, GFP_KERNEL | __GFP_NOWARN);\n10089:\t\tif (!log) {\n"
}

13/2 2026/09/20 09:40 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 28074
							output: 37
							thoughts: 39
						

Thoughts:
Here's my take on the thought process:

**Diving into the BPF Core Header**

Okay, so I need to understand the conditions under which `__register_bpf_struct_ops` is defined. I know it's a critical function, probably related to BPF structure registration, and I need to figure out the context. Let me navigate to `include/linux/bpf.h` - I'm pretty familiar with the BPF core headers, so I'm guessing the relevant definition will be somewhere around line 2308. I'll zero in on that `#if` block. That's where the conditional compilation magic happens, and understanding the guard will tell me precisely when this particular function gets hooked into the BPF subsystem.



14/2 2026/09/20 09:40 tool read-file
0m Args:
{
  "File": "include/linux/bpf.h",
  "FirstLine": 2290,
  "LineCount": 35
}

Results:
{
  "Contents": "2290:\tstruct bpf_dummy_ops_state {\n2291:\t\tint val;\n2292:\t};\n2293:\t\n2294:\tstruct bpf_dummy_ops {\n2295:\t\tint (*test_1)(struct bpf_dummy_ops_state *cb);\n2296:\t\tint (*test_2)(struct bpf_dummy_ops_state *cb, int a1, unsigned short a2,\n2297:\t\t\t      char a3, unsigned long a4);\n2298:\t\tint (*test_sleepable)(struct bpf_dummy_ops_state *cb);\n2299:\t};\n2300:\t\n2301:\tint bpf_struct_ops_test_run(struct bpf_prog *prog, const union bpf_attr *kattr,\n2302:\t\t\t\t    union bpf_attr __user *uattr);\n2303:\t#endif\n2304:\tint bpf_struct_ops_desc_init(struct bpf_struct_ops_desc *st_ops_desc,\n2305:\t\t\t\t     struct btf *btf,\n2306:\t\t\t\t     struct bpf_verifier_log *log);\n2307:\tvoid bpf_map_struct_ops_info_fill(struct bpf_map_info *info, struct bpf_map *map);\n2308:\tvoid bpf_struct_ops_desc_release(struct bpf_struct_ops_desc *st_ops_desc);\n2309:\t#else\n2310:\t#define register_bpf_struct_ops(st_ops, type) ({ (void *)(st_ops); 0; })\n2311:\tstatic inline bool bpf_try_module_get(const void *data, struct module *owner)\n2312:\t{\n2313:\t\treturn try_module_get(owner);\n2314:\t}\n2315:\tstatic inline void bpf_module_put(const void *data, struct module *owner)\n2316:\t{\n2317:\t\tmodule_put(owner);\n2318:\t}\n2319:\tstatic inline int bpf_struct_ops_supported(const struct bpf_struct_ops *st_ops, u32 moff)\n2320:\t{\n2321:\t\treturn -ENOTSUPP;\n2322:\t}\n2323:\tstatic inline int bpf_struct_ops_map_sys_lookup_elem(struct bpf_map *map,\n2324:\t\t\t\t\t\t\t     void *key,\n"
}

15/2 2026/09/20 09:40 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 28981
							output: 37
							thoughts: 30
						

Thoughts:
Here's my thought process, as requested:

**Navigating the BPF Header**

Okay, so I need to find something in `include/linux/bpf.h` before line 2290. The clue is that I'm looking for an `#ifdef`. This likely indicates some conditional compilation or feature flag definition related to BPF functionality. Given my expertise, I know the `bpf.h` header is a crucial file, so I need to navigate it carefully. My process will be to quickly scan the lines preceding that point to identify the `#ifdef` statement. I need to understand what it guards; what functionality is conditional. This likely impacts either how I use BPF, or how I debug BPF code, or how the kernel handles BPF. It's a key bit of information I need.



16/2 2026/09/20 09:40 tool read-file
0m Args:
{
  "File": "include/linux/bpf.h",
  "FirstLine": 2200,
  "LineCount": 40
}

Results:
{
  "Contents": "2200:\t\tactive[rctx]++;\n2201:\t\tval = le32_to_cpu(*(__le32 *)active);\n2202:\t\tpreempt_enable();\n2203:\t\tif (val != BIT(rctx * 8))\n2204:\t\t\treturn false;\n2205:\t\n2206:\t\treturn true;\n2207:\t#else\n2208:\t\treturn this_cpu_inc_return(*(int __percpu *)(prog-\u003eactive)) == 1;\n2209:\t#endif\n2210:\t}\n2211:\t\n2212:\tstatic inline void bpf_prog_put_recursion_context(struct bpf_prog *prog)\n2213:\t{\n2214:\t#ifdef CONFIG_ARM64\n2215:\t\tu8 rctx = interrupt_context_level();\n2216:\t\tu8 *active = this_cpu_ptr(prog-\u003eactive);\n2217:\t\n2218:\t\tpreempt_disable();\n2219:\t\tactive[rctx]--;\n2220:\t\tpreempt_enable();\n2221:\t#else\n2222:\t\tthis_cpu_dec(*(int __percpu *)(prog-\u003eactive));\n2223:\t#endif\n2224:\t}\n2225:\t\n2226:\tstatic inline bool is_tracing_multi(enum bpf_attach_type type)\n2227:\t{\n2228:\t\treturn type == BPF_TRACE_FENTRY_MULTI || type == BPF_TRACE_FEXIT_MULTI ||\n2229:\t\t       type == BPF_TRACE_FSESSION_MULTI;\n2230:\t}\n2231:\t\n2232:\tstatic inline bool is_struct_ops_tramp(const struct bpf_tramp_nodes *fentry_nodes)\n2233:\t{\n2234:\t\treturn fentry_nodes-\u003enr_nodes == 1 \u0026\u0026\n2235:\t\t       fentry_nodes-\u003enodes[0]-\u003elink-\u003etype == BPF_LINK_TYPE_STRUCT_OPS;\n2236:\t}\n2237:\t\n2238:\t#if defined(CONFIG_BPF_JIT) \u0026\u0026 defined(CONFIG_BPF_SYSCALL)\n2239:\t/* This macro helps developer to register a struct_ops type and generate\n"
}

17/2 2026/09/20 09:40 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 29838
							output: 336
							thoughts: 5926
						

Thoughts:
**Analysis of BPF Pluggable Cost Model for Block I/O Cost Controller**

Okay, so I've been dissecting this patch and I've got a pretty good handle on what's going on. This whole thing revolves around enabling BPF-based custom cost models for the block I/O cost controller. We're talking about a significant enhancement, letting users inject their own BPF programs to model I/O costs within cgroups. The key here is the `BLK_CGROUP_IOCOST_BPF` Kconfig option, depending on a few other pieces: `BLK_CGROUP_IOCOST`, `BPF_SYSCALL`, `BPF_JIT`, and `DEBUG_INFO_BTF`. Essentially, BPF is now tightly integrated with cgroup I/O accounting.

I've zeroed in on the critical functions added and modified. Specifically, in `block/blk-iocost-bpf.c`, we have the BPF-specific functions: `iocost_bpf_model_get`, `iocost_bpf_model_put`, `iocost_notify_blkcg_online`, `iocost_notify_blkcg_offline`, `bpf_iocost_reg`, `bpf_iocost_unreg`, and `bpf_iocost_validate`. These handle model lookup, reference counting, lifecycle management, and registration/unregistration of the BPF cost models. Then, the `block/blk-iocost.c` file has the core interactions with these BPF models: `ioc_cost_model_write`, `calc_vtime_cost`, and `calc_size_vtime_cost`. These are the actual entrypoints for cost model selection via sysfs, and the cost calculation functions themselves.

I've identified the key focus points: `ioc_cost_model_write` (the sysfs entrypoint), `iocost_bpf_model_get`, `iocost_bpf_model_put`, `iocost_notify_blkcg_online`, `iocost_notify_blkcg_offline`, `bpf_iocost_reg`, `bpf_iocost_unreg`, `bpf_iocost_validate`, `calc_vtime_cost`, and `calc_size_vtime_cost`. These are the prime candidates for fuzzing since they represent the interaction points between BPF programs and the I/O cost accounting logic. The static nature of `ioc_bpf_model_prepare` and `ioc_bpf_model_commit` in `blk-iocost.c`, made them less attractive as focus points. Also, all the configs should be enabled since these are dependencies.

Diving deeper, I've spotted some interesting concurrency issues and subtle logic flaws in `ioc_cost_model_write` related to reference counting and BPF model lifecycle. Specifically, I'm worried about the race between releasing and re-acquiring the lock while referencing the BPF model. There's also a potential use-after-free scenario in `ioc_rqos_exit` related to the interaction with `calc_vtime_cost`, particularly if the BPF struct_ops map/link are unregistered. In `iocost_bpf_model_put` there's a reference leak where refcounting isn't quite right.

This patch has a lot of complex interactions around reference counting, locking, RCU, registration/unregistration, and concurrency. Combining these factors with the ability to interact with the code through sysfs and the BPF subsystem, makes this a major target for syzkaller. The interaction between registering a BPF model, unregistering it, and a concurrent read with `calc_vtime_cost` is a prime example of where the issues lie. The unregistration and re-registration scenarios are also critical, particularly if they happen during I/O operations. The fact that the BPF struct_ops and maps are unregistered is also important. So, memory corruption, use-after-free, and refcount underflow/overflow are all possibilities here.



18/2 2026/09/20 09:41 tool set-results
0m Args:
{
  "EnableConfigs": [
    "BLK_CGROUP_IOCOST_BPF",
    "BLK_CGROUP_IOCOST",
    "BLK_CGROUP",
    "BPF_SYSCALL",
    "BPF_JIT",
    "DEBUG_INFO_BTF"
  ],
  "FocusSymbols": [
    "ioc_cost_model_write",
    "iocost_bpf_model_get",
    "iocost_bpf_model_put",
    "bpf_iocost_reg",
    "bpf_iocost_unreg",
    "bpf_iocost_validate",
    "calc_vtime_cost",
    "calc_size_vtime_cost",
    "iocost_notify_blkcg_online",
    "iocost_notify_blkcg_offline"
  ],
  "Reasoning": "The patch introduces pluggable BPF struct_ops cost model support (iocost_model_ops) for the cgroup iocost controller, bound via cgroup v2's io.cost.model interface. It modifies core block cgroup and iocost pricing logic, introduces complex refcounting and lifecycle state machines between BPF struct_ops map/link lifetime and bound block devices, hooks into blkcg css online/offline callbacks, and accesses the BPF model under RCU during I/O dispatch. This code is fully reachable in standard virtualized environments via BPF and cgroup syscalls and warrants fuzzing for concurrency, refcounting, and synchronization issues.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "BLK_CGROUP_IOCOST_BPF",
    "BLK_CGROUP_IOCOST",
    "BLK_CGROUP",
    "BPF_SYSCALL",
    "BPF_JIT",
    "DEBUG_INFO_BTF"
  ],
  "FocusSymbols": [
    "ioc_cost_model_write",
    "iocost_bpf_model_get",
    "iocost_bpf_model_put",
    "bpf_iocost_reg",
    "bpf_iocost_unreg",
    "bpf_iocost_validate",
    "calc_vtime_cost",
    "calc_size_vtime_cost",
    "iocost_notify_blkcg_online",
    "iocost_notify_blkcg_offline"
  ],
  "Reasoning": "The patch introduces pluggable BPF struct_ops cost model support (iocost_model_ops) for the cgroup iocost controller, bound via cgroup v2's io.cost.model interface. It modifies core block cgroup and iocost pricing logic, introduces complex refcounting and lifecycle state machines between BPF struct_ops map/link lifetime and bound block devices, hooks into blkcg css online/offline callbacks, and accesses the BPF model under RCU during I/O dispatch. This code is fully reachable in standard virtualized environments via BPF and cgroup syscalls and warrants fuzzing for concurrency, refcounting, and synchronization issues.",
  "WorthFuzzing": true
}

19/1 2026/09/20 09:41 action If
1m Args:
{
  "WorthFuzzing": true
}

Results:
null

20/2 2026/09/20 09:41 agent kmsan-evaluator
1m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch introduces BPF struct_ops support (`iocost_model_ops`) for the block iocost controller, allowing BPF programs to provide custom cost models bound to devices via cgroup v2 `io.cost.model`. It also introduces lifecycle notifications (`blkcg_online`/`blkcg_offline`) and a new tracepoint (`iocost_ioc_tick`).\n\nAnalysis of uninitialized memory risks:\n1. All heap allocations (specifically `struct iocost_bpf_model`) use `kzalloc_obj`, ensuring zero-initialization.\n2. String buffers on the stack (such as `bpf_model` in `ioc_cost_model_write`) are properly initialized and bounded using `strscpy`, `match_strlcpy`, and `bpf_obj_name_cpy` (which memsets the target buffer to zero before copying).\n3. The new tracepoint `trace_iocost_ioc_tick` explicitly snapshots all variables (`tick_period_us`, `tick_vrate`, `tick_busy`, `tick_running`, `tick_dur`) and assigns each field in `TP_fast_assign`.\n4. Kernel-to-userspace data flow occurs only through text formatting via `seq_printf` in `ioc_cost_model_prfill`; no binary structures or padded buffers are copied to user space.\n\nKASAN vs KMSAN applicability:\nAny potential risks introduced by this change involve concurrency, lock ordering (between `ioc-\u003elock` and `iocost_bpf_reg_lock`), RCU synchronization, and reference count management (`refcount_t`, `bpf_struct_ops_get`/`put`), which could manifest as use-after-free, double-free, or deadlocks. These bugs are fully covered by standard debugging tools (KASAN, LOCKDEP, and refcount checks). There is no risk of uninitialized memory reads or information leaks that would uniquely require KMSAN. Therefore, running a dedicated KMSAN session is not justified.",
  "NeedsKMSAN": false
}

Instruction:
You are an expert Linux kernel security engineer specializing in kernel memory
error detectors (KASAN and KMSAN). Your job is to review the provided patch series and
determine if the code changes justify spawning a dedicated KMSAN (KernelMemorySanitizer)
fuzzing session in addition to standard KASAN fuzzing.

CRITICAL DISTINCTION BETWEEN KASAN AND KMSAN:
- Standard KASAN kernel builds (upstream-apparmor-kasan.config) already enable
  a comprehensive suite of debugging tools and sanitizers, including KASAN
  (out-of-bounds accesses, use-after-free, double free, invalid free), LOCKDEP
  (locking bugs and deadlocks), UB-sanitizers, and memory corruption checks.
- KMSAN (KernelMemorySanitizer) detects reads of UNINITIALIZED memory (stack, heap,
  or page allocations) and kernel-to-user memory info-leaks.

Rule: THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN,
LOCKDEP, OR OTHER STANDARD BUG DETECTORS.
A dedicated KMSAN fuzzing session incurs significant resource costs. You must ONLY
set NeedsKMSAN=true if the code changes introduce or expose UNINITIALIZED MEMORY risks
that are detected ONLY by KMSAN.

Look holistically at the patch series and surrounding code. Even if no direct
uninitialized field accesses or new buffer allocations are added in the diff itself,
a patch may alter control flow, bounds checking, or data length calculations in ways
that change how the rest of the code operates on existing buffers (e.g. allowing
uninitialized stack/heap memory to be read, copied to user space, or used in control
flow). Do not hesitate to use your code access tools to inspect the surrounding code,
called functions, and callers.

Set NeedsKMSAN=true ONLY IF the patch introduces or modifies:
1. Kernel structures sent to user space (via copy_to_user, put_user, netlink skb
   attributes, ioctl output arguments, socket options, or BPF buffers) where fields
   or structure padding might not be fully initialized/zeroed.
2. Conditional logic or branching that depends on potentially uninitialized variables
   or struct fields.
3. Allocation or initialization of complex data structures where uninitialized fields
   could be read later in reachable code paths.
4. Bounds checks, lengths, or logic in a way that allows surrounding code to access
   uninitialized bytes of existing buffers.

Set NeedsKMSAN=false IF:
- The code changes primarily risk out-of-bounds access, array overflows, NULL pointer
  dereferences, locking deadlocks, or use-after-free bugs (these are already caught
  by KASAN, LOCKDEP, or standard bug detectors).
- All stack/heap structures touched or introduced by the patch are fully zeroed
  or initialized (e.g. using = {0}, memset, kzalloc) before being read or copied.
- The patch does not introduce any risk of uninitialized memory usage or info-leaks.

Use your code access tools to inspect the surrounding code if necessary, then provide
detailed KMSANReasoning contrasting KASAN vs KMSAN applicability for this patch.
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit 8b534faffc0c4eb3a498186f6484e9fc42190b59
Author: syz-cluster <triage@syzkaller.com>
Date:   Sun Sep 20 09:39:48 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/admin-guide/cgroup-v2.rst b/Documentation/admin-guide/cgroup-v2.rst
index 8d2603751c51a..d9d82559e2bc6 100644
--- a/Documentation/admin-guide/cgroup-v2.rst
+++ b/Documentation/admin-guide/cgroup-v2.rst
@@ -2115,8 +2115,10 @@ IO Interface Files
 	are defined.
 
 	  =====		================================
-	  ctrl		"auto" or "user"
+	  ctrl		"auto", "user" or "bpf"
 	  model		The cost model in use - "linear"
+			or the name of the bound
+			model
 	  =====		================================
 
 	When "ctrl" is "auto", the kernel may change all parameters
@@ -2124,6 +2126,23 @@ IO Interface Files
 	parameters are written to, "ctrl" become "user" and the
 	automatic changes are disabled.
 
+	When CONFIG_BLK_CGROUP_IOCOST_BPF is enabled, a bound model is
+	read back as "ctrl=bpf model=<name>", and writing "ctrl=bpf" is
+	accepted as a no-op so a saved configuration can be restored as-is.
+	"model" also accepts
+	the name of a registered iocost_model_ops BPF struct_ops model:
+	"model=<name>" binds the model to the device and the model fully
+	replaces the builtin linear pricing, for every operation including
+	flushes; "model=linear" (or "ctrl=auto/user") restores the builtin
+	model.  Writing an unknown name fails with ENOENT and nothing is
+	applied.  Unregistering a model removes its name from the
+	registry; devices already bound keep using it, and keep receiving
+	cgroup lifecycle notifications, until switched back to the builtin
+	model, and its name keeps working for writes (so a coefficient-only
+	write does not disturb the binding) until the last device unbinds.
+	See
+	include/linux/blk-iocost.h for the model interface.
+
 	When "model" is "linear", the following model parameters are
 	defined.
 
diff --git a/block/Kconfig b/block/Kconfig
index 70e4a66d941ff..91e808f86d28d 100644
--- a/block/Kconfig
+++ b/block/Kconfig
@@ -231,4 +231,13 @@ config BLK_ERROR_INJECTION
 
 source "block/Kconfig.iosched"
 
+config BLK_CGROUP_IOCOST_BPF
+	bool "Enable BPF pluggable cost model support for the cost IO controller"
+	depends on BLK_CGROUP_IOCOST && BPF_SYSCALL && BPF_JIT && DEBUG_INFO_BTF
+	help
+	 Enabling this option registers the "iocost_model_ops" BPF
+	 struct_ops type, which allows a BPF program to fully replace
+	 the builtin linear cost model on a device it is bound to
+	 through io.cost.model.
+
 endif # BLOCK
diff --git a/block/Makefile b/block/Makefile
index e7bd320e3d697..ee5cebeea006f 100644
--- a/block/Makefile
+++ b/block/Makefile
@@ -39,3 +39,4 @@ obj-$(CONFIG_BLK_INLINE_ENCRYPTION)	+= blk-crypto.o blk-crypto-profile.o \
 					   blk-crypto-sysfs.o
 obj-$(CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK)	+= blk-crypto-fallback.o
 obj-$(CONFIG_BLOCK_HOLDER_DEPRECATED)	+= holder.o
+obj-$(CONFIG_BLK_CGROUP_IOCOST_BPF)	+= blk-iocost-bpf.o
diff --git a/block/blk-cgroup.c b/block/blk-cgroup.c
index b56db1cc6778f..b08ceb94a281b 100644
--- a/block/blk-cgroup.c
+++ b/block/blk-cgroup.c
@@ -32,6 +32,7 @@
 #include <linux/part_stat.h>
 #include "blk.h"
 #include "blk-cgroup.h"
+#include <linux/blk-iocost.h>
 #include "blk-ioprio.h"
 #include "blk-throttle.h"
 
@@ -1341,6 +1342,7 @@ void blkcg_unpin_online(struct cgroup_subsys_state *blkcg_css)
  */
 static void blkcg_css_offline(struct cgroup_subsys_state *css)
 {
+	iocost_notify_blkcg_offline(css_to_blkcg(css));
 	/* this prevents anyone from attaching or migrating to this blkcg */
 	wb_blkcg_offline(css);
 
@@ -1447,6 +1449,8 @@ static int blkcg_css_online(struct cgroup_subsys_state *css)
 {
 	struct blkcg *parent = blkcg_parent(css_to_blkcg(css));
 
+	iocost_notify_blkcg_online(css_to_blkcg(css));
+
 	/*
 	 * blkcg_pin_online() is used to delay blkcg offline so that blkgs
 	 * don't go offline while cgwbs are still active on them.  Pin the
diff --git a/block/blk-iocost-bpf.c b/block/blk-iocost-bpf.c
new file mode 100644
index 0000000000000..444ca52ed0b08
--- /dev/null
+++ b/block/blk-iocost-bpf.c
@@ -0,0 +1,321 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * blk-iocost: BPF struct_ops plumbing for pluggable cost models.
+ *
+ * Registers the "iocost_model_ops" struct_ops type and maintains the
+ * name registry of registered models.  A registered model is bound to
+ * a device through io.cost.model; see include/linux/blk-iocost.h.
+ */
+#include <linux/init.h>
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/mutex.h>
+#include <linux/slab.h>
+#include <linux/bpf.h>
+#include <linux/bpf_verifier.h>
+#include <linux/btf.h>
+#include <linux/blk-iocost.h>
+
+static DEFINE_MUTEX(iocost_bpf_reg_lock);
+static LIST_HEAD(iocost_bpf_models);
+static LIST_HEAD(iocost_bpf_lifecycle);
+
+/*
+ * One node per registered model.  refcount: 1 while registered
+ * (dropped in .unreg) plus one per bound device (dropped in
+ * iocost_bpf_model_put(), which pairs its bpf_struct_ops_get(), so the
+ * kdata of an unregistered model stays alive while any device is still
+ * bound to it).  The node sits on the lifecycle notify list exactly
+ * while at least one device has the model bound.
+ */
+struct iocost_bpf_model {
+	struct list_head	list;		/* name registry */
+	struct list_head	lifecycle;	/* lifecycle notify list */
+	const struct iocost_model_ops *ops;
+	refcount_t		refs;
+};
+
+/*
+ * Take a name and acquire a binding reference on the model it selects.
+ * The registry is searched first; a model which is unregistered but
+ * still bound to a device remains selectable by name until the last
+ * device unbinds, so a coefficient-only write on such a device keeps
+ * the model bound instead of failing with ENOENT.  The registry lock
+ * is held across the lookup and bpf_struct_ops_get() so the model
+ * cannot be unregistered in between.  Returns the ops or an ERR_PTR.
+ */
+const struct iocost_model_ops *iocost_bpf_model_get(const char *name)
+{
+	struct iocost_bpf_model *m;
+	const struct iocost_model_ops *ops = ERR_PTR(-ENOENT);
+
+	mutex_lock(&iocost_bpf_reg_lock);
+	list_for_each_entry(m, &iocost_bpf_models, list) {
+		if (!strcmp(m->ops->name, name))
+			goto found;
+	}
+	list_for_each_entry(m, &iocost_bpf_lifecycle, lifecycle) {
+		if (!strcmp(m->ops->name, name))
+			goto found;
+	}
+	mutex_unlock(&iocost_bpf_reg_lock);
+	return ops;
+found:
+	if (bpf_struct_ops_get(m->ops)) {
+		refcount_inc(&m->refs);
+		/* first bind: join the notify list */
+		if (refcount_read(&m->refs) == 2 &&
+		    list_empty(&m->lifecycle))
+			list_add(&m->lifecycle, &iocost_bpf_lifecycle);
+		ops = m->ops;
+	}
+	mutex_unlock(&iocost_bpf_reg_lock);
+	return ops;
+}
+
+static struct iocost_bpf_model *
+iocost_bpf_model_lookup(const struct iocost_model_ops *ops)
+{
+	struct iocost_bpf_model *m;
+
+	list_for_each_entry(m, &iocost_bpf_models, list) {
+		if (m->ops == ops)
+			return m;
+	}
+	return NULL;
+}
+
+/*
+ * Lifecycle notifications walk the lifecycle list, which keeps a node
+ * for as long as any device has the model bound, so an unregistered
+ * but still-bound model keeps receiving blkcg online/offline.
+ */
+void iocost_notify_blkcg_online(struct blkcg *blkcg)
+{
+	struct iocost_bpf_model *m;
+
+	guard(mutex)(&iocost_bpf_reg_lock);
+	list_for_each_entry(m, &iocost_bpf_lifecycle, lifecycle) {
+		if (m->ops->blkcg_online)
+			m->ops->blkcg_online(blkcg);
+	}
+}
+
+void iocost_notify_blkcg_offline(struct blkcg *blkcg)
+{
+	struct iocost_bpf_model *m;
+
+	guard(mutex)(&iocost_bpf_reg_lock);
+	list_for_each_entry(m, &iocost_bpf_lifecycle, lifecycle) {
+		if (m->ops->blkcg_offline)
+			m->ops->blkcg_offline(blkcg);
+	}
+}
+
+static int bpf_iocost_model_init(struct btf *btf)
+{
+	s32 type_id;
+
+	type_id = btf_find_by_name_kind(btf, "iocost_model_ops", BTF_KIND_STRUCT);
+	if (type_id < 0)
+		return -EINVAL;
+	return 0;
+}
+
+static bool bpf_iocost_is_valid_access(int off, int size,
+				       enum bpf_access_type type,
+				       const struct bpf_prog *prog,
+				       struct bpf_insn_access_aux *info)
+{
+	return bpf_tracing_btf_ctx_access(off, size, type, prog, info);
+}
+
+/*
+ * No iocost-specific helpers; bpf_base_func_proto already covers the
+ * cgroup storage helpers under CONFIG_CGROUPS.
+ */
+static const struct bpf_func_proto *
+bpf_iocost_get_func_proto(enum bpf_func_id func_id,
+			  const struct bpf_prog *prog)
+{
+	return bpf_base_func_proto(func_id, prog);
+}
+
+static int bpf_iocost_check_member(const struct btf_type *t,
+				   const struct btf_member *member,
+				   const struct bpf_prog *prog)
+{
+	/* calc_cost() is called with RCU read lock held */
+	if (prog->sleepable)
+		return -EINVAL;
+	return 0;
+}
+
+static int bpf_iocost_init_member(const struct btf_type *t,
+				  const struct btf_member *member,
+				  void *kdata, const void *udata)
+{
+	struct iocost_model_ops *ops = kdata;
+	const struct iocost_model_ops *uops = udata;
+	u32 moff = __btf_member_bit_offset(t, member) / 8;
+
+	switch (moff) {
+	case offsetof(struct iocost_model_ops, name):
+		if (bpf_obj_name_cpy(ops->name, uops->name,
+				     sizeof(ops->name)) <= 0)
+			return -EINVAL;
+		return 1;
+	}
+
+	return 0;
+}
+
+/*
+ * kvalue is zeroed at map allocation and function members are only
+ * written when the BPF side provides a prog, so a model which did
+ * not implement calc_cost leaves it NULL.  The dispatch would call
+ * it on every bio, so reject it here.
+ */
+static int bpf_iocost_validate(void *kdata)
+{
+	struct iocost_model_ops *ops = kdata;
+
+	if (!ops->calc_cost)
+		return -EINVAL;
+	/* "linear" is the builtin model; model=linear unbinds */
+	if (!strcmp(ops->name, "linear"))
+		return -EINVAL;
+	return 0;
+}
+
+/*
+ * The struct_ops core holds a reference on the map while the model is
+ * registered, so kdata stays valid until .unreg returns; no extra
+ * reference is needed here.
+ */
+static int bpf_iocost_reg(void *kdata, struct bpf_link *link)
+{
+	struct iocost_model_ops *ops = kdata;
+	struct iocost_bpf_model *m;
+	int ret = 0;
+
+	m = kzalloc_obj(struct iocost_bpf_model, GFP_KERNEL);
+	if (!m)
+		return -ENOMEM;
+	refcount_set(&m->refs, 1);
+	INIT_LIST_HEAD(&m->lifecycle);
+
+	mutex_lock(&iocost_bpf_reg_lock);
+	{
+		struct iocost_bpf_model *other;
+
+		list_for_each_entry(other, &iocost_bpf_models, list) {
+			if (!strcmp(other->ops->name, ops->name)) {
+				ret = -EEXIST;
+				break;
+			}
+		}
+	}
+	if (!ret) {
+		m->ops = ops;
+		list_add(&m->list, &iocost_bpf_models);
+	}
+	mutex_unlock(&iocost_bpf_reg_lock);
+
+	if (ret)
+		kfree(m);
+	return ret;
+}
+
+/*
+ * Unregistering drops the registration reference.  If a device is
+ * still bound, the binding references keep the node (and the kdata,
+ * through their bpf_struct_ops_get()) alive and it keeps receiving
+ * blkcg online/offline notifications; otherwise the node is freed.
+ */
+static void bpf_iocost_unreg(void *kdata, struct bpf_link *link)
+{
+	struct iocost_model_ops *ops = kdata;
+	struct iocost_bpf_model *m;
+
+	mutex_lock(&iocost_bpf_reg_lock);
+	m = iocost_bpf_model_lookup(ops);
+	if (m) {
+		/*
+		 * keep the linkage queryable so model_put() can tell a
+		 * still-registered node (one ref held by the registry)
+		 * from one kept alive only by device bindings
+		 */
+		list_del_init(&m->list);
+		if (refcount_dec_and_test(&m->refs))
+			kfree(m);
+	}
+	mutex_unlock(&iocost_bpf_reg_lock);
+}
+
+void iocost_bpf_model_put(const struct iocost_model_ops *ops)
+{
+	struct iocost_bpf_model *m;
+
+	mutex_lock(&iocost_bpf_reg_lock);
+	list_for_each_entry(m, &iocost_bpf_lifecycle, lifecycle) {
+		if (m->ops == ops)
+			break;
+	}
+	if (&m->lifecycle != &iocost_bpf_lifecycle) {
+		bool freed = refcount_dec_and_test(&m->refs);
+
+		/*
+		 * leave the notify list with the last binding: refs is
+		 * now zero (node freed) or the registry's single one
+		 */
+		if (freed || (!list_empty(&m->list) &&
+			      refcount_read(&m->refs) == 1))
+			list_del_init(&m->lifecycle);
+		mutex_unlock(&iocost_bpf_reg_lock);
+		bpf_struct_ops_put(ops);
+		if (freed)
+			kfree(m);
+		return;
+	}
+	mutex_unlock(&iocost_bpf_reg_lock);
+}
+
+static const struct bpf_verifier_ops bpf_iocost_verifier_ops = {
+	.get_func_proto = bpf_iocost_get_func_proto,
+	.is_valid_access = bpf_iocost_is_valid_access,
+};
+
+static u64 bpf_iocost_calc_cost_stub(u64 opf, u64 nbytes, u64 sector,
+				     struct blkcg *blkcg, u64 flags)
+{
+	return 0;
+}
+
+static void bpf_iocost_blkcg_online_stub(struct blkcg *blkcg) { }
+static void bpf_iocost_blkcg_offline_stub(struct blkcg *blkcg) { }
+
+static struct iocost_model_ops __bpf_ops_iocost_model_ops = {
+	.calc_cost = bpf_iocost_calc_cost_stub,
+	.blkcg_online = bpf_iocost_blkcg_online_stub,
+	.blkcg_offline = bpf_iocost_blkcg_offline_stub,
+};
+
+static struct bpf_struct_ops bpf_iocost_model_ops = {
+	.verifier_ops = &bpf_iocost_verifier_ops,
+	.init = bpf_iocost_model_init,
+	.check_member = bpf_iocost_check_member,
+	.init_member = bpf_iocost_init_member,
+	.validate = bpf_iocost_validate,
+	.reg = bpf_iocost_reg,
+	.unreg = bpf_iocost_unreg,
+	.name = "iocost_model_ops",
+	.cfi_stubs = &__bpf_ops_iocost_model_ops,
+	.owner = THIS_MODULE,
+};
+
+static int __init bpf_iocost_init(void)
+{
+	return register_bpf_struct_ops(&bpf_iocost_model_ops, iocost_model_ops);
+}
+late_initcall(bpf_iocost_init);
diff --git a/block/blk-iocost.c b/block/blk-iocost.c
index 2745bffcd5eef..9eb97f38a39cf 100644
--- a/block/blk-iocost.c
+++ b/block/blk-iocost.c
@@ -177,6 +177,7 @@
 #include <linux/timer.h>
 #include <linux/time64.h>
 #include <linux/parser.h>
+#include <linux/blk-iocost.h>
 #include <linux/sched/signal.h>
 #include <asm/local.h>
 #include <asm/local64.h>
@@ -445,6 +446,11 @@ struct ioc {
 	int				autop_idx;
 	bool				user_qos_params:1;
 	bool				user_cost_model:1;
+
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	/* bound BPF cost model, NULL = builtin linear model */
+	const struct iocost_model_ops	__rcu *model;
+#endif
 };
 
 struct iocg_pcpu_stat {
@@ -2238,6 +2244,10 @@ static void ioc_timer_fn(struct timer_list *timer)
 	struct ioc_now now;
 	LIST_HEAD(surpluses);
 	int nr_debtors, nr_shortages = 0, nr_lagging = 0;
+	int nr_active = 0;
+	u32 tick_period_us;
+	u64 tick_vrate, tick_dur;
+	int tick_busy, tick_running;
 	u64 usage_us_sum = 0;
 	u32 ppm_rthr;
 	u32 ppm_wthr;
@@ -2274,6 +2284,8 @@ static void ioc_timer_fn(struct timer_list *timer)
 		u64 vdone, vtime, usage_us;
 		u32 hw_active, hw_inuse;
 
+		nr_active++;
+
 		/*
 		 * Collect unused and wind vtime closer to vnow to prevent
 		 * iocgs from accumulating a large amount of budget.
@@ -2435,6 +2447,14 @@ static void ioc_timer_fn(struct timer_list *timer)
 
 	ioc->busy_level = clamp(ioc->busy_level, -1000, 1000);
 
+	/*
+	 * vrate and period_us change right below; snapshot the values
+	 * this period ran in so the tick below reports the period's own
+	 * parameters instead of the next period's.
+	 */
+	tick_period_us = ioc->period_us;
+	tick_vrate = ioc->vtime_base_rate;
+
 	ioc_adjust_base_vrate(ioc, rq_wait_pct, nr_lagging, nr_shortages,
 			      prev_busy_level, missed_ppm);
 
@@ -2442,6 +2462,24 @@ static void ioc_timer_fn(struct timer_list *timer)
 
 	ioc_forgive_debts(ioc, usage_us_sum, nr_debtors, &now);
 
+	/*
+	 * Snapshot the state this period ran in before the idle
+	 * transition below wipes it, so the final tick reports the period's
+	 * own busy level (e.g. the saturation that drove the controller
+	 * idle) instead of the cleared one.  usage is normalized by the
+	 * measured period length, captured before ioc_start_period()
+	 * overwrites period_at, the same way the donation loop does.
+	 * Emitted before cur_period is bumped, so the tick carries the
+	 * number of the period it describes.
+	 */
+	tick_busy = ioc->busy_level;
+	tick_running = ioc->running;
+	tick_dur = now.now - ioc->period_at;
+
+	trace_iocost_ioc_tick(ioc, nr_active, usage_us_sum,
+			      tick_period_us, tick_vrate,
+			      tick_busy, tick_running, tick_dur);
+
 	/*
 	 * This period is done.  Move onto the next one.  If nothing's
 	 * going on with the device, stop the timer.
@@ -2571,10 +2609,28 @@ static void calc_vtime_cost_builtin(struct bio *bio, struct ioc_gq *iocg,
 
 static u64 calc_vtime_cost(struct bio *bio, struct ioc_gq *iocg, bool is_merge)
 {
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	const struct iocost_model_ops *model;
 	u64 cost;
 
-	calc_vtime_cost_builtin(bio, iocg, is_merge, &cost);
-	return cost;
+	rcu_read_lock();
+	model = rcu_dereference(iocg->ioc->model);
+	if (model) {
+		cost = model->calc_cost(bio->bi_opf, bio->bi_iter.bi_size,
+					bio->bi_iter.bi_sector,
+					iocg_to_blkg(iocg)->blkcg,
+					is_merge ? IOCOST_COST_F_MERGE : 0);
+		rcu_read_unlock();
+		return min(cost, VTIME_PER_SEC);
+	}
+	rcu_read_unlock();
+#endif
+	{
+		u64 cost;
+
+		calc_vtime_cost_builtin(bio, iocg, is_merge, &cost);
+		return cost;
+	}
 }
 
 static void calc_size_vtime_cost_builtin(struct request *rq, struct ioc *ioc,
@@ -2596,10 +2652,28 @@ static void calc_size_vtime_cost_builtin(struct request *rq, struct ioc *ioc,
 
 static u64 calc_size_vtime_cost(struct request *rq, struct ioc *ioc)
 {
-	u64 cost;
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	const struct iocost_model_ops *model;
 
-	calc_size_vtime_cost_builtin(rq, ioc, &cost);
-	return cost;
+	rcu_read_lock();
+	model = rcu_dereference(ioc->model);
+	if (model && rq->bio && rq->bio->bi_blkg) {
+		u64 cost;
+
+		cost = model->calc_cost(rq->cmd_flags, blk_rq_bytes(rq),
+					blk_rq_pos(rq),
+					rq->bio->bi_blkg->blkcg, 0);
+		rcu_read_unlock();
+		return min(cost, VTIME_PER_SEC);
+	}
+	rcu_read_unlock();
+#endif
+	{
+		u64 cost;
+
+		calc_size_vtime_cost_builtin(rq, ioc, &cost);
+		return cost;
+	}
 }
 
 enum over_budget_action {
@@ -2900,6 +2974,19 @@ static void ioc_rqos_exit(struct rq_qos *rqos)
 
 	timer_shutdown_sync(&ioc->timer);
 	free_percpu(ioc->pcpu_stat);
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	{
+		const struct iocost_model_ops *model;
+
+		spin_lock_irq(&ioc->lock);
+		model = rcu_dereference_protected(ioc->model,
+					lockdep_is_held(&ioc->lock));
+		rcu_assign_pointer(ioc->model, NULL);
+		spin_unlock_irq(&ioc->lock);
+		if (model)
+			iocost_bpf_model_put(model);
+	}
+#endif
 	kfree(ioc);
 }
 
@@ -3438,12 +3525,30 @@ static u64 ioc_cost_model_prfill(struct seq_file *sf,
 		return 0;
 
 	spin_lock_irq(&ioc->lock);
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	{
+		const struct iocost_model_ops *model =
+			rcu_dereference_protected(ioc->model,
+					lockdep_is_held(&ioc->lock));
+
+		seq_printf(sf, "%s ctrl=%s model=%s "
+			   "rbps=%llu rseqiops=%llu rrandiops=%llu "
+			   "wbps=%llu wseqiops=%llu wrandiops=%llu\n",
+			   dname, model ? "bpf" :
+				   ioc->user_cost_model ? "user" : "auto",
+			   model ? model->name : "linear",
+			   u[I_LCOEF_RBPS], u[I_LCOEF_RSEQIOPS],
+			   u[I_LCOEF_RRANDIOPS], u[I_LCOEF_WBPS],
+			   u[I_LCOEF_WSEQIOPS], u[I_LCOEF_WRANDIOPS]);
+	}
+#else
 	seq_printf(sf, "%s ctrl=%s model=linear "
 		   "rbps=%llu rseqiops=%llu rrandiops=%llu "
 		   "wbps=%llu wseqiops=%llu wrandiops=%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]);
+#endif
 	spin_unlock_irq(&ioc->lock);
 	return 0;
 }
@@ -3457,6 +3562,48 @@ static int ioc_cost_model_show(struct seq_file *sf, void *v)
 	return 0;
 }
 
+/*
+ * Resolve the model name and take a reference on the new model before
+ * anything is applied, so a bad name rejects the whole write.  The
+ * registry lookup takes the registration mutex and must stay outside
+ * ioc->lock.  The returned model is per-write state passed back into
+ * ioc_bpf_model_commit(), which performs the pointer swap under
+ * ioc->lock so concurrent writers cannot interleave a half-applied
+ * configuration, and the caller drops the old model's reference
+ * afterwards.
+ */
+static const struct iocost_model_ops *
+ioc_bpf_model_prepare(const char *name)
+{
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	if (!name[0])
+		return NULL;
+	return iocost_bpf_model_get(name);
+#else
+	return name[0] ? ERR_PTR(-ENOENT) : NULL;
+#endif
+}
+
+/*
+ * Swap in the model returned by ioc_bpf_model_prepare().  Called with
+ * ioc->lock held; dropping the old model's reference may sleep, so
+ * the caller does it after releasing the lock.
+ */
+static const struct iocost_model_ops *
+ioc_bpf_model_commit(struct ioc *ioc, const struct iocost_model_ops *new)
+{
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	const struct iocost_model_ops *old;
+
+	old = rcu_dereference_protected(ioc->model,
+					lockdep_is_held(&ioc->lock));
+	rcu_assign_pointer(ioc->model, new);
+	return old;
+#else
+	return NULL;
+#endif
+}
+
 static const match_table_t cost_ctrl_tokens = {
 	{ COST_CTRL,		"ctrl=%s"	},
 	{ COST_MODEL,		"model=%s"	},
@@ -3482,6 +3629,7 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 	struct ioc *ioc;
 	u64 u[NR_I_LCOEFS];
 	bool user;
+	char bpf_model[IOCOST_MODEL_NAME_LEN];
 	char *body, *p;
 	int ret;
 
@@ -3512,6 +3660,25 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 	spin_lock_irq(&ioc->lock);
 	memcpy(u, ioc->params.i_lcoefs, sizeof(u));
 	user = ioc->user_cost_model;
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	{
+		const struct iocost_model_ops *model =
+			rcu_dereference_protected(ioc->model,
+					lockdep_is_held(&ioc->lock));
+
+		/*
+		 * seed from the bound model so a coefficient-only write
+		 * keeps it bound; ctrl=auto/user and model=linear are
+		 * the explicit ways back to the builtin model
+		 */
+		if (model)
+			strscpy(bpf_model, model->name, sizeof(bpf_model));
+		else
+			bpf_model[0] = '\0';
+	}
+#else
+	bpf_model[0] = '\0';
+#endif
 
 	ret = -EINVAL;
 
@@ -3527,17 +3694,27 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 		switch (match_token(p, cost_ctrl_tokens, args)) {
 		case COST_CTRL:
 			match_strlcpy(buf, &args[0], sizeof(buf));
-			if (!strcmp(buf, "auto"))
+			if (!strcmp(buf, "auto")) {
 				user = false;
-			else if (!strcmp(buf, "user"))
+			} else if (!strcmp(buf, "user")) {
 				user = true;
-			else
+			} else if (!strcmp(buf, "bpf")) {
+				/* readback value; keep the bound model */
+				continue;
+			} else {
 				goto unlock;
+			}
+			/* ctrl=auto/user: explicit return to builtin */
+			bpf_model[0] = '\0';
 			continue;
 		case COST_MODEL:
 			match_strlcpy(buf, &args[0], sizeof(buf));
-			if (strcmp(buf, "linear"))
-				goto unlock;
+			if (!strcmp(buf, "linear")) {
+				/* back to the builtin linear model */
+				bpf_model[0] = '\0';
+				continue;
+			}
+			match_strlcpy(bpf_model, &args[0], sizeof(bpf_model));
 			continue;
 		}
 
@@ -3550,19 +3727,34 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 		user = true;
 	}
 
-	if (user) {
-		memcpy(ioc->params.i_lcoefs, u, sizeof(u));
-		ioc->user_cost_model = true;
-	} else {
-		ioc->user_cost_model = false;
-	}
-	ioc_refresh_params(ioc, true);
-
 	ret = 0;
 
 unlock:
 	spin_unlock_irq(&ioc->lock);
 
+	/* resolve the name outside ioc->lock; see ioc_bpf_model_prepare() */
+	if (!ret) {
+		const struct iocost_model_ops *new, *old;
+
+		new = ioc_bpf_model_prepare(bpf_model);
+		if (IS_ERR(new)) {
+			ret = PTR_ERR(new);
+		} else {
+			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;
+			}
+			ioc_refresh_params(ioc, true);
+			old = ioc_bpf_model_commit(ioc, new);
+			spin_unlock_irq(&ioc->lock);
+			if (IS_ENABLED(CONFIG_BLK_CGROUP_IOCOST_BPF) && old)
+				iocost_bpf_model_put(old);
+		}
+	}
+
 	blk_mq_unquiesce_queue(q);
 	blk_mq_unfreeze_queue(q, memflags);
 
diff --git a/include/linux/blk-iocost.h b/include/linux/blk-iocost.h
new file mode 100644
index 0000000000000..e6dc6772ef5c9
--- /dev/null
+++ b/include/linux/blk-iocost.h
@@ -0,0 +1,86 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _LINUX_BLK_IOCOST_H
+#define _LINUX_BLK_IOCOST_H
+
+#include <linux/types.h>
+#include <linux/blk_types.h>
+
+#define IOCOST_MODEL_NAME_LEN	16
+
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+
+struct blkcg;
+
+/*
+ * Pluggable cost model interface for blk-iocost.
+ *
+ * A BPF struct_ops implementation registered against "iocost_model_ops"
+ * fully replaces the builtin linear model on the devices it is bound to
+ * through io.cost.model.  The model owns pricing for every IO on a bound
+ * device: it prices all operations, including flushes, and it is called
+ * from the bio charging path.  The completion-time request sizing for
+ * the latency met/missed accounting still uses the builtin coefficients
+ * (the request's bio, and with it the issuing cgroup, is gone by then);
+ * extending the model there is left open by this interface.
+ *
+ * calc_cost() is called from the IO submission path with RCU read lock
+ * held and must not sleep.  It returns the cost of the IO in vtime
+ * units, where 1 second of device time equals VTIME_PER_SEC (2^37,
+ * available to BPF programs through vmlinux.h).  The returned value is
+ * clamped to 1 second of device time per IO.
+ *
+ * The model is passed the blkcg of the issuing cgroup so it can keep
+ * per-cgroup state.  State keyed by the blkcg alone is shared across
+ * every device the model is bound to, unlike the builtin cursor which
+ * is per (cgroup, device).  blkcg_online()/blkcg_offline() are optional
+ * callbacks mirroring the blkcg css lifecycle: they are delivered
+ * only while at least one device has the model bound, and state
+ * created on online (or lazily on first use) must be released on
+ * offline.
+ *
+ * The registration and binding model follows the TCP congestion
+ * control framework: registering a struct_ops makes the model available
+ * by its name, while io.cost.model binds one registered model to a
+ * device.  Unregistering removes the name from the registry; devices
+ * already bound keep using it until switched back to the builtin
+ * model, and the name remains usable for io.cost.model writes (so a
+ * coefficient-only write keeps such a model bound) until the last
+ * device unbinds.
+ */
+
+/*
+ * iocost-specific call metadata for calc_cost()'s model_flags
+ * argument; everything else, including REQ_PREFLUSH/REQ_FUA, is
+ * already present in the opf argument.  An enum so the value is
+ * exported through BTF and BPF models can use it from vmlinux.h.
+ */
+enum {
+	IOCOST_COST_F_MERGE	= 1 << 0,	/* called from merge path */
+};
+
+struct iocost_model_ops {
+	u64 (*calc_cost)(u64 opf, u64 nbytes, sector_t sector,
+			 struct blkcg *blkcg, u64 model_flags);
+	void (*blkcg_online)(struct blkcg *blkcg);
+	void (*blkcg_offline)(struct blkcg *blkcg);
+
+	/* model name, used to select the model through io.cost.model */
+	char name[IOCOST_MODEL_NAME_LEN];
+};
+
+const struct iocost_model_ops *iocost_bpf_model_get(const char *name);
+void iocost_bpf_model_put(const struct iocost_model_ops *ops);
+void iocost_notify_blkcg_online(struct blkcg *blkcg);
+void iocost_notify_blkcg_offline(struct blkcg *blkcg);
+
+#else	/* CONFIG_BLK_CGROUP_IOCOST_BPF */
+
+struct blkcg;
+struct iocost_model_ops;
+
+static inline void iocost_bpf_model_put(const struct iocost_model_ops *ops) { }
+static inline void iocost_notify_blkcg_online(struct blkcg *blkcg) { }
+static inline void iocost_notify_blkcg_offline(struct blkcg *blkcg) { }
+
+#endif	/* CONFIG_BLK_CGROUP_IOCOST_BPF */
+#endif	/* _LINUX_BLK_IOCOST_H */
diff --git a/include/trace/events/iocost.h b/include/trace/events/iocost.h
index e772b1bc60d60..32f19861a78fd 100644
--- a/include/trace/events/iocost.h
+++ b/include/trace/events/iocost.h
@@ -178,6 +178,51 @@ TRACE_EVENT(iocost_ioc_vrate_adj,
 	)
 );
 
+/*
+ * Periodic per-device summary, emitted once per period from the tail of
+ * ioc_timer_fn().  Unlike the state-change events above, this fires every
+ * period the controller is running, including steady states, and carries
+ * the overall controller state so basic monitoring doesn't require drgn.
+ */
+TRACE_EVENT(iocost_ioc_tick,
+
+	TP_PROTO(struct ioc *ioc, int nr_active, u64 usage_us_sum,
+		 u32 tick_period_us, u64 tick_vrate,
+		 int tick_busy, int tick_running, u64 tick_dur),
+
+	TP_ARGS(ioc, nr_active, usage_us_sum, tick_period_us, tick_vrate,
+		tick_busy, tick_running, tick_dur),
+
+	TP_STRUCT__entry (
+		__string(devname, ioc_name(ioc))
+		__field(u64, cur_period)
+		__field(u32, period_us)
+		__field(u64, vrate)
+		__field(int, busy_level)
+		__field(int, nr_active)
+		__field(u32, usage_pct)
+		__field(int, running)
+	),
+
+	TP_fast_assign(
+		__assign_str(devname);
+		__entry->cur_period = atomic64_read(&ioc->cur_period);
+		__entry->period_us = tick_period_us;
+		__entry->vrate = tick_vrate;
+		__entry->busy_level = tick_busy;
+		__entry->nr_active = nr_active;
+		__entry->usage_pct = tick_dur ?
+			div64_u64(usage_us_sum * 100, tick_dur) : 0;
+		__entry->running = tick_running;
+	),
+
+	TP_printk("[%s] period=%llu:%uus vrate=%llu busy=%d active=%d usage=%u%% running=%d",
+		__get_str(devname), __entry->cur_period, __entry->period_us,
+		__entry->vrate, __entry->busy_level, __entry->nr_active,
+		__entry->usage_pct, __entry->running
+	)
+);
+
 TRACE_EVENT(iocost_iocg_forgive_debt,
 
 	TP_PROTO(struct ioc_gq *iocg, const char *path, struct ioc_now *now,
diff --git a/tools/testing/selftests/bpf/config b/tools/testing/selftests/bpf/config
index 2f79688dcf7ce..67a630cb56148 100644
--- a/tools/testing/selftests/bpf/config
+++ b/tools/testing/selftests/bpf/config
@@ -138,3 +138,5 @@ CONFIG_SMC_HS_CTRL_BPF=y
 CONFIG_DIBS=y
 CONFIG_DIBS_LO=y
 CONFIG_PM_WAKELOCKS=y
+CONFIG_BLK_CGROUP_IOCOST=y
+CONFIG_BLK_CGROUP_IOCOST_BPF=y
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 0000000000000..ac734c0e09cb0
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/iocost_model.c
@@ -0,0 +1,200 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <test_progs.h>
+#include <ctype.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include "iocost_model.skel.h"
+#include "iocost_ms.skel.h"
+
+/*
+ * Write a line to io.cost.model with write(2) and return the errno of
+ * the failed write, or 0 on success.  stdio is not used here on
+ * purpose: the kernel's rejection happens in the write() syscall,
+ * not in the userspace buffer copy, and every write, including
+ * the error paths of the callers below, is checked.
+ */
+static int write_cost_model(const char *buf)
+{
+	int fd, err = 0;
+	ssize_t n;
+
+	fd = open("/sys/fs/cgroup/io.cost.model", O_WRONLY);
+	if (fd < 0)
+		return -errno;	/* negative: the file is not there */
+	n = write(fd, buf, strlen(buf));
+	if (n < 0)
+		err = errno;
+	close(fd);
+	return err;
+}
+
+/*
+ * 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 && !isspace(*end))
+		end++;
+	snprintf(model, model_sz, "%.*s", (int)(end - m), m);
+	return 0;
+}
+
+/*
+ * Bind the named model to a device with "model=<name>", verify the
+ * readback and restore the builtin model.  Returns 0 on success.
+ */
+static int bind_model(const char *dev, const char *name)
+{
+	char buf[300], got[64];
+	int err;
+
+	snprintf(buf, sizeof(buf), "%s model=%s\n", dev, name);
+	err = write_cost_model(buf);
+	if (err)
+		return err > 0 ? -err : -EIO;
+	err = readback_model(dev, got, sizeof(got));
+	if (!err && !strcmp(got, name)) {
+		/*
+		 * restore the builtin linear model on every path so
+		 * the device is not left bound to a model the caller
+		 * may unregister right after; the write is checked too
+		 */
+		snprintf(buf, sizeof(buf), "%s model=linear\n", dev);
+		err = write_cost_model(buf);
+		return err > 0 ? -err : (err ? -EIO : 0);
+	}
+
+	/*
+	 * bind failed or does not read back: still restore, but report
+	 * the original failure rather than the restore result
+	 */
+	snprintf(buf, sizeof(buf), "%s model=linear\n", dev);
+	write_cost_model(buf);
+	return err ? -EIO : -EINVAL;
+}
+
+/*
+ * True when the device line exists in io.cost.qos and iocost is
+ * enabled on it.
+ */
+static int dev_has_iocost(const char *dev)
+{
+	char line[256], word[256];
+	FILE *fp;
+	int found = 0;
+
+	fp = fopen("/sys/fs/cgroup/io.cost.qos", "r");
+	if (!fp)
+		return 0;
+	while (fgets(line, sizeof(line), fp)) {
+		if (sscanf(line, "%255s", word) == 1 && !strcmp(word, dev)) {
+			found = strstr(line, "enable=1") != NULL;
+			break;
+		}
+	}
+	fclose(fp);
+	return found;
+}
+
+/*
+ * Bind the 2x example model and verify the io.cost.model readback.
+ * IO accounting itself is not checked here; it needs a device doing
+ * real IO under iocost and is covered by the kernel-side validation
+ * described in the cover letter.
+ *
+ * Requires root, cgroup v2 and a device with iocost support.  The
+ * device must be given as major:minor in $IOCOST_TEST_DEV, otherwise
+ * the test is skipped.
+ */
+void serial_test_iocost_model(void)
+{
+	struct iocost_model *skel;
+	char buf[300], *dev;
+	int err;
+
+	dev = getenv("IOCOST_TEST_DEV");
+	if (!dev || geteuid() != 0) {
+		test__skip();
+		return;
+	}
+	if (!dev_has_iocost(dev)) {
+		printf("skip: %s has no iocost enabled\n", dev);
+		test__skip();
+		return;
+	}
+
+	/*
+	 * negative: binding an unknown model name must be rejected,
+	 * so a typo cannot silently disable cost model updates
+	 */
+	snprintf(buf, sizeof(buf), "%s model=no_such_model\n", dev);
+	err = write_cost_model(buf);
+	ASSERT_EQ(err > 0 ? err : 0, ENOENT, "unknown_model_rejected");
+
+	skel = iocost_model__open_and_load();
+	if (!ASSERT_OK_PTR(skel, "skel_open_load"))
+		return;
+
+	/* attaching the struct_ops registers the model by name */
+	err = iocost_model__attach(skel);
+	if (ASSERT_OK(err, "attach"))
+		ASSERT_OK(bind_model(dev, "iocost_2x"), "bind_and_readback");
+
+	iocost_model__destroy(skel);
+}
+
+/*
+ * Same check for the multi-stream example model.  Only one model can
+ * be bound to a device at a time; both tests bind and restore, so
+ * they are serial and independent.
+ */
+void serial_test_iocost_model_streams(void)
+{
+	struct iocost_ms *skel;
+	char *dev;
+	int err;
+
+	dev = getenv("IOCOST_TEST_DEV");
+	if (!dev || geteuid() != 0) {
+		test__skip();
+		return;
+	}
+	if (!dev_has_iocost(dev)) {
+		printf("skip: %s has no iocost enabled\n", dev);
+		test__skip();
+		return;
+	}
+
+	skel = iocost_ms__open_and_load();
+	if (!ASSERT_OK_PTR(skel, "skel_open_load"))
+		return;
+
+	err = iocost_ms__attach(skel);
+	if (ASSERT_OK(err, "attach"))
+		ASSERT_OK(bind_model(dev, "iocost_ms"), "bind_and_readback");
+
+	iocost_ms__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 0000000000000..66fab4711c0b5
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/iocost_model.c
@@ -0,0 +1,136 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Example iocost cost model: the builtin linear HDD formula with all
+ * costs doubled.
+ *
+ * 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 bound to this model through
+ * io.cost.model charges exactly twice the builtin model under the
+ * same workload, so the doubled cost is a direct check that
+ * accounting goes through the BPF path.  On a non-rotational device,
+ * or one with user-pinned coefficients, the ratio to the builtin
+ * model is arbitrary.
+ *
+ * The cursor handling mirrors the builtin: a zero cursor means "no
+ * previous IO", and the cursor is only advanced for READ and WRITE
+ * bios the builtin prices, so flushes and discards leave it alone.
+ *
+ * The model implements the full linear formula itself, including
+ * flushes: there is no fallback to the builtin model, a dataless
+ * WRITE|REQ_PREFLUSH is priced as a one-page write.
+ */
+
+#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_COST_F_MERGE come from vmlinux.h (BTF enum constants)
+ */
+#define LCOEF_RANDIO_PAGES	4096	/* 16MB seek threshold */
+#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, freed with it, so
+ * the model never leaks or reuses stale per-cgroup state
+ */
+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");
+
+SEC("struct_ops")
+u64 BPF_PROG(iocost_2x_calc_cost, u64 opf, u64 nbytes, u64 sector,
+	     struct blkcg *blkcg, u64 model_flags)
+{
+	u64 pages, seek_pages = 0, base, coef_page, randio, cost;
+
+	/* 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) {
+		base = WSEQIO; coef_page = WPAGE; randio = WRANDIO;
+	} else {
+		/*
+		 * a fully owning model must price every op; unknown
+		 * ops are priced as a single page write
+		 */
+		base = 0; coef_page = WPAGE; randio = 0;
+	}
+
+	/*
+	 * mirror the builtin cursor semantics: seek distance is only
+	 * computed against a non-zero cursor, and the cursor is
+	 * advanced for bios the builtin prices (READ/WRITE with a
+	 * non-zero size), merged ones included, so flushes and
+	 * discards leave it alone and long merged streams do not
+	 * drift past the 16MB seek threshold
+	 */
+	{
+		__u64 *cursor, cur;
+		int priced = (opf & IOCOST_REQ_OP_MASK) == REQ_OP_READ ||
+			     (opf & IOCOST_REQ_OP_MASK) == REQ_OP_WRITE;
+
+		cursor = bpf_cgrp_storage_get(&cursor_store,
+					      blkcg->css.cgroup, NULL,
+					      BPF_LOCAL_STORAGE_GET_F_CREATE);
+		if (!cursor) {
+			if (model_flags & IOCOST_COST_F_MERGE)
+				base = 0;
+			return 2 * (base + pages * coef_page);
+		}
+		cur = *cursor;
+		if (cur && priced) {
+			seek_pages = sector > cur ? sector - cur
+						   : cur - sector;
+			seek_pages >>= IOC_SECT_TO_PAGE_SHIFT;
+			if (seek_pages > LCOEF_RANDIO_PAGES)
+				base = randio;
+		}
+		if (priced && nbytes)
+			*cursor = sector + RU(nbytes, 512);
+	}
+
+	if (model_flags & IOCOST_COST_F_MERGE)
+		base = 0;
+
+	cost = 2 * (base + pages * coef_page);
+	return cost;
+}
+
+SEC(".struct_ops")
+struct iocost_model_ops iocost_2x = {
+	.calc_cost = (void *)iocost_2x_calc_cost,
+	.name = "iocost_2x",
+};
+
+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 0000000000000..70019db0fd790
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/iocost_ms.c
@@ -0,0 +1,156 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * 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 full builtin
+ * linear formula itself, including flush pricing.
+ */
+#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_COST_F_MERGE come 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");
+
+SEC("struct_ops")
+u64 BPF_PROG(iocost_ms_calc_cost, u64 opf, u64 nbytes, u64 sector,
+	     struct blkcg *blkcg, u64 model_flags)
+{
+	struct streams *s;
+	u64 pages, base, coef_page, randio, advance, now;
+	u32 i, victim = 0, found = 0xFFFFFFFF;
+
+	if ((opf & IOCOST_REQ_OP_MASK) == REQ_OP_READ) {
+		base = RSEQIO; coef_page = RPAGE; randio = RRANDIO;
+	} else if ((opf & IOCOST_REQ_OP_MASK) == REQ_OP_WRITE) {
+		base = WSEQIO; coef_page = WPAGE; randio = WRANDIO;
+	} else {
+		/*
+		 * a fully owning model must price every op; unknown
+		 * ops are priced as per-page writes
+		 */
+		base = 0; coef_page = WPAGE; randio = 0;
+	}
+	advance = RU(nbytes, 512);	/* sectors */
+
+	/* only bios the builtin prices participate in stream tracking */
+	if (!(((opf & IOCOST_REQ_OP_MASK) == REQ_OP_READ ||
+	       (opf & IOCOST_REQ_OP_MASK) == REQ_OP_WRITE) && 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 */
+		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 */
+		s->expected[found] = sector + advance;
+		s->stamp[found] = now;
+	} else {
+		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 (model_flags & IOCOST_COST_F_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")
+struct iocost_model_ops iocost_ms = {
+	.calc_cost = (void *)iocost_ms_calc_cost,
+	.name = "iocost_ms",
+};
+
+char LICENSE[] SEC("license") = "GPL";

21/3 2026/09/20 09:41 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 19878
							output: 22
							thoughts: 1513
						

Thoughts:
**KMSAN Fuzzing Analysis: iocost_model_ops BPF Integration**

Okay, let's dive into this patch and determine if we need a dedicated KMSAN fuzzing session. The goal is to see if this integration of BPF struct_ops for `iocost_model_ops` introduces any uninitialized memory reads, potential userspace copies of uninitialized data, or other bugs that KMSAN would be particularly good at catching. Given my expertise, I will focus on the most likely areas for memory safety issues.

First, I'll systematically review the changes. The patch adds BPF struct_ops support for `iocost_model_ops` which means that the main changes are around the BPF subsystem interacting with the `iocost` framework. Specifically, I'm watching for any instances where uninitialized memory might be read, passed to userspace, or otherwise lead to a KMSAN trigger.

I'm starting with the `trace_iocost_ioc_tick` tracepoint. From a quick glance at the code in `ioc_timer_fn`, it looks like all the variables passed to the tracepoint are initialized, and the `TRACE_EVENT` macro itself explicitly assigns values to each entry in the tracepoint struct. So, the tracepoint doesn't seem to be a problem.

Next, I'll investigate `block/blk-iocost-bpf.c`. `bpf_iocost_reg` uses `kzalloc_obj`, which is safe because it zeroes the memory. That is good. The key function here is `bpf_iocost_init_member`. Here, `bpf_obj_name_cpy` copies the name from the user space model to the kernel. This is worth closer scrutiny, so I need to check the kernel source for `bpf_obj_name_cpy` itself. Specifically, I'm interested in how it handles the source string and whether it could lead to uninitialized memory being copied if the user-provided name is malformed or shorter than expected. I need to understand the bounds and any internal checks within `bpf_obj_name_cpy`. Let me check the grepper or read the file.



22/3 2026/09/20 09:41 tool grepper
0m Args:
{
  "Expression": "bpf_obj_name_cpy"
}

Results:
{
  "Output": "block/blk-iocost-bpf.c=154=static int bpf_iocost_init_member(const struct btf_type *t,\n--\nblock/blk-iocost-bpf.c-163-\tcase offsetof(struct iocost_model_ops, name):\nblock/blk-iocost-bpf.c:164:\t\tif (bpf_obj_name_cpy(ops-\u003ename, uops-\u003ename,\nblock/blk-iocost-bpf.c-165-\t\t\t\t     sizeof(ops-\u003ename)) \u003c= 0)\n--\nfs/binfmt_misc_bpf.c=344=static int bm_bpf_init_member(const struct btf_type *t,\n--\nfs/binfmt_misc_bpf.c-353-\tcase offsetof(struct binfmt_misc_ops, name):\nfs/binfmt_misc_bpf.c:354:\t\tif (bpf_obj_name_cpy(ops-\u003ename, uops-\u003ename,\nfs/binfmt_misc_bpf.c-355-\t\t\t\t     sizeof(ops-\u003ename)) \u003c= 0)\n--\ninclude/linux/bpf.h=655=struct bpf_map *bpf_prog_arena(struct bpf_prog *prog);\ninclude/linux/bpf.h:656:int bpf_obj_name_cpy(char *dst, const char *src, unsigned int size);\ninclude/linux/bpf.h-657-\n--\nkernel/bpf/syscall.c=1203=int bpf_get_file_flag(int flags)\n--\nkernel/bpf/syscall.c-1224- */\nkernel/bpf/syscall.c:1225:int bpf_obj_name_cpy(char *dst, const char *src, unsigned int size)\nkernel/bpf/syscall.c-1226-{\n--\nkernel/bpf/syscall.c-1244-}\nkernel/bpf/syscall.c:1245:EXPORT_SYMBOL_GPL(bpf_obj_name_cpy);\nkernel/bpf/syscall.c-1246-\n--\nkernel/bpf/syscall.c=1382=static int map_create_alloc(union bpf_attr *attr, bpfptr_t uattr, struct bpf_verifier_log *log,\n--\nkernel/bpf/syscall.c-1541-\nkernel/bpf/syscall.c:1542:\terr = bpf_obj_name_cpy(map-\u003ename, attr-\u003emap_name,\nkernel/bpf/syscall.c-1543-\t\t\t       sizeof(attr-\u003emap_name));\n--\nkernel/bpf/syscall.c=2917=static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_attr *attr_log)\n--\nkernel/bpf/syscall.c-3126-\tprog-\u003eaux-\u003eload_time = ktime_get_boottime_ns();\nkernel/bpf/syscall.c:3127:\terr = bpf_obj_name_cpy(prog-\u003eaux-\u003ename, attr-\u003eprog_name,\nkernel/bpf/syscall.c-3128-\t\t\t       sizeof(attr-\u003eprog_name));\n--\nkernel/sched/ext/ext.c=8065=static int bpf_scx_init_member(const struct btf_type *t,\n--\nkernel/sched/ext/ext.c-8085-\tcase offsetof(struct sched_ext_ops, name):\nkernel/sched/ext/ext.c:8086:\t\tret = bpf_obj_name_cpy(ops-\u003ename, uops-\u003ename,\nkernel/sched/ext/ext.c-8087-\t\t\t\t       sizeof(ops-\u003ename));\n--\nnet/ipv4/bpf_tcp_ca.c=211=static int bpf_tcp_ca_init_member(const struct btf_type *t,\n--\nnet/ipv4/bpf_tcp_ca.c-229-\tcase offsetof(struct tcp_congestion_ops, name):\nnet/ipv4/bpf_tcp_ca.c:230:\t\tif (bpf_obj_name_cpy(tcp_ca-\u003ename, utcp_ca-\u003ename,\nnet/ipv4/bpf_tcp_ca.c-231-\t\t\t\t     sizeof(tcp_ca-\u003ename)) \u003c= 0)\n--\nnet/sched/bpf_qdisc.c=361=static int bpf_qdisc_init_member(const struct btf_type *t,\n--\nnet/sched/bpf_qdisc.c-382-\tcase offsetof(struct Qdisc_ops, id):\nnet/sched/bpf_qdisc.c:383:\t\tif (bpf_obj_name_cpy(qdisc_ops-\u003eid, uqdisc_ops-\u003eid,\nnet/sched/bpf_qdisc.c-384-\t\t\t\t     sizeof(qdisc_ops-\u003eid)) \u003c= 0)\n--\nnet/smc/smc_hs_bpf.c=85=static int smc_bpf_hs_ctrl_init_member(const struct btf_type *t,\n--\nnet/smc/smc_hs_bpf.c-98-\tcase offsetof(struct smc_hs_ctrl, name):\nnet/smc/smc_hs_bpf.c:99:\t\tif (bpf_obj_name_cpy(k_ctrl-\u003ename, u_ctrl-\u003ename,\nnet/smc/smc_hs_bpf.c-100-\t\t\t\t     sizeof(u_ctrl-\u003ename)) \u003c= 0)\n"
}

23/3 2026/09/20 09:41 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 23301
							output: 37
							thoughts: 26
						

Thoughts:
Here's a first-person summary, tailored for an expert audience, as requested:

**Diving into the BPF System Call Logic**

Okay, time to get my hands dirty. I'm going to jump into the `kernel/bpf/syscall.c` file and zero in on lines 1225 through 1244. That specific region should be where the core system call logic for BPF is implemented. I'm especially interested in [Specify what you are looking for. Examples: error handling, specific checks, security vulnerability], because it's been the source of [Mention a reason you are looking here. Example: recent performance bottlenecks, specific issues I've been tracking, security bulletins related to BPF, or recent development in eBPF]. My gut tells me something interesting is lurking in that section, and I need to confirm or dispel my suspicion. Let's see what the code reveals.



24/3 2026/09/20 09:41 tool read-file
0m Args:
{
  "File": "kernel/bpf/syscall.c",
  "FirstLine": 1224,
  "LineCount": 25
}

Results:
{
  "Contents": "1224:\t */\n1225:\tint bpf_obj_name_cpy(char *dst, const char *src, unsigned int size)\n1226:\t{\n1227:\t\tconst char *end = src + size;\n1228:\t\tconst char *orig_src = src;\n1229:\t\n1230:\t\tmemset(dst, 0, size);\n1231:\t\t/* Copy all isalnum(), '_' and '.' chars. */\n1232:\t\twhile (src \u003c end \u0026\u0026 *src) {\n1233:\t\t\tif (!isalnum(*src) \u0026\u0026\n1234:\t\t\t    *src != '_' \u0026\u0026 *src != '.')\n1235:\t\t\t\treturn -EINVAL;\n1236:\t\t\t*dst++ = *src++;\n1237:\t\t}\n1238:\t\n1239:\t\t/* No '\\0' found in \"size\" number of bytes */\n1240:\t\tif (src == end)\n1241:\t\t\treturn -EINVAL;\n1242:\t\n1243:\t\treturn src - orig_src;\n1244:\t}\n1245:\tEXPORT_SYMBOL_GPL(bpf_obj_name_cpy);\n1246:\t\n1247:\tint map_check_no_btf(struct bpf_map *map,\n1248:\t\t\t     const struct btf *btf,\n"
}

25/3 2026/09/20 09:41 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 23930
							output: 36
							thoughts: 507
						

Thoughts:
**Analyzing ioc_cost_model_write and bpf_model Initialization**

Okay, so `bpf_obj_name_cpy` zeroes out its destination. Good to keep in mind. Now, let's dive into `ioc_cost_model_write`. The code initializes a `bpf_model` buffer of `IOCOST_MODEL_NAME_LEN` size. I see two primary branches for initialization:

*   **First Branch:** Inside the `#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF` block, the code attempts to copy the model name from `ioc->model` using `strscpy`, *if* `ioc->model` is not NULL. Otherwise, it sets the first byte of `bpf_model` to null to terminate the string. This is good to prevent uninitialized string data.
*   **Second Branch:** Outside the preprocessor block, `bpf_model[0]` is initialized to NULL. Effectively, this ensures `bpf_model` is a null-terminated string initially in all scenarios.

Looking further, during token matching, `bpf_model` is explicitly reset to an empty string (`bpf_model[0] = '\0'`) under specific conditions, specifically if `ctrl=auto/user` or `model=linear`. These seem to be pathways to revert to a default/builtin linear model. Otherwise, the name is copied with `match_strlcpy` from the arguments provided via the buffer `args`.

This brings me to `match_strlcpy`, which is used in these critical sections where it is assigned. Let's dig deeper and inspect the implementation of `match_strlcpy` to understand exactly what kind of string manipulation it does. Knowing its behavior will give me a clearer picture of how `bpf_model` is actually populated, including any potential vulnerabilities or subtle behavior changes. This will be key to understanding the cost model functionality.



26/3 2026/09/20 09:41 tool grepper
0m Args:
{
  "Expression": "void match_strlcpy|int match_strlcpy|size_t match_strlcpy"
}

Results:
{
  "Output": "include/linux/parser.h=36=bool match_wildcard(const char *pattern, const char *str);\ninclude/linux/parser.h:37:size_t match_strlcpy(char *, const substring_t *, size_t);\ninclude/linux/parser.h-38-char *match_strdup(const substring_t *);\n--\nlib/parser.c=322=EXPORT_SYMBOL(match_wildcard);\n--\nlib/parser.c-335- */\nlib/parser.c:336:size_t match_strlcpy(char *dest, const substring_t *src, size_t size)\nlib/parser.c-337-{\n"
}

27/3 2026/09/20 09:41 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 25064
							output: 33
							thoughts: 15
						

Thoughts:
Here's my attempt at summarizing the thought process, tailored for an expert audience:

**Diving into the Parser**

Okay, time to dig in. The issue log flagged something funky with the parser, so I'm going to jump directly to `lib/parser.c:336`. That line number usually points me to a specific grammar rule or symbol handling. Knowing the codebase, and keeping in mind recent changes, I have a few specific areas I'll be looking at. I'll be checking to see if there's an issue with how operator precedence is handled, especially if there were recent changes around that area. Might be a semantic action problem during reduction, or perhaps a conflict in the grammar itself that's causing unexpected behavior. I'll need to refresh my mental map of the surrounding code and then look at the context around line 336. I'm going to start by confirming whether my gut feeling about the scope of the problem is right.



28/3 2026/09/20 09:41 tool read-file
0m Args:
{
  "File": "lib/parser.c",
  "FirstLine": 335,
  "LineCount": 15
}

Results:
{
  "Contents": " 335:\t */\n 336:\tsize_t match_strlcpy(char *dest, const substring_t *src, size_t size)\n 337:\t{\n 338:\t\tsize_t ret = src-\u003eto - src-\u003efrom;\n 339:\t\n 340:\t\tif (size) {\n 341:\t\t\tsize_t len = ret \u003e= size ? size - 1 : ret;\n 342:\t\t\tmemcpy(dest, src-\u003efrom, len);\n 343:\t\t\tdest[len] = '\\0';\n 344:\t\t}\n 345:\t\treturn ret;\n 346:\t}\n 347:\tEXPORT_SYMBOL(match_strlcpy);\n 348:\t\n 349:\t/**\n"
}

29/3 2026/09/20 09:41 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 25529
							output: 31
							thoughts: 2378
						

Thoughts:
**BPF iocost Model Analysis: A Deep Dive**

Okay, let's break this down systematically. My primary concern here is data integrity and potential vulnerabilities related to user-space interactions with the BPF iocost model. I've examined the code snippets provided to ensure I have a complete picture.

First, `match_strlcpy` is null-terminating the destination string, so that's good. When `ioc_bpf_model_prepare` is called, the name is guaranteed to be null-terminated, which is crucial.

Then, the critical part in `iocost_bpf_model_get`: The `name` parameter passed is null-terminated and `m->ops->name` comes from either `bpf_obj_name_cpy` (which null-terminates) or is guaranteed to be. The `strcmp` uses these validated strings, avoiding any buffer overreads. The locking is correct using mutexes. This part seems robust.

`ioc_cost_model_prfill`:  The use of `seq_printf` with `model->name` is safe since `model->name` is a null-terminated string and the format string sanitizes the output. No direct binary structure copy is happening to user space.

Moving to `blkcg_css_offline` / `blkcg_css_online`, the calls to `iocost_notify_blkcg_online` only trigger BPF callbacks. No direct data is passed, just function pointers and a `blkcg` pointer. That's a low-risk interaction, as it's just the callback execution.

Now the cost calculation parts: `calc_vtime_cost` and `calc_size_vtime_cost`. All arguments passed to `model->calc_cost` are either scalar values or valid pointers. Importantly, in `calc_size_vtime_cost`, the `cost` variable is initialized with the *return* value of the `calc_cost` function and the cost is clamped to the `VTIME_PER_SEC` value.

Finally, the `iocost_model_ops` via BPF struct_ops. I notice the verifier ops and stub functions. I'm going to look for similar BPF implementations in other areas, such as `tcp_congestion_ops`, `sched_ext_ops`, etc. The use of `bpf_tracing_btf_ctx_access` within `bpf_iocost_is_valid_access` is standard practice for BPF struct_ops, making sure the user space BPF code can't read/write memory it shouldn't be.

The remaining concern is how the kernel interacts with the user-provided BPF data. BPF maps and structs are allocated via `kzalloc`, and the structure operations define the validation.  The userspace writes to BPF maps, and that is where validation must take place, to verify what is being written into the `iocost_model_ops` data.  The BPF verifier is key here.

In summary, based on this review, and assuming the BPF verifier is functioning correctly, the interaction with user space data appears to be well-protected by null termination, validation of string copies and parameters, and the mechanisms of BPF struct_ops. However, a deeper dive into the BPF verifier rules would provide more detailed validation of the security model.



30/3 2026/09/20 09:41 tool grepper
0m Args:
{
  "Expression": "struct_ops_map_alloc",
  "PathPrefix": "kernel/bpf"
}

Results:
{
  "Output": "kernel/bpf/bpf_struct_ops.c=1027=static void bpf_struct_ops_map_free(struct bpf_map *map)\n--\nkernel/bpf/bpf_struct_ops.c-1061-\nkernel/bpf/bpf_struct_ops.c:1062:static int bpf_struct_ops_map_alloc_check(union bpf_attr *attr)\nkernel/bpf/bpf_struct_ops.c-1063-{\n--\nkernel/bpf/bpf_struct_ops.c=1071=static u32 count_func_ptrs(const struct btf *btf, const struct btf_type *t)\n--\nkernel/bpf/bpf_struct_ops.c-1083-\nkernel/bpf/bpf_struct_ops.c:1084:static struct bpf_map *bpf_struct_ops_map_alloc(union bpf_attr *attr)\nkernel/bpf/bpf_struct_ops.c-1085-{\n--\nkernel/bpf/bpf_struct_ops.c=1194=const struct bpf_map_ops bpf_struct_ops_map_ops = {\nkernel/bpf/bpf_struct_ops.c:1195:\t.map_alloc_check = bpf_struct_ops_map_alloc_check,\nkernel/bpf/bpf_struct_ops.c:1196:\t.map_alloc = bpf_struct_ops_map_alloc,\nkernel/bpf/bpf_struct_ops.c-1197-\t.map_free = bpf_struct_ops_map_free,\n"
}

31/3 2026/09/20 09:41 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 29094
							output: 42
							thoughts: 32
						

Thoughts:
Here's my attempt at summarizing the thought process, tailored for an expert audience:

**Diving into `bpf_struct_ops_map_alloc`**

Okay, time to dig into the guts of how BPF struct operations are handled. I'm specifically targeting the memory allocation strategy for these, so let's navigate directly to `kernel/bpf/bpf_struct_ops.c`. I need to understand the lifecycle of the `bpf_struct_ops_map_alloc` function; how exactly the allocator works, what arguments it consumes, how the metadata is populated, and finally how it handles freeing the allocated resources upon map destruction or update. Understanding the intricacies here will paint a clearer picture of potential memory management overhead, especially when dealing with large and frequently modified BPF programs. I'm keen to look for any hidden complexities or optimization opportunities.



32/3 2026/09/20 09:41 tool read-file
0m Args:
{
  "File": "kernel/bpf/bpf_struct_ops.c",
  "FirstLine": 1084,
  "LineCount": 40
}

Results:
{
  "Contents": "1084:\tstatic struct bpf_map *bpf_struct_ops_map_alloc(union bpf_attr *attr)\n1085:\t{\n1086:\t\tconst struct bpf_struct_ops_desc *st_ops_desc;\n1087:\t\tsize_t st_map_size;\n1088:\t\tstruct bpf_struct_ops_map *st_map;\n1089:\t\tconst struct btf_type *t, *vt;\n1090:\t\tstruct module *mod = NULL;\n1091:\t\tstruct bpf_map *map;\n1092:\t\tstruct btf *btf;\n1093:\t\tint ret;\n1094:\t\n1095:\t\tif (attr-\u003emap_flags \u0026 BPF_F_VTYPE_BTF_OBJ_FD) {\n1096:\t\t\t/* The map holds btf for its whole life time. */\n1097:\t\t\tbtf = btf_get_by_fd(attr-\u003evalue_type_btf_obj_fd);\n1098:\t\t\tif (IS_ERR(btf))\n1099:\t\t\t\treturn ERR_CAST(btf);\n1100:\t\t\tif (!btf_is_module(btf)) {\n1101:\t\t\t\tbtf_put(btf);\n1102:\t\t\t\treturn ERR_PTR(-EINVAL);\n1103:\t\t\t}\n1104:\t\n1105:\t\t\tmod = btf_try_get_module(btf);\n1106:\t\t\t/* mod holds a refcnt to btf. We don't need an extra refcnt\n1107:\t\t\t * here.\n1108:\t\t\t */\n1109:\t\t\tbtf_put(btf);\n1110:\t\t\tif (!mod)\n1111:\t\t\t\treturn ERR_PTR(-EINVAL);\n1112:\t\t} else {\n1113:\t\t\tbtf = bpf_get_btf_vmlinux();\n1114:\t\t\tif (IS_ERR(btf))\n1115:\t\t\t\treturn ERR_CAST(btf);\n1116:\t\t\tif (!btf)\n1117:\t\t\t\treturn ERR_PTR(-ENOTSUPP);\n1118:\t\t}\n1119:\t\n1120:\t\tst_ops_desc = bpf_struct_ops_find_value(btf, attr-\u003ebtf_vmlinux_value_type_id);\n1121:\t\tif (!st_ops_desc) {\n1122:\t\t\tret = -ENOTSUPP;\n1123:\t\t\tgoto errout;\n"
}

33/3 2026/09/20 09:41 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 30021
							output: 42
							thoughts: 19
						

Thoughts:
Okay, let's dive into the `bpf_struct_ops_map_alloc` function and see what it's all about. I'm curious to understand its purpose within the BPF framework. Let me check the documentation for context, I want to refresh myself on how this allocation function fits into the map lifecycle. Specifically, I'm thinking about the implications for memory management, the potential for locking issues, and whether it's designed to be thread-safe. I'll need to pay close attention to the data structures involved, the parameters it accepts, and how it interacts with other BPF components. Hopefully, it's well-optimized because BPF code is performance critical. I should also check if it contains any special handling for different BPF map types. This detailed analysis should reveal the inner workings of map allocation.



34/3 2026/09/20 09:41 tool read-file
0m Args:
{
  "File": "kernel/bpf/bpf_struct_ops.c",
  "FirstLine": 1124,
  "LineCount": 40
}

Results:
{
  "Contents": "1124:\t\t}\n1125:\t\n1126:\t\tvt = st_ops_desc-\u003evalue_type;\n1127:\t\tif (attr-\u003evalue_size != vt-\u003esize) {\n1128:\t\t\tret = -EINVAL;\n1129:\t\t\tgoto errout;\n1130:\t\t}\n1131:\t\n1132:\t\tt = st_ops_desc-\u003etype;\n1133:\t\n1134:\t\tst_map_size = sizeof(*st_map) +\n1135:\t\t\t/* kvalue stores the\n1136:\t\t\t * struct bpf_struct_ops_tcp_congestions_ops\n1137:\t\t\t */\n1138:\t\t\t(vt-\u003esize - sizeof(struct bpf_struct_ops_value));\n1139:\t\n1140:\t\tst_map = bpf_map_area_alloc(st_map_size, NUMA_NO_NODE);\n1141:\t\tif (!st_map) {\n1142:\t\t\tret = -ENOMEM;\n1143:\t\t\tgoto errout;\n1144:\t\t}\n1145:\t\n1146:\t\tst_map-\u003est_ops_desc = st_ops_desc;\n1147:\t\tmap = \u0026st_map-\u003emap;\n1148:\t\n1149:\t\tst_map-\u003euvalue = bpf_map_area_alloc(vt-\u003esize, NUMA_NO_NODE);\n1150:\t\tst_map-\u003efuncs_cnt = count_func_ptrs(btf, t);\n1151:\t\tst_map-\u003elinks =\n1152:\t\t\tbpf_map_area_alloc(st_map-\u003efuncs_cnt * sizeof(struct bpf_link *),\n1153:\t\t\t\t\t   NUMA_NO_NODE);\n1154:\t\n1155:\t\tst_map-\u003eksyms =\n1156:\t\t\tbpf_map_area_alloc(st_map-\u003efuncs_cnt * sizeof(struct bpf_ksym *),\n1157:\t\t\t\t\t   NUMA_NO_NODE);\n1158:\t\tif (!st_map-\u003euvalue || !st_map-\u003elinks || !st_map-\u003eksyms) {\n1159:\t\t\tret = -ENOMEM;\n1160:\t\t\tgoto errout_free;\n1161:\t\t}\n1162:\t\tst_map-\u003ebtf = btf;\n1163:\t\n"
}

35/3 2026/09/20 09:41 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 30898
							output: 38
							thoughts: 972
						

Thoughts:
**Analyzing Potential Memory Safety and Initialization Issues in the `iocost` Code**

Okay, let's break this down systematically. My initial thought is to look into potential memory safety concerns, especially with regard to the `iocost_bpf_model_put` function and the usage of `bpf_map_area_alloc`. The latter uses `kzalloc` or `vzalloc`, so that's good in terms of zero-initialization. However, I need to ensure that the lifecycle management within `iocost_bpf_model_put` is robust, especially given that it involves reference counting (`refcount_t`) and a linked list. The core of my concern here revolves around potential use-after-free, double-free, or reference count underflow scenarios. The current setup *should* be protected from those by the kernel tools like KASAN and the `refcount_t` itself but it needs careful review.

Specifically, inside `iocost_bpf_model_put`, I need to scrutinize the `freed` condition and the `list_del_init` call within the critical section protected by `mutex_lock(&iocost_bpf_reg_lock)`. The logic needs to be rock-solid to avoid any race conditions or memory leaks. The placement of the `bpf_struct_ops_put` call relative to `kfree(m)` is also important. The intention seems to be that after `refs` goes to zero, the function can remove the list entry and free the memory, assuming that the list and reference are managed carefully.

Next, I need to investigate the `TRACE_EVENT(iocost_ioc_tick)` tracepoint. The question is whether the arguments passed to `trace_iocost_ioc_tick` are properly initialized. I'm focusing on potential uninitialized value issues, which would be a serious flaw. Looking at the `TP_fast_assign` macro, all the fields appear to be assigned values, however, I need to ensure the values are assigned *before* the tracepoint is triggered.

Tracing `ioc_timer_fn` in `block/blk-iocost.c` is the right place to look. I can see that the variables used in the tracepoint are defined at the beginning and assigned values later. I'll need to confirm that no `goto` statements or control flow paths could lead to the tracepoint being called *before* all required fields have been populated. Specifically, I'm verifying the assignments to `tick_period_us`, `tick_vrate`, `tick_busy`, `tick_running`, and `tick_dur`. The `usage_us_sum` and `nr_active` variables also need careful consideration.

So the strategy is clear: I'll carefully check the entire function `ioc_timer_fn` to guarantee the assignment happens before the trace.



36/3 2026/09/20 09:42 tool read-file
0m Args:
{
  "File": "block/blk-iocost.c",
  "FirstLine": 2238,
  "LineCount": 100
}

Results:
{
  "Contents": "2238:\t}\n2239:\t\n2240:\tstatic void ioc_timer_fn(struct timer_list *timer)\n2241:\t{\n2242:\t\tstruct ioc *ioc = container_of(timer, struct ioc, timer);\n2243:\t\tstruct ioc_gq *iocg, *tiocg;\n2244:\t\tstruct ioc_now now;\n2245:\t\tLIST_HEAD(surpluses);\n2246:\t\tint nr_debtors, nr_shortages = 0, nr_lagging = 0;\n2247:\t\tint nr_active = 0;\n2248:\t\tu32 tick_period_us;\n2249:\t\tu64 tick_vrate, tick_dur;\n2250:\t\tint tick_busy, tick_running;\n2251:\t\tu64 usage_us_sum = 0;\n2252:\t\tu32 ppm_rthr;\n2253:\t\tu32 ppm_wthr;\n2254:\t\tu32 missed_ppm[2], rq_wait_pct, nr_done;\n2255:\t\tu64 period_vtime;\n2256:\t\tint prev_busy_level;\n2257:\t\n2258:\t\t/* how were the latencies during the period? */\n2259:\t\tioc_lat_stat(ioc, missed_ppm, \u0026rq_wait_pct, \u0026nr_done);\n2260:\t\n2261:\t\t/* take care of active iocgs */\n2262:\t\tspin_lock_irq(\u0026ioc-\u003elock);\n2263:\t\n2264:\t\tppm_rthr = MILLION - ioc-\u003eparams.qos[QOS_RPPM];\n2265:\t\tppm_wthr = MILLION - ioc-\u003eparams.qos[QOS_WPPM];\n2266:\t\tioc_now(ioc, \u0026now);\n2267:\t\n2268:\t\tperiod_vtime = now.vnow - ioc-\u003eperiod_at_vtime;\n2269:\t\tif (WARN_ON_ONCE(!period_vtime)) {\n2270:\t\t\tspin_unlock_irq(\u0026ioc-\u003elock);\n2271:\t\t\treturn;\n2272:\t\t}\n2273:\t\n2274:\t\tnr_debtors = ioc_check_iocgs(ioc, \u0026now);\n2275:\t\n2276:\t\t/*\n2277:\t\t * Wait and indebt stat are flushed above and the donation calculation\n2278:\t\t * below needs updated usage stat. Let's bring stat up-to-date.\n2279:\t\t */\n2280:\t\tiocg_flush_stat(\u0026ioc-\u003eactive_iocgs, \u0026now);\n2281:\t\n2282:\t\t/* calc usage and see whether some weights need to be moved around */\n2283:\t\tlist_for_each_entry(iocg, \u0026ioc-\u003eactive_iocgs, active_list) {\n2284:\t\t\tu64 vdone, vtime, usage_us;\n2285:\t\t\tu32 hw_active, hw_inuse;\n2286:\t\n2287:\t\t\tnr_active++;\n2288:\t\n2289:\t\t\t/*\n2290:\t\t\t * Collect unused and wind vtime closer to vnow to prevent\n2291:\t\t\t * iocgs from accumulating a large amount of budget.\n2292:\t\t\t */\n2293:\t\t\tvdone = atomic64_read(\u0026iocg-\u003edone_vtime);\n2294:\t\t\tvtime = atomic64_read(\u0026iocg-\u003evtime);\n2295:\t\t\tcurrent_hweight(iocg, \u0026hw_active, \u0026hw_inuse);\n2296:\t\n2297:\t\t\t/*\n2298:\t\t\t * Latency QoS detection doesn't account for IOs which are\n2299:\t\t\t * in-flight for longer than a period.  Detect them by\n2300:\t\t\t * comparing vdone against period start.  If lagging behind\n2301:\t\t\t * IOs from past periods, don't increase vrate.\n2302:\t\t\t */\n2303:\t\t\tif ((ppm_rthr != MILLION || ppm_wthr != MILLION) \u0026\u0026\n2304:\t\t\t    !atomic_read(\u0026iocg_to_blkg(iocg)-\u003euse_delay) \u0026\u0026\n2305:\t\t\t    time_after64(vtime, vdone) \u0026\u0026\n2306:\t\t\t    time_after64(vtime, now.vnow -\n2307:\t\t\t\t\t MAX_LAGGING_PERIODS * period_vtime) \u0026\u0026\n2308:\t\t\t    time_before64(vdone, now.vnow - period_vtime))\n2309:\t\t\t\tnr_lagging++;\n2310:\t\n2311:\t\t\t/*\n2312:\t\t\t * Determine absolute usage factoring in in-flight IOs to avoid\n2313:\t\t\t * high-latency completions appearing as idle.\n2314:\t\t\t */\n2315:\t\t\tusage_us = iocg-\u003eusage_delta_us;\n2316:\t\t\tusage_us_sum += usage_us;\n2317:\t\n2318:\t\t\t/* see whether there's surplus vtime */\n2319:\t\t\tWARN_ON_ONCE(!list_empty(\u0026iocg-\u003esurplus_list));\n2320:\t\t\tif (hw_inuse \u003c hw_active ||\n2321:\t\t\t    (!waitqueue_active(\u0026iocg-\u003ewaitq) \u0026\u0026\n2322:\t\t\t     time_before64(vtime, now.vnow - ioc-\u003emargins.low))) {\n2323:\t\t\t\tu32 hwa, old_hwi, hwm, new_hwi, usage;\n2324:\t\t\t\tu64 usage_dur;\n2325:\t\n2326:\t\t\t\tif (vdone != vtime) {\n2327:\t\t\t\t\tu64 inflight_us = DIV64_U64_ROUND_UP(\n2328:\t\t\t\t\t\tcost_to_abs_cost(vtime - vdone, hw_inuse),\n2329:\t\t\t\t\t\tioc-\u003evtime_base_rate);\n2330:\t\n2331:\t\t\t\t\tusage_us = max(usage_us, inflight_us);\n2332:\t\t\t\t}\n2333:\t\n2334:\t\t\t\t/* convert to hweight based usage ratio */\n2335:\t\t\t\tif (time_after64(iocg-\u003eactivated_at, ioc-\u003eperiod_at))\n2336:\t\t\t\t\tusage_dur = max_t(u64, now.now - iocg-\u003eactivated_at, 1);\n2337:\t\t\t\telse\n"
}

37/3 2026/09/20 09:42 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 34237
							output: 37
							thoughts: 14
						

Thoughts:
Okay, here's my attempt at summarizing the thought process, as requested, in the first person and assuming an expert audience:

**Diving into `ioc_timer_fn`**

Alright, let's get into the heart of this. I need to understand this `ioc_timer_fn` function inside out. It's obviously critical for whatever I/O control mechanism it's a part of, so a cursory glance won't do. I need to dissect its purpose and how it interacts with the broader system. I'm going to start by going through it line by line, really looking for the critical paths and any potential bottlenecks or edge cases that might jump out. I’m thinking about what assumptions it makes, if it uses any synchronization primitives, and how it handles errors. I'll focus on how the timer's behavior is implemented to be as efficient as possible. Is it a periodic timer? A one-shot timer? Are there any obvious timing issues I need to keep in mind? I need to understand this to make sure the I/O system doesn't introduce any performance bottlenecks or unexpected behaviors. Let's dig in.



38/3 2026/09/20 09:42 tool read-file
0m Args:
{
  "File": "block/blk-iocost.c",
  "FirstLine": 2430,
  "LineCount": 70
}

Results:
{
  "Contents": "2430:\t\t\t\t * them out before pushing the device harder.\n2431:\t\t\t\t */\n2432:\t\t\t\tif (!nr_lagging)\n2433:\t\t\t\t\tioc-\u003ebusy_level--;\n2434:\t\t\t} else {\n2435:\t\t\t\t/*\n2436:\t\t\t\t * Nobody is being throttled and the users aren't\n2437:\t\t\t\t * issuing enough IOs to saturate the device.  We\n2438:\t\t\t\t * simply don't know how close the device is to\n2439:\t\t\t\t * saturation.  Coast.\n2440:\t\t\t\t */\n2441:\t\t\t\tioc-\u003ebusy_level = 0;\n2442:\t\t\t}\n2443:\t\t} else {\n2444:\t\t\t/* inside the hysterisis margin, we're good */\n2445:\t\t\tioc-\u003ebusy_level = 0;\n2446:\t\t}\n2447:\t\n2448:\t\tioc-\u003ebusy_level = clamp(ioc-\u003ebusy_level, -1000, 1000);\n2449:\t\n2450:\t\t/*\n2451:\t\t * vrate and period_us change right below; snapshot the values\n2452:\t\t * this period ran in so the tick below reports the period's own\n2453:\t\t * parameters instead of the next period's.\n2454:\t\t */\n2455:\t\ttick_period_us = ioc-\u003eperiod_us;\n2456:\t\ttick_vrate = ioc-\u003evtime_base_rate;\n2457:\t\n2458:\t\tioc_adjust_base_vrate(ioc, rq_wait_pct, nr_lagging, nr_shortages,\n2459:\t\t\t\t      prev_busy_level, missed_ppm);\n2460:\t\n2461:\t\tioc_refresh_params(ioc, false);\n2462:\t\n2463:\t\tioc_forgive_debts(ioc, usage_us_sum, nr_debtors, \u0026now);\n2464:\t\n2465:\t\t/*\n2466:\t\t * Snapshot the state this period ran in before the idle\n2467:\t\t * transition below wipes it, so the final tick reports the period's\n2468:\t\t * own busy level (e.g. the saturation that drove the controller\n2469:\t\t * idle) instead of the cleared one.  usage is normalized by the\n2470:\t\t * measured period length, captured before ioc_start_period()\n2471:\t\t * overwrites period_at, the same way the donation loop does.\n2472:\t\t * Emitted before cur_period is bumped, so the tick carries the\n2473:\t\t * number of the period it describes.\n2474:\t\t */\n2475:\t\ttick_busy = ioc-\u003ebusy_level;\n2476:\t\ttick_running = ioc-\u003erunning;\n2477:\t\ttick_dur = now.now - ioc-\u003eperiod_at;\n2478:\t\n2479:\t\ttrace_iocost_ioc_tick(ioc, nr_active, usage_us_sum,\n2480:\t\t\t\t      tick_period_us, tick_vrate,\n2481:\t\t\t\t      tick_busy, tick_running, tick_dur);\n2482:\t\n2483:\t\t/*\n2484:\t\t * This period is done.  Move onto the next one.  If nothing's\n2485:\t\t * going on with the device, stop the timer.\n2486:\t\t */\n2487:\t\tatomic64_inc(\u0026ioc-\u003ecur_period);\n2488:\t\n2489:\t\tif (ioc-\u003erunning != IOC_STOP) {\n2490:\t\t\tif (!list_empty(\u0026ioc-\u003eactive_iocgs)) {\n2491:\t\t\t\tioc_start_period(ioc, \u0026now);\n2492:\t\t\t} else {\n2493:\t\t\t\tioc-\u003ebusy_level = 0;\n2494:\t\t\t\tioc-\u003evtime_err = 0;\n2495:\t\t\t\tioc-\u003erunning = IOC_IDLE;\n2496:\t\t\t}\n2497:\t\n2498:\t\t\tioc_refresh_vrate(ioc, \u0026now);\n2499:\t\t}\n"
}

39/3 2026/09/20 09:42 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 35620
							output: 37
							thoughts: 408
						

Thoughts:
**My Analysis of `calc_vtime_cost` and Potential Initialization Concerns**

Okay, so I'm digging into this code and I've noted a couple of things. First, there are no unexpected jumps or early returns in the data flow between line 2273 and 2482, so that's good. All the snapshot variables I'm interested in, `tick_period_us`, `tick_vrate`, `tick_busy`, `tick_running`, and `tick_dur`, are definitely fully initialized just before the `trace_iocost_ioc_tick` function call. That's a sanity check passed.

Now, I'm turning my attention to the `calc_vtime_cost` function, specifically comparing it to `calc_vtime_cost_builtin`. Looking at the code for `calc_vtime_cost`, the structure is pretty straightforward. It checks for a BPF model (conditional on `CONFIG_BLK_CGROUP_IOCOST_BPF`). If one exists, it uses the model's `calc_cost` function and returns the minimum of that cost and `VTIME_PER_SEC`. Otherwise, it falls back to using `calc_vtime_cost_builtin`.

My main concern here is the initialization of the `cost` variable in the `calc_vtime_cost` when the BPF model isn't active. It is initialized, as I suspected, within the scope of the `else` statement, as it will be passed to `calc_vtime_cost_builtin` by reference. I'll need to check the definition of `calc_vtime_cost_builtin` to be absolutely certain it's properly initializing the `cost` variable. Let me go check line 2570 in `block/blk-iocost.c` for that.



40/3 2026/09/20 09:42 tool read-file
0m Args:
{
  "File": "block/blk-iocost.c",
  "FirstLine": 2565,
  "LineCount": 40
}

Results:
{
  "Contents": "2565:\tstatic void calc_vtime_cost_builtin(struct bio *bio, struct ioc_gq *iocg,\n2566:\t\t\t\t\t    bool is_merge, u64 *costp)\n2567:\t{\n2568:\t\tstruct ioc *ioc = iocg-\u003eioc;\n2569:\t\tu64 coef_seqio, coef_randio, coef_page;\n2570:\t\tu64 pages = max_t(u64, bio_sectors(bio) \u003e\u003e IOC_SECT_TO_PAGE_SHIFT, 1);\n2571:\t\tu64 seek_pages = 0;\n2572:\t\tu64 cost = 0;\n2573:\t\n2574:\t\t/* Can't calculate cost for empty bio */\n2575:\t\tif (!bio-\u003ebi_iter.bi_size)\n2576:\t\t\tgoto out;\n2577:\t\n2578:\t\tswitch (bio_op(bio)) {\n2579:\t\tcase REQ_OP_READ:\n2580:\t\t\tcoef_seqio\t= ioc-\u003eparams.lcoefs[LCOEF_RSEQIO];\n2581:\t\t\tcoef_randio\t= ioc-\u003eparams.lcoefs[LCOEF_RRANDIO];\n2582:\t\t\tcoef_page\t= ioc-\u003eparams.lcoefs[LCOEF_RPAGE];\n2583:\t\t\tbreak;\n2584:\t\tcase REQ_OP_WRITE:\n2585:\t\t\tcoef_seqio\t= ioc-\u003eparams.lcoefs[LCOEF_WSEQIO];\n2586:\t\t\tcoef_randio\t= ioc-\u003eparams.lcoefs[LCOEF_WRANDIO];\n2587:\t\t\tcoef_page\t= ioc-\u003eparams.lcoefs[LCOEF_WPAGE];\n2588:\t\t\tbreak;\n2589:\t\tdefault:\n2590:\t\t\tgoto out;\n2591:\t\t}\n2592:\t\n2593:\t\tif (iocg-\u003ecursor) {\n2594:\t\t\tseek_pages = abs(bio-\u003ebi_iter.bi_sector - iocg-\u003ecursor);\n2595:\t\t\tseek_pages \u003e\u003e= IOC_SECT_TO_PAGE_SHIFT;\n2596:\t\t}\n2597:\t\n2598:\t\tif (!is_merge) {\n2599:\t\t\tif (seek_pages \u003e LCOEF_RANDIO_PAGES) {\n2600:\t\t\t\tcost += coef_randio;\n2601:\t\t\t} else {\n2602:\t\t\t\tcost += coef_seqio;\n2603:\t\t\t}\n2604:\t\t}\n"
}

41/3 2026/09/20 09:42 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 37159
							output: 37
							thoughts: 13
						

Thoughts:
Okay, I'm ready. Please provide the text you would like me to summarize in the first person, as though the thoughts are my own. I understand I should start with a **bolded header** and tailor the response to someone who is an expert in their field. I will focus on lines 2605-2615.



42/3 2026/09/20 09:42 tool read-file
0m Args:
{
  "File": "block/blk-iocost.c",
  "FirstLine": 2604,
  "LineCount": 15
}

Results:
{
  "Contents": "2604:\t\t}\n2605:\t\tcost += pages * coef_page;\n2606:\tout:\n2607:\t\t*costp = cost;\n2608:\t}\n2609:\t\n2610:\tstatic u64 calc_vtime_cost(struct bio *bio, struct ioc_gq *iocg, bool is_merge)\n2611:\t{\n2612:\t#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n2613:\t\tconst struct iocost_model_ops *model;\n2614:\t\tu64 cost;\n2615:\t\n2616:\t\trcu_read_lock();\n2617:\t\tmodel = rcu_dereference(iocg-\u003eioc-\u003emodel);\n2618:\t\tif (model) {\n"
}

43/3 2026/09/20 09:42 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 37509
							output: 37
							thoughts: 42
						

Thoughts:
Here's my take on those thoughts:

**Analyzing `calc_vtime_cost_builtin` and `calc_size_vtime_cost_builtin`**

Okay, I'm diving into this `calc_vtime_cost_builtin` function, and the first thing that jumps out is that it unconditionally assigns `*costp = cost;`. That's a pretty straightforward assignment of the calculated cost, but I need to understand the context. Is this always the right approach? Are there any potential edge cases where this might not be optimal, perhaps if there are varying levels of detail involved in what the user is calculating?

Now, I need to compare this to `calc_size_vtime_cost_builtin`. Is it doing the same thing? Do they handle cost calculations identically? I need to review it thoroughly, line by line, to see if there are any subtle differences in how the cost value is being set or how these built-in functions interact with any external processes. I should look specifically at where they're being called and why. And more importantly, I need to check the interactions they may have. This should tell me if the code design is consistent, as I need to be sure the design is well-structured and there aren't any problems. I'll need to go through the function code carefully to ensure the designs and implementations are consistent.



44/3 2026/09/20 09:42 tool read-file
0m Args:
{
  "File": "block/blk-iocost.c",
  "FirstLine": 2635,
  "LineCount": 35
}

Results:
{
  "Contents": "2635:\t\n2636:\tstatic void calc_size_vtime_cost_builtin(struct request *rq, struct ioc *ioc,\n2637:\t\t\t\t\t\t u64 *costp)\n2638:\t{\n2639:\t\tunsigned int pages = blk_rq_stats_sectors(rq) \u003e\u003e IOC_SECT_TO_PAGE_SHIFT;\n2640:\t\n2641:\t\tswitch (req_op(rq)) {\n2642:\t\tcase REQ_OP_READ:\n2643:\t\t\t*costp = pages * ioc-\u003eparams.lcoefs[LCOEF_RPAGE];\n2644:\t\t\tbreak;\n2645:\t\tcase REQ_OP_WRITE:\n2646:\t\t\t*costp = pages * ioc-\u003eparams.lcoefs[LCOEF_WPAGE];\n2647:\t\t\tbreak;\n2648:\t\tdefault:\n2649:\t\t\t*costp = 0;\n2650:\t\t}\n2651:\t}\n2652:\t\n2653:\tstatic u64 calc_size_vtime_cost(struct request *rq, struct ioc *ioc)\n2654:\t{\n2655:\t#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n2656:\t\tconst struct iocost_model_ops *model;\n2657:\t\n2658:\t\trcu_read_lock();\n2659:\t\tmodel = rcu_dereference(ioc-\u003emodel);\n2660:\t\tif (model \u0026\u0026 rq-\u003ebio \u0026\u0026 rq-\u003ebio-\u003ebi_blkg) {\n2661:\t\t\tu64 cost;\n2662:\t\n2663:\t\t\tcost = model-\u003ecalc_cost(rq-\u003ecmd_flags, blk_rq_bytes(rq),\n2664:\t\t\t\t\t\tblk_rq_pos(rq),\n2665:\t\t\t\t\t\trq-\u003ebio-\u003ebi_blkg-\u003eblkcg, 0);\n2666:\t\t\trcu_read_unlock();\n2667:\t\t\treturn min(cost, VTIME_PER_SEC);\n2668:\t\t}\n2669:\t\trcu_read_unlock();\n"
}

45/3 2026/09/20 09:42 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 38444
							output: 37
							thoughts: 71
						

Thoughts:
Here's my summary, as though I'm thinking through this process:

**Analyzing `calc_size_vtime_cost_builtin` and `ioc_cost_model_write`**

Okay, so I'm looking at `calc_size_vtime_cost_builtin`. One thing that immediately jumps out at me is that it seems to *always* update the `*costp` pointer, regardless of the path it takes. That's good to keep in mind, and potentially a source of subtle bugs if not handled carefully elsewhere, especially if it's relying on some kind of default value being consistently overwritten or if the update is somehow unnecessary in some paths.

Now, let's switch gears and focus on `ioc_cost_model_write`. I need to get a clear picture of what's going on within that function. I'm going to pull up the source code, specifically around lines 3630-3770 in `block/blk-iocost.c`. That should give me the core logic of the function, and I can start to dissect how the cost model is updated. Hopefully, this section gives me a good understanding of what it's doing.



46/3 2026/09/20 09:42 tool read-file
0m Args:
{
  "File": "block/blk-iocost.c",
  "FirstLine": 3625,
  "LineCount": 80
}

Results:
{
  "Contents": "3625:\t{\n3626:\t\tstruct blkg_conf_ctx ctx;\n3627:\t\tstruct request_queue *q;\n3628:\t\tunsigned int memflags;\n3629:\t\tstruct ioc *ioc;\n3630:\t\tu64 u[NR_I_LCOEFS];\n3631:\t\tbool user;\n3632:\t\tchar bpf_model[IOCOST_MODEL_NAME_LEN];\n3633:\t\tchar *body, *p;\n3634:\t\tint ret;\n3635:\t\n3636:\t\tblkg_conf_init(\u0026ctx, input);\n3637:\t\n3638:\t\tret = blkg_conf_open_bdev(\u0026ctx);\n3639:\t\tif (ret)\n3640:\t\t\treturn ret;\n3641:\t\n3642:\t\tbody = ctx.body;\n3643:\t\tq = bdev_get_queue(ctx.bdev);\n3644:\t\tif (!queue_is_mq(q)) {\n3645:\t\t\tret = -EOPNOTSUPP;\n3646:\t\t\tgoto close_bdev;\n3647:\t\t}\n3648:\t\n3649:\t\tioc = q_to_ioc(q);\n3650:\t\tif (!ioc) {\n3651:\t\t\tret = blk_iocost_init(ctx.bdev-\u003ebd_disk);\n3652:\t\t\tif (ret)\n3653:\t\t\t\tgoto close_bdev;\n3654:\t\t\tioc = q_to_ioc(q);\n3655:\t\t}\n3656:\t\n3657:\t\tmemflags = blk_mq_freeze_queue(q);\n3658:\t\tblk_mq_quiesce_queue(q);\n3659:\t\n3660:\t\tspin_lock_irq(\u0026ioc-\u003elock);\n3661:\t\tmemcpy(u, ioc-\u003eparams.i_lcoefs, sizeof(u));\n3662:\t\tuser = ioc-\u003euser_cost_model;\n3663:\t#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n3664:\t\t{\n3665:\t\t\tconst struct iocost_model_ops *model =\n3666:\t\t\t\trcu_dereference_protected(ioc-\u003emodel,\n3667:\t\t\t\t\t\tlockdep_is_held(\u0026ioc-\u003elock));\n3668:\t\n3669:\t\t\t/*\n3670:\t\t\t * seed from the bound model so a coefficient-only write\n3671:\t\t\t * keeps it bound; ctrl=auto/user and model=linear are\n3672:\t\t\t * the explicit ways back to the builtin model\n3673:\t\t\t */\n3674:\t\t\tif (model)\n3675:\t\t\t\tstrscpy(bpf_model, model-\u003ename, sizeof(bpf_model));\n3676:\t\t\telse\n3677:\t\t\t\tbpf_model[0] = '\\0';\n3678:\t\t}\n3679:\t#else\n3680:\t\tbpf_model[0] = '\\0';\n3681:\t#endif\n3682:\t\n3683:\t\tret = -EINVAL;\n3684:\t\n3685:\t\twhile ((p = strsep(\u0026body, \" \\t\\n\"))) {\n3686:\t\t\tsubstring_t args[MAX_OPT_ARGS];\n3687:\t\t\tchar buf[32];\n3688:\t\t\tint tok;\n3689:\t\t\tu64 v;\n3690:\t\n3691:\t\t\tif (!*p)\n3692:\t\t\t\tcontinue;\n3693:\t\n3694:\t\t\tswitch (match_token(p, cost_ctrl_tokens, args)) {\n3695:\t\t\tcase COST_CTRL:\n3696:\t\t\t\tmatch_strlcpy(buf, \u0026args[0], sizeof(buf));\n3697:\t\t\t\tif (!strcmp(buf, \"auto\")) {\n3698:\t\t\t\t\tuser = false;\n3699:\t\t\t\t} else if (!strcmp(buf, \"user\")) {\n3700:\t\t\t\t\tuser = true;\n3701:\t\t\t\t} else if (!strcmp(buf, \"bpf\")) {\n3702:\t\t\t\t\t/* readback value; keep the bound model */\n3703:\t\t\t\t\tcontinue;\n3704:\t\t\t\t} else {\n"
}

47/3 2026/09/20 09:42 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 39944
							output: 37
							thoughts: 16
						

Thoughts:
Okay, let's dive into this. Here's my take on that request, written as if it's my own thought process:

**Diving into `ioc_cost_model_write`**

Alright, so the task is to read the rest of `ioc_cost_model_write`. Hmm, that suggests there's a specific area within the code I need to focus on, and that I've likely been working with this function or module already. Let's see what gems we can find. Perhaps there's an opportunity to optimize? Improve efficiency? Or maybe there's a potential bug lurking that I can nip in the bud. Hopefully, I can enhance the project, no matter what. Let's get cracking!



48/3 2026/09/20 09:42 tool read-file
0m Args:
{
  "File": "block/blk-iocost.c",
  "FirstLine": 3705,
  "LineCount": 60
}

Results:
{
  "Contents": "3705:\t\t\t\t\tgoto unlock;\n3706:\t\t\t\t}\n3707:\t\t\t\t/* ctrl=auto/user: explicit return to builtin */\n3708:\t\t\t\tbpf_model[0] = '\\0';\n3709:\t\t\t\tcontinue;\n3710:\t\t\tcase COST_MODEL:\n3711:\t\t\t\tmatch_strlcpy(buf, \u0026args[0], sizeof(buf));\n3712:\t\t\t\tif (!strcmp(buf, \"linear\")) {\n3713:\t\t\t\t\t/* back to the builtin linear model */\n3714:\t\t\t\t\tbpf_model[0] = '\\0';\n3715:\t\t\t\t\tcontinue;\n3716:\t\t\t\t}\n3717:\t\t\t\tmatch_strlcpy(bpf_model, \u0026args[0], sizeof(bpf_model));\n3718:\t\t\t\tcontinue;\n3719:\t\t\t}\n3720:\t\n3721:\t\t\ttok = match_token(p, i_lcoef_tokens, args);\n3722:\t\t\tif (tok == NR_I_LCOEFS)\n3723:\t\t\t\tgoto unlock;\n3724:\t\t\tif (match_u64(\u0026args[0], \u0026v))\n3725:\t\t\t\tgoto unlock;\n3726:\t\t\tu[tok] = v;\n3727:\t\t\tuser = true;\n3728:\t\t}\n3729:\t\n3730:\t\tret = 0;\n3731:\t\n3732:\tunlock:\n3733:\t\tspin_unlock_irq(\u0026ioc-\u003elock);\n3734:\t\n3735:\t\t/* resolve the name outside ioc-\u003elock; see ioc_bpf_model_prepare() */\n3736:\t\tif (!ret) {\n3737:\t\t\tconst struct iocost_model_ops *new, *old;\n3738:\t\n3739:\t\t\tnew = ioc_bpf_model_prepare(bpf_model);\n3740:\t\t\tif (IS_ERR(new)) {\n3741:\t\t\t\tret = PTR_ERR(new);\n3742:\t\t\t} else {\n3743:\t\t\t\tspin_lock_irq(\u0026ioc-\u003elock);\n3744:\t\t\t\tif (user) {\n3745:\t\t\t\t\tmemcpy(ioc-\u003eparams.i_lcoefs, u, sizeof(u));\n3746:\t\t\t\t\tioc-\u003euser_cost_model = true;\n3747:\t\t\t\t} else {\n3748:\t\t\t\t\tioc-\u003euser_cost_model = false;\n3749:\t\t\t\t}\n3750:\t\t\t\tioc_refresh_params(ioc, true);\n3751:\t\t\t\told = ioc_bpf_model_commit(ioc, new);\n3752:\t\t\t\tspin_unlock_irq(\u0026ioc-\u003elock);\n3753:\t\t\t\tif (IS_ENABLED(CONFIG_BLK_CGROUP_IOCOST_BPF) \u0026\u0026 old)\n3754:\t\t\t\t\tiocost_bpf_model_put(old);\n3755:\t\t\t}\n3756:\t\t}\n3757:\t\n3758:\t\tblk_mq_unquiesce_queue(q);\n3759:\t\tblk_mq_unfreeze_queue(q, memflags);\n3760:\t\n3761:\tclose_bdev:\n3762:\t\tblkg_conf_close_bdev(\u0026ctx);\n3763:\t\treturn ret ?: nbytes;\n3764:\t}\n"
}

49/3 2026/09/20 09:42 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 41039
							output: 458
							thoughts: 1261
						

Thoughts:
**KMSAN Assessment: No Uninitialized Memory Concerns**

Okay, let's systematically go through this code and evaluate whether KMSAN (Kernel Memory Sanitizer) is needed. My initial thought is it's unlikely, but let's be thorough.

First, I examined the `bpf_model` buffer. It's a character array, `char bpf_model[IOCOST_MODEL_NAME_LEN]`. Crucially, it's either initialized with a string copy, using `strscpy`, or set to null initially. Importantly, `match_strlcpy` is used later, which guarantees null termination, no matter the input. So, that's clean.

Next, I looked at the `iocost_bpf_model` structure. This is allocated with `kzalloc_obj`, which is key. *kzalloc_obj* ensures the structure's memory is zeroed out at allocation. Furthermore, I see explicit initialization for the list heads, operations pointer, and reference count. This is all good and safe.

Now, for the key criteria for KMSAN to apply: uninitialized memory leaks to user space. Let's tick them off.

1.  **Kernel structures sent to user space?** I checked for any `copy_to_user`, `put_user`, netlink skb usage, ioctls, or socket options. I found `seq_printf` in `ioc_cost_model_prfill`, but it's formatted text via `seq_file`. The tracepoint `trace_iocost_ioc_tick` has all fields assigned. There are no new syscalls, ioctls, or binary structs passed to userspace.
2.  **Conditional logic based on uninitialized variables?** I see no such conditionals.
3.  **Complex data structures with uninitialized fields?** `iocost_bpf_model` is `kzalloc_obj` allocated and initialized.
4.  **Bounds checks exposing uninitialized data?** All string operations use safe, bounded functions: `strscpy`, `match_strlcpy`, and `bpf_obj_name_cpy`, all of which null terminate and zero out unused space. So, the string handling is safe.

Next, I reviewed the BPF verifier and `struct_ops` registration. The `bpf_iocost_model_ops` are set up, and I see standard BPF practices in its registration. No red flags here. I am confident that `bpf_iocost_is_valid_access`, `bpf_iocost_get_func_proto`, `bpf_iocost_check_member`, `bpf_iocost_init_member`, and `bpf_iocost_validate` are safe.

Finally, I considered potential memory safety bugs, such as concurrency issues. We've got `iocost_bpf_reg_lock` and `ioc->lock`, plus refcounting and RCU usage. While these could lead to use-after-free or refcount leaks, these are issues that KASAN and LOCKDEP are designed to catch. None of these involve uninitialized memory.

So, overall, after a comprehensive review, I'm confident that KMSAN is *not* needed here. The code is carefully handling memory initialization, and potential issues lie in concurrency and lifetime management, which are covered by other kernel debugging tools. Therefore, `NeedsKMSAN` should be set to `false`. Let's document this, now. I will use the set-results tool now.



50/3 2026/09/20 09:42 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch introduces BPF struct_ops support (`iocost_model_ops`) for the block iocost controller, allowing BPF programs to provide custom cost models bound to devices via cgroup v2 `io.cost.model`. It also introduces lifecycle notifications (`blkcg_online`/`blkcg_offline`) and a new tracepoint (`iocost_ioc_tick`).\n\nAnalysis of uninitialized memory risks:\n1. All heap allocations (specifically `struct iocost_bpf_model`) use `kzalloc_obj`, ensuring zero-initialization.\n2. String buffers on the stack (such as `bpf_model` in `ioc_cost_model_write`) are properly initialized and bounded using `strscpy`, `match_strlcpy`, and `bpf_obj_name_cpy` (which memsets the target buffer to zero before copying).\n3. The new tracepoint `trace_iocost_ioc_tick` explicitly snapshots all variables (`tick_period_us`, `tick_vrate`, `tick_busy`, `tick_running`, `tick_dur`) and assigns each field in `TP_fast_assign`.\n4. Kernel-to-userspace data flow occurs only through text formatting via `seq_printf` in `ioc_cost_model_prfill`; no binary structures or padded buffers are copied to user space.\n\nKASAN vs KMSAN applicability:\nAny potential risks introduced by this change involve concurrency, lock ordering (between `ioc-\u003elock` and `iocost_bpf_reg_lock`), RCU synchronization, and reference count management (`refcount_t`, `bpf_struct_ops_get`/`put`), which could manifest as use-after-free, double-free, or deadlocks. These bugs are fully covered by standard debugging tools (KASAN, LOCKDEP, and refcount checks). There is no risk of uninitialized memory reads or information leaks that would uniquely require KMSAN. Therefore, running a dedicated KMSAN session is not justified.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch introduces BPF struct_ops support (`iocost_model_ops`) for the block iocost controller, allowing BPF programs to provide custom cost models bound to devices via cgroup v2 `io.cost.model`. It also introduces lifecycle notifications (`blkcg_online`/`blkcg_offline`) and a new tracepoint (`iocost_ioc_tick`).\n\nAnalysis of uninitialized memory risks:\n1. All heap allocations (specifically `struct iocost_bpf_model`) use `kzalloc_obj`, ensuring zero-initialization.\n2. String buffers on the stack (such as `bpf_model` in `ioc_cost_model_write`) are properly initialized and bounded using `strscpy`, `match_strlcpy`, and `bpf_obj_name_cpy` (which memsets the target buffer to zero before copying).\n3. The new tracepoint `trace_iocost_ioc_tick` explicitly snapshots all variables (`tick_period_us`, `tick_vrate`, `tick_busy`, `tick_running`, `tick_dur`) and assigns each field in `TP_fast_assign`.\n4. Kernel-to-userspace data flow occurs only through text formatting via `seq_printf` in `ioc_cost_model_prfill`; no binary structures or padded buffers are copied to user space.\n\nKASAN vs KMSAN applicability:\nAny potential risks introduced by this change involve concurrency, lock ordering (between `ioc-\u003elock` and `iocost_bpf_reg_lock`), RCU synchronization, and reference count management (`refcount_t`, `bpf_struct_ops_get`/`put`), which could manifest as use-after-free, double-free, or deadlocks. These bugs are fully covered by standard debugging tools (KASAN, LOCKDEP, and refcount checks). There is no risk of uninitialized memory reads or information leaks that would uniquely require KMSAN. Therefore, running a dedicated KMSAN session is not justified.",
  "NeedsKMSAN": false
}

LLM Calls Summary:
Total Calls Total Tokens Avg Tokens Total Duration (Seconds) Avg Duration (Seconds)
Tool Calls Summary:
Total Calls Total Duration (Seconds) Avg Duration (Seconds)