AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/10/29 02:07 flow patch-triage
2m Args:
null

Results:
{
  "EnableConfigs": [
    "BLK_CGROUP_IOCOST",
    "BLK_CGROUP_IOCOST_BPF",
    "BPF_SYSCALL",
    "BPF_JIT",
    "DEBUG_INFO_BTF",
    "BLK_CGROUP"
  ],
  "FocusSymbols": [
    "ioc_bpf_attach",
    "ioc_bpf_detach",
    "ioc_bpf_eject",
    "ioc_bpf_deliver_iocg_callbacks",
    "bpf_iocost_reg",
    "bpf_iocost_unreg",
    "bpf_iocost_validate",
    "ioc_cost_model_write",
    "ioc_pd_online",
    "ioc_pd_free",
    "calc_vtime_cost",
    "calc_size_vtime_cost"
  ],
  "KMSANReasoning": "The patch series introduces BPF struct_ops support (`iocost_model_ops`) for pluggable cost models in the blk-iocost controller, along with cgroup v2 control/query integration, queue freeze/quiesce handling, an iocost tick tracepoint (`iocost_ioc_tick`), and BPF selftests.\n\nAnalysis regarding KMSAN applicability:\n1. No uninitialized memory or info-leak risks:\n   - All newly added struct members in `struct ioc` (`attached`, `model`, `bpf_link`) and `struct ioc_gq` (`bpf_iocg_inited`) reside in structures allocated using zeroing allocators (`kzalloc_obj` in `blk_iocost_init` and `kzalloc_node` in `ioc_pd_alloc`).\n   - Local variables in modified functions (e.g., `new_model`, `model_write` in `ioc_cost_model_write`, `cost` in `calc_vtime_cost` and `calc_size_vtime_cost`, `nr_active` and `now` in `ioc_timer_fn`) are explicitly initialized before any read.\n   - The tracepoint `iocost_ioc_tick` populates each TP_STRUCT__entry field explicitly from initialized state.\n   - No kernel data structures or uninitialized paddings are copied to userspace via `copy_to_user`, `put_user`, socket options, or netlink; cgroup file readbacks use `seq_printf` with static string literals.\n2. Bugs introduced by this patch are domain-specific to locking, RCU, and object lifetimes:\n   - Complex lock hierarchy (`rq_qos_mutex`, `blkcg_mutex`, `queue_lock`, `ioc-\u003elock`), queue freezing/quiescing, reference counting (`bpf_struct_ops_get`/`put`, `blkdev_get_no_open`/`blkdev_put_no_open`), and RCU dereferencing.\n   - Any bugs here (e.g., use-after-free, deadlocks, NULL pointer dereferences, or lock order inversions) are detected by KASAN and LOCKDEP.\n\nBecause there are no uninitialized memory access or info-leak risks, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch adds a new BPF struct_ops type (iocost_model_ops) allowing userspace BPF programs to dynamically implement pluggable cost models for the blk-iocost cgroup IO controller. The implementation introduces attach, detach, and eject lifecycles with intricate lock orchestration across rq_qos_mutex, blkcg_mutex, queue_lock, and ioc-\u003elock, plus lockdep assertions and RCU dereferencing during I/O submission/completion pricing paths. The code is reachable through standard syscalls (bpf syscall for struct_ops link registration, cgroupfs writes to io.cost.model, block I/O, and device removal), making it well-suited for syzkaller fuzzing to identify potential deadlocks, refcounting issues, or lifecycle races.",
  "WorthFuzzing": true
}

1/1 2026/10/29 02:07 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit 4aad694db0f87849c37acd272fd8ad3abb1e16a7\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Thu Oct 29 02:07:29 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 7e00a051382fb7..439b83dd3f6aa9 100644\n--- a/Documentation/admin-guide/cgroup-v2.rst\n+++ b/Documentation/admin-guide/cgroup-v2.rst\n@@ -2056,8 +2056,9 @@ IO Interface Files\n \tcurrently implements \"io.weight\" proportional control.  Lines\n \tare keyed by $MAJ:$MIN device numbers and not ordered.  The\n \tline for a given device is populated on the first write for\n-\tthe device on \"io.cost.qos\" or \"io.cost.model\".  The following\n-\tnested keys are defined.\n+\tthe device on \"io.cost.qos\" or \"io.cost.model\", or when a BPF\n+\tcost model is attached to it.  The following nested keys are\n+\tdefined.\n \n \t  ======\t=====================================\n \t  enable\tWeight-based control enable\n@@ -2111,13 +2112,41 @@ IO Interface Files\n \timplements \"io.weight\" proportional control.  Lines are keyed\n \tby $MAJ:$MIN device numbers and not ordered.  The line for a\n \tgiven device is populated on the first write for the device on\n-\t\"io.cost.qos\" or \"io.cost.model\".  The following nested keys\n-\tare defined.\n+\t\"io.cost.qos\" or \"io.cost.model\", or when a BPF cost model is\n+\tattached to it.  The following nested keys are defined.\n \n-\t  =====\t\t================================\n+\t  =====\t\t==========================================\n \t  ctrl\t\t\"auto\" or \"user\"\n-\t  model\t\tThe cost model in use - \"linear\"\n-\t  =====\t\t================================\n+\t  model\t\tThe cost model in use - \"linear\" or \"bpf\"\n+\t  =====\t\t==========================================\n+\n+\tWhen CONFIG_BLK_CGROUP_IOCOST_BPF is enabled, a BPF cost\n+\tmodel can be bound to a device by attaching an\n+\t\"iocost_model_ops\" struct_ops carrying the whole disk's\n+\tmajor:minor in its \"dev\" member (a partition's major:minor is\n+\trejected).  Attaching creates the controller if needed, like\n+\tan io.cost.model write does, switches the device's pricing to\n+\tthe model and populates the device's line in this file and in\n+\t\"io.cost.qos\" if it did not exist yet.  Attaching fails with\n+\t-EBUSY if the device already has a model attached.  The\n+\tattached model prices IOs only while the controller is\n+\tenabled through \"io.cost.qos\"; attaching does not enable it.\n+\n+\tWhile a model is attached, \"model\" selects between it and the\n+\tbuiltin model: \"model=bpf\" switches to the attached model and\n+\t\"model=linear\" switches back to the builtin model, and neither\n+\tdetaches the struct_ops.\n+\n+\tOnly detaching removes the model, after which \"model=bpf\"\n+\tfails and the device prices with the builtin model again.\n+\tDevice removal ejects the attached model as well, while the\n+\tstruct_ops link remains until userspace destroys it.  \"ctrl\"\n+\taccepts only \"auto\" and \"user\" and never selects a model.  It\n+\tkeeps describing the builtin coefficients, which take effect\n+\tagain when switched back.  The automatic profile stepping does\n+\tnot switch profiles while the BPF model is in use; as with\n+\tuser-set parameters, the profile selected from the device\n+\tclass still applies.\n \n \tWhen \"ctrl\" is \"auto\", the kernel may change all parameters\n \tdynamically.  When \"ctrl\" is set to \"user\" or any other\n@@ -2125,7 +2154,8 @@ IO Interface Files\n \tautomatic changes are disabled.\n \n \tWhen \"model\" is \"linear\", the following model parameters are\n-\tdefined.\n+\tdefined.  They remain readable and writable while \"model\" is\n+\t\"bpf\" but take effect only after switching back to \"linear\".\n \n \t  =============\t========================================\n \t  [r|w]bps\tThe maximum sequential IO throughput\ndiff --git a/MAINTAINERS b/MAINTAINERS\nindex 801f964899ba79..3abe3a089215a2 100644\n--- a/MAINTAINERS\n+++ b/MAINTAINERS\n@@ -6785,10 +6785,13 @@ T:\tgit git://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux.git\n F:\tDocumentation/admin-guide/cgroup-v1/blkio-controller.rst\n F:\tblock/bfq-cgroup.c\n F:\tblock/blk-cgroup.c\n+F:\tblock/blk-iocost-bpf.c\n F:\tblock/blk-iocost.c\n+F:\tblock/blk-iocost.h\n F:\tblock/blk-iolatency.c\n F:\tblock/blk-throttle.c\n F:\tinclude/linux/blk-cgroup.h\n+F:\tinclude/trace/events/iocost.h\n \n CONTROL GROUP - CPUSET\n M:\tWaiman Long \u003clongman@redhat.com\u003e\ndiff --git a/block/Kconfig b/block/Kconfig\nindex 70e4a66d941ff6..8eaa2a803b6178 100644\n--- a/block/Kconfig\n+++ b/block/Kconfig\n@@ -229,6 +229,10 @@ config BLK_ERROR_INJECTION\n \n \t  See Documentation/block/error-injection.rst for details.\n \n+config BLK_CGROUP_IOCOST_BPF\n+\tdef_bool y\n+\tdepends on BLK_CGROUP_IOCOST \u0026\u0026 BPF_SYSCALL \u0026\u0026 BPF_JIT \u0026\u0026 DEBUG_INFO_BTF\n+\n source \"block/Kconfig.iosched\"\n \n endif # BLOCK\ndiff --git a/block/Makefile b/block/Makefile\nindex e7bd320e3d6971..ee5cebeea006fa 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-iocost-bpf.c b/block/blk-iocost-bpf.c\nnew file mode 100644\nindex 00000000000000..8ff51c26fb253d\n--- /dev/null\n+++ b/block/blk-iocost-bpf.c\n@@ -0,0 +1,464 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/*\n+ * blk-iocost: BPF struct_ops plumbing for pluggable cost models.\n+ *\n+ * Copyright (C) 2026 KylinSoft Corporation.\n+ *\n+ * Registers the \"iocost_model_ops\" struct_ops type. Attachment is per-device:\n+ * the target device is set in the ops from userspace before load, .reg\n+ * attaches the model to that device, creating the ioc if needed and switching\n+ * to the model with the queue frozen before rq_qos_mutex, like io.cost.qos\n+ * writes, and .unreg detaches it; enabling and disabling the controller stays\n+ * with io.cost.qos. The struct_ops core owns the program lifetime.\n+ */\n+#include \u003clinux/init.h\u003e\n+#include \u003clinux/kernel.h\u003e\n+#include \u003clinux/module.h\u003e\n+#include \u003clinux/bpf.h\u003e\n+#include \u003clinux/bpf_verifier.h\u003e\n+#include \u003clinux/btf.h\u003e\n+#include \"blk-iocost.h\"\n+#include \u003clinux/blk-mq.h\u003e\n+#include \u003clinux/mutex.h\u003e\n+#include \"blk.h\"\n+\n+/*\n+/*\n+ * Deliver iocg_init()/iocg_free() to the cgroups already online on the\n+ * queue: init walks q-\u003eblkg_list in reverse so parents receive it first,\n+ * like blkcg_activate_policy(); free walks it forward like the blkcg\n+ * policy teardown. The queue is frozen and quiesced; queue_lock\n+ * serializes against blkg creation and blkcg_mutex against the delayed\n+ * list removal in blkg destruction; the callbacks are called with\n+ * ioc-\u003elock held, the same lock the attachment updates take.\n+ */\n+static void ioc_bpf_deliver_iocg_callbacks(struct ioc *ioc,\n+\t\t\t\t\t   const struct iocost_model_ops *ops,\n+\t\t\t\t\t   bool init)\n+{\n+\tstruct request_queue *q = ioc-\u003erqos.disk-\u003equeue;\n+\tstruct blkcg_gq *blkg;\n+\n+\tlockdep_assert_held(\u0026q-\u003eblkcg_mutex);\n+\tlockdep_assert_held(\u0026q-\u003equeue_lock);\n+\tlockdep_assert_held(\u0026ioc-\u003elock);\n+\n+\tif (init) {\n+\t\t/* parents first, like blkcg_activate_policy() */\n+\t\tlist_for_each_entry_reverse(blkg, \u0026q-\u003eblkg_list, q_node) {\n+\t\t\tstruct ioc_gq *iocg = blkg_to_iocg(blkg);\n+\n+\t\t\t/*\n+\t\t\t * A blkg which never went online never reached the\n+\t\t\t * radix tree, so it must not receive an init either;\n+\t\t\t * the attach runs under the same queue_lock as\n+\t\t\t * blkg_create(), so pd-\u003eonline is stable here. Any\n+\t\t\t * previous attachment had its delivered flags cleared\n+\t\t\t * before it went away, so none can still be set here.\n+\t\t\t */\n+\t\t\tif (!iocg || !iocg-\u003epd.online)\n+\t\t\t\tcontinue;\n+\t\t\tif (ops-\u003eiocg_init) {\n+\t\t\t\tops-\u003eiocg_init(blkg-\u003eblkcg, q);\n+\t\t\t\tiocg-\u003ebpf_iocg_inited = true;\n+\t\t\t}\n+\t\t}\n+\t} else {\n+\t\tlist_for_each_entry(blkg, \u0026q-\u003eblkg_list, q_node) {\n+\t\t\tstruct ioc_gq *iocg = blkg_to_iocg(blkg);\n+\n+\t\t\tif (!iocg || !iocg-\u003ebpf_iocg_inited)\n+\t\t\t\tcontinue;\n+\t\t\tif (ops-\u003eiocg_free)\n+\t\t\t\tops-\u003eiocg_free(blkg-\u003eblkcg, q);\n+\t\t\tiocg-\u003ebpf_iocg_inited = false;\n+\t\t}\n+\t}\n+}\n+\n+static int ioc_bpf_attach(struct iocost_model_ops *ops, struct bpf_link *link)\n+{\n+\tstruct block_device *bdev;\n+\tstruct request_queue *q;\n+\tstruct gendisk *disk;\n+\tstruct ioc *ioc;\n+\tunsigned int memflags;\n+\tint ret;\n+\n+\tbdev = blkdev_get_no_open(new_decode_dev(ops-\u003edev), false);\n+\tif (!bdev)\n+\t\treturn -ENODEV;\n+\tq = bdev-\u003ebd_queue;\n+\tdisk = bdev-\u003ebd_disk;\n+\n+\tif (bdev_is_partition(bdev)) {\n+\t\tblkdev_put_no_open(bdev);\n+\t\treturn -EINVAL;\n+\t}\n+\tif (!queue_is_mq(q)) {\n+\t\tblkdev_put_no_open(bdev);\n+\t\treturn -EOPNOTSUPP;\n+\t}\n+\n+\t/*\n+\t * The freeze is taken before rq_qos_mutex like ioc_qos_write() does;\n+\t * holding the mutex from the disk_live() check through the model\n+\t * switch keeps the ioc from being freed under us.\n+\t */\n+\tmemflags = blk_mq_freeze_queue(q);\n+\n+\tmutex_lock(\u0026q-\u003erq_qos_mutex);\n+\n+\tif (!disk_live(disk)) {\n+\t\tmutex_unlock(\u0026q-\u003erq_qos_mutex);\n+\t\tblk_mq_unfreeze_queue(q, memflags);\n+\t\tblkdev_put_no_open(bdev);\n+\t\treturn -ENODEV;\n+\t}\n+\tioc = q_to_ioc(q);\n+\tif (!ioc) {\n+\t\tret = blk_iocost_init(disk);\n+\t\tif (ret) {\n+\t\t\tmutex_unlock(\u0026q-\u003erq_qos_mutex);\n+\t\t\tblk_mq_unfreeze_queue(q, memflags);\n+\t\t\tblkdev_put_no_open(bdev);\n+\t\t\treturn ret;\n+\t\t}\n+\t\tioc = q_to_ioc(q);\n+\t}\n+\n+\tblk_mq_quiesce_queue(q);\n+\n+\t/*\n+\t * Scope the mutex so the tail bdev put runs with blkcg_mutex\n+\t * already released: dropping the last device reference can\n+\t * reach disk_release() -\u003e blkcg_exit_disk() -\u003e\n+\t * blkg_destroy_all(), which takes q-\u003eblkcg_mutex.\n+\t */\n+\t{\n+\t\tguard(mutex)(\u0026q-\u003eblkcg_mutex);\n+\t\tscoped_guard(spinlock_irqsave, \u0026q-\u003equeue_lock) {\n+\t\t\tspin_lock(\u0026ioc-\u003elock);\n+\t\t\tret = ioc_attached_model_locked(ioc) ? -EBUSY : 0;\n+\t\t\tif (!ret) {\n+\t\t\t\t/*\n+\t\t\t\t * Take the map reference before the attachment\n+\t\t\t\t * is published: the readers find the ops\n+\t\t\t\t * through it. get() cannot fail while .reg\n+\t\t\t\t * runs, as the core holds a map reference\n+\t\t\t\t * then, but check it anyway; on failure leave\n+\t\t\t\t * with no attachment set.\n+\t\t\t\t */\n+\t\t\t\tif (!bpf_struct_ops_get(ops)) {\n+\t\t\t\t\tret = -ENODEV;\n+\t\t\t\t} else {\n+\t\t\t\t\trcu_assign_pointer(ioc-\u003eattached, ops);\n+\t\t\t\t\trcu_assign_pointer(ioc-\u003emodel, ops);\n+\t\t\t\t\tioc-\u003ebpf_link = link;\n+\n+\t\t\t\t\t/* pair iocg_init() with the cgroups online */\n+\t\t\t\t\tioc_bpf_deliver_iocg_callbacks(ioc, ops,\n+\t\t\t\t\t\t\t\t       true);\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\tspin_unlock(\u0026ioc-\u003elock);\n+\t\t}\n+\t}\n+\n+\tblk_mq_unquiesce_queue(q);\n+\tblk_mq_unfreeze_queue(q, memflags);\n+\tmutex_unlock(\u0026q-\u003erq_qos_mutex);\n+\tblkdev_put_no_open(bdev);\n+\treturn ret;\n+}\n+\n+/*\n+ * Detach a model: switch back to the builtin model when the attached model is\n+ * in use, clear the attachment and deliver iocg_free() to the cgroups which\n+ * still exist, under the same freeze and quiesce as the attach.\n+ */\n+static void ioc_bpf_detach(struct iocost_model_ops *ops, struct bpf_link *link)\n+{\n+\tstruct block_device *bdev;\n+\tstruct request_queue *q;\n+\tstruct ioc *ioc;\n+\tbool matched;\n+\tunsigned int memflags;\n+\n+\t/*\n+\t * A failed lookup means the device is gone; the removal ejection will\n+\t * detach the model and drop the map reference when rq_qos_exit() runs,\n+\t * so there is nothing to do here.\n+\t */\n+\tbdev = blkdev_get_no_open(new_decode_dev(ops-\u003edev), false);\n+\tif (!bdev)\n+\t\treturn;\n+\tq = bdev-\u003ebd_queue;\n+\n+\t/*\n+\t * The attachment is checked under rq_qos_mutex first, so an unmatched\n+\t * detach exits without freezing.\n+\t */\n+\tmutex_lock(\u0026q-\u003erq_qos_mutex);\n+\tspin_lock_irq(\u0026q-\u003equeue_lock);\n+\tioc = q_to_ioc(q);\n+\tif (ioc) {\n+\t\tspin_lock(\u0026ioc-\u003elock);\n+\t\tmatched = ioc_attached_model_locked(ioc) == ops \u0026\u0026\n+\t\t\t  ioc-\u003ebpf_link == link;\n+\t\tspin_unlock(\u0026ioc-\u003elock);\n+\t} else {\n+\t\tmatched = false;\n+\t}\n+\tspin_unlock_irq(\u0026q-\u003equeue_lock);\n+\tmutex_unlock(\u0026q-\u003erq_qos_mutex);\n+\tif (!matched) {\n+\t\tblkdev_put_no_open(bdev);\n+\t\treturn;\n+\t}\n+\n+\t/* the freeze is taken before rq_qos_mutex like ioc_qos_write() */\n+\tmemflags = blk_mq_freeze_queue(q);\n+\n+\tmutex_lock(\u0026q-\u003erq_qos_mutex);\n+\n+\t/*\n+\t * Re-check under the mutex before quiescing: the freeze itself does\n+\t * not touch the tag set, and the removal ejection holds rq_qos_mutex\n+\t * before the driver frees the tag set, so the check passing here means\n+\t * the tag set is still alive.\n+\t */\n+\tspin_lock_irq(\u0026q-\u003equeue_lock);\n+\tioc = q_to_ioc(q);\n+\tif (ioc) {\n+\t\tspin_lock(\u0026ioc-\u003elock);\n+\t\tmatched = ioc_attached_model_locked(ioc) == ops \u0026\u0026\n+\t\t\t  ioc-\u003ebpf_link == link;\n+\t\tspin_unlock(\u0026ioc-\u003elock);\n+\t} else {\n+\t\tmatched = false;\n+\t}\n+\tspin_unlock_irq(\u0026q-\u003equeue_lock);\n+\tif (!matched) {\n+\t\tmutex_unlock(\u0026q-\u003erq_qos_mutex);\n+\t\tblk_mq_unfreeze_queue(q, memflags);\n+\t\tblkdev_put_no_open(bdev);\n+\t\treturn;\n+\t}\n+\n+\tblk_mq_quiesce_queue(q);\n+\n+\t/*\n+\t * Scope the mutex so the tail bdev put runs with blkcg_mutex\n+\t * already released: dropping the last device reference can\n+\t * reach disk_release() -\u003e blkcg_exit_disk() -\u003e\n+\t * blkg_destroy_all(), which takes q-\u003eblkcg_mutex.\n+\t */\n+\t{\n+\t\tguard(mutex)(\u0026q-\u003eblkcg_mutex);\n+\t\tscoped_guard(spinlock_irqsave, \u0026q-\u003equeue_lock) {\n+\t\t\tspin_lock(\u0026ioc-\u003elock);\n+\t\t\tif (ioc_bpf_model_locked(ioc) == ops)\n+\t\t\t\trcu_assign_pointer(ioc-\u003emodel, NULL);\n+\t\t\trcu_assign_pointer(ioc-\u003eattached, NULL);\n+\t\t\tioc-\u003ebpf_link = NULL;\n+\n+\t\t\tioc_bpf_deliver_iocg_callbacks(ioc, ops, false);\n+\t\t\tspin_unlock(\u0026ioc-\u003elock);\n+\t\t}\n+\t}\n+\n+\tblk_mq_unquiesce_queue(q);\n+\tblk_mq_unfreeze_queue(q, memflags);\n+\tmutex_unlock(\u0026q-\u003erq_qos_mutex);\n+\n+\tblkdev_put_no_open(bdev);\n+\tbpf_struct_ops_put(ops);\n+}\n+\n+/*\n+ * Eject the model on device removal. The caller holds rq_qos_mutex and\n+ * blkcg_deactivate_policy() has already run, so every existing blkg got\n+ * iocg_free() from ioc_pd_free() and no walk is needed. The ioc is freed right\n+ * after, so clearing the pointers and dropping the map reference is all that\n+ * is left to do.\n+ */\n+void ioc_bpf_eject(struct ioc *ioc)\n+{\n+\tconst struct iocost_model_ops *ops;\n+\tunsigned long flags;\n+\n+\tspin_lock_irqsave(\u0026ioc-\u003elock, flags);\n+\tops = ioc_attached_model_locked(ioc);\n+\tif (ops) {\n+\t\trcu_assign_pointer(ioc-\u003eattached, NULL);\n+\t\tif (ioc_bpf_model_locked(ioc) == ops)\n+\t\t\trcu_assign_pointer(ioc-\u003emodel, NULL);\n+\t\tioc-\u003ebpf_link = NULL;\n+\t}\n+\tspin_unlock_irqrestore(\u0026ioc-\u003elock, flags);\n+\n+\tif (ops)\n+\t\tbpf_struct_ops_put(ops);\n+}\n+\n+/* nothing to look up: the core finds the struct by name before calling */\n+static int bpf_iocost_model_init(struct btf *btf)\n+{\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/* every callback runs under RCU read lock or a spinlock */\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+\t/*\n+\t * The struct_ops core rejects a nonzero userspace value for\n+\t * non-function members this callback does not claim.\n+\t */\n+\tcase offsetof(struct iocost_model_ops, dev):\n+\t\tops-\u003edev = uops-\u003edev;\n+\t\treturn 1;\n+\tcase offsetof(struct iocost_model_ops, read_vtime_per_page):\n+\t\tops-\u003eread_vtime_per_page = uops-\u003eread_vtime_per_page;\n+\t\treturn 1;\n+\tcase offsetof(struct iocost_model_ops, write_vtime_per_page):\n+\t\tops-\u003ewrite_vtime_per_page = uops-\u003ewrite_vtime_per_page;\n+\t\treturn 1;\n+\t}\n+\n+\treturn 0;\n+}\n+\n+/*\n+ * A complete model prices every charged IO and carries both transfer\n+ * coefficients; a missing calc_cost would be a NULL call from the\n+ * submission path and missing coefficients would silently zero the\n+ * completion-time sizing (see ioc_rqos_done()), so the model is\n+ * rejected before it can be registered. iocg_init() and iocg_free()\n+ * must come in pairs too: a model implementing only one of them would\n+ * build per-cgroup state that nothing ever tears down.\n+ */\n+static bool iocost_model_complete(const struct iocost_model_ops *ops)\n+{\n+\treturn ops-\u003ecalc_cost \u0026\u0026 ops-\u003eread_vtime_per_page \u0026\u0026\n+\t       ops-\u003ewrite_vtime_per_page \u0026\u0026\n+\t       !!ops-\u003eiocg_init == !!ops-\u003eiocg_free;\n+}\n+\n+/*\n+ * kvalue is zeroed at map allocation and function members are only written\n+ * when the BPF side provides a prog, so a model which did not implement\n+ * calc_cost leaves it NULL, and missing coefficients read as zero. This is\n+ * reached from the map-update path of both map flavors, before the model can\n+ * be registered.\n+ */\n+static int bpf_iocost_validate(void *kdata)\n+{\n+\tstruct iocost_model_ops *ops = kdata;\n+\n+\t/*\n+\t * Bound the transfer coefficients so that coefficient * pages cannot\n+\t * wrap u64 for any possible request size.\n+\t */\n+\tif (ops-\u003eread_vtime_per_page \u003e (VTIME_PER_SEC \u003e\u003e IOC_SECT_TO_PAGE_SHIFT) ||\n+\t    ops-\u003ewrite_vtime_per_page \u003e (VTIME_PER_SEC \u003e\u003e IOC_SECT_TO_PAGE_SHIFT))\n+\t\treturn -EINVAL;\n+\n+\treturn iocost_model_complete(ops) ? 0 : -EINVAL;\n+}\n+\n+static int bpf_iocost_reg(void *kdata, struct bpf_link *link)\n+{\n+\tstruct iocost_model_ops *ops = kdata;\n+\n+\t/* validate() has run by now; only the device is left to check */\n+\tif (!ops-\u003edev)\n+\t\treturn -EINVAL;\n+\n+\treturn ioc_bpf_attach(ops, link);\n+}\n+\n+static void bpf_iocost_unreg(void *kdata, struct bpf_link *link)\n+{\n+\tstruct iocost_model_ops *ops = kdata;\n+\n+\t/* a gone device is handled inside ioc_bpf_detach() */\n+\tioc_bpf_detach(ops, link);\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(struct bio *bio, u64 flags)\n+{\n+\treturn 0;\n+}\n+\n+static void bpf_iocost_iocg_init_stub(struct blkcg *blkcg,\n+\t\t\t\t      struct request_queue *q)\n+{ }\n+static void bpf_iocost_iocg_free_stub(struct blkcg *blkcg,\n+\t\t\t\t      struct request_queue *q)\n+{ }\n+\n+static struct iocost_model_ops __bpf_ops_iocost_model_ops = {\n+\t.calc_cost = bpf_iocost_calc_cost_stub,\n+\t.iocg_init = bpf_iocost_iocg_init_stub,\n+\t.iocg_free = bpf_iocost_iocg_free_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 a81488c755cabf..9f7f5e5f0ebb7d 100644\n--- a/block/blk-iocost.c\n+++ b/block/blk-iocost.c\n@@ -184,6 +184,7 @@\n #include \"blk-stat.h\"\n #include \"blk-wbt.h\"\n #include \"blk-cgroup.h\"\n+#include \"blk-iocost.h\"\n \n #ifdef CONFIG_TRACEPOINTS\n \n@@ -209,374 +210,6 @@ static char trace_iocg_path[TRACE_IOCG_PATH_LEN];\n #define TRACE_IOCG_PATH(type, iocg, ...)\tdo { } while (0)\n #endif\t/* CONFIG_TRACE_POINTS */\n \n-enum {\n-\tMILLION\t\t\t= 1000000,\n-\n-\t/* timer period is calculated from latency requirements, bound it */\n-\tMIN_PERIOD\t\t= USEC_PER_MSEC,\n-\tMAX_PERIOD\t\t= USEC_PER_SEC,\n-\n-\t/*\n-\t * iocg-\u003evtime is targeted at 50% behind the device vtime, which\n-\t * serves as its IO credit buffer.  Surplus weight adjustment is\n-\t * immediately canceled if the vtime margin runs below 10%.\n-\t */\n-\tMARGIN_MIN_PCT\t\t= 10,\n-\tMARGIN_LOW_PCT\t\t= 20,\n-\tMARGIN_TARGET_PCT\t= 50,\n-\n-\tINUSE_ADJ_STEP_PCT\t= 25,\n-\n-\t/* Have some play in timer operations */\n-\tTIMER_SLACK_PCT\t\t= 1,\n-\n-\t/* 1/64k is granular enough and can easily be handled w/ u32 */\n-\tWEIGHT_ONE\t\t= 1 \u003c\u003c 16,\n-};\n-\n-enum {\n-\t/*\n-\t * As vtime is used to calculate the cost of each IO, it needs to\n-\t * be fairly high precision.  For example, it should be able to\n-\t * represent the cost of a single page worth of discard with\n-\t * suffificient accuracy.  At the same time, it should be able to\n-\t * represent reasonably long enough durations to be useful and\n-\t * convenient during operation.\n-\t *\n-\t * 1s worth of vtime is 2^37.  This gives us both sub-nanosecond\n-\t * granularity and days of wrap-around time even at extreme vrates.\n-\t */\n-\tVTIME_PER_SEC_SHIFT\t= 37,\n-\tVTIME_PER_SEC\t\t= 1LLU \u003c\u003c VTIME_PER_SEC_SHIFT,\n-\tVTIME_PER_USEC\t\t= VTIME_PER_SEC / USEC_PER_SEC,\n-\tVTIME_PER_NSEC\t\t= VTIME_PER_SEC / NSEC_PER_SEC,\n-\n-\t/* bound vrate adjustments within two orders of magnitude */\n-\tVRATE_MIN_PPM\t\t= 10000,\t/* 1% */\n-\tVRATE_MAX_PPM\t\t= 100000000,\t/* 10000% */\n-\n-\tVRATE_MIN\t\t= VTIME_PER_USEC * VRATE_MIN_PPM / MILLION,\n-\tVRATE_CLAMP_ADJ_PCT\t= 4,\n-\n-\t/* switch iff the conditions are met for longer than this */\n-\tAUTOP_CYCLE_NSEC\t= 10LLU * NSEC_PER_SEC,\n-};\n-\n-enum {\n-\t/* if IOs end up waiting for requests, issue less */\n-\tRQ_WAIT_BUSY_PCT\t= 5,\n-\n-\t/* unbusy hysterisis */\n-\tUNBUSY_THR_PCT\t\t= 75,\n-\n-\t/*\n-\t * The effect of delay is indirect and non-linear and a huge amount of\n-\t * future debt can accumulate abruptly while unthrottled. Linearly scale\n-\t * up delay as debt is going up and then let it decay exponentially.\n-\t * This gives us quick ramp ups while delay is accumulating and long\n-\t * tails which can help reducing the frequency of debt explosions on\n-\t * unthrottle. The parameters are experimentally determined.\n-\t *\n-\t * The delay mechanism provides adequate protection and behavior in many\n-\t * cases. However, this is far from ideal and falls shorts on both\n-\t * fronts. The debtors are often throttled too harshly costing a\n-\t * significant level of fairness and possibly total work while the\n-\t * protection against their impacts on the system can be choppy and\n-\t * unreliable.\n-\t *\n-\t * The shortcoming primarily stems from the fact that, unlike for page\n-\t * cache, the kernel doesn't have well-defined back-pressure propagation\n-\t * mechanism and policies for anonymous memory. Fully addressing this\n-\t * issue will likely require substantial improvements in the area.\n-\t */\n-\tMIN_DELAY_THR_PCT\t= 500,\n-\tMAX_DELAY_THR_PCT\t= 25000,\n-\tMIN_DELAY\t\t= 250,\n-\tMAX_DELAY\t\t= 250 * USEC_PER_MSEC,\n-\n-\t/* halve debts if avg usage over 100ms is under 50% */\n-\tDFGV_USAGE_PCT\t\t= 50,\n-\tDFGV_PERIOD\t\t= 100 * USEC_PER_MSEC,\n-\n-\t/* don't let cmds which take a very long time pin lagging for too long */\n-\tMAX_LAGGING_PERIODS\t= 10,\n-\n-\t/*\n-\t * Count IO size in 4k pages.  The 12bit shift helps keeping\n-\t * size-proportional components of cost calculation in closer\n-\t * numbers of digits to per-IO cost components.\n-\t */\n-\tIOC_PAGE_SHIFT\t\t= 12,\n-\tIOC_PAGE_SIZE\t\t= 1 \u003c\u003c IOC_PAGE_SHIFT,\n-\tIOC_SECT_TO_PAGE_SHIFT\t= IOC_PAGE_SHIFT - SECTOR_SHIFT,\n-\n-\t/* if apart further than 16M, consider randio for linear model */\n-\tLCOEF_RANDIO_PAGES\t= 4096,\n-};\n-\n-enum ioc_running {\n-\tIOC_IDLE,\n-\tIOC_RUNNING,\n-\tIOC_STOP,\n-};\n-\n-/* io.cost.qos controls including per-dev enable of the whole controller */\n-enum {\n-\tQOS_ENABLE,\n-\tQOS_CTRL,\n-\tNR_QOS_CTRL_PARAMS,\n-};\n-\n-/* io.cost.qos params */\n-enum {\n-\tQOS_RPPM,\n-\tQOS_RLAT,\n-\tQOS_WPPM,\n-\tQOS_WLAT,\n-\tQOS_MIN,\n-\tQOS_MAX,\n-\tNR_QOS_PARAMS,\n-};\n-\n-/* io.cost.model controls */\n-enum {\n-\tCOST_CTRL,\n-\tCOST_MODEL,\n-\tNR_COST_CTRL_PARAMS,\n-};\n-\n-/* builtin linear cost model coefficients */\n-enum {\n-\tI_LCOEF_RBPS,\n-\tI_LCOEF_RSEQIOPS,\n-\tI_LCOEF_RRANDIOPS,\n-\tI_LCOEF_WBPS,\n-\tI_LCOEF_WSEQIOPS,\n-\tI_LCOEF_WRANDIOPS,\n-\tI_LCOEF_FLUSHIOPS,\n-\tNR_I_LCOEFS,\n-};\n-\n-enum {\n-\tLCOEF_RPAGE,\n-\tLCOEF_RSEQIO,\n-\tLCOEF_RRANDIO,\n-\tLCOEF_WPAGE,\n-\tLCOEF_WSEQIO,\n-\tLCOEF_WRANDIO,\n-\tLCOEF_FLUSH,\n-\tNR_LCOEFS,\n-};\n-\n-enum {\n-\tAUTOP_INVALID,\n-\tAUTOP_HDD,\n-\tAUTOP_SSD_QD1,\n-\tAUTOP_SSD_DFL,\n-\tAUTOP_SSD_FAST,\n-};\n-\n-struct ioc_params {\n-\tu32\t\t\t\tqos[NR_QOS_PARAMS];\n-\tu64\t\t\t\ti_lcoefs[NR_I_LCOEFS];\n-\tu64\t\t\t\tlcoefs[NR_LCOEFS];\n-\tu32\t\t\t\ttoo_fast_vrate_pct;\n-\tu32\t\t\t\ttoo_slow_vrate_pct;\n-};\n-\n-struct ioc_margins {\n-\ts64\t\t\t\tmin;\n-\ts64\t\t\t\tlow;\n-\ts64\t\t\t\ttarget;\n-};\n-\n-struct ioc_missed {\n-\tlocal_t\t\t\t\tnr_met;\n-\tlocal_t\t\t\t\tnr_missed;\n-\tu32\t\t\t\tlast_met;\n-\tu32\t\t\t\tlast_missed;\n-};\n-\n-struct ioc_pcpu_stat {\n-\tstruct ioc_missed\t\tmissed[2];\n-\n-\tlocal64_t\t\t\trq_wait_ns;\n-\tu64\t\t\t\tlast_rq_wait_ns;\n-};\n-\n-/* per device */\n-struct ioc {\n-\tstruct rq_qos\t\t\trqos;\n-\n-\tbool\t\t\t\tenabled;\n-\n-\tstruct ioc_params\t\tparams;\n-\tstruct ioc_margins\t\tmargins;\n-\tu32\t\t\t\tperiod_us;\n-\tu32\t\t\t\ttimer_slack_ns;\n-\tu64\t\t\t\tvrate_min;\n-\tu64\t\t\t\tvrate_max;\n-\n-\tspinlock_t\t\t\tlock;\n-\tstruct timer_list\t\ttimer;\n-\tstruct list_head\t\tactive_iocgs;\t/* active cgroups */\n-\tstruct ioc_pcpu_stat __percpu\t*pcpu_stat;\n-\n-\tenum ioc_running\t\trunning;\n-\tatomic64_t\t\t\tvtime_rate;\n-\tu64\t\t\t\tvtime_base_rate;\n-\ts64\t\t\t\tvtime_err;\n-\n-\tseqcount_spinlock_t\t\tperiod_seqcount;\n-\tu64\t\t\t\tperiod_at;\t/* wallclock starttime */\n-\tu64\t\t\t\tperiod_at_vtime; /* vtime starttime */\n-\n-\tatomic64_t\t\t\tcur_period;\t/* inc'd each period */\n-\tint\t\t\t\tbusy_level;\t/* saturation history */\n-\n-\tbool\t\t\t\tweights_updated;\n-\tatomic_t\t\t\thweight_gen;\t/* for lazy hweights */\n-\n-\t/* debt forgivness */\n-\tu64\t\t\t\tdfgv_period_at;\n-\tu64\t\t\t\tdfgv_period_rem;\n-\tu64\t\t\t\tdfgv_usage_us_sum;\n-\n-\tu64\t\t\t\tautop_too_fast_at;\n-\tu64\t\t\t\tautop_too_slow_at;\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-\n-struct iocg_pcpu_stat {\n-\tlocal64_t\t\t\tabs_vusage;\n-};\n-\n-struct iocg_stat {\n-\tu64\t\t\t\tusage_us;\n-\tu64\t\t\t\twait_us;\n-\tu64\t\t\t\tindebt_us;\n-\tu64\t\t\t\tindelay_us;\n-};\n-\n-/* per device-cgroup pair */\n-struct ioc_gq {\n-\tstruct blkg_policy_data\t\tpd;\n-\tstruct ioc\t\t\t*ioc;\n-\n-\t/*\n-\t * A iocg can get its weight from two sources - an explicit\n-\t * per-device-cgroup configuration or the default weight of the\n-\t * cgroup.  `cfg_weight` is the explicit per-device-cgroup\n-\t * configuration.  `weight` is the effective considering both\n-\t * sources.\n-\t *\n-\t * When an idle cgroup becomes active its `active` goes from 0 to\n-\t * `weight`.  `inuse` is the surplus adjusted active weight.\n-\t * `active` and `inuse` are used to calculate `hweight_active` and\n-\t * `hweight_inuse`.\n-\t *\n-\t * `last_inuse` remembers `inuse` while an iocg is idle to persist\n-\t * surplus adjustments.\n-\t *\n-\t * `inuse` may be adjusted dynamically during period. `saved_*` are used\n-\t * to determine and track adjustments.\n-\t */\n-\tu32\t\t\t\tcfg_weight;\n-\tu32\t\t\t\tweight;\n-\tu32\t\t\t\tactive;\n-\tu32\t\t\t\tinuse;\n-\n-\tu32\t\t\t\tlast_inuse;\n-\ts64\t\t\t\tsaved_margin;\n-\n-\tsector_t\t\t\tcursor;\t\t/* to detect randio */\n-\n-\t/*\n-\t * `vtime` is this iocg's vtime cursor which progresses as IOs are\n-\t * issued.  If lagging behind device vtime, the delta represents\n-\t * the currently available IO budget.  If running ahead, the\n-\t * overage.\n-\t *\n-\t * `vtime_done` is the same but progressed on completion rather\n-\t * than issue.  The delta behind `vtime` represents the cost of\n-\t * currently in-flight IOs.\n-\t */\n-\tatomic64_t\t\t\tvtime;\n-\tatomic64_t\t\t\tdone_vtime;\n-\tu64\t\t\t\tabs_vdebt;\n-\n-\t/* current delay in effect and when it started */\n-\tu64\t\t\t\tdelay;\n-\tu64\t\t\t\tdelay_at;\n-\n-\t/*\n-\t * The period this iocg was last active in.  Used for deactivation\n-\t * and invalidating `vtime`.\n-\t */\n-\tatomic64_t\t\t\tactive_period;\n-\tstruct list_head\t\tactive_list;\n-\n-\t/* see __propagate_weights() and current_hweight() for details */\n-\tu64\t\t\t\tchild_active_sum;\n-\tu64\t\t\t\tchild_inuse_sum;\n-\tu64\t\t\t\tchild_adjusted_sum;\n-\tint\t\t\t\thweight_gen;\n-\tu32\t\t\t\thweight_active;\n-\tu32\t\t\t\thweight_inuse;\n-\tu32\t\t\t\thweight_donating;\n-\tu32\t\t\t\thweight_after_donation;\n-\n-\tstruct list_head\t\twalk_list;\n-\tstruct list_head\t\tsurplus_list;\n-\n-\tstruct wait_queue_head\t\twaitq;\n-\tstruct hrtimer\t\t\twaitq_timer;\n-\n-\t/* timestamp at the latest activation */\n-\tu64\t\t\t\tactivated_at;\n-\n-\t/* statistics */\n-\tstruct iocg_pcpu_stat __percpu\t*pcpu_stat;\n-\tstruct iocg_stat\t\tstat;\n-\tstruct iocg_stat\t\tlast_stat;\n-\tu64\t\t\t\tlast_stat_abs_vusage;\n-\tu64\t\t\t\tusage_delta_us;\n-\tu64\t\t\t\twait_since;\n-\tu64\t\t\t\tindebt_since;\n-\tu64\t\t\t\tindelay_since;\n-\n-\t/* this iocg's depth in the hierarchy and ancestors including self */\n-\tint\t\t\t\tlevel;\n-\tstruct ioc_gq\t\t\t*ancestors[];\n-};\n-\n-/* per cgroup */\n-struct ioc_cgrp {\n-\tstruct blkcg_policy_data\tcpd;\n-\tunsigned int\t\t\tdfl_weight;\n-};\n-\n-struct ioc_now {\n-\tu64\t\t\t\tnow_ns;\n-\tu64\t\t\t\tnow;\n-\tu64\t\t\t\tvnow;\n-};\n-\n-struct iocg_wait {\n-\tstruct wait_queue_entry\t\twait;\n-\tstruct bio\t\t\t*bio;\n-\tu64\t\t\t\tabs_cost;\n-\tbool\t\t\t\tcommitted;\n-};\n-\n-struct iocg_wake_ctx {\n-\tstruct ioc_gq\t\t\t*iocg;\n-\tu32\t\t\t\thw_inuse;\n-\ts64\t\t\t\tvbudget;\n-};\n-\n static const struct ioc_params autop[] = {\n \t[AUTOP_HDD] = {\n \t\t.qos\t\t\t\t= {\n@@ -656,49 +289,6 @@ static const u32 vrate_adj_pct[] =\n \t  2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n \t  4, 4, 4, 4, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8, 16 };\n \n-static struct blkcg_policy blkcg_policy_iocost;\n-\n-/* accessors and helpers */\n-static struct ioc *rqos_to_ioc(struct rq_qos *rqos)\n-{\n-\treturn container_of(rqos, struct ioc, rqos);\n-}\n-\n-static struct ioc *q_to_ioc(struct request_queue *q)\n-{\n-\treturn rqos_to_ioc(rq_qos_id(q, RQ_QOS_COST));\n-}\n-\n-static const char __maybe_unused *ioc_name(struct ioc *ioc)\n-{\n-\tstruct gendisk *disk = ioc-\u003erqos.disk;\n-\n-\tif (!disk)\n-\t\treturn \"\u003cunknown\u003e\";\n-\treturn disk-\u003edisk_name;\n-}\n-\n-static struct ioc_gq *pd_to_iocg(struct blkg_policy_data *pd)\n-{\n-\treturn pd ? container_of(pd, struct ioc_gq, pd) : NULL;\n-}\n-\n-static struct ioc_gq *blkg_to_iocg(struct blkcg_gq *blkg)\n-{\n-\treturn pd_to_iocg(blkg_to_pd(blkg, \u0026blkcg_policy_iocost));\n-}\n-\n-static struct blkcg_gq *iocg_to_blkg(struct ioc_gq *iocg)\n-{\n-\treturn pd_to_blkg(\u0026iocg-\u003epd);\n-}\n-\n-static struct ioc_cgrp *blkcg_to_iocc(struct blkcg *blkcg)\n-{\n-\treturn container_of(blkcg_to_cpd(blkcg, \u0026blkcg_policy_iocost),\n-\t\t\t    struct ioc_cgrp, cpd);\n-}\n-\n /*\n  * Scale @abs_cost to the inverse of @hw_inuse.  The lower the hierarchical\n  * weight, the more expensive each IO.  Must round up.\n@@ -805,8 +395,14 @@ static int ioc_autop_idx(struct ioc *ioc, struct gendisk *disk)\n \tif (idx \u003c AUTOP_SSD_DFL)\n \t\treturn AUTOP_SSD_DFL;\n \n-\t/* if user is overriding anything, maintain what was there */\n-\tif (ioc-\u003euser_qos_params || ioc-\u003euser_cost_model)\n+\t/*\n+\t * If user is overriding anything, or a BPF model is in use, maintain\n+\t * what was there: with a BPF model the builtin cost coefficients are\n+\t * inert, and stepping the profile would change the builtin parameters\n+\t * that apply again after switching back, for no benefit in between.\n+\t */\n+\tif (ioc-\u003euser_qos_params || ioc-\u003euser_cost_model ||\n+\t    ioc_bpf_model_locked(ioc))\n \t\treturn idx;\n \n \t/* step up/down based on the vrate */\n@@ -2243,6 +1839,7 @@ 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 \tu64 usage_us_sum = 0;\n \tu32 ppm_rthr;\n \tu32 ppm_wthr;\n@@ -2279,6 +1876,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@@ -2440,6 +2039,16 @@ 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 * Everything the tick reports is final here: busy_level was just\n+\t * computed, cur_period hasn't changed, nr_active and usage_us_sum are\n+\t * complete, and vrate and period_us still hold the values this period\n+\t * ran in. usage is wall time over wall time, summed over iocgs, and is\n+\t * not capped at 100. Emit before the refresh below so the event reads\n+\t * the completed period directly.\n+\t */\n+\ttrace_iocost_ioc_tick(ioc, \u0026now, nr_active, usage_us_sum);\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@@ -2588,7 +2197,9 @@ static u64 calc_vtime_cost(struct bio *bio, struct ioc_gq *iocg, bool is_merge)\n {\n \tu64 cost;\n \n-\tcalc_vtime_cost_builtin(bio, iocg, is_merge, \u0026cost);\n+\tif (!ioc_model_calc_cost(iocg-\u003eioc, bio, is_merge, \u0026cost))\n+\t\tcalc_vtime_cost_builtin(bio, iocg, is_merge, \u0026cost);\n+\n \treturn cost;\n }\n \n@@ -2610,11 +2221,19 @@ static void calc_size_vtime_cost_builtin(struct request *rq, struct ioc *ioc,\n \t}\n }\n \n-static u64 calc_size_vtime_cost(struct request *rq, struct ioc *ioc)\n+/*\n+ * Called from the request completion path for READ and WRITE\n+ * requests, where no ioc-\u003elock is held; the model pointer is read\n+ * under RCU, matching the bio-side calc_vtime_cost().\n+ */\n+static u64 calc_size_vtime_cost(struct request *rq, struct ioc *ioc,\n+\t\t\t\tbool is_read)\n {\n \tu64 cost;\n \n-\tcalc_size_vtime_cost_builtin(rq, ioc, \u0026cost);\n+\tif (!ioc_model_size_cost(ioc, rq, is_read, \u0026cost))\n+\t\tcalc_size_vtime_cost_builtin(rq, ioc, \u0026cost);\n+\n \treturn cost;\n }\n \n@@ -2884,7 +2503,8 @@ static void ioc_rqos_done(struct rq_qos *rqos, struct request *rq)\n \n \ton_q_ns = blk_time_get_ns() - rq-\u003ealloc_time_ns;\n \trq_wait_ns = rq-\u003estart_time_ns - rq-\u003ealloc_time_ns;\n-\tsize_nsec = div64_u64(calc_size_vtime_cost(rq, ioc), VTIME_PER_NSEC);\n+\tsize_nsec = div64_u64(calc_size_vtime_cost(rq, ioc, pidx == QOS_RLAT),\n+\t\t\t       VTIME_PER_NSEC);\n \n \tccs = get_cpu_ptr(ioc-\u003epcpu_stat);\n \n@@ -2920,6 +2540,10 @@ static void ioc_rqos_exit(struct rq_qos *rqos)\n \n \ttimer_shutdown_sync(\u0026ioc-\u003etimer);\n \tfree_percpu(ioc-\u003epcpu_stat);\n+\n+\t/* eject the model on device removal */\n+\tioc_bpf_eject(ioc);\n+\n \tkfree(ioc);\n }\n \n@@ -2932,7 +2556,7 @@ static const struct rq_qos_ops ioc_rqos_ops = {\n \t.exit = ioc_rqos_exit,\n };\n \n-static int blk_iocost_init(struct gendisk *disk)\n+int blk_iocost_init(struct gendisk *disk)\n {\n \tstruct ioc *ioc;\n \tint i, cpu, ret;\n@@ -3070,6 +2694,35 @@ static void ioc_pd_init(struct blkg_policy_data *pd)\n \tspin_unlock_irqrestore(\u0026ioc-\u003elock, flags);\n }\n \n+/*\n+ * iocg_init() delivery for the attached model. blkg_create() calls this only\n+ * after the blkg has been inserted into the radix tree and the queue's blkg\n+ * list, so a blkg whose insertion failed is never seen here and the init/free\n+ * pairing cannot be broken by a model switch in between; the caller holds\n+ * queue_lock, the same lock the attachment updates are serialized with.\n+ */\n+static void ioc_pd_online(struct blkg_policy_data *pd)\n+{\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\tstruct ioc_gq *iocg = pd_to_iocg(pd);\n+\tstruct blkcg_gq *blkg = pd_to_blkg(pd);\n+\tstruct ioc *ioc = iocg-\u003eioc;\n+\tconst struct iocost_model_ops *model;\n+\tunsigned long flags;\n+\n+\tif (!ioc)\n+\t\treturn;\n+\n+\tspin_lock_irqsave(\u0026ioc-\u003elock, flags);\n+\tmodel = ioc_attached_model_locked(ioc);\n+\tif (model \u0026\u0026 model-\u003eiocg_init) {\n+\t\tmodel-\u003eiocg_init(blkg-\u003eblkcg, ioc-\u003erqos.disk-\u003equeue);\n+\t\tiocg-\u003ebpf_iocg_inited = true;\n+\t}\n+\tspin_unlock_irqrestore(\u0026ioc-\u003elock, flags);\n+#endif\n+}\n+\n static void iocg_release(struct rcu_head *rcu)\n {\n \tstruct blkg_policy_data *pd =\n@@ -3090,6 +2743,25 @@ static void ioc_pd_free(struct blkg_policy_data *pd)\n \tif (ioc) {\n \t\tspin_lock_irqsave(\u0026ioc-\u003elock, flags);\n \n+\t\t/*\n+\t\t * Gate the free on the delivered flag: a blkg which never went\n+\t\t * online never received iocg_init(), and bios still holding\n+\t\t * the blkg can be priced between its going offline and this\n+\t\t * free, so iocg_free() follows pd_free() rather than\n+\t\t * pd_offline.\n+\t\t */\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\t\tif (iocg-\u003ebpf_iocg_inited) {\n+\t\t\tconst struct iocost_model_ops *amodel =\n+\t\t\t\tioc_attached_model_locked(ioc);\n+\n+\t\t\tif (amodel \u0026\u0026 amodel-\u003eiocg_free)\n+\t\t\t\tamodel-\u003eiocg_free(blkg-\u003eblkcg,\n+\t\t\t\t\t\t  ioc-\u003erqos.disk-\u003equeue);\n+\t\t\tiocg-\u003ebpf_iocg_inited = false;\n+\t\t}\n+#endif\n+\n \t\tif (!list_empty(\u0026iocg-\u003eactive_list)) {\n \t\t\tstruct ioc_now now;\n \n@@ -3150,7 +2822,6 @@ static u64 ioc_weight_prfill(struct seq_file *sf, struct blkg_policy_data *pd,\n \treturn 0;\n }\n \n-\n static int ioc_weight_show(struct seq_file *sf, void *v)\n {\n \tstruct blkcg *blkcg = css_to_blkcg(seq_css(sf));\n@@ -3453,16 +3124,19 @@ static u64 ioc_cost_model_prfill(struct seq_file *sf,\n \tconst char *dname = blkg_dev_name(pd-\u003eblkg);\n \tstruct ioc *ioc = pd_to_iocg(pd)-\u003eioc;\n \tu64 *u = ioc-\u003eparams.i_lcoefs;\n+\tconst struct iocost_model_ops *model;\n \n \tif (!dname)\n \t\treturn 0;\n \n \tspin_lock_irq(\u0026ioc-\u003elock);\n-\tseq_printf(sf, \"%s ctrl=%s model=linear \"\n+\tmodel = ioc_bpf_model_locked(ioc);\n+\tseq_printf(sf, \"%s ctrl=%s model=%s \"\n \t\t   \"rbps=%llu rseqiops=%llu rrandiops=%llu \"\n \t\t   \"wbps=%llu wseqiops=%llu wrandiops=%llu \"\n \t\t   \"flushiops=%llu\\n\",\n \t\t   dname, ioc-\u003euser_cost_model ? \"user\" : \"auto\",\n+\t\t   model ? \"bpf\" : \"linear\",\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 \t\t   u[I_LCOEF_FLUSHIOPS]);\n@@ -3507,6 +3181,10 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,\n \tbool user;\n \tchar *body, *p;\n \tint ret;\n+\tconst struct iocost_model_ops *new_model = NULL;\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\tbool model_write = false;\n+#endif\n \n \tblkg_conf_init(\u0026ctx, input);\n \n@@ -3559,9 +3237,30 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,\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\tcontinue;\n+\t\t\tif (!strcmp(buf, \"linear\")) {\n+\t\t\t\t/*\n+\t\t\t\t * Staged and committed below, so a parse\n+\t\t\t\t * error later in the same write leaves the\n+\t\t\t\t * model selection untouched.\n+\t\t\t\t */\n+\t\t\t\tnew_model = NULL;\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\t\t\t\tmodel_write = true;\n+#endif\n+\t\t\t\tcontinue;\n+\t\t\t}\n+\t\t\tif (!strcmp(buf, \"bpf\")) {\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\t\t\t\tnew_model = rcu_dereference_protected(\n+\t\t\t\t\t\tioc-\u003eattached,\n+\t\t\t\t\t\tlockdep_is_held(\u0026ioc-\u003elock));\n+\t\t\t\tmodel_write = true;\n+#endif\n+\t\t\t\tif (!new_model)\n+\t\t\t\t\tgoto unlock;\n+\t\t\t\tcontinue;\n+\t\t\t}\n+\t\t\tgoto unlock;\n \t\t}\n \n \t\ttok = match_token(p, i_lcoef_tokens, args);\n@@ -3579,6 +3278,10 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,\n \t} else {\n \t\tioc-\u003euser_cost_model = false;\n \t}\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\tif (model_write)\n+\t\trcu_assign_pointer(ioc-\u003emodel, new_model);\n+#endif\n \tioc_refresh_params(ioc, true);\n \n \tret = 0;\n@@ -3616,12 +3319,13 @@ static struct cftype ioc_files[] = {\n \t{}\n };\n \n-static struct blkcg_policy blkcg_policy_iocost = {\n+struct blkcg_policy blkcg_policy_iocost = {\n \t.dfl_cftypes\t= ioc_files,\n \t.cpd_alloc_fn\t= ioc_cpd_alloc,\n \t.cpd_free_fn\t= ioc_cpd_free,\n \t.pd_alloc_fn\t= ioc_pd_alloc,\n \t.pd_init_fn\t= ioc_pd_init,\n+\t.pd_online_fn\t= ioc_pd_online,\n \t.pd_free_fn\t= ioc_pd_free,\n \t.pd_stat_fn\t= ioc_pd_stat,\n };\ndiff --git a/block/blk-iocost.h b/block/blk-iocost.h\nnew file mode 100644\nindex 00000000000000..6d62b4fd0c543d\n--- /dev/null\n+++ b/block/blk-iocost.h\n@@ -0,0 +1,615 @@\n+/* SPDX-License-Identifier: GPL-2.0 */\n+/*\n+ * blk-iocost private definitions, shared between blk-iocost.c and\n+ * blk-iocost-bpf.c. Not for direct inclusion by other files.\n+ */\n+#ifndef _BLK_IOCOST_H\n+#define _BLK_IOCOST_H\n+\n+#include \u003clinux/types.h\u003e\n+#include \u003clinux/blk_types.h\u003e\n+#include \u003clinux/blkdev.h\u003e\n+#include \"blk-cgroup.h\"\n+#include \u003clinux/blk-mq.h\u003e\n+#include \u003clinux/timer.h\u003e\n+#include \u003clinux/hrtimer.h\u003e\n+#include \u003clinux/seqlock.h\u003e\n+#include \u003clinux/atomic.h\u003e\n+#include \u003clinux/minmax.h\u003e\n+#include \u003clinux/time64.h\u003e\n+#include \u003clinux/wait.h\u003e\n+#include \u003casm/local.h\u003e\n+#include \u003casm/local64.h\u003e\n+#include \"blk-rq-qos.h\"\n+\n+struct bpf_link;\n+\n+/*\n+ * Pluggable cost model interface for blk-iocost.\n+ *\n+ * A BPF struct_ops implementation can take over the cost model of one device.\n+ * The device is identified by the dev member, which is set from userspace\n+ * before the program is loaded; the struct_ops core owns the program lifetime.\n+ * Attaching creates the ioc if needed, like an io.cost.model write, and\n+ * switches the device to the BPF model with the queue frozen before\n+ * rq_qos_mutex, like an io.cost.qos write, and delivers iocg_init() to the\n+ * cgroups which already exist on the device. Enabling and disabling the\n+ * controller stays with io.cost.qos.\n+ *\n+ * While a model is attached, io.cost.model selects between it and the builtin\n+ * model: \"model=bpf\" switches to the attached model and \"model=linear\" back to\n+ * the builtin. Neither detaches the struct_ops; only detaching does. The\n+ * builtin linear coefficients are kept while the BPF model is in use and take\n+ * effect again when switched back.\n+ *\n+ * While in use, the BPF model prices every charged IO on the device, including\n+ * flushes, from the bio charging path. calc_cost() is called from the IO\n+ * submission path with RCU read lock held and must not sleep. It receives the\n+ * bio itself so that the model can use what it needs (operation flags, size,\n+ * sector, the issuing cgroup through bio-\u003ebi_blkg, which is guaranteed\n+ * non-NULL) and returns the cost of the IO in vtime units, where 1 second\n+ * of device time equals VTIME_PER_SEC (2^37,\n+ * available to BPF programs through vmlinux.h). The return value is clamped to\n+ * 1 second of device time per IO.\n+ *\n+ * The struct_ops also carries the transfer cost coefficients, vtime per page\n+ * for reads and writes. While the BPF model is in use, they replace the\n+ * builtin coefficients in the completion-time request sizing of READ and\n+ * WRITE requests, with ZONE_APPEND counted as a write. Taking over the QoS\n+ * side (latency tracking, vrate control) is left for later extensions.\n+ *\n+ * The cgroup callbacks are bound to the iocg policy lifetime, one (cgroup,\n+ * device) pair per invocation. iocg_init() is delivered from ioc_pd_online()\n+ * and on attach to the cgroups already online on the device; iocg_free() on\n+ * detach to the cgroups which still exist then and at pd_free() time for the\n+ * rest, so that init and free pair up exactly. iocg_free() is gated on a\n+ * per-iocg delivered flag, as bios can still be priced between the blkg going\n+ * offline and its free. Both callbacks are called with ioc-\u003elock held and must\n+ * not sleep; the delivery points nest inside queue_lock except for iocg_free()\n+ * from ioc_pd_free() in blkg_free_workfn().\n+ */\n+\n+/*\n+ * Call metadata for calc_cost()'s model_flags; the merge indicator is not a\n+ * property of the bio. An enum so that the value is exported through BTF and\n+ * usable 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+\t/*\n+\t * target device (major:minor), set from userspace before load\n+\t * through the struct_ops map's initial value, in the userspace\n+\t * dev_t encoding new_decode_dev() accepts\n+\t */\n+\tdev_t dev;\n+\n+\t/* vtime per page for the completion-time request sizing */\n+\tu64 read_vtime_per_page;\n+\tu64 write_vtime_per_page;\n+\n+\tu64 (*calc_cost)(struct bio *bio, u64 model_flags);\n+\tvoid (*iocg_init)(struct blkcg *blkcg, struct request_queue *q);\n+\tvoid (*iocg_free)(struct blkcg *blkcg, struct request_queue *q);\n+};\n+\n+enum {\n+\tMILLION\t\t\t= 1000000,\n+\n+\t/* timer period is calculated from latency requirements, bound it */\n+\tMIN_PERIOD\t\t= USEC_PER_MSEC,\n+\tMAX_PERIOD\t\t= USEC_PER_SEC,\n+\n+\t/*\n+\t * iocg-\u003evtime is targeted at 50% behind the device vtime, which\n+\t * serves as its IO credit buffer.  Surplus weight adjustment is\n+\t * immediately canceled if the vtime margin runs below 10%.\n+\t */\n+\tMARGIN_MIN_PCT\t\t= 10,\n+\tMARGIN_LOW_PCT\t\t= 20,\n+\tMARGIN_TARGET_PCT\t= 50,\n+\n+\tINUSE_ADJ_STEP_PCT\t= 25,\n+\n+\t/* Have some play in timer operations */\n+\tTIMER_SLACK_PCT\t\t= 1,\n+\n+\t/* 1/64k is granular enough and can easily be handled w/ u32 */\n+\tWEIGHT_ONE\t\t= 1 \u003c\u003c 16,\n+};\n+\n+enum {\n+\t/*\n+\t * As vtime is used to calculate the cost of each IO, it needs to\n+\t * be fairly high precision.  For example, it should be able to\n+\t * represent the cost of a single page worth of discard with\n+\t * suffificient accuracy.  At the same time, it should be able to\n+\t * represent reasonably long enough durations to be useful and\n+\t * convenient during operation.\n+\t *\n+\t * 1s worth of vtime is 2^37.  This gives us both sub-nanosecond\n+\t * granularity and days of wrap-around time even at extreme vrates.\n+\t */\n+\tVTIME_PER_SEC_SHIFT\t= 37,\n+\tVTIME_PER_SEC\t\t= 1LLU \u003c\u003c VTIME_PER_SEC_SHIFT,\n+\tVTIME_PER_USEC\t\t= VTIME_PER_SEC / USEC_PER_SEC,\n+\tVTIME_PER_NSEC\t\t= VTIME_PER_SEC / NSEC_PER_SEC,\n+\n+\t/* bound vrate adjustments within two orders of magnitude */\n+\tVRATE_MIN_PPM\t\t= 10000,\t/* 1% */\n+\tVRATE_MAX_PPM\t\t= 100000000,\t/* 10000% */\n+\n+\tVRATE_MIN\t\t= VTIME_PER_USEC * VRATE_MIN_PPM / MILLION,\n+\tVRATE_CLAMP_ADJ_PCT\t= 4,\n+\n+\t/* switch iff the conditions are met for longer than this */\n+\tAUTOP_CYCLE_NSEC\t= 10LLU * NSEC_PER_SEC,\n+};\n+\n+enum {\n+\t/* if IOs end up waiting for requests, issue less */\n+\tRQ_WAIT_BUSY_PCT\t= 5,\n+\n+\t/* unbusy hysterisis */\n+\tUNBUSY_THR_PCT\t\t= 75,\n+\n+\t/*\n+\t * The effect of delay is indirect and non-linear and a huge amount of\n+\t * future debt can accumulate abruptly while unthrottled. Linearly scale\n+\t * up delay as debt is going up and then let it decay exponentially.\n+\t * This gives us quick ramp ups while delay is accumulating and long\n+\t * tails which can help reducing the frequency of debt explosions on\n+\t * unthrottle. The parameters are experimentally determined.\n+\t *\n+\t * The delay mechanism provides adequate protection and behavior in many\n+\t * cases. However, this is far from ideal and falls shorts on both\n+\t * fronts. The debtors are often throttled too harshly costing a\n+\t * significant level of fairness and possibly total work while the\n+\t * protection against their impacts on the system can be choppy and\n+\t * unreliable.\n+\t *\n+\t * The shortcoming primarily stems from the fact that, unlike for page\n+\t * cache, the kernel doesn't have well-defined back-pressure propagation\n+\t * mechanism and policies for anonymous memory. Fully addressing this\n+\t * issue will likely require substantial improvements in the area.\n+\t */\n+\tMIN_DELAY_THR_PCT\t= 500,\n+\tMAX_DELAY_THR_PCT\t= 25000,\n+\tMIN_DELAY\t\t= 250,\n+\tMAX_DELAY\t\t= 250 * USEC_PER_MSEC,\n+\n+\t/* halve debts if avg usage over 100ms is under 50% */\n+\tDFGV_USAGE_PCT\t\t= 50,\n+\tDFGV_PERIOD\t\t= 100 * USEC_PER_MSEC,\n+\n+\t/* don't let cmds which take a very long time pin lagging for too long */\n+\tMAX_LAGGING_PERIODS\t= 10,\n+\n+\t/*\n+\t * Count IO size in 4k pages.  The 12bit shift helps keeping\n+\t * size-proportional components of cost calculation in closer\n+\t * numbers of digits to per-IO cost components.\n+\t */\n+\tIOC_PAGE_SHIFT\t\t= 12,\n+\tIOC_PAGE_SIZE\t\t= 1 \u003c\u003c IOC_PAGE_SHIFT,\n+\tIOC_SECT_TO_PAGE_SHIFT\t= IOC_PAGE_SHIFT - SECTOR_SHIFT,\n+\n+\t/* if apart further than 16M, consider randio for linear model */\n+\tLCOEF_RANDIO_PAGES\t= 4096,\n+};\n+\n+enum ioc_running {\n+\tIOC_IDLE,\n+\tIOC_RUNNING,\n+\tIOC_STOP,\n+};\n+\n+/* io.cost.qos controls including per-dev enable of the whole controller */\n+enum {\n+\tQOS_ENABLE,\n+\tQOS_CTRL,\n+\tNR_QOS_CTRL_PARAMS,\n+};\n+\n+/* io.cost.qos params */\n+enum {\n+\tQOS_RPPM,\n+\tQOS_RLAT,\n+\tQOS_WPPM,\n+\tQOS_WLAT,\n+\tQOS_MIN,\n+\tQOS_MAX,\n+\tNR_QOS_PARAMS,\n+};\n+\n+/* io.cost.model controls */\n+enum {\n+\tCOST_CTRL,\n+\tCOST_MODEL,\n+\tNR_COST_CTRL_PARAMS,\n+};\n+\n+/* builtin linear cost model coefficients */\n+enum {\n+\tI_LCOEF_RBPS,\n+\tI_LCOEF_RSEQIOPS,\n+\tI_LCOEF_RRANDIOPS,\n+\tI_LCOEF_WBPS,\n+\tI_LCOEF_WSEQIOPS,\n+\tI_LCOEF_WRANDIOPS,\n+\tI_LCOEF_FLUSHIOPS,\n+\tNR_I_LCOEFS,\n+};\n+\n+enum {\n+\tLCOEF_RPAGE,\n+\tLCOEF_RSEQIO,\n+\tLCOEF_RRANDIO,\n+\tLCOEF_WPAGE,\n+\tLCOEF_WSEQIO,\n+\tLCOEF_WRANDIO,\n+\tLCOEF_FLUSH,\n+\tNR_LCOEFS,\n+};\n+\n+enum {\n+\tAUTOP_INVALID,\n+\tAUTOP_HDD,\n+\tAUTOP_SSD_QD1,\n+\tAUTOP_SSD_DFL,\n+\tAUTOP_SSD_FAST,\n+};\n+\n+struct ioc_params {\n+\tu32\t\t\t\tqos[NR_QOS_PARAMS];\n+\tu64\t\t\t\ti_lcoefs[NR_I_LCOEFS];\n+\tu64\t\t\t\tlcoefs[NR_LCOEFS];\n+\tu32\t\t\t\ttoo_fast_vrate_pct;\n+\tu32\t\t\t\ttoo_slow_vrate_pct;\n+};\n+\n+struct ioc_margins {\n+\ts64\t\t\t\tmin;\n+\ts64\t\t\t\tlow;\n+\ts64\t\t\t\ttarget;\n+};\n+\n+struct ioc_missed {\n+\tlocal_t\t\t\t\tnr_met;\n+\tlocal_t\t\t\t\tnr_missed;\n+\tu32\t\t\t\tlast_met;\n+\tu32\t\t\t\tlast_missed;\n+};\n+\n+struct ioc_pcpu_stat {\n+\tstruct ioc_missed\t\tmissed[2];\n+\n+\tlocal64_t\t\t\trq_wait_ns;\n+\tu64\t\t\t\tlast_rq_wait_ns;\n+};\n+\n+/* per device */\n+struct ioc {\n+\tstruct rq_qos\t\t\trqos;\n+\n+\tbool\t\t\t\tenabled;\n+\n+\tstruct ioc_params\t\tparams;\n+\tstruct ioc_margins\t\tmargins;\n+\tu32\t\t\t\tperiod_us;\n+\tu32\t\t\t\ttimer_slack_ns;\n+\tu64\t\t\t\tvrate_min;\n+\tu64\t\t\t\tvrate_max;\n+\n+\tspinlock_t\t\t\tlock;\n+\tstruct timer_list\t\ttimer;\n+\tstruct list_head\t\tactive_iocgs;\t/* active cgroups */\n+\tstruct ioc_pcpu_stat __percpu\t*pcpu_stat;\n+\n+\tenum ioc_running\t\trunning;\n+\tatomic64_t\t\t\tvtime_rate;\n+\tu64\t\t\t\tvtime_base_rate;\n+\ts64\t\t\t\tvtime_err;\n+\n+\tseqcount_spinlock_t\t\tperiod_seqcount;\n+\tu64\t\t\t\tperiod_at;\t/* wallclock starttime */\n+\tu64\t\t\t\tperiod_at_vtime; /* vtime starttime */\n+\n+\tatomic64_t\t\t\tcur_period;\t/* inc'd each period */\n+\tint\t\t\t\tbusy_level;\t/* saturation history */\n+\n+\tbool\t\t\t\tweights_updated;\n+\tatomic_t\t\t\thweight_gen;\t/* for lazy hweights */\n+\n+\t/* debt forgivness */\n+\tu64\t\t\t\tdfgv_period_at;\n+\tu64\t\t\t\tdfgv_period_rem;\n+\tu64\t\t\t\tdfgv_usage_us_sum;\n+\n+\tu64\t\t\t\tautop_too_fast_at;\n+\tu64\t\t\t\tautop_too_slow_at;\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+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\t/* the struct_ops attached to this device, NULL = none */\n+\tconst struct iocost_model_ops\t__rcu *attached;\n+\t/* the link which owns the attachment, written with ioc-\u003elock held */\n+\tstruct bpf_link\t\t\t*bpf_link;\n+\t/* the cost model in use, NULL = builtin linear model */\n+\tconst struct iocost_model_ops\t__rcu *model;\n+#endif\n+};\n+\n+struct iocg_pcpu_stat {\n+\tlocal64_t\t\t\tabs_vusage;\n+};\n+\n+struct iocg_stat {\n+\tu64\t\t\t\tusage_us;\n+\tu64\t\t\t\twait_us;\n+\tu64\t\t\t\tindebt_us;\n+\tu64\t\t\t\tindelay_us;\n+};\n+\n+/* per device-cgroup pair */\n+struct ioc_gq {\n+\tstruct blkg_policy_data\t\tpd;\n+\tstruct ioc\t\t\t*ioc;\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\t/* whether the attached model's iocg_init() was delivered */\n+\tbool\t\t\t\tbpf_iocg_inited;\n+#endif\n+\n+\t/*\n+\t * A iocg can get its weight from two sources - an explicit\n+\t * per-device-cgroup configuration or the default weight of the\n+\t * cgroup.  `cfg_weight` is the explicit per-device-cgroup\n+\t * configuration.  `weight` is the effective considering both\n+\t * sources.\n+\t *\n+\t * When an idle cgroup becomes active its `active` goes from 0 to\n+\t * `weight`.  `inuse` is the surplus adjusted active weight.\n+\t * `active` and `inuse` are used to calculate `hweight_active` and\n+\t * `hweight_inuse`.\n+\t *\n+\t * `last_inuse` remembers `inuse` while an iocg is idle to persist\n+\t * surplus adjustments.\n+\t *\n+\t * `inuse` may be adjusted dynamically during period. `saved_*` are used\n+\t * to determine and track adjustments.\n+\t */\n+\tu32\t\t\t\tcfg_weight;\n+\tu32\t\t\t\tweight;\n+\tu32\t\t\t\tactive;\n+\tu32\t\t\t\tinuse;\n+\n+\tu32\t\t\t\tlast_inuse;\n+\ts64\t\t\t\tsaved_margin;\n+\n+\tsector_t\t\t\tcursor;\t\t/* to detect randio */\n+\n+\t/*\n+\t * `vtime` is this iocg's vtime cursor which progresses as IOs are\n+\t * issued.  If lagging behind device vtime, the delta represents\n+\t * the currently available IO budget.  If running ahead, the\n+\t * overage.\n+\t *\n+\t * `vtime_done` is the same but progressed on completion rather\n+\t * than issue.  The delta behind `vtime` represents the cost of\n+\t * currently in-flight IOs.\n+\t */\n+\tatomic64_t\t\t\tvtime;\n+\tatomic64_t\t\t\tdone_vtime;\n+\tu64\t\t\t\tabs_vdebt;\n+\n+\t/* current delay in effect and when it started */\n+\tu64\t\t\t\tdelay;\n+\tu64\t\t\t\tdelay_at;\n+\n+\t/*\n+\t * The period this iocg was last active in.  Used for deactivation\n+\t * and invalidating `vtime`.\n+\t */\n+\tatomic64_t\t\t\tactive_period;\n+\tstruct list_head\t\tactive_list;\n+\n+\t/* see __propagate_weights() and current_hweight() for details */\n+\tu64\t\t\t\tchild_active_sum;\n+\tu64\t\t\t\tchild_inuse_sum;\n+\tu64\t\t\t\tchild_adjusted_sum;\n+\tint\t\t\t\thweight_gen;\n+\tu32\t\t\t\thweight_active;\n+\tu32\t\t\t\thweight_inuse;\n+\tu32\t\t\t\thweight_donating;\n+\tu32\t\t\t\thweight_after_donation;\n+\n+\tstruct list_head\t\twalk_list;\n+\tstruct list_head\t\tsurplus_list;\n+\n+\tstruct wait_queue_head\t\twaitq;\n+\tstruct hrtimer\t\t\twaitq_timer;\n+\n+\t/* timestamp at the latest activation */\n+\tu64\t\t\t\tactivated_at;\n+\n+\t/* statistics */\n+\tstruct iocg_pcpu_stat __percpu\t*pcpu_stat;\n+\tstruct iocg_stat\t\tstat;\n+\tstruct iocg_stat\t\tlast_stat;\n+\tu64\t\t\t\tlast_stat_abs_vusage;\n+\tu64\t\t\t\tusage_delta_us;\n+\tu64\t\t\t\twait_since;\n+\tu64\t\t\t\tindebt_since;\n+\tu64\t\t\t\tindelay_since;\n+\n+\t/* this iocg's depth in the hierarchy and ancestors including self */\n+\tint\t\t\t\tlevel;\n+\tstruct ioc_gq\t\t\t*ancestors[];\n+};\n+\n+/* per cgroup */\n+struct ioc_cgrp {\n+\tstruct blkcg_policy_data\tcpd;\n+\tunsigned int\t\t\tdfl_weight;\n+};\n+\n+struct ioc_now {\n+\tu64\t\t\t\tnow_ns;\n+\tu64\t\t\t\tnow;\n+\tu64\t\t\t\tvnow;\n+};\n+\n+struct iocg_wait {\n+\tstruct wait_queue_entry\t\twait;\n+\tstruct bio\t\t\t*bio;\n+\tu64\t\t\t\tabs_cost;\n+\tbool\t\t\t\tcommitted;\n+};\n+\n+struct iocg_wake_ctx {\n+\tstruct ioc_gq\t\t\t*iocg;\n+\tu32\t\t\t\thw_inuse;\n+\ts64\t\t\t\tvbudget;\n+};\n+\n+extern struct blkcg_policy blkcg_policy_iocost;\n+\n+static inline struct ioc *rqos_to_ioc(struct rq_qos *rqos)\n+{\n+\treturn container_of(rqos, struct ioc, rqos);\n+}\n+\n+static inline struct ioc *q_to_ioc(struct request_queue *q)\n+{\n+\treturn rqos_to_ioc(rq_qos_id(q, RQ_QOS_COST));\n+}\n+\n+static inline const char __maybe_unused *ioc_name(struct ioc *ioc)\n+{\n+\tstruct gendisk *disk = ioc-\u003erqos.disk;\n+\n+\tif (!disk)\n+\t\treturn \"\u003cunknown\u003e\";\n+\treturn disk-\u003edisk_name;\n+}\n+\n+static inline struct ioc_gq *pd_to_iocg(struct blkg_policy_data *pd)\n+{\n+\treturn pd ? container_of(pd, struct ioc_gq, pd) : NULL;\n+}\n+\n+static inline struct ioc_gq *blkg_to_iocg(struct blkcg_gq *blkg)\n+{\n+\treturn pd_to_iocg(blkg_to_pd(blkg, \u0026blkcg_policy_iocost));\n+}\n+\n+static inline struct blkcg_gq *iocg_to_blkg(struct ioc_gq *iocg)\n+{\n+\treturn pd_to_blkg(\u0026iocg-\u003epd);\n+}\n+\n+static inline struct ioc_cgrp *blkcg_to_iocc(struct blkcg *blkcg)\n+{\n+\treturn container_of(blkcg_to_cpd(blkcg, \u0026blkcg_policy_iocost),\n+\t\t\t    struct ioc_cgrp, cpd);\n+}\n+\n+/*\n+ * The attached struct_ops and the model in use. The writers hold\n+ * ioc-\u003elock, the hot path readers are inside rcu_read_lock() and the\n+ * map is not freed until after an RCU grace period, the slow readers\n+ * hold ioc-\u003elock.\n+ */\n+static inline const struct iocost_model_ops *\n+ioc_attached_model_locked(struct ioc *ioc)\n+{\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\treturn rcu_dereference_protected(ioc-\u003eattached,\n+\t\t\t\t\t lockdep_is_held(\u0026ioc-\u003elock));\n+#else\n+\treturn NULL;\n+#endif\n+}\n+\n+static inline const struct iocost_model_ops *\n+ioc_bpf_model_locked(struct ioc *ioc)\n+{\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\treturn rcu_dereference_protected(ioc-\u003emodel,\n+\t\t\t\t\t lockdep_is_held(\u0026ioc-\u003elock));\n+#else\n+\treturn NULL;\n+#endif\n+}\n+\n+/*\n+ * Price one charged IO with the model in use into *@cost and return\n+ * true, or return false when no model is in use and the builtin model\n+ * must price it. The model is read under rcu_read_lock(), which the\n+ * helper takes and releases itself, and the returned cost is clamped\n+ * to one second of device time. calc_cost() may be invoked for a\n+ * (cgroup, device) pair before iocg_init() has been delivered for\n+ * it; models relying on per-pair state must tolerate that window.\n+ */\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+static inline bool ioc_model_calc_cost(struct ioc *ioc, struct bio *bio,\n+\t\t\t\t       bool is_merge, u64 *cost)\n+{\n+\tconst struct iocost_model_ops *model;\n+\n+\trcu_read_lock();\n+\tmodel = rcu_dereference(ioc-\u003emodel);\n+\tif (model)\n+\t\t*cost = min(model-\u003ecalc_cost(bio, is_merge ?\n+\t\t\t    IOCOST_COST_F_MERGE : 0), VTIME_PER_SEC);\n+\trcu_read_unlock();\n+\treturn model;\n+}\n+#else\t/* CONFIG_BLK_CGROUP_IOCOST_BPF */\n+static inline bool ioc_model_calc_cost(struct ioc *ioc, struct bio *bio,\n+\t\t\t\t       bool is_merge, u64 *cost)\n+{\n+\treturn false;\n+}\n+#endif\t/* CONFIG_BLK_CGROUP_IOCOST_BPF */\n+\n+/*\n+ * The same for the completion-time request sizing: the transfer cost\n+ * is the model's vtime per page for the request direction, and the\n+ * returned cost is clamped to one second of device time.\n+ */\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+static inline bool ioc_model_size_cost(struct ioc *ioc, struct request *rq,\n+\t\t\t\t       bool is_read, u64 *cost)\n+{\n+\tconst struct iocost_model_ops *model;\n+\n+\trcu_read_lock();\n+\tmodel = rcu_dereference(ioc-\u003emodel);\n+\tif (model)\n+\t\t*cost = min((is_read ? model-\u003eread_vtime_per_page :\n+\t\t\t     model-\u003ewrite_vtime_per_page) *\n+\t\t\t    (blk_rq_stats_sectors(rq) \u003e\u003e IOC_SECT_TO_PAGE_SHIFT),\n+\t\t\t    VTIME_PER_SEC);\n+\trcu_read_unlock();\n+\treturn model;\n+}\n+#else\t/* CONFIG_BLK_CGROUP_IOCOST_BPF */\n+static inline bool ioc_model_size_cost(struct ioc *ioc, struct request *rq,\n+\t\t\t\t       bool is_read, u64 *cost)\n+{\n+\treturn false;\n+}\n+#endif\t/* CONFIG_BLK_CGROUP_IOCOST_BPF */\n+\n+int blk_iocost_init(struct gendisk *disk);\n+\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+void ioc_bpf_eject(struct ioc *ioc);\n+#else\t/* CONFIG_BLK_CGROUP_IOCOST_BPF */\n+static inline void ioc_bpf_eject(struct ioc *ioc) { }\n+#endif\t/* CONFIG_BLK_CGROUP_IOCOST_BPF */\n+#endif\t/* _BLK_IOCOST_H */\ndiff --git a/include/trace/events/iocost.h b/include/trace/events/iocost.h\nindex e772b1bc60d603..39229605f499d7 100644\n--- a/include/trace/events/iocost.h\n+++ b/include/trace/events/iocost.h\n@@ -178,6 +178,49 @@ TRACE_EVENT(iocost_ioc_vrate_adj,\n \t)\n );\n \n+/*\n+ * Periodic per-device summary, emitted once per period before the vrate\n+ * adjustment and the period transition in ioc_timer_fn(). Unlike the\n+ * state-change events above, this fires every period the controller is\n+ * running, including steady states, and carries the overall controller state\n+ * so basic monitoring doesn't require drgn.\n+ */\n+TRACE_EVENT(iocost_ioc_tick,\n+\n+\tTP_PROTO(struct ioc *ioc, const struct ioc_now *now,\n+\t\t int nr_active, u64 usage_us_sum),\n+\n+\tTP_ARGS(ioc, now, nr_active, usage_us_sum),\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),\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 = ioc-\u003eperiod_us;\n+\t\t__entry-\u003evrate = ioc-\u003evtime_base_rate;\n+\t\t__entry-\u003ebusy_level = ioc-\u003ebusy_level;\n+\t\t__entry-\u003enr_active = nr_active;\n+\t\t__entry-\u003eusage_pct = now-\u003enow \u003e ioc-\u003eperiod_at ?\n+\t\t\tdiv64_u64(usage_us_sum * 100,\n+\t\t\t\t  now-\u003enow - ioc-\u003eperiod_at) : 0;\n+\t),\n+\n+\tTP_printk(\"[%s] period=%llu:%uus vrate=%llu busy=%d active=%d usage=%u%%\",\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\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 49dfe939467cc8..78ed59f83a16ac 100644\n--- a/tools/testing/selftests/bpf/config\n+++ b/tools/testing/selftests/bpf/config\n@@ -141,3 +141,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_DEV_NULL_BLK=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 00000000000000..5373d52d93a66a\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/prog_tests/iocost_model.c\n@@ -0,0 +1,806 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/* Copyright (C) 2026 KylinSoft Corporation. */\n+#define _GNU_SOURCE\n+#include \u003ctest_progs.h\u003e\n+#include \u003cfcntl.h\u003e\n+#include \u003csched.h\u003e\n+#include \u003csys/statfs.h\u003e\n+#include \u003clinux/magic.h\u003e\n+#include \u003csys/mount.h\u003e\n+#include \u003csys/stat.h\u003e\n+#include \u003csys/sysmacros.h\u003e\n+#include \u003cunistd.h\u003e\n+#include \"iocost_model.skel.h\"\n+#include \"iocost_ms.skel.h\"\n+\n+/*\n+ * Write val to the configfs attribute at path, returning the errno of the\n+ * write negated (0 on success).\n+ */\n+static int configfs_write(const char *path, const char *val)\n+{\n+\tFILE *fp;\n+\tint err = 0;\n+\n+\tfp = fopen(path, \"w\");\n+\tif (!fp)\n+\t\treturn -errno;\n+\tif (fwrite(val, 1, strlen(val), fp) != strlen(val))\n+\t\terr = ferror(fp) ? -errno : -EIO;\n+\tif (fclose(fp) \u0026\u0026 !err)\n+\t\terr = -errno;\n+\treturn err;\n+}\n+\n+/*\n+ * Read the first token of the file at path, for the dev attribute.\n+ */\n+static int read_file_token(const char *path, char *tok, size_t tok_sz)\n+{\n+\tchar fmt[16];\n+\tFILE *fp;\n+\n+\tfp = fopen(path, \"r\");\n+\tif (!fp)\n+\t\treturn -errno;\n+\tsnprintf(fmt, sizeof(fmt), \"%%%zus\", tok_sz - 1);\n+\tif (fscanf(fp, fmt, tok) != 1) {\n+\t\tfclose(fp);\n+\t\treturn -EIO;\n+\t}\n+\tfclose(fp);\n+\treturn 0;\n+}\n+\n+/*\n+ * Create a null_blk instance through configfs and copy its maj:min\n+ * into @dev. The device appears only once power is written, and is\n+ * removed by rmdir of the instance directory; the maj:min comes from\n+ * the sysfs directory of the created disk, which is named after the\n+ * instance.\n+ */\n+static int nullb_create(const char *name, char *dev, size_t dev_sz)\n+{\n+\tchar path[128];\n+\tchar p2[128];\n+\tint err;\n+\n+\tsnprintf(path, sizeof(path), \"/sys/kernel/config/nullb/%s\", name);\n+\tif (mkdir(path, 0755)) {\n+\t\tif (errno != EEXIST)\n+\t\t\treturn -errno;\n+\t\t/*\n+\t\t * a leftover instance from an earlier crashed run may\n+\t\t * still be powered: tear it down before reusing the\n+\t\t * name\n+\t\t */\n+\t\tsnprintf(p2, sizeof(p2),\n+\t\t\t \"/sys/kernel/config/nullb/%s/power\", name);\n+\t\tconfigfs_write(p2, \"0\");\n+\t\tif (rmdir(path) \u0026\u0026 errno != ENOENT)\n+\t\t\treturn -errno;\n+\t\tif (mkdir(path, 0755) \u0026\u0026 errno != EEXIST)\n+\t\t\treturn -errno;\n+\t}\n+\n+\tsnprintf(path, sizeof(path), \"/sys/kernel/config/nullb/%s/size\", name);\n+\terr = configfs_write(path, \"128\");\n+\tif (err)\n+\t\treturn err;\n+\n+\tsnprintf(path, sizeof(path), \"/sys/kernel/config/nullb/%s/power\", name);\n+\terr = configfs_write(path, \"1\");\n+\tif (err)\n+\t\treturn err;\n+\n+\tsnprintf(path, sizeof(path), \"/sys/block/%s/dev\", name);\n+\terr = read_file_token(path, dev, dev_sz);\n+\tif (err) {\n+\t\t/* do not leave a powered instance behind */\n+\t\tsnprintf(path, sizeof(path),\n+\t\t\t \"/sys/kernel/config/nullb/%s/power\", name);\n+\t\tconfigfs_write(path, \"0\");\n+\t\tsnprintf(path, sizeof(path),\n+\t\t\t \"/sys/kernel/config/nullb/%s\", name);\n+\t\trmdir(path);\n+\t}\n+\treturn err;\n+}\n+\n+static int nullb_remove(const char *name)\n+{\n+\tchar path[128];\n+\n+\t/* a powered instance cannot be removed */\n+\tsnprintf(path, sizeof(path), \"/sys/kernel/config/nullb/%s/power\", name);\n+\tconfigfs_write(path, \"0\");\n+\tsnprintf(path, sizeof(path), \"/sys/kernel/config/nullb/%s\", name);\n+\tif (rmdir(path))\n+\t\treturn -errno;\n+\treturn 0;\n+}\n+\n+#define IOCOST_NULLB\t\"iocost_model_test\"\n+#define IOCOST_NULLB2\t\"iocost_model_test2\"\n+\n+/*\n+ * The tests run against their own null_blk instance created through configfs,\n+ * so they need root, configfs and the null_blk driver.\n+ */\n+/*\n+ * The BPF cost model needs cgroup v2 at /sys/fs/cgroup and\n+ * CONFIG_BLK_CGROUP_IOCOST_BPF in the running kernel; both are environment\n+ * properties, so their absence is a skip.\n+ */\n+static bool iocost_bpf_supported(void)\n+{\n+\tFILE *f;\n+\tchar line[128];\n+\tbool any = false, on = false;\n+\n+\tf = popen(\"zcat /proc/config.gz 2\u003e/dev/null\", \"r\");\n+\tif (!f)\n+\t\treturn false;\n+\twhile (fgets(line, sizeof(line), f)) {\n+\t\tif (strstr(line, \"CONFIG_\"))\n+\t\t\tany = true;\n+\t\tif (strstr(line, \"CONFIG_BLK_CGROUP_IOCOST_BPF=y\"))\n+\t\t\ton = true;\n+\t}\n+\tpclose(f);\n+\treturn on;\n+}\n+\n+static bool iocost_test_env(void)\n+{\n+\tstruct statfs sf;\n+\n+\tif (geteuid() != 0) {\n+\t\tprintf(\"%s:SKIP:needs root\\n\", __func__);\n+\t\ttest__skip();\n+\t\treturn false;\n+\t}\n+\n+\tif (statfs(\"/sys/fs/cgroup\", \u0026sf) ||\n+\t    sf.f_type != CGROUP2_SUPER_MAGIC) {\n+\t\tprintf(\"%s:SKIP:needs cgroup v2 at /sys/fs/cgroup\\n\",\n+\t\t       __func__);\n+\t\ttest__skip();\n+\t\treturn false;\n+\t}\n+\n+\tif (!iocost_bpf_supported()) {\n+\t\tprintf(\"%s:SKIP:needs CONFIG_BLK_CGROUP_IOCOST_BPF\\n\",\n+\t\t       __func__);\n+\t\ttest__skip();\n+\t\treturn false;\n+\t}\n+\n+\t/* isolate the configfs and cgroup mounts from the host */\n+\tif (unshare(CLONE_NEWNS)) {\n+\t\tprintf(\"%s:SKIP:unshare(CLONE_NEWNS) failed: %s\\n\",\n+\t\t       __func__, strerror(errno));\n+\t\ttest__skip();\n+\t\treturn false;\n+\t}\n+\tmkdir(\"/sys/kernel/config\", 0755);\n+\t(void)mount(\"none\", \"/sys/kernel/config\", \"configfs\", 0, NULL);\n+\tSYS_NOFAIL(\"modprobe null_blk nr_devices=0\");\n+\tif (access(\"/sys/kernel/config/nullb\", W_OK)) {\n+\t\tprintf(\"%s:SKIP:needs null_blk with configfs support\\n\",\n+\t\t       __func__);\n+\t\ttest__skip();\n+\t\treturn false;\n+\t}\n+\treturn true;\n+}\n+\n+/*\n+ * Read back the io.cost.model line of dev and copy the model= value into\n+ * @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 *end != ' ')\n+\t\tend++;\n+\tsnprintf(model, model_sz, \"%.*s\", (int)(end - m), m);\n+\treturn 0;\n+}\n+\n+/*\n+ * Read the cost.usage accumulator of dev from the cgroup's io.stat. Returns 0\n+ * on success, -ENODEV when the device has no line yet (no charge recorded).\n+ */\n+static int read_cost_usage(const char *cgroup, const char *dev,\n+\t\t\t   unsigned long long *usage)\n+{\n+\tchar line[512];\n+\tFILE *fp;\n+\tint found = 0;\n+\n+\tfp = fopen(cgroup, \"r\");\n+\tif (!fp)\n+\t\treturn -EIO;\n+\t*usage = 0;\n+\twhile (fgets(line, sizeof(line), fp)) {\n+\t\tchar *tok = strtok(line, \" \\n\");\n+\n+\t\tif (!tok || strcmp(tok, dev))\n+\t\t\tcontinue;\n+\t\tfound = 1;\n+\t\twhile ((tok = strtok(NULL, \" \\n\"))) {\n+\t\t\tif (!strncmp(tok, \"cost.usage=\", 11)) {\n+\t\t\t\t*usage = strtoull(tok + 11, NULL, 0);\n+\t\t\t\tfclose(fp);\n+\t\t\t\treturn 0;\n+\t\t\t}\n+\t\t}\n+\t}\n+\tfclose(fp);\n+\treturn found ? -ENOENT : -ENODEV;\n+}\n+\n+/* mkdir, recovering from a leftover of an aborted earlier run */\n+static int cgroup_mkdir(const char *path)\n+{\n+\tif (!mkdir(path, 0755))\n+\t\treturn 0;\n+\tif (errno == EEXIST \u0026\u0026 !rmdir(path))\n+\t\treturn mkdir(path, 0755) ? -errno : 0;\n+\treturn -errno;\n+}\n+\n+/*\n+ * Write a line to io.cost.model for dev and return the errno of the write\n+ * negated (0 on success), as ASSERT_ERR() expects.\n+ */\n+static int write_cost_model(const char *dev, const char *what)\n+{\n+\tchar buf[128];\n+\tFILE *fp;\n+\tint err = 0;\n+\n+\tsnprintf(buf, sizeof(buf), \"%s %s\", dev, what);\n+\tfp = fopen(\"/sys/fs/cgroup/io.cost.model\", \"w\");\n+\tif (!fp)\n+\t\treturn -EACCES;\n+\tif (fwrite(buf, 1, strlen(buf), fp) != strlen(buf))\n+\t\terr = ferror(fp) ? -errno : -EIO;\n+\tif (fclose(fp) \u0026\u0026 !err)\n+\t\terr = -errno;\n+\treturn err;\n+}\n+\n+/*\n+ * Attach the example model to the null_blk instance the test creates: the dev\n+ * member is written through the struct_ops map's initial value before load,\n+ * and attaching the struct_ops attaches the model to the device. Detaching the\n+ * struct_ops restores the builtin model.\n+ *\n+ * Requires root, cgroup v2 and null_blk with configfs support.\n+ */\n+void serial_test_iocost_model(void)\n+{\n+\tstruct iocost_model *skel, *second, *bad;\n+\tunsigned int maj, min;\n+\tchar pidbuf[16], buf[4096], path[64], qbuf[160], dev2[32];\n+\tint devfd, i, err, lfd;\n+\tchar model[32], dev[32];\n+\tunsigned long long u1, u2, inits1;\n+\n+\tif (!iocost_test_env())\n+\t\treturn;\n+\tif (!ASSERT_OK(nullb_create(IOCOST_NULLB, dev, sizeof(dev)),\n+\t\t       \"nullb_create\"))\n+\t\treturn;\n+\tif (sscanf(dev, \"%u:%u\", \u0026maj, \u0026min) != 2) {\n+\t\tASSERT_TRUE(false, \"dev_parse\");\n+\t\tnullb_remove(IOCOST_NULLB);\n+\t\treturn;\n+\t}\n+\n+\tskel = iocost_model__open();\n+\tif (!ASSERT_OK_PTR(skel, \"skel_open\")) {\n+\t\tnullb_remove(IOCOST_NULLB);\n+\t\treturn;\n+\t}\n+\n+\t/*\n+\t * a model with a zero coefficient must fail to attach instead of\n+\t * silently zeroing the completion sizing (validate rejects it on\n+\t * the map update the attach performs; the link form of the\n+\t * struct_ops only reaches it there)\n+\t */\n+\tbad = iocost_model__open();\n+\tif (!ASSERT_OK_PTR(bad, \"bad_open\")) {\n+\t\tiocost_model__destroy(skel);\n+\t\tnullb_remove(IOCOST_NULLB);\n+\t\treturn;\n+\t}\n+\tbad-\u003estruct_ops.iocost_2x-\u003edev = (__u32)makedev(maj, min);\n+\tbad-\u003estruct_ops.iocost_2x-\u003ewrite_vtime_per_page = 0;\n+\tif (ASSERT_OK(iocost_model__load(bad), \"bad_load\"))\n+\t\tASSERT_EQ(iocost_model__attach(bad), -EINVAL,\n+\t\t\t  \"attach_rejects_zero_coeff\");\n+\tiocost_model__destroy(bad);\n+\n+\t/* same for the read-side transfer coefficient */\n+\tbad = iocost_model__open();\n+\tif (!ASSERT_OK_PTR(bad, \"bad_read_open\")) {\n+\t\tiocost_model__destroy(skel);\n+\t\tnullb_remove(IOCOST_NULLB);\n+\t\treturn;\n+\t}\n+\tbad-\u003estruct_ops.iocost_2x-\u003edev = (__u32)makedev(maj, min);\n+\tbad-\u003estruct_ops.iocost_2x-\u003eread_vtime_per_page = 0;\n+\tif (ASSERT_OK(iocost_model__load(bad), \"bad_read_load\"))\n+\t\tASSERT_EQ(iocost_model__attach(bad), -EINVAL,\n+\t\t\t  \"attach_rejects_zero_read\");\n+\tiocost_model__destroy(bad);\n+\n+\tskel-\u003estruct_ops.iocost_2x-\u003edev = (__u32)makedev(maj, min);\n+\t/*\n+\t * create a cgroup for the pairing checks; its blkg comes to life\n+\t * when the controller is enabled and the cgroup configured below,\n+\t * exercising the iocg_init()/iocg_free() pairing end to end\n+\t */\n+\t/*\n+\t * Enable the io controller for the pairing cgroup: without it\n+\t * the cgroup has no io.weight/io.stat and the iocg never\n+\t * activates, so the model is consulted but nothing is charged.\n+\t */\n+\tASSERT_OK(configfs_write(\"/sys/fs/cgroup/cgroup.subtree_control\",\n+\t\t\t\t \"+io\"), \"subtree_io\");\n+\tif (!ASSERT_OK(cgroup_mkdir(\"/sys/fs/cgroup/iocost_pairing\"),\n+\t\t       \"mkdir_cg\")) {\n+\t\tiocost_model__destroy(skel);\n+\t\tnullb_remove(IOCOST_NULLB);\n+\t\treturn;\n+\t}\n+\tsnprintf(pidbuf, sizeof(pidbuf), \"%d\", getpid());\n+\tASSERT_OK(configfs_write(\"/sys/fs/cgroup/iocost_pairing/cgroup.procs\",\n+\t\t\t\t  pidbuf), \"cgroup_procs\");\n+\tsnprintf(path, sizeof(path), \"/dev/%s\", IOCOST_NULLB);\n+\tdevfd = open(path, O_RDONLY);\n+\tif (!ASSERT_OK(devfd \u003c 0 ? -errno : 0, \"open_dev\")) {\n+\t\tconfigfs_write(\"/sys/fs/cgroup/cgroup.procs\", pidbuf);\n+\t\trmdir(\"/sys/fs/cgroup/iocost_pairing\");\n+\t\tiocost_model__destroy(skel);\n+\t\tnullb_remove(IOCOST_NULLB);\n+\t\treturn;\n+\t}\n+\tfor (i = 0; i \u003c 32; i++)\n+\t\t(void)read(devfd, buf, sizeof(buf));\n+\tclose(devfd);\n+\tconfigfs_write(\"/sys/fs/cgroup/cgroup.procs\", pidbuf);\n+\n+\n+\terr = iocost_model__load(skel);\n+\tif (!ASSERT_OK(err, \"skel_load\")) {\n+\t\tiocost_model__destroy(skel);\n+\t\trmdir(\"/sys/fs/cgroup/iocost_pairing\");\n+\t\tnullb_remove(IOCOST_NULLB);\n+\t\treturn;\n+\t}\n+\n+\terr = iocost_model__attach(skel);\n+\tif (err == -EOPNOTSUPP || err == -ENODEV) {\n+\t\tprintf(\"%s:SKIP:device is not blk-mq, has no iocost or does not exist\\n\",\n+\t\t       __func__);\n+\t\tiocost_model__destroy(skel);\n+\t\trmdir(\"/sys/fs/cgroup/iocost_pairing\");\n+\t\tnullb_remove(IOCOST_NULLB);\n+\t\ttest__skip();\n+\t\treturn;\n+\t}\n+\tif (ASSERT_OK(err, \"attach\")) {\n+\t\t/*\n+\t\t * attached: the read path reports model=bpf until the\n+\t\t * struct_ops is detached; ctrl keeps describing the\n+\t\t * builtin coefficients\n+\t\t */\n+\t\terr = readback_model(dev, model, sizeof(model));\n+\t\tif (ASSERT_OK(err, \"readback\"))\n+\t\t\tASSERT_STREQ(model, \"bpf\", \"model_bpf\");\n+\n+\t\t/*\n+\t\t * the blkg created above was already on the blkg list\n+\t\t * (online) when the attach walk ran, so the walk\n+\t\t * delivered iocg_init() to it and to every other cgroup\n+\t\t * which has a blkg on this device (the count depends on\n+\t\t * the environment); none of them can have received\n+\t\t * iocg_free() yet\n+\t\t */\n+\t\tASSERT_GT(skel-\u003ebss-\u003eiocg_inits, 0, \"pair_init\");\n+\t\tASSERT_EQ(skel-\u003ebss-\u003eiocg_frees, 0, \"pair_no_free\");\n+\n+\t\t/* a second model on the same device fails with -EBUSY */\n+\t\tsecond = iocost_model__open();\n+\t\tif (ASSERT_OK_PTR(second, \"second_open\")) {\n+\t\t\tsecond-\u003estruct_ops.iocost_2x-\u003edev =\n+\t\t\t\t(__u32)makedev(maj, min);\n+\t\t\terr = iocost_model__load(second);\n+\t\t\tif (ASSERT_OK(err, \"second_load\")) {\n+\t\t\t\tstruct bpf_link *l2;\n+\n+\t\t\t\t/*\n+\t\t\t\t * the kernel rejects attaching a second\n+\t\t\t\t * model to the device with EBUSY\n+\t\t\t\t */\n+\t\t\t\tl2 = bpf_map__attach_struct_ops(\n+\t\t\t\t\t\tsecond-\u003emaps.iocost_2x);\n+\t\t\t\tif (!ASSERT_ERR_PTR(l2, \"second_ebusy\"))\n+\t\t\t\t\tbpf_link__destroy(l2);\n+\t\t\t\telse\n+\t\t\t\t\tASSERT_EQ(libbpf_get_error(l2), -EBUSY,\n+\t\t\t\t\t\t  \"second_ebusy_errno\");\n+\t\t\t}\n+\t\t\tiocost_model__destroy(second);\n+\t\t}\n+\n+\t\t/*\n+\t\t * pricing coverage: root cgroup IOs bypass the model, so\n+\t\t * move into the pairing cgroup, enable the controller\n+\t\t * and verify IOs actually go through calc_cost() and get\n+\t\t * charged\n+\t\t */\n+\t\tASSERT_OK(configfs_write(\n+\t\t\t\t\"/sys/fs/cgroup/iocost_pairing/cgroup.procs\",\n+\t\t\t\tpidbuf), \"procs_pairing_priced\");\n+\t\tsnprintf(qbuf, sizeof(qbuf), \"%s 1000\", dev);\n+\t\tASSERT_OK(configfs_write(\n+\t\t\t\t\"/sys/fs/cgroup/iocost_pairing/io.weight\",\n+\t\t\t\tqbuf), \"weight_pairing\");\n+\t\tsnprintf(qbuf, sizeof(qbuf),\n+\t\t\t \"%s enable=1 ctrl=user min=100.00 max=100.00\", dev);\n+\t\tASSERT_OK(configfs_write(\"/sys/fs/cgroup/io.cost.qos\", qbuf),\n+\t\t\t  \"qos_enable\");\n+\n+\t\tdevfd = open(path, O_RDONLY);\n+\t\tif (!ASSERT_OK(devfd \u003c 0 ? -errno : 0, \"open_dev_priced\")) {\n+\t\t\tiocost_model__destroy(skel);\n+\t\t\tconfigfs_write(\"/sys/fs/cgroup/cgroup.procs\", pidbuf);\n+\t\t\tsnprintf(qbuf, sizeof(qbuf), \"%s enable=0\", dev);\n+\t\t\t(void)configfs_write(\"/sys/fs/cgroup/io.cost.qos\", qbuf);\n+\t\t\tif (rmdir(\"/sys/fs/cgroup/iocost_pairing\") \u0026\u0026 errno != ENOENT)\n+\t\t\t\tprintf(\"%s: rmdir cgroup failed: %s\\n\", __func__,\n+\t\t\t\t       strerror(errno));\n+\t\t\tnullb_remove(IOCOST_NULLB);\n+\t\t\treturn;\n+\t\t}\n+\t\tASSERT_OK(read_cost_usage(\"/sys/fs/cgroup/iocost_pairing/io.stat\",\n+\t\t\t\t\t  dev, \u0026u1), \"cost_usage_pre\");\n+\t\tfor (i = 0; i \u003c 500; i++)\n+\t\t\t(void)read(devfd, buf, sizeof(buf));\n+\t\tclose(devfd);\n+\t\tASSERT_GT(skel-\u003ebss-\u003ecalc_costs, 0, \"model_priced\");\n+\t\t/*\n+\t\t * the usage stat is flushed by the iocost timer, give\n+\t\t * the current period a chance to end before reading\n+\t\t */\n+\t\tsleep(3);\n+\t\tASSERT_OK(read_cost_usage(\"/sys/fs/cgroup/iocost_pairing/io.stat\",\n+\t\t\t\t\t  dev, \u0026u2), \"cost_usage_post\");\n+\t\tASSERT_GT(u2, u1, \"cost_charged\");\n+\t\tASSERT_GT(skel-\u003ebss-\u003eioc_ticks, 0, \"tick_seen\");\n+\n+\t\t/*\n+\t\t * a cgroup created while the model is attached gets its\n+\t\t * iocg_init() when its first IO onlines the blkg\n+\t\t */\n+\t\tinits1 = skel-\u003ebss-\u003eiocg_inits;\n+\t\tASSERT_OK(cgroup_mkdir(\"/sys/fs/cgroup/iocost_late\"),\n+\t\t\t  \"mkdir_late\");\n+\t\tASSERT_OK(configfs_write(\n+\t\t\t\t\"/sys/fs/cgroup/iocost_late/cgroup.procs\",\n+\t\t\t\tpidbuf), \"procs_late\");\n+\t\tdevfd = open(path, O_RDONLY);\n+\t\tif (ASSERT_OK(devfd \u003c 0 ? -errno : 0, \"open_dev_late\")) {\n+\t\t\tfor (i = 0; i \u003c 32; i++)\n+\t\t\t\t(void)read(devfd, buf, sizeof(buf));\n+\t\t\tclose(devfd);\n+\t\t}\n+\t\tASSERT_GT(skel-\u003ebss-\u003eiocg_inits, inits1, \"late_init\");\n+\t\tASSERT_OK(configfs_write(\"/sys/fs/cgroup/cgroup.procs\",\n+\t\t\t\t\t pidbuf), \"procs_back\");\n+\t\trmdir(\"/sys/fs/cgroup/iocost_late\");\n+\n+\t\t/*\n+\t\t * a second device is independent: enabling it shows\n+\t\t * the builtin model, not the one attached to the\n+\t\t * first\n+\t\t */\n+\t\tif (ASSERT_OK(nullb_create(IOCOST_NULLB2, dev2,\n+\t\t\t\t\t   sizeof(dev2)), \"nullb_create2\")) {\n+\t\t\tsnprintf(qbuf, sizeof(qbuf),\n+\t\t\t\t \"%s enable=1 ctrl=auto\", dev2);\n+\t\t\tASSERT_OK(configfs_write(\n+\t\t\t\t\t\"/sys/fs/cgroup/io.cost.qos\", qbuf),\n+\t\t\t\t  \"qos_nullb2\");\n+\t\t\terr = readback_model(dev2, model, sizeof(model));\n+\t\t\tif (ASSERT_OK(err, \"readback_nullb2\"))\n+\t\t\t\tASSERT_STREQ(model, \"linear\",\n+\t\t\t\t\t     \"model_linear_nullb2\");\n+\t\t\tsnprintf(qbuf, sizeof(qbuf), \"%s enable=0\", dev2);\n+\t\t\tASSERT_OK(configfs_write(\n+\t\t\t\t\t\"/sys/fs/cgroup/io.cost.qos\", qbuf),\n+\t\t\t\t  \"qos_nullb2_off\");\n+\t\t}\n+\t\tnullb_remove(IOCOST_NULLB2);\n+\n+\t\t/*\n+\t\t * attachment and model selection are independent:\n+\t\t * ctrl=bpf is never accepted, model=linear switches\n+\t\t * back to the builtin without detaching, model=bpf\n+\t\t * switches to the attached model again\n+\t\t */\n+\t\terr = write_cost_model(dev, \"ctrl=bpf\");\n+\t\tASSERT_ERR(err, \"ctrl_bpf_rejected\");\n+\n+\t\terr = write_cost_model(dev, \"model=linear\");\n+\t\tASSERT_OK(err, \"model_linear_write\");\n+\t\terr = readback_model(dev, model, sizeof(model));\n+\t\tif (ASSERT_OK(err, \"readback_linear\"))\n+\t\t\tASSERT_STREQ(model, \"linear\", \"model_linear\");\n+\n+\t\t/* still attached: the switch must not free the slot */\n+\t\tsecond = iocost_model__open();\n+\t\tif (ASSERT_OK_PTR(second, \"second_open2\")) {\n+\t\t\tsecond-\u003estruct_ops.iocost_2x-\u003edev =\n+\t\t\t\t(__u32)makedev(maj, min);\n+\t\t\terr = iocost_model__load(second);\n+\t\t\tif (ASSERT_OK(err, \"second_load2\")) {\n+\t\t\t\tstruct bpf_link *l2;\n+\n+\t\t\t\tl2 = bpf_map__attach_struct_ops(\n+\t\t\t\t\t\tsecond-\u003emaps.iocost_2x);\n+\t\t\t\tif (!ASSERT_ERR_PTR(l2, \"second_ebusy2\"))\n+\t\t\t\t\tbpf_link__destroy(l2);\n+\t\t\t\telse\n+\t\t\t\t\tASSERT_EQ(libbpf_get_error(l2), -EBUSY,\n+\t\t\t\t\t\t  \"second_ebusy2_errno\");\n+\t\t\t}\n+\t\t\tiocost_model__destroy(second);\n+\t\t}\n+\n+\t\t/* still attached: switching back to the model works */\n+\t\terr = write_cost_model(dev, \"model=bpf\");\n+\t\tASSERT_OK(err, \"model_bpf_write\");\n+\t\terr = readback_model(dev, model, sizeof(model));\n+\t\tif (ASSERT_OK(err, \"readback_bpf\"))\n+\t\t\tASSERT_STREQ(model, \"bpf\", \"model_bpf\");\n+\n+\t\t/*\n+\t\t * detach implicitly by closing the link fd instead of\n+\t\t * calling bpf_link__destroy() explicitly: the release\n+\t\t * path must detach the model just like the explicit\n+\t\t * call does\n+\t\t */\n+\t\tlfd = bpf_link__fd(skel-\u003elinks.iocost_2x);\n+\t\tbpf_link__disconnect(skel-\u003elinks.iocost_2x);\n+\t\tclose(lfd);\n+\t\tskel-\u003elinks.iocost_2x = NULL;\n+\n+\t\t/* after detach, model=bpf fails: nothing is attached */\n+\t\terr = write_cost_model(dev, \"model=bpf\");\n+\t\tASSERT_ERR(err, \"model_bpf_after_detach\");\n+\n+\t\terr = readback_model(dev, model, sizeof(model));\n+\t\tif (ASSERT_OK(err, \"readback_after_detach\"))\n+\t\t\tASSERT_STREQ(model, \"linear\", \"model_linear\");\n+\n+\t\t/* the detach walk delivered the matching iocg_free()s */\n+\t\tASSERT_EQ(skel-\u003ebss-\u003eiocg_frees, skel-\u003ebss-\u003eiocg_inits,\n+\t\t\t  \"pair_free\");\n+\t}\n+\n+\tiocost_model__destroy(skel);\n+\t(void)configfs_write(\"/sys/fs/cgroup/cgroup.procs\", pidbuf);\n+\tsnprintf(qbuf, sizeof(qbuf), \"%s enable=0\", dev);\n+\t(void)configfs_write(\"/sys/fs/cgroup/io.cost.qos\", qbuf);\n+\tif (rmdir(\"/sys/fs/cgroup/iocost_pairing\") \u0026\u0026 errno != ENOENT)\n+\t\tprintf(\"%s: rmdir cgroup failed: %s\\n\", __func__,\n+\t\t       strerror(errno));\n+\tnullb_remove(IOCOST_NULLB);\n+}\n+/*\n+ * Same check for the multi-stream example model. Only one model can be\n+ * attached to a device at a time; each test creates its own device and\n+ * attaches and detaches, so they are serial.\n+ */\n+void serial_test_iocost_model_streams(void)\n+{\n+\tstruct iocost_ms *skel;\n+\tunsigned int maj, min;\n+\tint err;\n+\tchar model[32], dev[32];\n+\n+\tif (!iocost_test_env())\n+\t\treturn;\n+\tif (!ASSERT_OK(nullb_create(IOCOST_NULLB, dev, sizeof(dev)),\n+\t\t       \"nullb_create\"))\n+\t\treturn;\n+\tif (sscanf(dev, \"%u:%u\", \u0026maj, \u0026min) != 2) {\n+\t\tASSERT_TRUE(false, \"dev_parse\");\n+\t\tnullb_remove(IOCOST_NULLB);\n+\t\treturn;\n+\t}\n+\n+\tskel = iocost_ms__open();\n+\tif (!ASSERT_OK_PTR(skel, \"skel_open\")) {\n+\t\tnullb_remove(IOCOST_NULLB);\n+\t\treturn;\n+\t}\n+\n+\tskel-\u003estruct_ops.iocost_ms-\u003edev = (__u32)makedev(maj, min);\n+\n+\terr = iocost_ms__load(skel);\n+\tif (!ASSERT_OK(err, \"skel_load\")) {\n+\t\tiocost_ms__destroy(skel);\n+\t\tnullb_remove(IOCOST_NULLB);\n+\t\treturn;\n+\t}\n+\n+\terr = iocost_ms__attach(skel);\n+\tif (err == -EOPNOTSUPP || err == -ENODEV) {\n+\t\tprintf(\"%s:SKIP:device is not blk-mq, has no iocost or does not exist\\n\",\n+\t\t       __func__);\n+\t\tiocost_ms__destroy(skel);\n+\t\tnullb_remove(IOCOST_NULLB);\n+\t\ttest__skip();\n+\t\treturn;\n+\t}\n+\tif (ASSERT_OK(err, \"attach\")) {\n+\t\terr = readback_model(dev, model, sizeof(model));\n+\t\tif (ASSERT_OK(err, \"readback\"))\n+\t\t\tASSERT_STREQ(model, \"bpf\", \"model_bpf\");\n+\n+\t\tbpf_link__destroy(skel-\u003elinks.iocost_ms);\n+\t\tskel-\u003elinks.iocost_ms = NULL;\n+\n+\t\terr = readback_model(dev, model, sizeof(model));\n+\t\tif (ASSERT_OK(err, \"readback_after_detach\"))\n+\t\t\tASSERT_STREQ(model, \"linear\", \"model_linear\");\n+\t}\n+\n+\tiocost_ms__destroy(skel);\n+\tnullb_remove(IOCOST_NULLB);\n+}\n+\n+/*\n+ * Removal of the device while a model is attached: the test builds\n+ * its own null_blk instance through configfs like the other tests,\n+ * attaches to it, then removes the device out from under the model.\n+ * The ejection must drop the device from the cgroup interface,\n+ * down, and a recreated device must be attachable again.\n+ */\n+void serial_test_iocost_model_removal(void)\n+{\n+\tstruct iocost_model *skel, *skel2;\n+\tunsigned int maj, min;\n+\tchar dev[32], model[32];\n+\tint err;\n+\n+\tif (!iocost_test_env())\n+\t\treturn;\n+\n+\tskel = iocost_model__open();\n+\tif (!ASSERT_OK_PTR(skel, \"skel_open\"))\n+\t\treturn;\n+\n+\terr = nullb_create(\"iocost_removal\", dev, sizeof(dev));\n+\tif (!ASSERT_OK(err, \"nullb_create\"))\n+\t\tgoto out;\n+\tif (sscanf(dev, \"%u:%u\", \u0026maj, \u0026min) != 2) {\n+\t\tASSERT_TRUE(false, \"dev_parse\");\n+\t\tgoto out;\n+\t}\n+\n+\tskel-\u003estruct_ops.iocost_2x-\u003edev = (__u32)makedev(maj, min);\n+\terr = iocost_model__load(skel);\n+\tif (!ASSERT_OK(err, \"skel_load\"))\n+\t\tgoto out;\n+\n+\terr = iocost_model__attach(skel);\n+\tif (!ASSERT_OK(err, \"attach\"))\n+\t\tgoto out;\n+\n+\terr = readback_model(dev, model, sizeof(model));\n+\tif (ASSERT_OK(err, \"readback\"))\n+\t\tASSERT_STREQ(model, \"bpf\", \"model_bpf\");\n+\n+\t/* remove the device out from under the attached model */\n+\tif (!ASSERT_OK(nullb_remove(\"iocost_removal\"), \"nullb_remove\"))\n+\t\tgoto detach;\n+\n+\t/* the ejection drops the device from the cgroup files */\n+\terr = readback_model(dev, model, sizeof(model));\n+\tASSERT_ERR(err, \"readback_after_removal\");\n+\n+\terr = write_cost_model(dev, \"model=bpf\");\n+\tASSERT_ERR(err, \"model_bpf_after_removal\");\n+\n+\t/*\n+\t * the ejection path must deliver iocg_free() for every blkg\n+\t * which was online on the removed device: pd_free() runs from\n+\t * blkcg_deactivate_policy() before ioc_bpf_eject() drops the\n+\t * map reference\n+\t */\n+\tASSERT_GT(skel-\u003ebss-\u003eiocg_inits, 0, \"eject_had_inits\");\n+\tASSERT_EQ(skel-\u003ebss-\u003eiocg_frees, skel-\u003ebss-\u003eiocg_inits,\n+\t\t  \"eject_balanced\");\n+\n+detach:\n+\t/*\n+\t * detaching after the device is gone must be a clean no-op;\n+\t * this exercises the eject-then-detach ordering in the kernel\n+\t */\n+\tbpf_link__destroy(skel-\u003elinks.iocost_2x);\n+\tskel-\u003elinks.iocost_2x = NULL;\n+\n+\t/* the same attach and detach against a recreated device */\n+\tskel2 = iocost_model__open();\n+\tif (!ASSERT_OK_PTR(skel2, \"skel2_open\"))\n+\t\tgoto out;\n+\n+\terr = nullb_create(\"iocost_removal\", dev, sizeof(dev));\n+\tif (!ASSERT_OK(err, \"nullb_create_again\"))\n+\t\tgoto out2;\n+\tif (sscanf(dev, \"%u:%u\", \u0026maj, \u0026min) != 2) {\n+\t\tASSERT_TRUE(false, \"dev_parse_again\");\n+\t\tgoto out2;\n+\t}\n+\n+\tskel2-\u003estruct_ops.iocost_2x-\u003edev = (__u32)makedev(maj, min);\n+\terr = iocost_model__load(skel2);\n+\tif (!ASSERT_OK(err, \"skel2_load\"))\n+\t\tgoto out2;\n+\n+\terr = iocost_model__attach(skel2);\n+\tif (!ASSERT_OK(err, \"attach_again\"))\n+\t\tgoto out2;\n+\n+\terr = readback_model(dev, model, sizeof(model));\n+\tif (ASSERT_OK(err, \"readback_again\"))\n+\t\tASSERT_STREQ(model, \"bpf\", \"model_bpf_again\");\n+\tASSERT_GT(skel2-\u003ebss-\u003eiocg_inits, 0, \"pair_init_again\");\n+\n+\tbpf_link__destroy(skel2-\u003elinks.iocost_2x);\n+\tskel2-\u003elinks.iocost_2x = NULL;\n+\n+\terr = readback_model(dev, model, sizeof(model));\n+\tif (ASSERT_OK(err, \"readback_after_detach_again\"))\n+\t\tASSERT_STREQ(model, \"linear\", \"model_linear_again\");\n+\n+\t/* the re-attach walk delivered init for the recreated device */\n+\tASSERT_EQ(skel2-\u003ebss-\u003eiocg_frees, skel2-\u003ebss-\u003eiocg_inits,\n+\t\t  \"pair_balanced_again\");\n+\n+out2:\n+\tiocost_model__destroy(skel2);\n+out:\n+\tnullb_remove(\"iocost_removal\");\n+\tiocost_model__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 00000000000000..8875fb0f441749\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/progs/iocost_model.c\n@@ -0,0 +1,201 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/* Copyright (C) 2026 KylinSoft Corporation. */\n+/*\n+ * Example iocost cost model: the builtin linear HDD formula with all costs\n+ * doubled, for one device given by the dev member of the struct_ops.\n+ *\n+ * The constants mirror what calc_lcoefs() derives from the AUTOP_HDD defaults\n+ * (rbps=174019176 rseqiops=41708 rrandiops=370, w-side analog) in vtime units\n+ * where 1s == 2^37. On a rotational device still on ctrl=auto, a device with\n+ * this model attached charges twice the builtin model under the same\n+ * read/write workload (the builtin prices flushes as zero and adds a fixed\n+ * flush term to data-bearing preflushes, which this model omits; this model\n+ * prices flushes as one-page writes), so the doubled cost is a direct check\n+ * that accounting goes through the BPF path. On a non-rotational device, or\n+ * one with user-pinned coefficients, the ratio to the builtin model is\n+ * arbitrary.\n+ *\n+ * The cursor handling follows the builtin: a zero cursor means \"no previous\n+ * IO\", and the cursor is advanced for the bios the builtin prices\n+ * (READ/WRITE/ZONE_APPEND with a non-zero size), so flushes and discards leave\n+ * it alone and long merged streams do not drift past the 16MB seek threshold.\n+ * One known deviation, mispricing only: the builtin does not move its cursor\n+ * for an IO whose cgroup fails to activate; this model does not see the\n+ * activation result.\n+ *\n+ * The model implements the full linear formula itself, including flushes:\n+ * there is no fallback to the builtin model, which prices a dataless\n+ * WRITE|REQ_PREFLUSH as zero unless flushiops is configured; this model prices\n+ * it as a one-page sequential write. What a flush actually costs depends on\n+ * the IOs before it, which a static formula cannot express - pricing it as a\n+ * small constant is a crude penalty for unnecessarily frequent flushes, and a\n+ * stateful model would be the way to do better. Discards and other unpriced\n+ * operations pass through at zero cost, like the builtin.\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,\n+ * LCOEF_RANDIO_PAGES (the 16MB seek threshold) and IOCOST_COST_F_MERGE\n+ * come from vmlinux.h (BTF constants; the enum64 ones need pahole\n+ * \u003e= 1.23 to be emitted)\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+/*\n+ * per-cgroup cursor storage: keyed by the cgroup and freed with it,\n+ * so a cgroup that comes back starts with no cursor\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+/*\n+ * cgroup callback counters: the test reads them back to verify the\n+ * init/free pairing across attach, detach and device removal\n+ */\n+__u64 iocg_inits;\n+__u64 iocg_frees;\n+\n+/*\n+ * incremented by calc_cost(): the test asserts pricing went\n+ * through the model while it is attached and the controller is\n+ * enabled\n+ */\n+__u64 calc_costs;\n+\n+/* counts iocost_ioc_tick emissions observed from BPF side */\n+__u64 ioc_ticks;\n+\n+SEC(\"struct_ops\")\n+void BPF_PROG(iocost_2x_iocg_init, struct blkcg *blkcg,\n+\t      struct request_queue *q)\n+{\n+\tiocg_inits++;\n+}\n+\n+SEC(\"struct_ops\")\n+void BPF_PROG(iocost_2x_iocg_free, struct blkcg *blkcg,\n+\t      struct request_queue *q)\n+{\n+\tiocg_frees++;\n+}\n+\n+SEC(\"struct_ops\")\n+u64 BPF_PROG(iocost_2x_calc_cost, struct bio *bio, u64 model_flags)\n+{\n+\tu64 opf = bio-\u003ebi_opf, nbytes = bio-\u003ebi_iter.bi_size;\n+\tu64 sector = bio-\u003ebi_iter.bi_sector;\n+\tstruct blkcg *blkcg = bio-\u003ebi_blkg-\u003eblkcg;\n+\tu64 pages, seek_pages = 0, base, coef_page, randio, cost;\n+\t__u64 *cursor, cur;\n+\tint priced;\n+\n+\tcalc_costs++;\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\t   (opf \u0026 IOCOST_REQ_OP_MASK) == REQ_OP_ZONE_APPEND) {\n+\t\tbase = WSEQIO; coef_page = WPAGE; randio = WRANDIO;\n+\t} else {\n+\t\t/*\n+\t\t * the builtin prices other operations at zero and\n+\t\t * leaves them unthrottled; pass them through the same\n+\t\t * way instead of inventing costs\n+\t\t */\n+\t\treturn 0;\n+\t}\n+\n+\t/* mirror the builtin cursor semantics described above */\n+\tpriced = (opf \u0026 IOCOST_REQ_OP_MASK) == REQ_OP_READ ||\n+\t\t (opf \u0026 IOCOST_REQ_OP_MASK) == REQ_OP_WRITE ||\n+\t\t (opf \u0026 IOCOST_REQ_OP_MASK) == REQ_OP_ZONE_APPEND;\n+\tcursor = bpf_cgrp_storage_get(\u0026cursor_store,\n+\t\t\t\t      blkcg-\u003ecss.cgroup, NULL,\n+\t\t\t\t      BPF_LOCAL_STORAGE_GET_F_CREATE);\n+\tif (!cursor) {\n+\t\tif (model_flags \u0026 IOCOST_COST_F_MERGE)\n+\t\t\tbase = 0;\n+\t\treturn 2 * (base + pages * coef_page);\n+\t}\n+\tcur = *cursor;\n+\t/*\n+\t * a size-zero IO never moves the cursor, so it must not be\n+\t * judged against it either; the builtin skips it entirely,\n+\t * this model prices it as a one-page sequential write\n+\t */\n+\tif (cur \u0026\u0026 priced \u0026\u0026 nbytes) {\n+\t\tseek_pages = sector \u003e cur ? sector - cur\n+\t\t\t\t\t   : cur - sector;\n+\t\tseek_pages \u003e\u003e= IOC_SECT_TO_PAGE_SHIFT;\n+\t\tif (seek_pages \u003e LCOEF_RANDIO_PAGES)\n+\t\t\tbase = randio;\n+\t}\n+\t/*\n+\t * the builtin moves the cursor unconditionally on submit, but\n+\t * on a merge only for a back merge into the request ending at\n+\t * it; a merged bio starts right at the cursor exactly then,\n+\t * and a zero cursor means no history so it never matches\n+\t */\n+\tif (priced \u0026\u0026 nbytes \u0026\u0026\n+\t    (!(model_flags \u0026 IOCOST_COST_F_MERGE) || (cur \u0026\u0026 cur == sector)))\n+\t\t*cursor = sector + (nbytes \u003e\u003e 9);\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+/* consumes the new iocost_ioc_tick tracepoint from BPF side */\n+SEC(\"tp_btf/iocost_ioc_tick\")\n+__u64 BPF_PROG(iocost_2x_tick_count, struct ioc *ioc,\n+\t       const struct ioc_now *now, int nr_active, u64 usage_us_sum)\n+{\n+\tioc_ticks++;\n+\treturn 0;\n+}\n+\n+SEC(\".struct_ops.link\") /* detach on close */\n+struct iocost_model_ops iocost_2x = {\n+\t.read_vtime_per_page = 2 * RPAGE,\n+\t.write_vtime_per_page = 2 * WPAGE,\n+\t.calc_cost = (void *)iocost_2x_calc_cost,\n+\t.iocg_init = (void *)iocost_2x_iocg_init,\n+\t.iocg_free = (void *)iocost_2x_iocg_free,\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 00000000000000..87d4abcbf69340\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/progs/iocost_ms.c\n@@ -0,0 +1,175 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/* Copyright (C) 2026 KylinSoft Corporation. */\n+/*\n+ * Example multi-stream sequentiality detection cost model.\n+ *\n+ * The builtin model keeps a single cursor per cgroup, so two interleaved\n+ * sequential readers in one cgroup are all priced random (measured 89x\n+ * overcharge, 12.9x throughput collapse), while random IO inside a hot window\n+ * smaller than the 16MB seek threshold is priced sequential (measured 107x\n+ * undercharge). This model replaces the single cursor with a per-cgroup table\n+ * of stream slots: an IO is sequential iff its sector matches the expected\n+ * next sector of any tracked stream. Interleaved streams keep their own slots,\n+ * and windowed random IO rarely matches a moving expectation.\n+ *\n+ * Stream state lives in a CGRP_STORAGE map, so it is created and freed with\n+ * the cgroup. The model implements the builtin linear formula itself; unlike\n+ * the builtin it has no flush term, so preflushed IOs are priced as plain\n+ * writes (mispricing only, the test never issues flushes).\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, struct bio *bio, u64 model_flags)\n+{\n+\tu64 opf = bio-\u003ebi_opf, nbytes = bio-\u003ebi_iter.bi_size;\n+\tu64 sector = bio-\u003ebi_iter.bi_sector;\n+\tstruct blkcg *blkcg = bio-\u003ebi_blkg-\u003eblkcg;\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\t   (opf \u0026 IOCOST_REQ_OP_MASK) == REQ_OP_ZONE_APPEND) {\n+\t\tbase = WSEQIO; coef_page = WPAGE; randio = WRANDIO;\n+\t} else {\n+\t\t/*\n+\t\t * the builtin prices other operations at zero and\n+\t\t * leaves them unthrottled; pass them through the same\n+\t\t * way instead of inventing costs\n+\t\t */\n+\t\treturn 0;\n+\t}\n+\tadvance = nbytes \u003e\u003e 9;\t/* sectors, truncated like the builtin */\n+\n+\t/*\n+\t * only bios the builtin prices participate in stream tracking;\n+\t * the early return below skips the merge discount, which only\n+\t * applies to tracked data bios\n+\t */\n+\tif (!(((opf \u0026 IOCOST_REQ_OP_MASK) == REQ_OP_READ ||\n+\t       (opf \u0026 IOCOST_REQ_OP_MASK) == REQ_OP_WRITE ||\n+\t       (opf \u0026 IOCOST_REQ_OP_MASK) == REQ_OP_ZONE_APPEND) \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\t/*\n+\t\t * a merge which matches no slot is not a new stream:\n+\t\t * replacing a slot could evict a live stream, so merged\n+\t\t * bios are priced without touching the table (and skip\n+\t\t * the base cost below)\n+\t\t */\n+\t\tif (!(model_flags \u0026 IOCOST_COST_F_MERGE)) {\n+\t\t\tbase = randio;\n+\t\t\tfor (i = 1; i \u003c NSLOTS; i++) {\n+\t\t\t\tif (s-\u003estamp[i] \u003c s-\u003estamp[victim])\n+\t\t\t\t\tvictim = i;\n+\t\t\t}\n+\t\t\ts-\u003eexpected[victim] = sector + advance;\n+\t\t\ts-\u003estamp[victim] = now;\n+\t\t}\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.link\") /* detach on close */\n+struct iocost_model_ops iocost_ms = {\n+\t.read_vtime_per_page = RPAGE,\n+\t.write_vtime_per_page = WPAGE,\n+\t.calc_cost = (void *)iocost_ms_calc_cost,\n+};\n+\n+char LICENSE[] SEC(\"license\") = \"GPL\";\n"
}

2/1 2026/10/29 02:07 agent patch-evaluator
1m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "BLK_CGROUP_IOCOST",
    "BLK_CGROUP_IOCOST_BPF",
    "BPF_SYSCALL",
    "BPF_JIT",
    "DEBUG_INFO_BTF",
    "BLK_CGROUP"
  ],
  "FocusSymbols": [
    "ioc_bpf_attach",
    "ioc_bpf_detach",
    "ioc_bpf_eject",
    "ioc_bpf_deliver_iocg_callbacks",
    "bpf_iocost_reg",
    "bpf_iocost_unreg",
    "bpf_iocost_validate",
    "ioc_cost_model_write",
    "ioc_pd_online",
    "ioc_pd_free",
    "calc_vtime_cost",
    "calc_size_vtime_cost"
  ],
  "Reasoning": "The patch adds a new BPF struct_ops type (iocost_model_ops) allowing userspace BPF programs to dynamically implement pluggable cost models for the blk-iocost cgroup IO controller. The implementation introduces attach, detach, and eject lifecycles with intricate lock orchestration across rq_qos_mutex, blkcg_mutex, queue_lock, and ioc-\u003elock, plus lockdep assertions and RCU dereferencing during I/O submission/completion pricing paths. The code is reachable through standard syscalls (bpf syscall for struct_ops link registration, cgroupfs writes to io.cost.model, block I/O, and device removal), making it well-suited for syzkaller fuzzing to identify potential deadlocks, refcounting issues, or lifecycle races.",
  "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 4aad694db0f87849c37acd272fd8ad3abb1e16a7
Author: syz-cluster <triage@syzkaller.com>
Date:   Thu Oct 29 02:07:29 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 7e00a051382fb7..439b83dd3f6aa9 100644
--- a/Documentation/admin-guide/cgroup-v2.rst
+++ b/Documentation/admin-guide/cgroup-v2.rst
@@ -2056,8 +2056,9 @@ IO Interface Files
 	currently implements "io.weight" proportional control.  Lines
 	are keyed by $MAJ:$MIN device numbers and not ordered.  The
 	line for a given device is populated on the first write for
-	the device on "io.cost.qos" or "io.cost.model".  The following
-	nested keys are defined.
+	the device on "io.cost.qos" or "io.cost.model", or when a BPF
+	cost model is attached to it.  The following nested keys are
+	defined.
 
 	  ======	=====================================
 	  enable	Weight-based control enable
@@ -2111,13 +2112,41 @@ IO Interface Files
 	implements "io.weight" proportional control.  Lines are keyed
 	by $MAJ:$MIN device numbers and not ordered.  The line for a
 	given device is populated on the first write for the device on
-	"io.cost.qos" or "io.cost.model".  The following nested keys
-	are defined.
+	"io.cost.qos" or "io.cost.model", or when a BPF cost model is
+	attached to it.  The following nested keys are defined.
 
-	  =====		================================
+	  =====		==========================================
 	  ctrl		"auto" or "user"
-	  model		The cost model in use - "linear"
-	  =====		================================
+	  model		The cost model in use - "linear" or "bpf"
+	  =====		==========================================
+
+	When CONFIG_BLK_CGROUP_IOCOST_BPF is enabled, a BPF cost
+	model can be bound to a device by attaching an
+	"iocost_model_ops" struct_ops carrying the whole disk's
+	major:minor in its "dev" member (a partition's major:minor is
+	rejected).  Attaching creates the controller if needed, like
+	an io.cost.model write does, switches the device's pricing to
+	the model and populates the device's line in this file and in
+	"io.cost.qos" if it did not exist yet.  Attaching fails with
+	-EBUSY if the device already has a model attached.  The
+	attached model prices IOs only while the controller is
+	enabled through "io.cost.qos"; attaching does not enable it.
+
+	While a model is attached, "model" selects between it and the
+	builtin model: "model=bpf" switches to the attached model and
+	"model=linear" switches back to the builtin model, and neither
+	detaches the struct_ops.
+
+	Only detaching removes the model, after which "model=bpf"
+	fails and the device prices with the builtin model again.
+	Device removal ejects the attached model as well, while the
+	struct_ops link remains until userspace destroys it.  "ctrl"
+	accepts only "auto" and "user" and never selects a model.  It
+	keeps describing the builtin coefficients, which take effect
+	again when switched back.  The automatic profile stepping does
+	not switch profiles while the BPF model is in use; as with
+	user-set parameters, the profile selected from the device
+	class still applies.
 
 	When "ctrl" is "auto", the kernel may change all parameters
 	dynamically.  When "ctrl" is set to "user" or any other
@@ -2125,7 +2154,8 @@ IO Interface Files
 	automatic changes are disabled.
 
 	When "model" is "linear", the following model parameters are
-	defined.
+	defined.  They remain readable and writable while "model" is
+	"bpf" but take effect only after switching back to "linear".
 
 	  =============	========================================
 	  [r|w]bps	The maximum sequential IO throughput
diff --git a/MAINTAINERS b/MAINTAINERS
index 801f964899ba79..3abe3a089215a2 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -6785,10 +6785,13 @@ T:	git git://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux.git
 F:	Documentation/admin-guide/cgroup-v1/blkio-controller.rst
 F:	block/bfq-cgroup.c
 F:	block/blk-cgroup.c
+F:	block/blk-iocost-bpf.c
 F:	block/blk-iocost.c
+F:	block/blk-iocost.h
 F:	block/blk-iolatency.c
 F:	block/blk-throttle.c
 F:	include/linux/blk-cgroup.h
+F:	include/trace/events/iocost.h
 
 CONTROL GROUP - CPUSET
 M:	Waiman Long <longman@redhat.com>
diff --git a/block/Kconfig b/block/Kconfig
index 70e4a66d941ff6..8eaa2a803b6178 100644
--- a/block/Kconfig
+++ b/block/Kconfig
@@ -229,6 +229,10 @@ config BLK_ERROR_INJECTION
 
 	  See Documentation/block/error-injection.rst for details.
 
+config BLK_CGROUP_IOCOST_BPF
+	def_bool y
+	depends on BLK_CGROUP_IOCOST && BPF_SYSCALL && BPF_JIT && DEBUG_INFO_BTF
+
 source "block/Kconfig.iosched"
 
 endif # BLOCK
diff --git a/block/Makefile b/block/Makefile
index e7bd320e3d6971..ee5cebeea006fa 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-iocost-bpf.c b/block/blk-iocost-bpf.c
new file mode 100644
index 00000000000000..8ff51c26fb253d
--- /dev/null
+++ b/block/blk-iocost-bpf.c
@@ -0,0 +1,464 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * blk-iocost: BPF struct_ops plumbing for pluggable cost models.
+ *
+ * Copyright (C) 2026 KylinSoft Corporation.
+ *
+ * Registers the "iocost_model_ops" struct_ops type. Attachment is per-device:
+ * the target device is set in the ops from userspace before load, .reg
+ * attaches the model to that device, creating the ioc if needed and switching
+ * to the model with the queue frozen before rq_qos_mutex, like io.cost.qos
+ * writes, and .unreg detaches it; enabling and disabling the controller stays
+ * with io.cost.qos. The struct_ops core owns the program lifetime.
+ */
+#include <linux/init.h>
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/bpf.h>
+#include <linux/bpf_verifier.h>
+#include <linux/btf.h>
+#include "blk-iocost.h"
+#include <linux/blk-mq.h>
+#include <linux/mutex.h>
+#include "blk.h"
+
+/*
+/*
+ * Deliver iocg_init()/iocg_free() to the cgroups already online on the
+ * queue: init walks q->blkg_list in reverse so parents receive it first,
+ * like blkcg_activate_policy(); free walks it forward like the blkcg
+ * policy teardown. The queue is frozen and quiesced; queue_lock
+ * serializes against blkg creation and blkcg_mutex against the delayed
+ * list removal in blkg destruction; the callbacks are called with
+ * ioc->lock held, the same lock the attachment updates take.
+ */
+static void ioc_bpf_deliver_iocg_callbacks(struct ioc *ioc,
+					   const struct iocost_model_ops *ops,
+					   bool init)
+{
+	struct request_queue *q = ioc->rqos.disk->queue;
+	struct blkcg_gq *blkg;
+
+	lockdep_assert_held(&q->blkcg_mutex);
+	lockdep_assert_held(&q->queue_lock);
+	lockdep_assert_held(&ioc->lock);
+
+	if (init) {
+		/* parents first, like blkcg_activate_policy() */
+		list_for_each_entry_reverse(blkg, &q->blkg_list, q_node) {
+			struct ioc_gq *iocg = blkg_to_iocg(blkg);
+
+			/*
+			 * A blkg which never went online never reached the
+			 * radix tree, so it must not receive an init either;
+			 * the attach runs under the same queue_lock as
+			 * blkg_create(), so pd->online is stable here. Any
+			 * previous attachment had its delivered flags cleared
+			 * before it went away, so none can still be set here.
+			 */
+			if (!iocg || !iocg->pd.online)
+				continue;
+			if (ops->iocg_init) {
+				ops->iocg_init(blkg->blkcg, q);
+				iocg->bpf_iocg_inited = true;
+			}
+		}
+	} else {
+		list_for_each_entry(blkg, &q->blkg_list, q_node) {
+			struct ioc_gq *iocg = blkg_to_iocg(blkg);
+
+			if (!iocg || !iocg->bpf_iocg_inited)
+				continue;
+			if (ops->iocg_free)
+				ops->iocg_free(blkg->blkcg, q);
+			iocg->bpf_iocg_inited = false;
+		}
+	}
+}
+
+static int ioc_bpf_attach(struct iocost_model_ops *ops, struct bpf_link *link)
+{
+	struct block_device *bdev;
+	struct request_queue *q;
+	struct gendisk *disk;
+	struct ioc *ioc;
+	unsigned int memflags;
+	int ret;
+
+	bdev = blkdev_get_no_open(new_decode_dev(ops->dev), false);
+	if (!bdev)
+		return -ENODEV;
+	q = bdev->bd_queue;
+	disk = bdev->bd_disk;
+
+	if (bdev_is_partition(bdev)) {
+		blkdev_put_no_open(bdev);
+		return -EINVAL;
+	}
+	if (!queue_is_mq(q)) {
+		blkdev_put_no_open(bdev);
+		return -EOPNOTSUPP;
+	}
+
+	/*
+	 * The freeze is taken before rq_qos_mutex like ioc_qos_write() does;
+	 * holding the mutex from the disk_live() check through the model
+	 * switch keeps the ioc from being freed under us.
+	 */
+	memflags = blk_mq_freeze_queue(q);
+
+	mutex_lock(&q->rq_qos_mutex);
+
+	if (!disk_live(disk)) {
+		mutex_unlock(&q->rq_qos_mutex);
+		blk_mq_unfreeze_queue(q, memflags);
+		blkdev_put_no_open(bdev);
+		return -ENODEV;
+	}
+	ioc = q_to_ioc(q);
+	if (!ioc) {
+		ret = blk_iocost_init(disk);
+		if (ret) {
+			mutex_unlock(&q->rq_qos_mutex);
+			blk_mq_unfreeze_queue(q, memflags);
+			blkdev_put_no_open(bdev);
+			return ret;
+		}
+		ioc = q_to_ioc(q);
+	}
+
+	blk_mq_quiesce_queue(q);
+
+	/*
+	 * Scope the mutex so the tail bdev put runs with blkcg_mutex
+	 * already released: dropping the last device reference can
+	 * reach disk_release() -> blkcg_exit_disk() ->
+	 * blkg_destroy_all(), which takes q->blkcg_mutex.
+	 */
+	{
+		guard(mutex)(&q->blkcg_mutex);
+		scoped_guard(spinlock_irqsave, &q->queue_lock) {
+			spin_lock(&ioc->lock);
+			ret = ioc_attached_model_locked(ioc) ? -EBUSY : 0;
+			if (!ret) {
+				/*
+				 * Take the map reference before the attachment
+				 * is published: the readers find the ops
+				 * through it. get() cannot fail while .reg
+				 * runs, as the core holds a map reference
+				 * then, but check it anyway; on failure leave
+				 * with no attachment set.
+				 */
+				if (!bpf_struct_ops_get(ops)) {
+					ret = -ENODEV;
+				} else {
+					rcu_assign_pointer(ioc->attached, ops);
+					rcu_assign_pointer(ioc->model, ops);
+					ioc->bpf_link = link;
+
+					/* pair iocg_init() with the cgroups online */
+					ioc_bpf_deliver_iocg_callbacks(ioc, ops,
+								       true);
+				}
+			}
+			spin_unlock(&ioc->lock);
+		}
+	}
+
+	blk_mq_unquiesce_queue(q);
+	blk_mq_unfreeze_queue(q, memflags);
+	mutex_unlock(&q->rq_qos_mutex);
+	blkdev_put_no_open(bdev);
+	return ret;
+}
+
+/*
+ * Detach a model: switch back to the builtin model when the attached model is
+ * in use, clear the attachment and deliver iocg_free() to the cgroups which
+ * still exist, under the same freeze and quiesce as the attach.
+ */
+static void ioc_bpf_detach(struct iocost_model_ops *ops, struct bpf_link *link)
+{
+	struct block_device *bdev;
+	struct request_queue *q;
+	struct ioc *ioc;
+	bool matched;
+	unsigned int memflags;
+
+	/*
+	 * A failed lookup means the device is gone; the removal ejection will
+	 * detach the model and drop the map reference when rq_qos_exit() runs,
+	 * so there is nothing to do here.
+	 */
+	bdev = blkdev_get_no_open(new_decode_dev(ops->dev), false);
+	if (!bdev)
+		return;
+	q = bdev->bd_queue;
+
+	/*
+	 * The attachment is checked under rq_qos_mutex first, so an unmatched
+	 * detach exits without freezing.
+	 */
+	mutex_lock(&q->rq_qos_mutex);
+	spin_lock_irq(&q->queue_lock);
+	ioc = q_to_ioc(q);
+	if (ioc) {
+		spin_lock(&ioc->lock);
+		matched = ioc_attached_model_locked(ioc) == ops &&
+			  ioc->bpf_link == link;
+		spin_unlock(&ioc->lock);
+	} else {
+		matched = false;
+	}
+	spin_unlock_irq(&q->queue_lock);
+	mutex_unlock(&q->rq_qos_mutex);
+	if (!matched) {
+		blkdev_put_no_open(bdev);
+		return;
+	}
+
+	/* the freeze is taken before rq_qos_mutex like ioc_qos_write() */
+	memflags = blk_mq_freeze_queue(q);
+
+	mutex_lock(&q->rq_qos_mutex);
+
+	/*
+	 * Re-check under the mutex before quiescing: the freeze itself does
+	 * not touch the tag set, and the removal ejection holds rq_qos_mutex
+	 * before the driver frees the tag set, so the check passing here means
+	 * the tag set is still alive.
+	 */
+	spin_lock_irq(&q->queue_lock);
+	ioc = q_to_ioc(q);
+	if (ioc) {
+		spin_lock(&ioc->lock);
+		matched = ioc_attached_model_locked(ioc) == ops &&
+			  ioc->bpf_link == link;
+		spin_unlock(&ioc->lock);
+	} else {
+		matched = false;
+	}
+	spin_unlock_irq(&q->queue_lock);
+	if (!matched) {
+		mutex_unlock(&q->rq_qos_mutex);
+		blk_mq_unfreeze_queue(q, memflags);
+		blkdev_put_no_open(bdev);
+		return;
+	}
+
+	blk_mq_quiesce_queue(q);
+
+	/*
+	 * Scope the mutex so the tail bdev put runs with blkcg_mutex
+	 * already released: dropping the last device reference can
+	 * reach disk_release() -> blkcg_exit_disk() ->
+	 * blkg_destroy_all(), which takes q->blkcg_mutex.
+	 */
+	{
+		guard(mutex)(&q->blkcg_mutex);
+		scoped_guard(spinlock_irqsave, &q->queue_lock) {
+			spin_lock(&ioc->lock);
+			if (ioc_bpf_model_locked(ioc) == ops)
+				rcu_assign_pointer(ioc->model, NULL);
+			rcu_assign_pointer(ioc->attached, NULL);
+			ioc->bpf_link = NULL;
+
+			ioc_bpf_deliver_iocg_callbacks(ioc, ops, false);
+			spin_unlock(&ioc->lock);
+		}
+	}
+
+	blk_mq_unquiesce_queue(q);
+	blk_mq_unfreeze_queue(q, memflags);
+	mutex_unlock(&q->rq_qos_mutex);
+
+	blkdev_put_no_open(bdev);
+	bpf_struct_ops_put(ops);
+}
+
+/*
+ * Eject the model on device removal. The caller holds rq_qos_mutex and
+ * blkcg_deactivate_policy() has already run, so every existing blkg got
+ * iocg_free() from ioc_pd_free() and no walk is needed. The ioc is freed right
+ * after, so clearing the pointers and dropping the map reference is all that
+ * is left to do.
+ */
+void ioc_bpf_eject(struct ioc *ioc)
+{
+	const struct iocost_model_ops *ops;
+	unsigned long flags;
+
+	spin_lock_irqsave(&ioc->lock, flags);
+	ops = ioc_attached_model_locked(ioc);
+	if (ops) {
+		rcu_assign_pointer(ioc->attached, NULL);
+		if (ioc_bpf_model_locked(ioc) == ops)
+			rcu_assign_pointer(ioc->model, NULL);
+		ioc->bpf_link = NULL;
+	}
+	spin_unlock_irqrestore(&ioc->lock, flags);
+
+	if (ops)
+		bpf_struct_ops_put(ops);
+}
+
+/* nothing to look up: the core finds the struct by name before calling */
+static int bpf_iocost_model_init(struct btf *btf)
+{
+	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)
+{
+	/* every callback runs under RCU read lock or a spinlock */
+	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) {
+	/*
+	 * The struct_ops core rejects a nonzero userspace value for
+	 * non-function members this callback does not claim.
+	 */
+	case offsetof(struct iocost_model_ops, dev):
+		ops->dev = uops->dev;
+		return 1;
+	case offsetof(struct iocost_model_ops, read_vtime_per_page):
+		ops->read_vtime_per_page = uops->read_vtime_per_page;
+		return 1;
+	case offsetof(struct iocost_model_ops, write_vtime_per_page):
+		ops->write_vtime_per_page = uops->write_vtime_per_page;
+		return 1;
+	}
+
+	return 0;
+}
+
+/*
+ * A complete model prices every charged IO and carries both transfer
+ * coefficients; a missing calc_cost would be a NULL call from the
+ * submission path and missing coefficients would silently zero the
+ * completion-time sizing (see ioc_rqos_done()), so the model is
+ * rejected before it can be registered. iocg_init() and iocg_free()
+ * must come in pairs too: a model implementing only one of them would
+ * build per-cgroup state that nothing ever tears down.
+ */
+static bool iocost_model_complete(const struct iocost_model_ops *ops)
+{
+	return ops->calc_cost && ops->read_vtime_per_page &&
+	       ops->write_vtime_per_page &&
+	       !!ops->iocg_init == !!ops->iocg_free;
+}
+
+/*
+ * 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, and missing coefficients read as zero. This is
+ * reached from the map-update path of both map flavors, before the model can
+ * be registered.
+ */
+static int bpf_iocost_validate(void *kdata)
+{
+	struct iocost_model_ops *ops = kdata;
+
+	/*
+	 * Bound the transfer coefficients so that coefficient * pages cannot
+	 * wrap u64 for any possible request size.
+	 */
+	if (ops->read_vtime_per_page > (VTIME_PER_SEC >> IOC_SECT_TO_PAGE_SHIFT) ||
+	    ops->write_vtime_per_page > (VTIME_PER_SEC >> IOC_SECT_TO_PAGE_SHIFT))
+		return -EINVAL;
+
+	return iocost_model_complete(ops) ? 0 : -EINVAL;
+}
+
+static int bpf_iocost_reg(void *kdata, struct bpf_link *link)
+{
+	struct iocost_model_ops *ops = kdata;
+
+	/* validate() has run by now; only the device is left to check */
+	if (!ops->dev)
+		return -EINVAL;
+
+	return ioc_bpf_attach(ops, link);
+}
+
+static void bpf_iocost_unreg(void *kdata, struct bpf_link *link)
+{
+	struct iocost_model_ops *ops = kdata;
+
+	/* a gone device is handled inside ioc_bpf_detach() */
+	ioc_bpf_detach(ops, link);
+}
+
+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(struct bio *bio, u64 flags)
+{
+	return 0;
+}
+
+static void bpf_iocost_iocg_init_stub(struct blkcg *blkcg,
+				      struct request_queue *q)
+{ }
+static void bpf_iocost_iocg_free_stub(struct blkcg *blkcg,
+				      struct request_queue *q)
+{ }
+
+static struct iocost_model_ops __bpf_ops_iocost_model_ops = {
+	.calc_cost = bpf_iocost_calc_cost_stub,
+	.iocg_init = bpf_iocost_iocg_init_stub,
+	.iocg_free = bpf_iocost_iocg_free_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 a81488c755cabf..9f7f5e5f0ebb7d 100644
--- a/block/blk-iocost.c
+++ b/block/blk-iocost.c
@@ -184,6 +184,7 @@
 #include "blk-stat.h"
 #include "blk-wbt.h"
 #include "blk-cgroup.h"
+#include "blk-iocost.h"
 
 #ifdef CONFIG_TRACEPOINTS
 
@@ -209,374 +210,6 @@ static char trace_iocg_path[TRACE_IOCG_PATH_LEN];
 #define TRACE_IOCG_PATH(type, iocg, ...)	do { } while (0)
 #endif	/* CONFIG_TRACE_POINTS */
 
-enum {
-	MILLION			= 1000000,
-
-	/* timer period is calculated from latency requirements, bound it */
-	MIN_PERIOD		= USEC_PER_MSEC,
-	MAX_PERIOD		= USEC_PER_SEC,
-
-	/*
-	 * iocg->vtime is targeted at 50% behind the device vtime, which
-	 * serves as its IO credit buffer.  Surplus weight adjustment is
-	 * immediately canceled if the vtime margin runs below 10%.
-	 */
-	MARGIN_MIN_PCT		= 10,
-	MARGIN_LOW_PCT		= 20,
-	MARGIN_TARGET_PCT	= 50,
-
-	INUSE_ADJ_STEP_PCT	= 25,
-
-	/* Have some play in timer operations */
-	TIMER_SLACK_PCT		= 1,
-
-	/* 1/64k is granular enough and can easily be handled w/ u32 */
-	WEIGHT_ONE		= 1 << 16,
-};
-
-enum {
-	/*
-	 * As vtime is used to calculate the cost of each IO, it needs to
-	 * be fairly high precision.  For example, it should be able to
-	 * represent the cost of a single page worth of discard with
-	 * suffificient accuracy.  At the same time, it should be able to
-	 * represent reasonably long enough durations to be useful and
-	 * convenient during operation.
-	 *
-	 * 1s worth of vtime is 2^37.  This gives us both sub-nanosecond
-	 * granularity and days of wrap-around time even at extreme vrates.
-	 */
-	VTIME_PER_SEC_SHIFT	= 37,
-	VTIME_PER_SEC		= 1LLU << VTIME_PER_SEC_SHIFT,
-	VTIME_PER_USEC		= VTIME_PER_SEC / USEC_PER_SEC,
-	VTIME_PER_NSEC		= VTIME_PER_SEC / NSEC_PER_SEC,
-
-	/* bound vrate adjustments within two orders of magnitude */
-	VRATE_MIN_PPM		= 10000,	/* 1% */
-	VRATE_MAX_PPM		= 100000000,	/* 10000% */
-
-	VRATE_MIN		= VTIME_PER_USEC * VRATE_MIN_PPM / MILLION,
-	VRATE_CLAMP_ADJ_PCT	= 4,
-
-	/* switch iff the conditions are met for longer than this */
-	AUTOP_CYCLE_NSEC	= 10LLU * NSEC_PER_SEC,
-};
-
-enum {
-	/* if IOs end up waiting for requests, issue less */
-	RQ_WAIT_BUSY_PCT	= 5,
-
-	/* unbusy hysterisis */
-	UNBUSY_THR_PCT		= 75,
-
-	/*
-	 * The effect of delay is indirect and non-linear and a huge amount of
-	 * future debt can accumulate abruptly while unthrottled. Linearly scale
-	 * up delay as debt is going up and then let it decay exponentially.
-	 * This gives us quick ramp ups while delay is accumulating and long
-	 * tails which can help reducing the frequency of debt explosions on
-	 * unthrottle. The parameters are experimentally determined.
-	 *
-	 * The delay mechanism provides adequate protection and behavior in many
-	 * cases. However, this is far from ideal and falls shorts on both
-	 * fronts. The debtors are often throttled too harshly costing a
-	 * significant level of fairness and possibly total work while the
-	 * protection against their impacts on the system can be choppy and
-	 * unreliable.
-	 *
-	 * The shortcoming primarily stems from the fact that, unlike for page
-	 * cache, the kernel doesn't have well-defined back-pressure propagation
-	 * mechanism and policies for anonymous memory. Fully addressing this
-	 * issue will likely require substantial improvements in the area.
-	 */
-	MIN_DELAY_THR_PCT	= 500,
-	MAX_DELAY_THR_PCT	= 25000,
-	MIN_DELAY		= 250,
-	MAX_DELAY		= 250 * USEC_PER_MSEC,
-
-	/* halve debts if avg usage over 100ms is under 50% */
-	DFGV_USAGE_PCT		= 50,
-	DFGV_PERIOD		= 100 * USEC_PER_MSEC,
-
-	/* don't let cmds which take a very long time pin lagging for too long */
-	MAX_LAGGING_PERIODS	= 10,
-
-	/*
-	 * Count IO size in 4k pages.  The 12bit shift helps keeping
-	 * size-proportional components of cost calculation in closer
-	 * numbers of digits to per-IO cost components.
-	 */
-	IOC_PAGE_SHIFT		= 12,
-	IOC_PAGE_SIZE		= 1 << IOC_PAGE_SHIFT,
-	IOC_SECT_TO_PAGE_SHIFT	= IOC_PAGE_SHIFT - SECTOR_SHIFT,
-
-	/* if apart further than 16M, consider randio for linear model */
-	LCOEF_RANDIO_PAGES	= 4096,
-};
-
-enum ioc_running {
-	IOC_IDLE,
-	IOC_RUNNING,
-	IOC_STOP,
-};
-
-/* io.cost.qos controls including per-dev enable of the whole controller */
-enum {
-	QOS_ENABLE,
-	QOS_CTRL,
-	NR_QOS_CTRL_PARAMS,
-};
-
-/* io.cost.qos params */
-enum {
-	QOS_RPPM,
-	QOS_RLAT,
-	QOS_WPPM,
-	QOS_WLAT,
-	QOS_MIN,
-	QOS_MAX,
-	NR_QOS_PARAMS,
-};
-
-/* io.cost.model controls */
-enum {
-	COST_CTRL,
-	COST_MODEL,
-	NR_COST_CTRL_PARAMS,
-};
-
-/* builtin linear cost model coefficients */
-enum {
-	I_LCOEF_RBPS,
-	I_LCOEF_RSEQIOPS,
-	I_LCOEF_RRANDIOPS,
-	I_LCOEF_WBPS,
-	I_LCOEF_WSEQIOPS,
-	I_LCOEF_WRANDIOPS,
-	I_LCOEF_FLUSHIOPS,
-	NR_I_LCOEFS,
-};
-
-enum {
-	LCOEF_RPAGE,
-	LCOEF_RSEQIO,
-	LCOEF_RRANDIO,
-	LCOEF_WPAGE,
-	LCOEF_WSEQIO,
-	LCOEF_WRANDIO,
-	LCOEF_FLUSH,
-	NR_LCOEFS,
-};
-
-enum {
-	AUTOP_INVALID,
-	AUTOP_HDD,
-	AUTOP_SSD_QD1,
-	AUTOP_SSD_DFL,
-	AUTOP_SSD_FAST,
-};
-
-struct ioc_params {
-	u32				qos[NR_QOS_PARAMS];
-	u64				i_lcoefs[NR_I_LCOEFS];
-	u64				lcoefs[NR_LCOEFS];
-	u32				too_fast_vrate_pct;
-	u32				too_slow_vrate_pct;
-};
-
-struct ioc_margins {
-	s64				min;
-	s64				low;
-	s64				target;
-};
-
-struct ioc_missed {
-	local_t				nr_met;
-	local_t				nr_missed;
-	u32				last_met;
-	u32				last_missed;
-};
-
-struct ioc_pcpu_stat {
-	struct ioc_missed		missed[2];
-
-	local64_t			rq_wait_ns;
-	u64				last_rq_wait_ns;
-};
-
-/* per device */
-struct ioc {
-	struct rq_qos			rqos;
-
-	bool				enabled;
-
-	struct ioc_params		params;
-	struct ioc_margins		margins;
-	u32				period_us;
-	u32				timer_slack_ns;
-	u64				vrate_min;
-	u64				vrate_max;
-
-	spinlock_t			lock;
-	struct timer_list		timer;
-	struct list_head		active_iocgs;	/* active cgroups */
-	struct ioc_pcpu_stat __percpu	*pcpu_stat;
-
-	enum ioc_running		running;
-	atomic64_t			vtime_rate;
-	u64				vtime_base_rate;
-	s64				vtime_err;
-
-	seqcount_spinlock_t		period_seqcount;
-	u64				period_at;	/* wallclock starttime */
-	u64				period_at_vtime; /* vtime starttime */
-
-	atomic64_t			cur_period;	/* inc'd each period */
-	int				busy_level;	/* saturation history */
-
-	bool				weights_updated;
-	atomic_t			hweight_gen;	/* for lazy hweights */
-
-	/* debt forgivness */
-	u64				dfgv_period_at;
-	u64				dfgv_period_rem;
-	u64				dfgv_usage_us_sum;
-
-	u64				autop_too_fast_at;
-	u64				autop_too_slow_at;
-	int				autop_idx;
-	bool				user_qos_params:1;
-	bool				user_cost_model:1;
-};
-
-struct iocg_pcpu_stat {
-	local64_t			abs_vusage;
-};
-
-struct iocg_stat {
-	u64				usage_us;
-	u64				wait_us;
-	u64				indebt_us;
-	u64				indelay_us;
-};
-
-/* per device-cgroup pair */
-struct ioc_gq {
-	struct blkg_policy_data		pd;
-	struct ioc			*ioc;
-
-	/*
-	 * A iocg can get its weight from two sources - an explicit
-	 * per-device-cgroup configuration or the default weight of the
-	 * cgroup.  `cfg_weight` is the explicit per-device-cgroup
-	 * configuration.  `weight` is the effective considering both
-	 * sources.
-	 *
-	 * When an idle cgroup becomes active its `active` goes from 0 to
-	 * `weight`.  `inuse` is the surplus adjusted active weight.
-	 * `active` and `inuse` are used to calculate `hweight_active` and
-	 * `hweight_inuse`.
-	 *
-	 * `last_inuse` remembers `inuse` while an iocg is idle to persist
-	 * surplus adjustments.
-	 *
-	 * `inuse` may be adjusted dynamically during period. `saved_*` are used
-	 * to determine and track adjustments.
-	 */
-	u32				cfg_weight;
-	u32				weight;
-	u32				active;
-	u32				inuse;
-
-	u32				last_inuse;
-	s64				saved_margin;
-
-	sector_t			cursor;		/* to detect randio */
-
-	/*
-	 * `vtime` is this iocg's vtime cursor which progresses as IOs are
-	 * issued.  If lagging behind device vtime, the delta represents
-	 * the currently available IO budget.  If running ahead, the
-	 * overage.
-	 *
-	 * `vtime_done` is the same but progressed on completion rather
-	 * than issue.  The delta behind `vtime` represents the cost of
-	 * currently in-flight IOs.
-	 */
-	atomic64_t			vtime;
-	atomic64_t			done_vtime;
-	u64				abs_vdebt;
-
-	/* current delay in effect and when it started */
-	u64				delay;
-	u64				delay_at;
-
-	/*
-	 * The period this iocg was last active in.  Used for deactivation
-	 * and invalidating `vtime`.
-	 */
-	atomic64_t			active_period;
-	struct list_head		active_list;
-
-	/* see __propagate_weights() and current_hweight() for details */
-	u64				child_active_sum;
-	u64				child_inuse_sum;
-	u64				child_adjusted_sum;
-	int				hweight_gen;
-	u32				hweight_active;
-	u32				hweight_inuse;
-	u32				hweight_donating;
-	u32				hweight_after_donation;
-
-	struct list_head		walk_list;
-	struct list_head		surplus_list;
-
-	struct wait_queue_head		waitq;
-	struct hrtimer			waitq_timer;
-
-	/* timestamp at the latest activation */
-	u64				activated_at;
-
-	/* statistics */
-	struct iocg_pcpu_stat __percpu	*pcpu_stat;
-	struct iocg_stat		stat;
-	struct iocg_stat		last_stat;
-	u64				last_stat_abs_vusage;
-	u64				usage_delta_us;
-	u64				wait_since;
-	u64				indebt_since;
-	u64				indelay_since;
-
-	/* this iocg's depth in the hierarchy and ancestors including self */
-	int				level;
-	struct ioc_gq			*ancestors[];
-};
-
-/* per cgroup */
-struct ioc_cgrp {
-	struct blkcg_policy_data	cpd;
-	unsigned int			dfl_weight;
-};
-
-struct ioc_now {
-	u64				now_ns;
-	u64				now;
-	u64				vnow;
-};
-
-struct iocg_wait {
-	struct wait_queue_entry		wait;
-	struct bio			*bio;
-	u64				abs_cost;
-	bool				committed;
-};
-
-struct iocg_wake_ctx {
-	struct ioc_gq			*iocg;
-	u32				hw_inuse;
-	s64				vbudget;
-};
-
 static const struct ioc_params autop[] = {
 	[AUTOP_HDD] = {
 		.qos				= {
@@ -656,49 +289,6 @@ static const u32 vrate_adj_pct[] =
 	  2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
 	  4, 4, 4, 4, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8, 16 };
 
-static struct blkcg_policy blkcg_policy_iocost;
-
-/* accessors and helpers */
-static struct ioc *rqos_to_ioc(struct rq_qos *rqos)
-{
-	return container_of(rqos, struct ioc, rqos);
-}
-
-static struct ioc *q_to_ioc(struct request_queue *q)
-{
-	return rqos_to_ioc(rq_qos_id(q, RQ_QOS_COST));
-}
-
-static const char __maybe_unused *ioc_name(struct ioc *ioc)
-{
-	struct gendisk *disk = ioc->rqos.disk;
-
-	if (!disk)
-		return "<unknown>";
-	return disk->disk_name;
-}
-
-static struct ioc_gq *pd_to_iocg(struct blkg_policy_data *pd)
-{
-	return pd ? container_of(pd, struct ioc_gq, pd) : NULL;
-}
-
-static struct ioc_gq *blkg_to_iocg(struct blkcg_gq *blkg)
-{
-	return pd_to_iocg(blkg_to_pd(blkg, &blkcg_policy_iocost));
-}
-
-static struct blkcg_gq *iocg_to_blkg(struct ioc_gq *iocg)
-{
-	return pd_to_blkg(&iocg->pd);
-}
-
-static struct ioc_cgrp *blkcg_to_iocc(struct blkcg *blkcg)
-{
-	return container_of(blkcg_to_cpd(blkcg, &blkcg_policy_iocost),
-			    struct ioc_cgrp, cpd);
-}
-
 /*
  * Scale @abs_cost to the inverse of @hw_inuse.  The lower the hierarchical
  * weight, the more expensive each IO.  Must round up.
@@ -805,8 +395,14 @@ static int ioc_autop_idx(struct ioc *ioc, struct gendisk *disk)
 	if (idx < AUTOP_SSD_DFL)
 		return AUTOP_SSD_DFL;
 
-	/* if user is overriding anything, maintain what was there */
-	if (ioc->user_qos_params || ioc->user_cost_model)
+	/*
+	 * If user is overriding anything, or a BPF model is in use, maintain
+	 * what was there: with a BPF model the builtin cost coefficients are
+	 * inert, and stepping the profile would change the builtin parameters
+	 * that apply again after switching back, for no benefit in between.
+	 */
+	if (ioc->user_qos_params || ioc->user_cost_model ||
+	    ioc_bpf_model_locked(ioc))
 		return idx;
 
 	/* step up/down based on the vrate */
@@ -2243,6 +1839,7 @@ static void ioc_timer_fn(struct timer_list *timer)
 	struct ioc_now now;
 	LIST_HEAD(surpluses);
 	int nr_debtors, nr_shortages = 0, nr_lagging = 0;
+	int nr_active = 0;
 	u64 usage_us_sum = 0;
 	u32 ppm_rthr;
 	u32 ppm_wthr;
@@ -2279,6 +1876,8 @@ static void ioc_timer_fn(struct timer_list *timer)
 		u64 vdone, vtime, usage_us;
 		u32 hw_active, hw_inuse;
 
+		nr_active++;
+
 		/*
 		 * Collect unused and wind vtime closer to vnow to prevent
 		 * iocgs from accumulating a large amount of budget.
@@ -2440,6 +2039,16 @@ static void ioc_timer_fn(struct timer_list *timer)
 
 	ioc->busy_level = clamp(ioc->busy_level, -1000, 1000);
 
+	/*
+	 * Everything the tick reports is final here: busy_level was just
+	 * computed, cur_period hasn't changed, nr_active and usage_us_sum are
+	 * complete, and vrate and period_us still hold the values this period
+	 * ran in. usage is wall time over wall time, summed over iocgs, and is
+	 * not capped at 100. Emit before the refresh below so the event reads
+	 * the completed period directly.
+	 */
+	trace_iocost_ioc_tick(ioc, &now, nr_active, usage_us_sum);
+
 	ioc_adjust_base_vrate(ioc, rq_wait_pct, nr_lagging, nr_shortages,
 			      prev_busy_level, missed_ppm);
 
@@ -2588,7 +2197,9 @@ static u64 calc_vtime_cost(struct bio *bio, struct ioc_gq *iocg, bool is_merge)
 {
 	u64 cost;
 
-	calc_vtime_cost_builtin(bio, iocg, is_merge, &cost);
+	if (!ioc_model_calc_cost(iocg->ioc, bio, is_merge, &cost))
+		calc_vtime_cost_builtin(bio, iocg, is_merge, &cost);
+
 	return cost;
 }
 
@@ -2610,11 +2221,19 @@ 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)
+/*
+ * Called from the request completion path for READ and WRITE
+ * requests, where no ioc->lock is held; the model pointer is read
+ * under RCU, matching the bio-side calc_vtime_cost().
+ */
+static u64 calc_size_vtime_cost(struct request *rq, struct ioc *ioc,
+				bool is_read)
 {
 	u64 cost;
 
-	calc_size_vtime_cost_builtin(rq, ioc, &cost);
+	if (!ioc_model_size_cost(ioc, rq, is_read, &cost))
+		calc_size_vtime_cost_builtin(rq, ioc, &cost);
+
 	return cost;
 }
 
@@ -2884,7 +2503,8 @@ static void ioc_rqos_done(struct rq_qos *rqos, struct request *rq)
 
 	on_q_ns = blk_time_get_ns() - rq->alloc_time_ns;
 	rq_wait_ns = rq->start_time_ns - rq->alloc_time_ns;
-	size_nsec = div64_u64(calc_size_vtime_cost(rq, ioc), VTIME_PER_NSEC);
+	size_nsec = div64_u64(calc_size_vtime_cost(rq, ioc, pidx == QOS_RLAT),
+			       VTIME_PER_NSEC);
 
 	ccs = get_cpu_ptr(ioc->pcpu_stat);
 
@@ -2920,6 +2540,10 @@ static void ioc_rqos_exit(struct rq_qos *rqos)
 
 	timer_shutdown_sync(&ioc->timer);
 	free_percpu(ioc->pcpu_stat);
+
+	/* eject the model on device removal */
+	ioc_bpf_eject(ioc);
+
 	kfree(ioc);
 }
 
@@ -2932,7 +2556,7 @@ static const struct rq_qos_ops ioc_rqos_ops = {
 	.exit = ioc_rqos_exit,
 };
 
-static int blk_iocost_init(struct gendisk *disk)
+int blk_iocost_init(struct gendisk *disk)
 {
 	struct ioc *ioc;
 	int i, cpu, ret;
@@ -3070,6 +2694,35 @@ static void ioc_pd_init(struct blkg_policy_data *pd)
 	spin_unlock_irqrestore(&ioc->lock, flags);
 }
 
+/*
+ * iocg_init() delivery for the attached model. blkg_create() calls this only
+ * after the blkg has been inserted into the radix tree and the queue's blkg
+ * list, so a blkg whose insertion failed is never seen here and the init/free
+ * pairing cannot be broken by a model switch in between; the caller holds
+ * queue_lock, the same lock the attachment updates are serialized with.
+ */
+static void ioc_pd_online(struct blkg_policy_data *pd)
+{
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	struct ioc_gq *iocg = pd_to_iocg(pd);
+	struct blkcg_gq *blkg = pd_to_blkg(pd);
+	struct ioc *ioc = iocg->ioc;
+	const struct iocost_model_ops *model;
+	unsigned long flags;
+
+	if (!ioc)
+		return;
+
+	spin_lock_irqsave(&ioc->lock, flags);
+	model = ioc_attached_model_locked(ioc);
+	if (model && model->iocg_init) {
+		model->iocg_init(blkg->blkcg, ioc->rqos.disk->queue);
+		iocg->bpf_iocg_inited = true;
+	}
+	spin_unlock_irqrestore(&ioc->lock, flags);
+#endif
+}
+
 static void iocg_release(struct rcu_head *rcu)
 {
 	struct blkg_policy_data *pd =
@@ -3090,6 +2743,25 @@ static void ioc_pd_free(struct blkg_policy_data *pd)
 	if (ioc) {
 		spin_lock_irqsave(&ioc->lock, flags);
 
+		/*
+		 * Gate the free on the delivered flag: a blkg which never went
+		 * online never received iocg_init(), and bios still holding
+		 * the blkg can be priced between its going offline and this
+		 * free, so iocg_free() follows pd_free() rather than
+		 * pd_offline.
+		 */
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+		if (iocg->bpf_iocg_inited) {
+			const struct iocost_model_ops *amodel =
+				ioc_attached_model_locked(ioc);
+
+			if (amodel && amodel->iocg_free)
+				amodel->iocg_free(blkg->blkcg,
+						  ioc->rqos.disk->queue);
+			iocg->bpf_iocg_inited = false;
+		}
+#endif
+
 		if (!list_empty(&iocg->active_list)) {
 			struct ioc_now now;
 
@@ -3150,7 +2822,6 @@ static u64 ioc_weight_prfill(struct seq_file *sf, struct blkg_policy_data *pd,
 	return 0;
 }
 
-
 static int ioc_weight_show(struct seq_file *sf, void *v)
 {
 	struct blkcg *blkcg = css_to_blkcg(seq_css(sf));
@@ -3453,16 +3124,19 @@ static u64 ioc_cost_model_prfill(struct seq_file *sf,
 	const char *dname = blkg_dev_name(pd->blkg);
 	struct ioc *ioc = pd_to_iocg(pd)->ioc;
 	u64 *u = ioc->params.i_lcoefs;
+	const struct iocost_model_ops *model;
 
 	if (!dname)
 		return 0;
 
 	spin_lock_irq(&ioc->lock);
-	seq_printf(sf, "%s ctrl=%s model=linear "
+	model = ioc_bpf_model_locked(ioc);
+	seq_printf(sf, "%s ctrl=%s model=%s "
 		   "rbps=%llu rseqiops=%llu rrandiops=%llu "
 		   "wbps=%llu wseqiops=%llu wrandiops=%llu "
 		   "flushiops=%llu\n",
 		   dname, ioc->user_cost_model ? "user" : "auto",
+		   model ? "bpf" : "linear",
 		   u[I_LCOEF_RBPS], u[I_LCOEF_RSEQIOPS], u[I_LCOEF_RRANDIOPS],
 		   u[I_LCOEF_WBPS], u[I_LCOEF_WSEQIOPS], u[I_LCOEF_WRANDIOPS],
 		   u[I_LCOEF_FLUSHIOPS]);
@@ -3507,6 +3181,10 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 	bool user;
 	char *body, *p;
 	int ret;
+	const struct iocost_model_ops *new_model = NULL;
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	bool model_write = false;
+#endif
 
 	blkg_conf_init(&ctx, input);
 
@@ -3559,9 +3237,30 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 			continue;
 		case COST_MODEL:
 			match_strlcpy(buf, &args[0], sizeof(buf));
-			if (strcmp(buf, "linear"))
-				goto unlock;
-			continue;
+			if (!strcmp(buf, "linear")) {
+				/*
+				 * Staged and committed below, so a parse
+				 * error later in the same write leaves the
+				 * model selection untouched.
+				 */
+				new_model = NULL;
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+				model_write = true;
+#endif
+				continue;
+			}
+			if (!strcmp(buf, "bpf")) {
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+				new_model = rcu_dereference_protected(
+						ioc->attached,
+						lockdep_is_held(&ioc->lock));
+				model_write = true;
+#endif
+				if (!new_model)
+					goto unlock;
+				continue;
+			}
+			goto unlock;
 		}
 
 		tok = match_token(p, i_lcoef_tokens, args);
@@ -3579,6 +3278,10 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 	} else {
 		ioc->user_cost_model = false;
 	}
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	if (model_write)
+		rcu_assign_pointer(ioc->model, new_model);
+#endif
 	ioc_refresh_params(ioc, true);
 
 	ret = 0;
@@ -3616,12 +3319,13 @@ static struct cftype ioc_files[] = {
 	{}
 };
 
-static struct blkcg_policy blkcg_policy_iocost = {
+struct blkcg_policy blkcg_policy_iocost = {
 	.dfl_cftypes	= ioc_files,
 	.cpd_alloc_fn	= ioc_cpd_alloc,
 	.cpd_free_fn	= ioc_cpd_free,
 	.pd_alloc_fn	= ioc_pd_alloc,
 	.pd_init_fn	= ioc_pd_init,
+	.pd_online_fn	= ioc_pd_online,
 	.pd_free_fn	= ioc_pd_free,
 	.pd_stat_fn	= ioc_pd_stat,
 };
diff --git a/block/blk-iocost.h b/block/blk-iocost.h
new file mode 100644
index 00000000000000..6d62b4fd0c543d
--- /dev/null
+++ b/block/blk-iocost.h
@@ -0,0 +1,615 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * blk-iocost private definitions, shared between blk-iocost.c and
+ * blk-iocost-bpf.c. Not for direct inclusion by other files.
+ */
+#ifndef _BLK_IOCOST_H
+#define _BLK_IOCOST_H
+
+#include <linux/types.h>
+#include <linux/blk_types.h>
+#include <linux/blkdev.h>
+#include "blk-cgroup.h"
+#include <linux/blk-mq.h>
+#include <linux/timer.h>
+#include <linux/hrtimer.h>
+#include <linux/seqlock.h>
+#include <linux/atomic.h>
+#include <linux/minmax.h>
+#include <linux/time64.h>
+#include <linux/wait.h>
+#include <asm/local.h>
+#include <asm/local64.h>
+#include "blk-rq-qos.h"
+
+struct bpf_link;
+
+/*
+ * Pluggable cost model interface for blk-iocost.
+ *
+ * A BPF struct_ops implementation can take over the cost model of one device.
+ * The device is identified by the dev member, which is set from userspace
+ * before the program is loaded; the struct_ops core owns the program lifetime.
+ * Attaching creates the ioc if needed, like an io.cost.model write, and
+ * switches the device to the BPF model with the queue frozen before
+ * rq_qos_mutex, like an io.cost.qos write, and delivers iocg_init() to the
+ * cgroups which already exist on the device. Enabling and disabling the
+ * controller stays with io.cost.qos.
+ *
+ * While a model is attached, io.cost.model selects between it and the builtin
+ * model: "model=bpf" switches to the attached model and "model=linear" back to
+ * the builtin. Neither detaches the struct_ops; only detaching does. The
+ * builtin linear coefficients are kept while the BPF model is in use and take
+ * effect again when switched back.
+ *
+ * While in use, the BPF model prices every charged IO on the device, including
+ * flushes, from the bio charging path. calc_cost() is called from the IO
+ * submission path with RCU read lock held and must not sleep. It receives the
+ * bio itself so that the model can use what it needs (operation flags, size,
+ * sector, the issuing cgroup through bio->bi_blkg, which is guaranteed
+ * non-NULL) and returns the cost of the IO in vtime units, where 1 second
+ * of device time equals VTIME_PER_SEC (2^37,
+ * available to BPF programs through vmlinux.h). The return value is clamped to
+ * 1 second of device time per IO.
+ *
+ * The struct_ops also carries the transfer cost coefficients, vtime per page
+ * for reads and writes. While the BPF model is in use, they replace the
+ * builtin coefficients in the completion-time request sizing of READ and
+ * WRITE requests, with ZONE_APPEND counted as a write. Taking over the QoS
+ * side (latency tracking, vrate control) is left for later extensions.
+ *
+ * The cgroup callbacks are bound to the iocg policy lifetime, one (cgroup,
+ * device) pair per invocation. iocg_init() is delivered from ioc_pd_online()
+ * and on attach to the cgroups already online on the device; iocg_free() on
+ * detach to the cgroups which still exist then and at pd_free() time for the
+ * rest, so that init and free pair up exactly. iocg_free() is gated on a
+ * per-iocg delivered flag, as bios can still be priced between the blkg going
+ * offline and its free. Both callbacks are called with ioc->lock held and must
+ * not sleep; the delivery points nest inside queue_lock except for iocg_free()
+ * from ioc_pd_free() in blkg_free_workfn().
+ */
+
+/*
+ * Call metadata for calc_cost()'s model_flags; the merge indicator is not a
+ * property of the bio. An enum so that the value is exported through BTF and
+ * usable from vmlinux.h.
+ */
+enum {
+	IOCOST_COST_F_MERGE	= 1 << 0,	/* called from merge path */
+};
+
+struct iocost_model_ops {
+	/*
+	 * target device (major:minor), set from userspace before load
+	 * through the struct_ops map's initial value, in the userspace
+	 * dev_t encoding new_decode_dev() accepts
+	 */
+	dev_t dev;
+
+	/* vtime per page for the completion-time request sizing */
+	u64 read_vtime_per_page;
+	u64 write_vtime_per_page;
+
+	u64 (*calc_cost)(struct bio *bio, u64 model_flags);
+	void (*iocg_init)(struct blkcg *blkcg, struct request_queue *q);
+	void (*iocg_free)(struct blkcg *blkcg, struct request_queue *q);
+};
+
+enum {
+	MILLION			= 1000000,
+
+	/* timer period is calculated from latency requirements, bound it */
+	MIN_PERIOD		= USEC_PER_MSEC,
+	MAX_PERIOD		= USEC_PER_SEC,
+
+	/*
+	 * iocg->vtime is targeted at 50% behind the device vtime, which
+	 * serves as its IO credit buffer.  Surplus weight adjustment is
+	 * immediately canceled if the vtime margin runs below 10%.
+	 */
+	MARGIN_MIN_PCT		= 10,
+	MARGIN_LOW_PCT		= 20,
+	MARGIN_TARGET_PCT	= 50,
+
+	INUSE_ADJ_STEP_PCT	= 25,
+
+	/* Have some play in timer operations */
+	TIMER_SLACK_PCT		= 1,
+
+	/* 1/64k is granular enough and can easily be handled w/ u32 */
+	WEIGHT_ONE		= 1 << 16,
+};
+
+enum {
+	/*
+	 * As vtime is used to calculate the cost of each IO, it needs to
+	 * be fairly high precision.  For example, it should be able to
+	 * represent the cost of a single page worth of discard with
+	 * suffificient accuracy.  At the same time, it should be able to
+	 * represent reasonably long enough durations to be useful and
+	 * convenient during operation.
+	 *
+	 * 1s worth of vtime is 2^37.  This gives us both sub-nanosecond
+	 * granularity and days of wrap-around time even at extreme vrates.
+	 */
+	VTIME_PER_SEC_SHIFT	= 37,
+	VTIME_PER_SEC		= 1LLU << VTIME_PER_SEC_SHIFT,
+	VTIME_PER_USEC		= VTIME_PER_SEC / USEC_PER_SEC,
+	VTIME_PER_NSEC		= VTIME_PER_SEC / NSEC_PER_SEC,
+
+	/* bound vrate adjustments within two orders of magnitude */
+	VRATE_MIN_PPM		= 10000,	/* 1% */
+	VRATE_MAX_PPM		= 100000000,	/* 10000% */
+
+	VRATE_MIN		= VTIME_PER_USEC * VRATE_MIN_PPM / MILLION,
+	VRATE_CLAMP_ADJ_PCT	= 4,
+
+	/* switch iff the conditions are met for longer than this */
+	AUTOP_CYCLE_NSEC	= 10LLU * NSEC_PER_SEC,
+};
+
+enum {
+	/* if IOs end up waiting for requests, issue less */
+	RQ_WAIT_BUSY_PCT	= 5,
+
+	/* unbusy hysterisis */
+	UNBUSY_THR_PCT		= 75,
+
+	/*
+	 * The effect of delay is indirect and non-linear and a huge amount of
+	 * future debt can accumulate abruptly while unthrottled. Linearly scale
+	 * up delay as debt is going up and then let it decay exponentially.
+	 * This gives us quick ramp ups while delay is accumulating and long
+	 * tails which can help reducing the frequency of debt explosions on
+	 * unthrottle. The parameters are experimentally determined.
+	 *
+	 * The delay mechanism provides adequate protection and behavior in many
+	 * cases. However, this is far from ideal and falls shorts on both
+	 * fronts. The debtors are often throttled too harshly costing a
+	 * significant level of fairness and possibly total work while the
+	 * protection against their impacts on the system can be choppy and
+	 * unreliable.
+	 *
+	 * The shortcoming primarily stems from the fact that, unlike for page
+	 * cache, the kernel doesn't have well-defined back-pressure propagation
+	 * mechanism and policies for anonymous memory. Fully addressing this
+	 * issue will likely require substantial improvements in the area.
+	 */
+	MIN_DELAY_THR_PCT	= 500,
+	MAX_DELAY_THR_PCT	= 25000,
+	MIN_DELAY		= 250,
+	MAX_DELAY		= 250 * USEC_PER_MSEC,
+
+	/* halve debts if avg usage over 100ms is under 50% */
+	DFGV_USAGE_PCT		= 50,
+	DFGV_PERIOD		= 100 * USEC_PER_MSEC,
+
+	/* don't let cmds which take a very long time pin lagging for too long */
+	MAX_LAGGING_PERIODS	= 10,
+
+	/*
+	 * Count IO size in 4k pages.  The 12bit shift helps keeping
+	 * size-proportional components of cost calculation in closer
+	 * numbers of digits to per-IO cost components.
+	 */
+	IOC_PAGE_SHIFT		= 12,
+	IOC_PAGE_SIZE		= 1 << IOC_PAGE_SHIFT,
+	IOC_SECT_TO_PAGE_SHIFT	= IOC_PAGE_SHIFT - SECTOR_SHIFT,
+
+	/* if apart further than 16M, consider randio for linear model */
+	LCOEF_RANDIO_PAGES	= 4096,
+};
+
+enum ioc_running {
+	IOC_IDLE,
+	IOC_RUNNING,
+	IOC_STOP,
+};
+
+/* io.cost.qos controls including per-dev enable of the whole controller */
+enum {
+	QOS_ENABLE,
+	QOS_CTRL,
+	NR_QOS_CTRL_PARAMS,
+};
+
+/* io.cost.qos params */
+enum {
+	QOS_RPPM,
+	QOS_RLAT,
+	QOS_WPPM,
+	QOS_WLAT,
+	QOS_MIN,
+	QOS_MAX,
+	NR_QOS_PARAMS,
+};
+
+/* io.cost.model controls */
+enum {
+	COST_CTRL,
+	COST_MODEL,
+	NR_COST_CTRL_PARAMS,
+};
+
+/* builtin linear cost model coefficients */
+enum {
+	I_LCOEF_RBPS,
+	I_LCOEF_RSEQIOPS,
+	I_LCOEF_RRANDIOPS,
+	I_LCOEF_WBPS,
+	I_LCOEF_WSEQIOPS,
+	I_LCOEF_WRANDIOPS,
+	I_LCOEF_FLUSHIOPS,
+	NR_I_LCOEFS,
+};
+
+enum {
+	LCOEF_RPAGE,
+	LCOEF_RSEQIO,
+	LCOEF_RRANDIO,
+	LCOEF_WPAGE,
+	LCOEF_WSEQIO,
+	LCOEF_WRANDIO,
+	LCOEF_FLUSH,
+	NR_LCOEFS,
+};
+
+enum {
+	AUTOP_INVALID,
+	AUTOP_HDD,
+	AUTOP_SSD_QD1,
+	AUTOP_SSD_DFL,
+	AUTOP_SSD_FAST,
+};
+
+struct ioc_params {
+	u32				qos[NR_QOS_PARAMS];
+	u64				i_lcoefs[NR_I_LCOEFS];
+	u64				lcoefs[NR_LCOEFS];
+	u32				too_fast_vrate_pct;
+	u32				too_slow_vrate_pct;
+};
+
+struct ioc_margins {
+	s64				min;
+	s64				low;
+	s64				target;
+};
+
+struct ioc_missed {
+	local_t				nr_met;
+	local_t				nr_missed;
+	u32				last_met;
+	u32				last_missed;
+};
+
+struct ioc_pcpu_stat {
+	struct ioc_missed		missed[2];
+
+	local64_t			rq_wait_ns;
+	u64				last_rq_wait_ns;
+};
+
+/* per device */
+struct ioc {
+	struct rq_qos			rqos;
+
+	bool				enabled;
+
+	struct ioc_params		params;
+	struct ioc_margins		margins;
+	u32				period_us;
+	u32				timer_slack_ns;
+	u64				vrate_min;
+	u64				vrate_max;
+
+	spinlock_t			lock;
+	struct timer_list		timer;
+	struct list_head		active_iocgs;	/* active cgroups */
+	struct ioc_pcpu_stat __percpu	*pcpu_stat;
+
+	enum ioc_running		running;
+	atomic64_t			vtime_rate;
+	u64				vtime_base_rate;
+	s64				vtime_err;
+
+	seqcount_spinlock_t		period_seqcount;
+	u64				period_at;	/* wallclock starttime */
+	u64				period_at_vtime; /* vtime starttime */
+
+	atomic64_t			cur_period;	/* inc'd each period */
+	int				busy_level;	/* saturation history */
+
+	bool				weights_updated;
+	atomic_t			hweight_gen;	/* for lazy hweights */
+
+	/* debt forgivness */
+	u64				dfgv_period_at;
+	u64				dfgv_period_rem;
+	u64				dfgv_usage_us_sum;
+
+	u64				autop_too_fast_at;
+	u64				autop_too_slow_at;
+	int				autop_idx;
+	bool				user_qos_params:1;
+	bool				user_cost_model:1;
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	/* the struct_ops attached to this device, NULL = none */
+	const struct iocost_model_ops	__rcu *attached;
+	/* the link which owns the attachment, written with ioc->lock held */
+	struct bpf_link			*bpf_link;
+	/* the cost model in use, NULL = builtin linear model */
+	const struct iocost_model_ops	__rcu *model;
+#endif
+};
+
+struct iocg_pcpu_stat {
+	local64_t			abs_vusage;
+};
+
+struct iocg_stat {
+	u64				usage_us;
+	u64				wait_us;
+	u64				indebt_us;
+	u64				indelay_us;
+};
+
+/* per device-cgroup pair */
+struct ioc_gq {
+	struct blkg_policy_data		pd;
+	struct ioc			*ioc;
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	/* whether the attached model's iocg_init() was delivered */
+	bool				bpf_iocg_inited;
+#endif
+
+	/*
+	 * A iocg can get its weight from two sources - an explicit
+	 * per-device-cgroup configuration or the default weight of the
+	 * cgroup.  `cfg_weight` is the explicit per-device-cgroup
+	 * configuration.  `weight` is the effective considering both
+	 * sources.
+	 *
+	 * When an idle cgroup becomes active its `active` goes from 0 to
+	 * `weight`.  `inuse` is the surplus adjusted active weight.
+	 * `active` and `inuse` are used to calculate `hweight_active` and
+	 * `hweight_inuse`.
+	 *
+	 * `last_inuse` remembers `inuse` while an iocg is idle to persist
+	 * surplus adjustments.
+	 *
+	 * `inuse` may be adjusted dynamically during period. `saved_*` are used
+	 * to determine and track adjustments.
+	 */
+	u32				cfg_weight;
+	u32				weight;
+	u32				active;
+	u32				inuse;
+
+	u32				last_inuse;
+	s64				saved_margin;
+
+	sector_t			cursor;		/* to detect randio */
+
+	/*
+	 * `vtime` is this iocg's vtime cursor which progresses as IOs are
+	 * issued.  If lagging behind device vtime, the delta represents
+	 * the currently available IO budget.  If running ahead, the
+	 * overage.
+	 *
+	 * `vtime_done` is the same but progressed on completion rather
+	 * than issue.  The delta behind `vtime` represents the cost of
+	 * currently in-flight IOs.
+	 */
+	atomic64_t			vtime;
+	atomic64_t			done_vtime;
+	u64				abs_vdebt;
+
+	/* current delay in effect and when it started */
+	u64				delay;
+	u64				delay_at;
+
+	/*
+	 * The period this iocg was last active in.  Used for deactivation
+	 * and invalidating `vtime`.
+	 */
+	atomic64_t			active_period;
+	struct list_head		active_list;
+
+	/* see __propagate_weights() and current_hweight() for details */
+	u64				child_active_sum;
+	u64				child_inuse_sum;
+	u64				child_adjusted_sum;
+	int				hweight_gen;
+	u32				hweight_active;
+	u32				hweight_inuse;
+	u32				hweight_donating;
+	u32				hweight_after_donation;
+
+	struct list_head		walk_list;
+	struct list_head		surplus_list;
+
+	struct wait_queue_head		waitq;
+	struct hrtimer			waitq_timer;
+
+	/* timestamp at the latest activation */
+	u64				activated_at;
+
+	/* statistics */
+	struct iocg_pcpu_stat __percpu	*pcpu_stat;
+	struct iocg_stat		stat;
+	struct iocg_stat		last_stat;
+	u64				last_stat_abs_vusage;
+	u64				usage_delta_us;
+	u64				wait_since;
+	u64				indebt_since;
+	u64				indelay_since;
+
+	/* this iocg's depth in the hierarchy and ancestors including self */
+	int				level;
+	struct ioc_gq			*ancestors[];
+};
+
+/* per cgroup */
+struct ioc_cgrp {
+	struct blkcg_policy_data	cpd;
+	unsigned int			dfl_weight;
+};
+
+struct ioc_now {
+	u64				now_ns;
+	u64				now;
+	u64				vnow;
+};
+
+struct iocg_wait {
+	struct wait_queue_entry		wait;
+	struct bio			*bio;
+	u64				abs_cost;
+	bool				committed;
+};
+
+struct iocg_wake_ctx {
+	struct ioc_gq			*iocg;
+	u32				hw_inuse;
+	s64				vbudget;
+};
+
+extern struct blkcg_policy blkcg_policy_iocost;
+
+static inline struct ioc *rqos_to_ioc(struct rq_qos *rqos)
+{
+	return container_of(rqos, struct ioc, rqos);
+}
+
+static inline struct ioc *q_to_ioc(struct request_queue *q)
+{
+	return rqos_to_ioc(rq_qos_id(q, RQ_QOS_COST));
+}
+
+static inline const char __maybe_unused *ioc_name(struct ioc *ioc)
+{
+	struct gendisk *disk = ioc->rqos.disk;
+
+	if (!disk)
+		return "<unknown>";
+	return disk->disk_name;
+}
+
+static inline struct ioc_gq *pd_to_iocg(struct blkg_policy_data *pd)
+{
+	return pd ? container_of(pd, struct ioc_gq, pd) : NULL;
+}
+
+static inline struct ioc_gq *blkg_to_iocg(struct blkcg_gq *blkg)
+{
+	return pd_to_iocg(blkg_to_pd(blkg, &blkcg_policy_iocost));
+}
+
+static inline struct blkcg_gq *iocg_to_blkg(struct ioc_gq *iocg)
+{
+	return pd_to_blkg(&iocg->pd);
+}
+
+static inline struct ioc_cgrp *blkcg_to_iocc(struct blkcg *blkcg)
+{
+	return container_of(blkcg_to_cpd(blkcg, &blkcg_policy_iocost),
+			    struct ioc_cgrp, cpd);
+}
+
+/*
+ * The attached struct_ops and the model in use. The writers hold
+ * ioc->lock, the hot path readers are inside rcu_read_lock() and the
+ * map is not freed until after an RCU grace period, the slow readers
+ * hold ioc->lock.
+ */
+static inline const struct iocost_model_ops *
+ioc_attached_model_locked(struct ioc *ioc)
+{
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	return rcu_dereference_protected(ioc->attached,
+					 lockdep_is_held(&ioc->lock));
+#else
+	return NULL;
+#endif
+}
+
+static inline const struct iocost_model_ops *
+ioc_bpf_model_locked(struct ioc *ioc)
+{
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	return rcu_dereference_protected(ioc->model,
+					 lockdep_is_held(&ioc->lock));
+#else
+	return NULL;
+#endif
+}
+
+/*
+ * Price one charged IO with the model in use into *@cost and return
+ * true, or return false when no model is in use and the builtin model
+ * must price it. The model is read under rcu_read_lock(), which the
+ * helper takes and releases itself, and the returned cost is clamped
+ * to one second of device time. calc_cost() may be invoked for a
+ * (cgroup, device) pair before iocg_init() has been delivered for
+ * it; models relying on per-pair state must tolerate that window.
+ */
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+static inline bool ioc_model_calc_cost(struct ioc *ioc, struct bio *bio,
+				       bool is_merge, u64 *cost)
+{
+	const struct iocost_model_ops *model;
+
+	rcu_read_lock();
+	model = rcu_dereference(ioc->model);
+	if (model)
+		*cost = min(model->calc_cost(bio, is_merge ?
+			    IOCOST_COST_F_MERGE : 0), VTIME_PER_SEC);
+	rcu_read_unlock();
+	return model;
+}
+#else	/* CONFIG_BLK_CGROUP_IOCOST_BPF */
+static inline bool ioc_model_calc_cost(struct ioc *ioc, struct bio *bio,
+				       bool is_merge, u64 *cost)
+{
+	return false;
+}
+#endif	/* CONFIG_BLK_CGROUP_IOCOST_BPF */
+
+/*
+ * The same for the completion-time request sizing: the transfer cost
+ * is the model's vtime per page for the request direction, and the
+ * returned cost is clamped to one second of device time.
+ */
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+static inline bool ioc_model_size_cost(struct ioc *ioc, struct request *rq,
+				       bool is_read, u64 *cost)
+{
+	const struct iocost_model_ops *model;
+
+	rcu_read_lock();
+	model = rcu_dereference(ioc->model);
+	if (model)
+		*cost = min((is_read ? model->read_vtime_per_page :
+			     model->write_vtime_per_page) *
+			    (blk_rq_stats_sectors(rq) >> IOC_SECT_TO_PAGE_SHIFT),
+			    VTIME_PER_SEC);
+	rcu_read_unlock();
+	return model;
+}
+#else	/* CONFIG_BLK_CGROUP_IOCOST_BPF */
+static inline bool ioc_model_size_cost(struct ioc *ioc, struct request *rq,
+				       bool is_read, u64 *cost)
+{
+	return false;
+}
+#endif	/* CONFIG_BLK_CGROUP_IOCOST_BPF */
+
+int blk_iocost_init(struct gendisk *disk);
+
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+void ioc_bpf_eject(struct ioc *ioc);
+#else	/* CONFIG_BLK_CGROUP_IOCOST_BPF */
+static inline void ioc_bpf_eject(struct ioc *ioc) { }
+#endif	/* CONFIG_BLK_CGROUP_IOCOST_BPF */
+#endif	/* _BLK_IOCOST_H */
diff --git a/include/trace/events/iocost.h b/include/trace/events/iocost.h
index e772b1bc60d603..39229605f499d7 100644
--- a/include/trace/events/iocost.h
+++ b/include/trace/events/iocost.h
@@ -178,6 +178,49 @@ TRACE_EVENT(iocost_ioc_vrate_adj,
 	)
 );
 
+/*
+ * Periodic per-device summary, emitted once per period before the vrate
+ * adjustment and the period transition in 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, const struct ioc_now *now,
+		 int nr_active, u64 usage_us_sum),
+
+	TP_ARGS(ioc, now, nr_active, usage_us_sum),
+
+	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)
+	),
+
+	TP_fast_assign(
+		__assign_str(devname);
+		__entry->cur_period = atomic64_read(&ioc->cur_period);
+		__entry->period_us = ioc->period_us;
+		__entry->vrate = ioc->vtime_base_rate;
+		__entry->busy_level = ioc->busy_level;
+		__entry->nr_active = nr_active;
+		__entry->usage_pct = now->now > ioc->period_at ?
+			div64_u64(usage_us_sum * 100,
+				  now->now - ioc->period_at) : 0;
+	),
+
+	TP_printk("[%s] period=%llu:%uus vrate=%llu busy=%d active=%d usage=%u%%",
+		__get_str(devname), __entry->cur_period, __entry->period_us,
+		__entry->vrate, __entry->busy_level, __entry->nr_active,
+		__entry->usage_pct
+	)
+);
+
 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 49dfe939467cc8..78ed59f83a16ac 100644
--- a/tools/testing/selftests/bpf/config
+++ b/tools/testing/selftests/bpf/config
@@ -141,3 +141,5 @@ CONFIG_SMC_HS_CTRL_BPF=y
 CONFIG_DIBS=y
 CONFIG_DIBS_LO=y
 CONFIG_PM_WAKELOCKS=y
+CONFIG_BLK_CGROUP_IOCOST=y
+CONFIG_BLK_DEV_NULL_BLK=y
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 00000000000000..5373d52d93a66a
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/iocost_model.c
@@ -0,0 +1,806 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (C) 2026 KylinSoft Corporation. */
+#define _GNU_SOURCE
+#include <test_progs.h>
+#include <fcntl.h>
+#include <sched.h>
+#include <sys/statfs.h>
+#include <linux/magic.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <sys/sysmacros.h>
+#include <unistd.h>
+#include "iocost_model.skel.h"
+#include "iocost_ms.skel.h"
+
+/*
+ * Write val to the configfs attribute at path, returning the errno of the
+ * write negated (0 on success).
+ */
+static int configfs_write(const char *path, const char *val)
+{
+	FILE *fp;
+	int err = 0;
+
+	fp = fopen(path, "w");
+	if (!fp)
+		return -errno;
+	if (fwrite(val, 1, strlen(val), fp) != strlen(val))
+		err = ferror(fp) ? -errno : -EIO;
+	if (fclose(fp) && !err)
+		err = -errno;
+	return err;
+}
+
+/*
+ * Read the first token of the file at path, for the dev attribute.
+ */
+static int read_file_token(const char *path, char *tok, size_t tok_sz)
+{
+	char fmt[16];
+	FILE *fp;
+
+	fp = fopen(path, "r");
+	if (!fp)
+		return -errno;
+	snprintf(fmt, sizeof(fmt), "%%%zus", tok_sz - 1);
+	if (fscanf(fp, fmt, tok) != 1) {
+		fclose(fp);
+		return -EIO;
+	}
+	fclose(fp);
+	return 0;
+}
+
+/*
+ * Create a null_blk instance through configfs and copy its maj:min
+ * into @dev. The device appears only once power is written, and is
+ * removed by rmdir of the instance directory; the maj:min comes from
+ * the sysfs directory of the created disk, which is named after the
+ * instance.
+ */
+static int nullb_create(const char *name, char *dev, size_t dev_sz)
+{
+	char path[128];
+	char p2[128];
+	int err;
+
+	snprintf(path, sizeof(path), "/sys/kernel/config/nullb/%s", name);
+	if (mkdir(path, 0755)) {
+		if (errno != EEXIST)
+			return -errno;
+		/*
+		 * a leftover instance from an earlier crashed run may
+		 * still be powered: tear it down before reusing the
+		 * name
+		 */
+		snprintf(p2, sizeof(p2),
+			 "/sys/kernel/config/nullb/%s/power", name);
+		configfs_write(p2, "0");
+		if (rmdir(path) && errno != ENOENT)
+			return -errno;
+		if (mkdir(path, 0755) && errno != EEXIST)
+			return -errno;
+	}
+
+	snprintf(path, sizeof(path), "/sys/kernel/config/nullb/%s/size", name);
+	err = configfs_write(path, "128");
+	if (err)
+		return err;
+
+	snprintf(path, sizeof(path), "/sys/kernel/config/nullb/%s/power", name);
+	err = configfs_write(path, "1");
+	if (err)
+		return err;
+
+	snprintf(path, sizeof(path), "/sys/block/%s/dev", name);
+	err = read_file_token(path, dev, dev_sz);
+	if (err) {
+		/* do not leave a powered instance behind */
+		snprintf(path, sizeof(path),
+			 "/sys/kernel/config/nullb/%s/power", name);
+		configfs_write(path, "0");
+		snprintf(path, sizeof(path),
+			 "/sys/kernel/config/nullb/%s", name);
+		rmdir(path);
+	}
+	return err;
+}
+
+static int nullb_remove(const char *name)
+{
+	char path[128];
+
+	/* a powered instance cannot be removed */
+	snprintf(path, sizeof(path), "/sys/kernel/config/nullb/%s/power", name);
+	configfs_write(path, "0");
+	snprintf(path, sizeof(path), "/sys/kernel/config/nullb/%s", name);
+	if (rmdir(path))
+		return -errno;
+	return 0;
+}
+
+#define IOCOST_NULLB	"iocost_model_test"
+#define IOCOST_NULLB2	"iocost_model_test2"
+
+/*
+ * The tests run against their own null_blk instance created through configfs,
+ * so they need root, configfs and the null_blk driver.
+ */
+/*
+ * The BPF cost model needs cgroup v2 at /sys/fs/cgroup and
+ * CONFIG_BLK_CGROUP_IOCOST_BPF in the running kernel; both are environment
+ * properties, so their absence is a skip.
+ */
+static bool iocost_bpf_supported(void)
+{
+	FILE *f;
+	char line[128];
+	bool any = false, on = false;
+
+	f = popen("zcat /proc/config.gz 2>/dev/null", "r");
+	if (!f)
+		return false;
+	while (fgets(line, sizeof(line), f)) {
+		if (strstr(line, "CONFIG_"))
+			any = true;
+		if (strstr(line, "CONFIG_BLK_CGROUP_IOCOST_BPF=y"))
+			on = true;
+	}
+	pclose(f);
+	return on;
+}
+
+static bool iocost_test_env(void)
+{
+	struct statfs sf;
+
+	if (geteuid() != 0) {
+		printf("%s:SKIP:needs root\n", __func__);
+		test__skip();
+		return false;
+	}
+
+	if (statfs("/sys/fs/cgroup", &sf) ||
+	    sf.f_type != CGROUP2_SUPER_MAGIC) {
+		printf("%s:SKIP:needs cgroup v2 at /sys/fs/cgroup\n",
+		       __func__);
+		test__skip();
+		return false;
+	}
+
+	if (!iocost_bpf_supported()) {
+		printf("%s:SKIP:needs CONFIG_BLK_CGROUP_IOCOST_BPF\n",
+		       __func__);
+		test__skip();
+		return false;
+	}
+
+	/* isolate the configfs and cgroup mounts from the host */
+	if (unshare(CLONE_NEWNS)) {
+		printf("%s:SKIP:unshare(CLONE_NEWNS) failed: %s\n",
+		       __func__, strerror(errno));
+		test__skip();
+		return false;
+	}
+	mkdir("/sys/kernel/config", 0755);
+	(void)mount("none", "/sys/kernel/config", "configfs", 0, NULL);
+	SYS_NOFAIL("modprobe null_blk nr_devices=0");
+	if (access("/sys/kernel/config/nullb", W_OK)) {
+		printf("%s:SKIP:needs null_blk with configfs support\n",
+		       __func__);
+		test__skip();
+		return false;
+	}
+	return true;
+}
+
+/*
+ * Read back the io.cost.model line of dev and copy the model= value into
+ * @model. Returns 0 on success.
+ */
+static int readback_model(const char *dev, char *model, size_t model_sz)
+{
+	char line[256], word[256], *m, *end;
+	FILE *fp;
+	int found = 0;
+
+	fp = fopen("/sys/fs/cgroup/io.cost.model", "r");
+	if (!fp)
+		return -1;
+	while (fgets(line, sizeof(line), fp)) {
+		if (sscanf(line, "%255s", word) == 1 && !strcmp(word, dev)) {
+			found = 1;
+			break;
+		}
+	}
+	fclose(fp);
+	if (!found)
+		return -1;
+
+	m = strstr(line, "model=");
+	if (!m)
+		return -1;
+	m += strlen("model=");
+	end = m;
+	while (*end && *end != ' ')
+		end++;
+	snprintf(model, model_sz, "%.*s", (int)(end - m), m);
+	return 0;
+}
+
+/*
+ * Read the cost.usage accumulator of dev from the cgroup's io.stat. Returns 0
+ * on success, -ENODEV when the device has no line yet (no charge recorded).
+ */
+static int read_cost_usage(const char *cgroup, const char *dev,
+			   unsigned long long *usage)
+{
+	char line[512];
+	FILE *fp;
+	int found = 0;
+
+	fp = fopen(cgroup, "r");
+	if (!fp)
+		return -EIO;
+	*usage = 0;
+	while (fgets(line, sizeof(line), fp)) {
+		char *tok = strtok(line, " \n");
+
+		if (!tok || strcmp(tok, dev))
+			continue;
+		found = 1;
+		while ((tok = strtok(NULL, " \n"))) {
+			if (!strncmp(tok, "cost.usage=", 11)) {
+				*usage = strtoull(tok + 11, NULL, 0);
+				fclose(fp);
+				return 0;
+			}
+		}
+	}
+	fclose(fp);
+	return found ? -ENOENT : -ENODEV;
+}
+
+/* mkdir, recovering from a leftover of an aborted earlier run */
+static int cgroup_mkdir(const char *path)
+{
+	if (!mkdir(path, 0755))
+		return 0;
+	if (errno == EEXIST && !rmdir(path))
+		return mkdir(path, 0755) ? -errno : 0;
+	return -errno;
+}
+
+/*
+ * Write a line to io.cost.model for dev and return the errno of the write
+ * negated (0 on success), as ASSERT_ERR() expects.
+ */
+static int write_cost_model(const char *dev, const char *what)
+{
+	char buf[128];
+	FILE *fp;
+	int err = 0;
+
+	snprintf(buf, sizeof(buf), "%s %s", dev, what);
+	fp = fopen("/sys/fs/cgroup/io.cost.model", "w");
+	if (!fp)
+		return -EACCES;
+	if (fwrite(buf, 1, strlen(buf), fp) != strlen(buf))
+		err = ferror(fp) ? -errno : -EIO;
+	if (fclose(fp) && !err)
+		err = -errno;
+	return err;
+}
+
+/*
+ * Attach the example model to the null_blk instance the test creates: the dev
+ * member is written through the struct_ops map's initial value before load,
+ * and attaching the struct_ops attaches the model to the device. Detaching the
+ * struct_ops restores the builtin model.
+ *
+ * Requires root, cgroup v2 and null_blk with configfs support.
+ */
+void serial_test_iocost_model(void)
+{
+	struct iocost_model *skel, *second, *bad;
+	unsigned int maj, min;
+	char pidbuf[16], buf[4096], path[64], qbuf[160], dev2[32];
+	int devfd, i, err, lfd;
+	char model[32], dev[32];
+	unsigned long long u1, u2, inits1;
+
+	if (!iocost_test_env())
+		return;
+	if (!ASSERT_OK(nullb_create(IOCOST_NULLB, dev, sizeof(dev)),
+		       "nullb_create"))
+		return;
+	if (sscanf(dev, "%u:%u", &maj, &min) != 2) {
+		ASSERT_TRUE(false, "dev_parse");
+		nullb_remove(IOCOST_NULLB);
+		return;
+	}
+
+	skel = iocost_model__open();
+	if (!ASSERT_OK_PTR(skel, "skel_open")) {
+		nullb_remove(IOCOST_NULLB);
+		return;
+	}
+
+	/*
+	 * a model with a zero coefficient must fail to attach instead of
+	 * silently zeroing the completion sizing (validate rejects it on
+	 * the map update the attach performs; the link form of the
+	 * struct_ops only reaches it there)
+	 */
+	bad = iocost_model__open();
+	if (!ASSERT_OK_PTR(bad, "bad_open")) {
+		iocost_model__destroy(skel);
+		nullb_remove(IOCOST_NULLB);
+		return;
+	}
+	bad->struct_ops.iocost_2x->dev = (__u32)makedev(maj, min);
+	bad->struct_ops.iocost_2x->write_vtime_per_page = 0;
+	if (ASSERT_OK(iocost_model__load(bad), "bad_load"))
+		ASSERT_EQ(iocost_model__attach(bad), -EINVAL,
+			  "attach_rejects_zero_coeff");
+	iocost_model__destroy(bad);
+
+	/* same for the read-side transfer coefficient */
+	bad = iocost_model__open();
+	if (!ASSERT_OK_PTR(bad, "bad_read_open")) {
+		iocost_model__destroy(skel);
+		nullb_remove(IOCOST_NULLB);
+		return;
+	}
+	bad->struct_ops.iocost_2x->dev = (__u32)makedev(maj, min);
+	bad->struct_ops.iocost_2x->read_vtime_per_page = 0;
+	if (ASSERT_OK(iocost_model__load(bad), "bad_read_load"))
+		ASSERT_EQ(iocost_model__attach(bad), -EINVAL,
+			  "attach_rejects_zero_read");
+	iocost_model__destroy(bad);
+
+	skel->struct_ops.iocost_2x->dev = (__u32)makedev(maj, min);
+	/*
+	 * create a cgroup for the pairing checks; its blkg comes to life
+	 * when the controller is enabled and the cgroup configured below,
+	 * exercising the iocg_init()/iocg_free() pairing end to end
+	 */
+	/*
+	 * Enable the io controller for the pairing cgroup: without it
+	 * the cgroup has no io.weight/io.stat and the iocg never
+	 * activates, so the model is consulted but nothing is charged.
+	 */
+	ASSERT_OK(configfs_write("/sys/fs/cgroup/cgroup.subtree_control",
+				 "+io"), "subtree_io");
+	if (!ASSERT_OK(cgroup_mkdir("/sys/fs/cgroup/iocost_pairing"),
+		       "mkdir_cg")) {
+		iocost_model__destroy(skel);
+		nullb_remove(IOCOST_NULLB);
+		return;
+	}
+	snprintf(pidbuf, sizeof(pidbuf), "%d", getpid());
+	ASSERT_OK(configfs_write("/sys/fs/cgroup/iocost_pairing/cgroup.procs",
+				  pidbuf), "cgroup_procs");
+	snprintf(path, sizeof(path), "/dev/%s", IOCOST_NULLB);
+	devfd = open(path, O_RDONLY);
+	if (!ASSERT_OK(devfd < 0 ? -errno : 0, "open_dev")) {
+		configfs_write("/sys/fs/cgroup/cgroup.procs", pidbuf);
+		rmdir("/sys/fs/cgroup/iocost_pairing");
+		iocost_model__destroy(skel);
+		nullb_remove(IOCOST_NULLB);
+		return;
+	}
+	for (i = 0; i < 32; i++)
+		(void)read(devfd, buf, sizeof(buf));
+	close(devfd);
+	configfs_write("/sys/fs/cgroup/cgroup.procs", pidbuf);
+
+
+	err = iocost_model__load(skel);
+	if (!ASSERT_OK(err, "skel_load")) {
+		iocost_model__destroy(skel);
+		rmdir("/sys/fs/cgroup/iocost_pairing");
+		nullb_remove(IOCOST_NULLB);
+		return;
+	}
+
+	err = iocost_model__attach(skel);
+	if (err == -EOPNOTSUPP || err == -ENODEV) {
+		printf("%s:SKIP:device is not blk-mq, has no iocost or does not exist\n",
+		       __func__);
+		iocost_model__destroy(skel);
+		rmdir("/sys/fs/cgroup/iocost_pairing");
+		nullb_remove(IOCOST_NULLB);
+		test__skip();
+		return;
+	}
+	if (ASSERT_OK(err, "attach")) {
+		/*
+		 * attached: the read path reports model=bpf until the
+		 * struct_ops is detached; ctrl keeps describing the
+		 * builtin coefficients
+		 */
+		err = readback_model(dev, model, sizeof(model));
+		if (ASSERT_OK(err, "readback"))
+			ASSERT_STREQ(model, "bpf", "model_bpf");
+
+		/*
+		 * the blkg created above was already on the blkg list
+		 * (online) when the attach walk ran, so the walk
+		 * delivered iocg_init() to it and to every other cgroup
+		 * which has a blkg on this device (the count depends on
+		 * the environment); none of them can have received
+		 * iocg_free() yet
+		 */
+		ASSERT_GT(skel->bss->iocg_inits, 0, "pair_init");
+		ASSERT_EQ(skel->bss->iocg_frees, 0, "pair_no_free");
+
+		/* a second model on the same device fails with -EBUSY */
+		second = iocost_model__open();
+		if (ASSERT_OK_PTR(second, "second_open")) {
+			second->struct_ops.iocost_2x->dev =
+				(__u32)makedev(maj, min);
+			err = iocost_model__load(second);
+			if (ASSERT_OK(err, "second_load")) {
+				struct bpf_link *l2;
+
+				/*
+				 * the kernel rejects attaching a second
+				 * model to the device with EBUSY
+				 */
+				l2 = bpf_map__attach_struct_ops(
+						second->maps.iocost_2x);
+				if (!ASSERT_ERR_PTR(l2, "second_ebusy"))
+					bpf_link__destroy(l2);
+				else
+					ASSERT_EQ(libbpf_get_error(l2), -EBUSY,
+						  "second_ebusy_errno");
+			}
+			iocost_model__destroy(second);
+		}
+
+		/*
+		 * pricing coverage: root cgroup IOs bypass the model, so
+		 * move into the pairing cgroup, enable the controller
+		 * and verify IOs actually go through calc_cost() and get
+		 * charged
+		 */
+		ASSERT_OK(configfs_write(
+				"/sys/fs/cgroup/iocost_pairing/cgroup.procs",
+				pidbuf), "procs_pairing_priced");
+		snprintf(qbuf, sizeof(qbuf), "%s 1000", dev);
+		ASSERT_OK(configfs_write(
+				"/sys/fs/cgroup/iocost_pairing/io.weight",
+				qbuf), "weight_pairing");
+		snprintf(qbuf, sizeof(qbuf),
+			 "%s enable=1 ctrl=user min=100.00 max=100.00", dev);
+		ASSERT_OK(configfs_write("/sys/fs/cgroup/io.cost.qos", qbuf),
+			  "qos_enable");
+
+		devfd = open(path, O_RDONLY);
+		if (!ASSERT_OK(devfd < 0 ? -errno : 0, "open_dev_priced")) {
+			iocost_model__destroy(skel);
+			configfs_write("/sys/fs/cgroup/cgroup.procs", pidbuf);
+			snprintf(qbuf, sizeof(qbuf), "%s enable=0", dev);
+			(void)configfs_write("/sys/fs/cgroup/io.cost.qos", qbuf);
+			if (rmdir("/sys/fs/cgroup/iocost_pairing") && errno != ENOENT)
+				printf("%s: rmdir cgroup failed: %s\n", __func__,
+				       strerror(errno));
+			nullb_remove(IOCOST_NULLB);
+			return;
+		}
+		ASSERT_OK(read_cost_usage("/sys/fs/cgroup/iocost_pairing/io.stat",
+					  dev, &u1), "cost_usage_pre");
+		for (i = 0; i < 500; i++)
+			(void)read(devfd, buf, sizeof(buf));
+		close(devfd);
+		ASSERT_GT(skel->bss->calc_costs, 0, "model_priced");
+		/*
+		 * the usage stat is flushed by the iocost timer, give
+		 * the current period a chance to end before reading
+		 */
+		sleep(3);
+		ASSERT_OK(read_cost_usage("/sys/fs/cgroup/iocost_pairing/io.stat",
+					  dev, &u2), "cost_usage_post");
+		ASSERT_GT(u2, u1, "cost_charged");
+		ASSERT_GT(skel->bss->ioc_ticks, 0, "tick_seen");
+
+		/*
+		 * a cgroup created while the model is attached gets its
+		 * iocg_init() when its first IO onlines the blkg
+		 */
+		inits1 = skel->bss->iocg_inits;
+		ASSERT_OK(cgroup_mkdir("/sys/fs/cgroup/iocost_late"),
+			  "mkdir_late");
+		ASSERT_OK(configfs_write(
+				"/sys/fs/cgroup/iocost_late/cgroup.procs",
+				pidbuf), "procs_late");
+		devfd = open(path, O_RDONLY);
+		if (ASSERT_OK(devfd < 0 ? -errno : 0, "open_dev_late")) {
+			for (i = 0; i < 32; i++)
+				(void)read(devfd, buf, sizeof(buf));
+			close(devfd);
+		}
+		ASSERT_GT(skel->bss->iocg_inits, inits1, "late_init");
+		ASSERT_OK(configfs_write("/sys/fs/cgroup/cgroup.procs",
+					 pidbuf), "procs_back");
+		rmdir("/sys/fs/cgroup/iocost_late");
+
+		/*
+		 * a second device is independent: enabling it shows
+		 * the builtin model, not the one attached to the
+		 * first
+		 */
+		if (ASSERT_OK(nullb_create(IOCOST_NULLB2, dev2,
+					   sizeof(dev2)), "nullb_create2")) {
+			snprintf(qbuf, sizeof(qbuf),
+				 "%s enable=1 ctrl=auto", dev2);
+			ASSERT_OK(configfs_write(
+					"/sys/fs/cgroup/io.cost.qos", qbuf),
+				  "qos_nullb2");
+			err = readback_model(dev2, model, sizeof(model));
+			if (ASSERT_OK(err, "readback_nullb2"))
+				ASSERT_STREQ(model, "linear",
+					     "model_linear_nullb2");
+			snprintf(qbuf, sizeof(qbuf), "%s enable=0", dev2);
+			ASSERT_OK(configfs_write(
+					"/sys/fs/cgroup/io.cost.qos", qbuf),
+				  "qos_nullb2_off");
+		}
+		nullb_remove(IOCOST_NULLB2);
+
+		/*
+		 * attachment and model selection are independent:
+		 * ctrl=bpf is never accepted, model=linear switches
+		 * back to the builtin without detaching, model=bpf
+		 * switches to the attached model again
+		 */
+		err = write_cost_model(dev, "ctrl=bpf");
+		ASSERT_ERR(err, "ctrl_bpf_rejected");
+
+		err = write_cost_model(dev, "model=linear");
+		ASSERT_OK(err, "model_linear_write");
+		err = readback_model(dev, model, sizeof(model));
+		if (ASSERT_OK(err, "readback_linear"))
+			ASSERT_STREQ(model, "linear", "model_linear");
+
+		/* still attached: the switch must not free the slot */
+		second = iocost_model__open();
+		if (ASSERT_OK_PTR(second, "second_open2")) {
+			second->struct_ops.iocost_2x->dev =
+				(__u32)makedev(maj, min);
+			err = iocost_model__load(second);
+			if (ASSERT_OK(err, "second_load2")) {
+				struct bpf_link *l2;
+
+				l2 = bpf_map__attach_struct_ops(
+						second->maps.iocost_2x);
+				if (!ASSERT_ERR_PTR(l2, "second_ebusy2"))
+					bpf_link__destroy(l2);
+				else
+					ASSERT_EQ(libbpf_get_error(l2), -EBUSY,
+						  "second_ebusy2_errno");
+			}
+			iocost_model__destroy(second);
+		}
+
+		/* still attached: switching back to the model works */
+		err = write_cost_model(dev, "model=bpf");
+		ASSERT_OK(err, "model_bpf_write");
+		err = readback_model(dev, model, sizeof(model));
+		if (ASSERT_OK(err, "readback_bpf"))
+			ASSERT_STREQ(model, "bpf", "model_bpf");
+
+		/*
+		 * detach implicitly by closing the link fd instead of
+		 * calling bpf_link__destroy() explicitly: the release
+		 * path must detach the model just like the explicit
+		 * call does
+		 */
+		lfd = bpf_link__fd(skel->links.iocost_2x);
+		bpf_link__disconnect(skel->links.iocost_2x);
+		close(lfd);
+		skel->links.iocost_2x = NULL;
+
+		/* after detach, model=bpf fails: nothing is attached */
+		err = write_cost_model(dev, "model=bpf");
+		ASSERT_ERR(err, "model_bpf_after_detach");
+
+		err = readback_model(dev, model, sizeof(model));
+		if (ASSERT_OK(err, "readback_after_detach"))
+			ASSERT_STREQ(model, "linear", "model_linear");
+
+		/* the detach walk delivered the matching iocg_free()s */
+		ASSERT_EQ(skel->bss->iocg_frees, skel->bss->iocg_inits,
+			  "pair_free");
+	}
+
+	iocost_model__destroy(skel);
+	(void)configfs_write("/sys/fs/cgroup/cgroup.procs", pidbuf);
+	snprintf(qbuf, sizeof(qbuf), "%s enable=0", dev);
+	(void)configfs_write("/sys/fs/cgroup/io.cost.qos", qbuf);
+	if (rmdir("/sys/fs/cgroup/iocost_pairing") && errno != ENOENT)
+		printf("%s: rmdir cgroup failed: %s\n", __func__,
+		       strerror(errno));
+	nullb_remove(IOCOST_NULLB);
+}
+/*
+ * Same check for the multi-stream example model. Only one model can be
+ * attached to a device at a time; each test creates its own device and
+ * attaches and detaches, so they are serial.
+ */
+void serial_test_iocost_model_streams(void)
+{
+	struct iocost_ms *skel;
+	unsigned int maj, min;
+	int err;
+	char model[32], dev[32];
+
+	if (!iocost_test_env())
+		return;
+	if (!ASSERT_OK(nullb_create(IOCOST_NULLB, dev, sizeof(dev)),
+		       "nullb_create"))
+		return;
+	if (sscanf(dev, "%u:%u", &maj, &min) != 2) {
+		ASSERT_TRUE(false, "dev_parse");
+		nullb_remove(IOCOST_NULLB);
+		return;
+	}
+
+	skel = iocost_ms__open();
+	if (!ASSERT_OK_PTR(skel, "skel_open")) {
+		nullb_remove(IOCOST_NULLB);
+		return;
+	}
+
+	skel->struct_ops.iocost_ms->dev = (__u32)makedev(maj, min);
+
+	err = iocost_ms__load(skel);
+	if (!ASSERT_OK(err, "skel_load")) {
+		iocost_ms__destroy(skel);
+		nullb_remove(IOCOST_NULLB);
+		return;
+	}
+
+	err = iocost_ms__attach(skel);
+	if (err == -EOPNOTSUPP || err == -ENODEV) {
+		printf("%s:SKIP:device is not blk-mq, has no iocost or does not exist\n",
+		       __func__);
+		iocost_ms__destroy(skel);
+		nullb_remove(IOCOST_NULLB);
+		test__skip();
+		return;
+	}
+	if (ASSERT_OK(err, "attach")) {
+		err = readback_model(dev, model, sizeof(model));
+		if (ASSERT_OK(err, "readback"))
+			ASSERT_STREQ(model, "bpf", "model_bpf");
+
+		bpf_link__destroy(skel->links.iocost_ms);
+		skel->links.iocost_ms = NULL;
+
+		err = readback_model(dev, model, sizeof(model));
+		if (ASSERT_OK(err, "readback_after_detach"))
+			ASSERT_STREQ(model, "linear", "model_linear");
+	}
+
+	iocost_ms__destroy(skel);
+	nullb_remove(IOCOST_NULLB);
+}
+
+/*
+ * Removal of the device while a model is attached: the test builds
+ * its own null_blk instance through configfs like the other tests,
+ * attaches to it, then removes the device out from under the model.
+ * The ejection must drop the device from the cgroup interface,
+ * down, and a recreated device must be attachable again.
+ */
+void serial_test_iocost_model_removal(void)
+{
+	struct iocost_model *skel, *skel2;
+	unsigned int maj, min;
+	char dev[32], model[32];
+	int err;
+
+	if (!iocost_test_env())
+		return;
+
+	skel = iocost_model__open();
+	if (!ASSERT_OK_PTR(skel, "skel_open"))
+		return;
+
+	err = nullb_create("iocost_removal", dev, sizeof(dev));
+	if (!ASSERT_OK(err, "nullb_create"))
+		goto out;
+	if (sscanf(dev, "%u:%u", &maj, &min) != 2) {
+		ASSERT_TRUE(false, "dev_parse");
+		goto out;
+	}
+
+	skel->struct_ops.iocost_2x->dev = (__u32)makedev(maj, min);
+	err = iocost_model__load(skel);
+	if (!ASSERT_OK(err, "skel_load"))
+		goto out;
+
+	err = iocost_model__attach(skel);
+	if (!ASSERT_OK(err, "attach"))
+		goto out;
+
+	err = readback_model(dev, model, sizeof(model));
+	if (ASSERT_OK(err, "readback"))
+		ASSERT_STREQ(model, "bpf", "model_bpf");
+
+	/* remove the device out from under the attached model */
+	if (!ASSERT_OK(nullb_remove("iocost_removal"), "nullb_remove"))
+		goto detach;
+
+	/* the ejection drops the device from the cgroup files */
+	err = readback_model(dev, model, sizeof(model));
+	ASSERT_ERR(err, "readback_after_removal");
+
+	err = write_cost_model(dev, "model=bpf");
+	ASSERT_ERR(err, "model_bpf_after_removal");
+
+	/*
+	 * the ejection path must deliver iocg_free() for every blkg
+	 * which was online on the removed device: pd_free() runs from
+	 * blkcg_deactivate_policy() before ioc_bpf_eject() drops the
+	 * map reference
+	 */
+	ASSERT_GT(skel->bss->iocg_inits, 0, "eject_had_inits");
+	ASSERT_EQ(skel->bss->iocg_frees, skel->bss->iocg_inits,
+		  "eject_balanced");
+
+detach:
+	/*
+	 * detaching after the device is gone must be a clean no-op;
+	 * this exercises the eject-then-detach ordering in the kernel
+	 */
+	bpf_link__destroy(skel->links.iocost_2x);
+	skel->links.iocost_2x = NULL;
+
+	/* the same attach and detach against a recreated device */
+	skel2 = iocost_model__open();
+	if (!ASSERT_OK_PTR(skel2, "skel2_open"))
+		goto out;
+
+	err = nullb_create("iocost_removal", dev, sizeof(dev));
+	if (!ASSERT_OK(err, "nullb_create_again"))
+		goto out2;
+	if (sscanf(dev, "%u:%u", &maj, &min) != 2) {
+		ASSERT_TRUE(false, "dev_parse_again");
+		goto out2;
+	}
+
+	skel2->struct_ops.iocost_2x->dev = (__u32)makedev(maj, min);
+	err = iocost_model__load(skel2);
+	if (!ASSERT_OK(err, "skel2_load"))
+		goto out2;
+
+	err = iocost_model__attach(skel2);
+	if (!ASSERT_OK(err, "attach_again"))
+		goto out2;
+
+	err = readback_model(dev, model, sizeof(model));
+	if (ASSERT_OK(err, "readback_again"))
+		ASSERT_STREQ(model, "bpf", "model_bpf_again");
+	ASSERT_GT(skel2->bss->iocg_inits, 0, "pair_init_again");
+
+	bpf_link__destroy(skel2->links.iocost_2x);
+	skel2->links.iocost_2x = NULL;
+
+	err = readback_model(dev, model, sizeof(model));
+	if (ASSERT_OK(err, "readback_after_detach_again"))
+		ASSERT_STREQ(model, "linear", "model_linear_again");
+
+	/* the re-attach walk delivered init for the recreated device */
+	ASSERT_EQ(skel2->bss->iocg_frees, skel2->bss->iocg_inits,
+		  "pair_balanced_again");
+
+out2:
+	iocost_model__destroy(skel2);
+out:
+	nullb_remove("iocost_removal");
+	iocost_model__destroy(skel);
+}
diff --git a/tools/testing/selftests/bpf/progs/iocost_model.c b/tools/testing/selftests/bpf/progs/iocost_model.c
new file mode 100644
index 00000000000000..8875fb0f441749
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/iocost_model.c
@@ -0,0 +1,201 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (C) 2026 KylinSoft Corporation. */
+/*
+ * Example iocost cost model: the builtin linear HDD formula with all costs
+ * doubled, for one device given by the dev member of the struct_ops.
+ *
+ * The constants mirror what calc_lcoefs() derives from the AUTOP_HDD defaults
+ * (rbps=174019176 rseqiops=41708 rrandiops=370, w-side analog) in vtime units
+ * where 1s == 2^37. On a rotational device still on ctrl=auto, a device with
+ * this model attached charges twice the builtin model under the same
+ * read/write workload (the builtin prices flushes as zero and adds a fixed
+ * flush term to data-bearing preflushes, which this model omits; this model
+ * prices flushes as one-page writes), 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 follows the builtin: a zero cursor means "no previous
+ * IO", and the cursor is advanced for the bios the builtin prices
+ * (READ/WRITE/ZONE_APPEND with a non-zero size), so flushes and discards leave
+ * it alone and long merged streams do not drift past the 16MB seek threshold.
+ * One known deviation, mispricing only: the builtin does not move its cursor
+ * for an IO whose cgroup fails to activate; this model does not see the
+ * activation result.
+ *
+ * The model implements the full linear formula itself, including flushes:
+ * there is no fallback to the builtin model, which prices a dataless
+ * WRITE|REQ_PREFLUSH as zero unless flushiops is configured; this model prices
+ * it as a one-page sequential write. What a flush actually costs depends on
+ * the IOs before it, which a static formula cannot express - pricing it as a
+ * small constant is a crude penalty for unnecessarily frequent flushes, and a
+ * stateful model would be the way to do better. Discards and other unpriced
+ * operations pass through at zero cost, like the builtin.
+ */
+
+#include "vmlinux.h"
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+
+/*
+ * VTIME_PER_SEC, IOC_PAGE_SIZE/SHIFT, IOC_SECT_TO_PAGE_SHIFT,
+ * LCOEF_RANDIO_PAGES (the 16MB seek threshold) and IOCOST_COST_F_MERGE
+ * come from vmlinux.h (BTF constants; the enum64 ones need pahole
+ * >= 1.23 to be emitted)
+ */
+#define IOCOST_REQ_OP_MASK	0xff		/* REQ_OP_MASK, not in BTF */
+
+/*
+ * DIV64_U64_ROUND_UP / DIV_ROUND_UP_ULL equivalents, folded at
+ * compile time
+ */
+#define RU(x, y)		((x) / (y) + (((x) % (y)) ? 1 : 0))
+
+#define RBPS	174019176ULL
+#define RSEQIOPS	41708ULL
+#define RRANDIOPS	370ULL
+#define WBPS	178075866ULL
+#define WSEQIOPS	42705ULL
+#define WRANDIOPS	378ULL
+
+#define RPAGE	(RU(VTIME_PER_SEC, RU(RBPS, IOC_PAGE_SIZE)))
+#define RSEQIO	(RU(VTIME_PER_SEC, RSEQIOPS) - RPAGE)
+#define RRANDIO	(RU(VTIME_PER_SEC, RRANDIOPS) - RPAGE)
+#define WPAGE	(RU(VTIME_PER_SEC, RU(WBPS, IOC_PAGE_SIZE)))
+#define WSEQIO	(RU(VTIME_PER_SEC, WSEQIOPS) - WPAGE)
+#define WRANDIO	(RU(VTIME_PER_SEC, WRANDIOPS) - WPAGE)
+
+/*
+ * per-cgroup cursor storage: keyed by the cgroup and freed with it,
+ * so a cgroup that comes back starts with no cursor
+ */
+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");
+
+/*
+ * cgroup callback counters: the test reads them back to verify the
+ * init/free pairing across attach, detach and device removal
+ */
+__u64 iocg_inits;
+__u64 iocg_frees;
+
+/*
+ * incremented by calc_cost(): the test asserts pricing went
+ * through the model while it is attached and the controller is
+ * enabled
+ */
+__u64 calc_costs;
+
+/* counts iocost_ioc_tick emissions observed from BPF side */
+__u64 ioc_ticks;
+
+SEC("struct_ops")
+void BPF_PROG(iocost_2x_iocg_init, struct blkcg *blkcg,
+	      struct request_queue *q)
+{
+	iocg_inits++;
+}
+
+SEC("struct_ops")
+void BPF_PROG(iocost_2x_iocg_free, struct blkcg *blkcg,
+	      struct request_queue *q)
+{
+	iocg_frees++;
+}
+
+SEC("struct_ops")
+u64 BPF_PROG(iocost_2x_calc_cost, struct bio *bio, u64 model_flags)
+{
+	u64 opf = bio->bi_opf, nbytes = bio->bi_iter.bi_size;
+	u64 sector = bio->bi_iter.bi_sector;
+	struct blkcg *blkcg = bio->bi_blkg->blkcg;
+	u64 pages, seek_pages = 0, base, coef_page, randio, cost;
+	__u64 *cursor, cur;
+	int priced;
+
+	calc_costs++;
+
+	/* builtin truncates: max(sectors >> IOC_SECT_TO_PAGE_SHIFT, 1) */
+	pages = nbytes >> IOC_PAGE_SHIFT;
+	if (!pages)
+		pages = 1;
+
+	if ((opf & IOCOST_REQ_OP_MASK) == REQ_OP_READ) {
+		base = RSEQIO; coef_page = RPAGE; randio = RRANDIO;
+	} else if ((opf & IOCOST_REQ_OP_MASK) == REQ_OP_WRITE ||
+		   (opf & IOCOST_REQ_OP_MASK) == REQ_OP_ZONE_APPEND) {
+		base = WSEQIO; coef_page = WPAGE; randio = WRANDIO;
+	} else {
+		/*
+		 * the builtin prices other operations at zero and
+		 * leaves them unthrottled; pass them through the same
+		 * way instead of inventing costs
+		 */
+		return 0;
+	}
+
+	/* mirror the builtin cursor semantics described above */
+	priced = (opf & IOCOST_REQ_OP_MASK) == REQ_OP_READ ||
+		 (opf & IOCOST_REQ_OP_MASK) == REQ_OP_WRITE ||
+		 (opf & IOCOST_REQ_OP_MASK) == REQ_OP_ZONE_APPEND;
+	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;
+	/*
+	 * a size-zero IO never moves the cursor, so it must not be
+	 * judged against it either; the builtin skips it entirely,
+	 * this model prices it as a one-page sequential write
+	 */
+	if (cur && priced && nbytes) {
+		seek_pages = sector > cur ? sector - cur
+					   : cur - sector;
+		seek_pages >>= IOC_SECT_TO_PAGE_SHIFT;
+		if (seek_pages > LCOEF_RANDIO_PAGES)
+			base = randio;
+	}
+	/*
+	 * the builtin moves the cursor unconditionally on submit, but
+	 * on a merge only for a back merge into the request ending at
+	 * it; a merged bio starts right at the cursor exactly then,
+	 * and a zero cursor means no history so it never matches
+	 */
+	if (priced && nbytes &&
+	    (!(model_flags & IOCOST_COST_F_MERGE) || (cur && cur == sector)))
+		*cursor = sector + (nbytes >> 9);
+
+	if (model_flags & IOCOST_COST_F_MERGE)
+		base = 0;
+
+	cost = 2 * (base + pages * coef_page);
+	return cost;
+}
+
+/* consumes the new iocost_ioc_tick tracepoint from BPF side */
+SEC("tp_btf/iocost_ioc_tick")
+__u64 BPF_PROG(iocost_2x_tick_count, struct ioc *ioc,
+	       const struct ioc_now *now, int nr_active, u64 usage_us_sum)
+{
+	ioc_ticks++;
+	return 0;
+}
+
+SEC(".struct_ops.link") /* detach on close */
+struct iocost_model_ops iocost_2x = {
+	.read_vtime_per_page = 2 * RPAGE,
+	.write_vtime_per_page = 2 * WPAGE,
+	.calc_cost = (void *)iocost_2x_calc_cost,
+	.iocg_init = (void *)iocost_2x_iocg_init,
+	.iocg_free = (void *)iocost_2x_iocg_free,
+};
+
+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 00000000000000..87d4abcbf69340
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/iocost_ms.c
@@ -0,0 +1,175 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (C) 2026 KylinSoft Corporation. */
+/*
+ * Example multi-stream sequentiality detection cost model.
+ *
+ * The builtin model keeps a single cursor per cgroup, so two interleaved
+ * sequential readers in one cgroup are all priced random (measured 89x
+ * overcharge, 12.9x throughput collapse), while random IO inside a hot window
+ * smaller than the 16MB seek threshold is priced sequential (measured 107x
+ * undercharge). This model replaces the single cursor with a per-cgroup table
+ * of stream slots: an IO is sequential iff its sector matches the expected
+ * next sector of any tracked stream. Interleaved streams keep their own slots,
+ * and windowed random IO rarely matches a moving expectation.
+ *
+ * Stream state lives in a CGRP_STORAGE map, so it is created and freed with
+ * the cgroup. The model implements the builtin linear formula itself; unlike
+ * the builtin it has no flush term, so preflushed IOs are priced as plain
+ * writes (mispricing only, the test never issues flushes).
+ */
+#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, struct bio *bio, u64 model_flags)
+{
+	u64 opf = bio->bi_opf, nbytes = bio->bi_iter.bi_size;
+	u64 sector = bio->bi_iter.bi_sector;
+	struct blkcg *blkcg = bio->bi_blkg->blkcg;
+	struct streams *s;
+	u64 pages, base, coef_page, randio, advance, now;
+	u32 i, victim = 0, found = 0xFFFFFFFF;
+
+	if ((opf & IOCOST_REQ_OP_MASK) == REQ_OP_READ) {
+		base = RSEQIO; coef_page = RPAGE; randio = RRANDIO;
+	} else if ((opf & IOCOST_REQ_OP_MASK) == REQ_OP_WRITE ||
+		   (opf & IOCOST_REQ_OP_MASK) == REQ_OP_ZONE_APPEND) {
+		base = WSEQIO; coef_page = WPAGE; randio = WRANDIO;
+	} else {
+		/*
+		 * the builtin prices other operations at zero and
+		 * leaves them unthrottled; pass them through the same
+		 * way instead of inventing costs
+		 */
+		return 0;
+	}
+	advance = nbytes >> 9;	/* sectors, truncated like the builtin */
+
+	/*
+	 * only bios the builtin prices participate in stream tracking;
+	 * the early return below skips the merge discount, which only
+	 * applies to tracked data bios
+	 */
+	if (!(((opf & IOCOST_REQ_OP_MASK) == REQ_OP_READ ||
+	       (opf & IOCOST_REQ_OP_MASK) == REQ_OP_WRITE ||
+	       (opf & IOCOST_REQ_OP_MASK) == REQ_OP_ZONE_APPEND) && 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 {
+		/*
+		 * a merge which matches no slot is not a new stream:
+		 * replacing a slot could evict a live stream, so merged
+		 * bios are priced without touching the table (and skip
+		 * the base cost below)
+		 */
+		if (!(model_flags & IOCOST_COST_F_MERGE)) {
+			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.link") /* detach on close */
+struct iocost_model_ops iocost_ms = {
+	.read_vtime_per_page = RPAGE,
+	.write_vtime_per_page = WPAGE,
+	.calc_cost = (void *)iocost_ms_calc_cost,
+};
+
+char LICENSE[] SEC("license") = "GPL";

3/2 2026/10/29 02:07 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 41210
							output: 33
							thoughts: 435
						

Thoughts:
**Analyzing the BPF Struct_Ops Patch for `iocost_model_ops`**

Okay, let's break down this patch adding BPF struct_ops support for `iocost_model_ops`. My first step is always to analyze the changes according to a structured approach, keeping in mind my target architecture - AMD64 in this case.

The changes are clearly focused on the block layer, specifically the `blk-iocost` subsystem, and involve several files: `blk-iocost-bpf.c`, `blk-iocost.c`, and `blk-iocost.h`, plus documentation and selftests, naturally. The critical question: is this reachable code? Absolutely. We're dealing with `iocost`, which is demonstrably reachable in virtualized environments, even with setups like `null_blk` or standard disks. The key is cgroup v2, and the use of BPF struct_ops, leveraging `BPF_SYSCALL`, `BPF_PROG_TYPE_STRUCT_OPS`, and similar mechanisms.

The interaction is multifaceted. Userspace can register `iocost_model_ops` via the `bpf()` syscall. Then, attach to a block device, write to cgroup files like `/sys/fs/cgroup/io.cost.model` and `/sys/fs/cgroup/io.cost.qos`, and subsequently trigger `calc_vtime_cost` calculations with IOs. There are also cgroup operations involved triggering `ioc_pd_online` and `ioc_pd_free`, leading to `iocg_init` and `iocg_free` calls. Finally, there's the standard detach and unregister process for the BPF struct_ops. I also need to make sure to keep in mind the various locking mechanisms present such as `lockdep_assert_held`, `guard(mutex)`, `scoped_guard`, and `spin_lock(&ioc->lock)`.

The crucial question: Is this WorthFuzzing? Definitely yes! This hits core subsystems, specifically the block layer, BPF struct_ops, and the cgroup IO controller. The attack surface is broad, exposed through syscalls (the `bpf()` syscall in particular) and interactions with cgroup files, and most importantly, IO operations themselves.

Now I need to move on to the Kconfig requirements. I'll meticulously inspect `block/Kconfig` and any relevant configuration options to ensure the necessary features are enabled and correctly configured.



4/2 2026/10/29 02:07 tool grepper
0m Args:
{
  "Expression": "config BLK_CGROUP_IOCOST",
  "PathPrefixes": [
    "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=224=config BLK_ERROR_INJECTION\n--\nblock/Kconfig-231-\nblock/Kconfig:232:config BLK_CGROUP_IOCOST_BPF\nblock/Kconfig-233-\tdef_bool y\n"
}

5/2 2026/10/29 02:07 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 42367
							output: 32
							thoughts: 64
						

Thoughts:
Okay, let's dive into this.

**Investigating Block IO Accounting in the Linux Kernel**

Right, so I need to figure out the dependencies for `BLK_CGROUP_IOCOST` and `BLK_CGROUP_IOCOST_BPF`. My immediate thought is to check the kernel configuration files. The most logical place to start is the block subsystem's `Kconfig` file. I'll need to open that up and zero in on the relevant sections. My instinct tells me the configuration options will be grouped together.

Let me take a quick look around lines 150-165, and then also scan around lines 230-240. That should give me a good overview of what these options rely on in terms of other kernel features or configurations. Hopefully, I can quickly ascertain any pre-requisites like specific cgroup versions, or other related subsystems that need to be enabled before I can even consider using `BLK_CGROUP_IOCOST` or `BLK_CGROUP_IOCOST_BPF`. It's all about understanding the building blocks and their dependencies. This is just the first step in understanding the complete picture of how the block IO accounting is integrated into the kernel.



6/2 2026/10/29 02:07 tool read-file
0m Args:
{
  "File": "block/Kconfig",
  "FirstLine": 150,
  "LineCount": 25
}

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 170:\t\tscheduler and block devices process requests. Only some I/O schedulers\n 171:\t\tand some block devices support I/O priorities.\n 172:\t\n 173:\tconfig BLK_DEBUG_FS\n 174:\t\tbool \"Block layer debugging information in debugfs\"\n"
}

7/2 2026/10/29 02:07 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 43140
							output: 32
							thoughts: 21
						

Thoughts:
Here's a summary of my thought process, as requested:

**Diving into Block Device Configuration**

Alright, so I'm digging into this `block/Kconfig` file again. Let's see...I need to understand how these block device options are being handled. To get a handle on the key choices, I need to understand what's in line 230 to 240. I'll need to know what's specifically being configured in that block. This should give me some critical context for the current analysis and help guide the rest of my investigation. Let's get to it.



8/2 2026/10/29 02:07 tool read-file
0m Args:
{
  "File": "block/Kconfig",
  "FirstLine": 230,
  "LineCount": 15
}

Results:
{
  "Contents": " 230:\t\t  See Documentation/block/error-injection.rst for details.\n 231:\t\n 232:\tconfig BLK_CGROUP_IOCOST_BPF\n 233:\t\tdef_bool y\n 234:\t\tdepends on BLK_CGROUP_IOCOST \u0026\u0026 BPF_SYSCALL \u0026\u0026 BPF_JIT \u0026\u0026 DEBUG_INFO_BTF\n 235:\t\n 236:\tsource \"block/Kconfig.iosched\"\n 237:\t\n 238:\tendif # BLOCK\n"
}

9/2 2026/10/29 02:07 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 43475
							output: 33
							thoughts: 173
						

Thoughts:
**Analyzing Kernel Configuration Dependencies**

Okay, let's break this down. I see that `BLK_CGROUP_IOCOST_BPF` has some pretty specific dependencies. It's a `def_bool y`, which means it's enabled by default, but it's *highly* reliant on `BLK_CGROUP_IOCOST`, `BPF_SYSCALL`, `BPF_JIT`, and `DEBUG_INFO_BTF`. And, naturally, `BLK_CGROUP_IOCOST` itself leans on `BLK_CGROUP`. No surprises there; these things often cascade.

Now, that list has me thinking. With `BLK_CGROUP_IOCOST_BPF` being a BPF-based feature, I wonder if we need to explicitly enable more advanced BPF features like `BPF_PROG_TYPE_STRUCT_OPS` or `BPF_STRUCT_OPS`. I'm going to quickly check `kernel/bpf/Kconfig` to confirm if those are independently configurable options or something implicit. It's always good to be thorough when dealing with BPF.



10/2 2026/10/29 02:07 tool grepper
0m Error:
no matches

Args:
{
  "Expression": "config BPF_STRUCT_OPS",
  "PathPrefixes": [
    "kernel/bpf/"
  ]
}

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

11/2 2026/10/29 02:07 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 43938
							output: 34
							thoughts: 21
						

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

**Digging into BPF Structure Operations**

Okay, so I need to find where the kernel handles BPF structure operations. The logical place to start is within the BPF subsystem itself. I'm going to leverage my expertise here and immediately reach for `grep`. I'll focus the search within the `kernel/bpf/` directory, as that's where I'd expect to find the core BPF implementation. The specific function I'm looking for is `register_bpf_struct_ops`. This function name, based on my understanding of how the kernel often structures its internal APIs, strongly suggests that it's involved in, well, registering the operations related to handling BPF structures. That's precisely what I'm after. Let's see what `grep` turns up.



12/2 2026/10/29 02:07 tool grepper
0m Args:
{
  "Expression": "register_bpf_struct_ops",
  "PathPrefixes": [
    "kernel/bpf/"
  ]
}

Results:
{
  "Output": "kernel/bpf/btf.c=10917=bpf_struct_ops_find(struct btf *btf, u32 type_id)\n--\nkernel/bpf/btf.c-10937-\nkernel/bpf/btf.c:10938:int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)\nkernel/bpf/btf.c-10939-{\n--\nkernel/bpf/btf.c-10965-}\nkernel/bpf/btf.c:10966:EXPORT_SYMBOL_GPL(__register_bpf_struct_ops);\nkernel/bpf/btf.c-10967-#endif\n"
}

13/2 2026/10/29 02:07 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 44373
							output: 39
							thoughts: 32
						

Thoughts:
Okay, let's dive into this. Here's how I'd approach this task, as if these were my internal thoughts:

**Analyzing the BTF Registration within the BPF Kernel Context**

Right, so I need to understand how the `__register_bpf_struct_ops` function interacts within the BPF (Berkeley Packet Filter) code. My initial thought is to check the `#ifdef` directives surrounding that function in `kernel/bpf/btf.c`. This strongly suggests the function's availability is conditional, probably based on some kernel configuration or feature flag. That `#ifdef` is going to be key to seeing *when* and *why* it's actually compiled and available. I need to figure out what preprocessor macro controls that conditional compilation. That will tell me a great deal about the context in which we can expect this registration to happen. Is it a compile-time option, a kernel version check, a specific hardware architecture, or maybe even related to a security feature? I have to understand the logic behind that conditional compilation before I can fully grasp the implications of how `__register_bpf_struct_ops` is used or *isn't* used.



14/2 2026/10/29 02:08 tool read-file
0m Args:
{
  "File": "kernel/bpf/btf.c",
  "FirstLine": 10930,
  "LineCount": 20
}

Results:
{
  "Contents": "10930:\t\tfor (i = 0; i \u003c cnt; i++) {\n10931:\t\t\tif (st_ops_list[i].type_id == type_id)\n10932:\t\t\t\treturn \u0026st_ops_list[i];\n10933:\t\t}\n10934:\t\n10935:\t\treturn NULL;\n10936:\t}\n10937:\t\n10938:\tint __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)\n10939:\t{\n10940:\t\tstruct bpf_verifier_log *log;\n10941:\t\tstruct btf *btf;\n10942:\t\tint err = 0;\n10943:\t\n10944:\t\tbtf = btf_get_module_btf(st_ops-\u003eowner);\n10945:\t\tif (!btf)\n10946:\t\t\treturn check_btf_kconfigs(st_ops-\u003eowner, \"struct_ops\");\n10947:\t\tif (IS_ERR(btf))\n10948:\t\t\treturn PTR_ERR(btf);\n10949:\t\n"
}

15/2 2026/10/29 02:08 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 45023
							output: 32
							thoughts: 37
						

Thoughts:
Okay, let's dive into this. Here's my thought process on this specific scenario, aimed at my fellow expert:

**Investigating `#ifdef` Guards and `bpf_struct_ops`**

Alright, I'm going to quickly get to the bottom of this. The first thing that jumps out is the need to understand what's guarded by those `#ifdef` directives on line 10930, particularly in relation to the `bpf_struct_ops` file. My initial thought is that this is likely some kind of feature flag, an optimization, or possibly some version-specific code. The file itself probably holds structures or operations related to BPF functionality. Given that it's in the BPF subsystem, it likely means any functionality reliant on the struct defined by `bpf_struct_ops` is conditional based on the macro.

To understand the broader implications of this `#ifdef`, I'll immediately pivot to the `kernel/bpf/Makefile`. This is the single source of truth for all things BPF build-related. I expect it to have definitions for those macros, or at least point me in the right direction. I'm going to look for any logic relating to compiler options or kernel configuration that might define this particular macro that is affecting this specific line. From there, I'll be able to trace down what specific feature or kernel configuration enables or disables the relevant code block. That's the most efficient way to understand what's happening.



16/2 2026/10/29 02:08 tool grepper
0m Args:
{
  "Expression": "bpf_struct_ops",
  "PathPrefixes": [
    "kernel/bpf/"
  ]
}

Results:
{
  "Output": "\nFull output is too long, showing 200 out of 695 lines.\nUse more precise expression or PathPrefixes if possible.\n\nNumber of matching lines per file (6 files in total):\nkernel/bpf/Makefile:1\nkernel/bpf/bpf_struct_ops.c:196\nkernel/bpf/btf.c:14\nkernel/bpf/cgroup.c:10\nkernel/bpf/syscall.c:2\nkernel/bpf/verifier.c:6\n\nkernel/bpf/Makefile=47=ifeq ($(CONFIG_BPF_JIT),y)\nkernel/bpf/Makefile:48:obj-$(CONFIG_BPF_SYSCALL) += bpf_struct_ops.o\nkernel/bpf/Makefile-49-obj-$(CONFIG_BPF_SYSCALL) += cpumask.o\n--\nkernel/bpf/bpf_struct_ops.c-17-\nkernel/bpf/bpf_struct_ops.c:18:struct bpf_struct_ops_value {\nkernel/bpf/bpf_struct_ops.c:19:\tstruct bpf_struct_ops_common_value common;\nkernel/bpf/bpf_struct_ops.c-20-\tchar data[] ____cacheline_aligned_in_smp;\n--\nkernel/bpf/bpf_struct_ops.c-24-\nkernel/bpf/bpf_struct_ops.c:25:struct bpf_struct_ops_map {\nkernel/bpf/bpf_struct_ops.c-26-\tstruct bpf_map map;\nkernel/bpf/bpf_struct_ops.c:27:\tconst struct bpf_struct_ops_desc *st_ops_desc;\nkernel/bpf/bpf_struct_ops.c-28-\t/* protect map_update */\n--\nkernel/bpf/bpf_struct_ops.c-50-\t */\nkernel/bpf/bpf_struct_ops.c:51:\tstruct bpf_struct_ops_value *uvalue;\nkernel/bpf/bpf_struct_ops.c-52-\t/* kvalue.data stores the actual kernel's struct\n--\nkernel/bpf/bpf_struct_ops.c-55-\t */\nkernel/bpf/bpf_struct_ops.c:56:\tstruct bpf_struct_ops_value kvalue;\nkernel/bpf/bpf_struct_ops.c-57-};\nkernel/bpf/bpf_struct_ops.c-58-\nkernel/bpf/bpf_struct_ops.c:59:struct bpf_struct_ops_link {\nkernel/bpf/bpf_struct_ops.c-60-\tstruct bpf_link link;\n--\nkernel/bpf/bpf_struct_ops.c=65=static DEFINE_MUTEX(update_mutex);\nkernel/bpf/bpf_struct_ops.c-66-\nkernel/bpf/bpf_struct_ops.c:67:#define VALUE_PREFIX \"bpf_struct_ops_\"\nkernel/bpf/bpf_struct_ops.c-68-#define VALUE_PREFIX_LEN (sizeof(VALUE_PREFIX) - 1)\nkernel/bpf/bpf_struct_ops.c-69-\nkernel/bpf/bpf_struct_ops.c:70:const struct bpf_verifier_ops bpf_struct_ops_verifier_ops = {\nkernel/bpf/bpf_struct_ops.c-71-};\nkernel/bpf/bpf_struct_ops.c-72-\nkernel/bpf/bpf_struct_ops.c:73:const struct bpf_prog_ops bpf_struct_ops_prog_ops = {\nkernel/bpf/bpf_struct_ops.c-74-#ifdef CONFIG_NET\nkernel/bpf/bpf_struct_ops.c:75:\t.test_run = bpf_struct_ops_test_run,\nkernel/bpf/bpf_struct_ops.c-76-#endif\n--\nkernel/bpf/bpf_struct_ops.c=80=BTF_ID(struct, module)\nkernel/bpf/bpf_struct_ops.c:81:BTF_ID(struct, bpf_struct_ops_common_value)\nkernel/bpf/bpf_struct_ops.c-82-\n--\nkernel/bpf/bpf_struct_ops.c=90=static bool is_valid_value_type(struct btf *btf, s32 value_id,\n--\nkernel/bpf/bpf_struct_ops.c-108-\tif (mt != common_value_type) {\nkernel/bpf/bpf_struct_ops.c:109:\t\tpr_warn(\"The first member of %s should be bpf_struct_ops_common_value\\n\",\nkernel/bpf/bpf_struct_ops.c-110-\t\t\tvalue_name);\n--\nkernel/bpf/bpf_struct_ops.c-123-\nkernel/bpf/bpf_struct_ops.c:124:static void *bpf_struct_ops_image_alloc(void)\nkernel/bpf/bpf_struct_ops.c-125-{\n--\nkernel/bpf/bpf_struct_ops.c-140-\nkernel/bpf/bpf_struct_ops.c:141:void bpf_struct_ops_image_free(void *image)\nkernel/bpf/bpf_struct_ops.c-142-{\n--\nkernel/bpf/bpf_struct_ops.c-156- *\nkernel/bpf/bpf_struct_ops.c:157: * Initialize a struct bpf_struct_ops_arg_info according to type info of\nkernel/bpf/bpf_struct_ops.c-158- * the arguments of a stub function. (Check kCFI for more information about\n--\nkernel/bpf/bpf_struct_ops.c-160- *\nkernel/bpf/bpf_struct_ops.c:161: * Each member in the struct_ops type has a struct bpf_struct_ops_arg_info\nkernel/bpf/bpf_struct_ops.c-162- * to provide an array of struct bpf_ctx_arg_aux, which in turn provides\n--\nkernel/bpf/bpf_struct_ops.c=174=static int prepare_arg_info(struct btf *btf,\n--\nkernel/bpf/bpf_struct_ops.c-178-\t\t\t    struct btf_func_model *model,\nkernel/bpf/bpf_struct_ops.c:179:\t\t\t    struct bpf_struct_ops_arg_info *arg_info)\nkernel/bpf/bpf_struct_ops.c-180-{\n--\nkernel/bpf/bpf_struct_ops.c-324-\nkernel/bpf/bpf_struct_ops.c:325:/* Clean up the arg_info in a struct bpf_struct_ops_desc. */\nkernel/bpf/bpf_struct_ops.c:326:void bpf_struct_ops_desc_release(struct bpf_struct_ops_desc *st_ops_desc)\nkernel/bpf/bpf_struct_ops.c-327-{\nkernel/bpf/bpf_struct_ops.c:328:\tstruct bpf_struct_ops_arg_info *arg_info;\nkernel/bpf/bpf_struct_ops.c-329-\tint i;\n--\nkernel/bpf/bpf_struct_ops.c=338=static bool is_module_member(const struct btf *btf, u32 id)\n--\nkernel/bpf/bpf_struct_ops.c-351-\nkernel/bpf/bpf_struct_ops.c:352:int bpf_struct_ops_supported(const struct bpf_struct_ops *st_ops, u32 moff)\nkernel/bpf/bpf_struct_ops.c-353-{\n--\nkernel/bpf/bpf_struct_ops.c-358-\nkernel/bpf/bpf_struct_ops.c:359:int bpf_struct_ops_desc_init(struct bpf_struct_ops_desc *st_ops_desc,\nkernel/bpf/bpf_struct_ops.c-360-\t\t\t     struct btf *btf,\n--\nkernel/bpf/bpf_struct_ops.c-362-{\nkernel/bpf/bpf_struct_ops.c:363:\tstruct bpf_struct_ops *st_ops = st_ops_desc-\u003est_ops;\nkernel/bpf/bpf_struct_ops.c:364:\tstruct bpf_struct_ops_arg_info *arg_info;\nkernel/bpf/bpf_struct_ops.c-365-\tconst struct btf_member *member;\n--\nkernel/bpf/bpf_struct_ops.c-440-\t\tif (!st_ops_ids[IDX_MODULE_ID] \u0026\u0026 is_module_member(btf, member-\u003etype)) {\nkernel/bpf/bpf_struct_ops.c:441:\t\t\tpr_warn(\"'struct module' btf id not found. Is CONFIG_MODULES enabled? bpf_struct_ops '%s' needs module support.\\n\",\nkernel/bpf/bpf_struct_ops.c-442-\t\t\t\tst_ops-\u003ename);\n--\nkernel/bpf/bpf_struct_ops.c-453-\t\t */\nkernel/bpf/bpf_struct_ops.c:454:\t\tif (!func_proto || bpf_struct_ops_supported(st_ops, moff))\nkernel/bpf/bpf_struct_ops.c-455-\t\t\tcontinue;\n--\nkernel/bpf/bpf_struct_ops.c-497-\tif (st_ops-\u003einit(btf)) {\nkernel/bpf/bpf_struct_ops.c:498:\t\tpr_warn(\"Error in init bpf_struct_ops %s\\n\",\nkernel/bpf/bpf_struct_ops.c-499-\t\t\tst_ops-\u003ename);\n--\nkernel/bpf/bpf_struct_ops.c-506-errout:\nkernel/bpf/bpf_struct_ops.c:507:\tbpf_struct_ops_desc_release(st_ops_desc);\nkernel/bpf/bpf_struct_ops.c-508-\n--\nkernel/bpf/bpf_struct_ops.c-511-\nkernel/bpf/bpf_struct_ops.c:512:static int bpf_struct_ops_map_get_next_key(struct bpf_map *map, void *key,\nkernel/bpf/bpf_struct_ops.c-513-\t\t\t\t\t   void *next_key)\n--\nkernel/bpf/bpf_struct_ops.c-521-\nkernel/bpf/bpf_struct_ops.c:522:int bpf_struct_ops_map_sys_lookup_elem(struct bpf_map *map, void *key,\nkernel/bpf/bpf_struct_ops.c-523-\t\t\t\t       void *value)\nkernel/bpf/bpf_struct_ops.c-524-{\nkernel/bpf/bpf_struct_ops.c:525:\tstruct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;\nkernel/bpf/bpf_struct_ops.c:526:\tstruct bpf_struct_ops_value *uvalue, *kvalue;\nkernel/bpf/bpf_struct_ops.c:527:\tenum bpf_struct_ops_state state;\nkernel/bpf/bpf_struct_ops.c-528-\ts64 refcnt;\n--\nkernel/bpf/bpf_struct_ops.c-558-\nkernel/bpf/bpf_struct_ops.c:559:static void *bpf_struct_ops_map_lookup_elem(struct bpf_map *map, void *key)\nkernel/bpf/bpf_struct_ops.c-560-{\n--\nkernel/bpf/bpf_struct_ops.c-563-\nkernel/bpf/bpf_struct_ops.c:564:static void bpf_struct_ops_map_put_progs(struct bpf_struct_ops_map *st_map)\nkernel/bpf/bpf_struct_ops.c-565-{\n--\nkernel/bpf/bpf_struct_ops.c-575-\nkernel/bpf/bpf_struct_ops.c:576:static void bpf_struct_ops_map_dissoc_progs(struct bpf_struct_ops_map *st_map)\nkernel/bpf/bpf_struct_ops.c-577-{\n--\nkernel/bpf/bpf_struct_ops.c-586-\nkernel/bpf/bpf_struct_ops.c:587:static void bpf_struct_ops_map_free_image(struct bpf_struct_ops_map *st_map)\nkernel/bpf/bpf_struct_ops.c-588-{\n--\nkernel/bpf/bpf_struct_ops.c-591-\tfor (i = 0; i \u003c st_map-\u003eimage_pages_cnt; i++)\nkernel/bpf/bpf_struct_ops.c:592:\t\tbpf_struct_ops_image_free(st_map-\u003eimage_pages[i]);\nkernel/bpf/bpf_struct_ops.c-593-\tst_map-\u003eimage_pages_cnt = 0;\n--\nkernel/bpf/bpf_struct_ops.c=596=static int check_zero_holes(const struct btf *btf, const struct btf_type *t, void *data)\n--\nkernel/bpf/bpf_struct_ops.c-621-\nkernel/bpf/bpf_struct_ops.c:622:static void bpf_struct_ops_link_release(struct bpf_link *link)\nkernel/bpf/bpf_struct_ops.c-623-{\n--\nkernel/bpf/bpf_struct_ops.c-625-\nkernel/bpf/bpf_struct_ops.c:626:static void bpf_struct_ops_link_dealloc(struct bpf_link *link)\nkernel/bpf/bpf_struct_ops.c-627-{\n--\nkernel/bpf/bpf_struct_ops.c-632-\nkernel/bpf/bpf_struct_ops.c:633:const struct bpf_link_ops bpf_struct_ops_link_lops = {\nkernel/bpf/bpf_struct_ops.c:634:\t.release = bpf_struct_ops_link_release,\nkernel/bpf/bpf_struct_ops.c:635:\t.dealloc = bpf_struct_ops_link_dealloc,\nkernel/bpf/bpf_struct_ops.c-636-};\nkernel/bpf/bpf_struct_ops.c-637-\nkernel/bpf/bpf_struct_ops.c:638:int bpf_struct_ops_prepare_trampoline(struct bpf_tramp_nodes *tnodes,\nkernel/bpf/bpf_struct_ops.c-639-\t\t\t\t      struct bpf_tramp_node *node,\n--\nkernel/bpf/bpf_struct_ops.c-663-\nkernel/bpf/bpf_struct_ops.c:664:\t\timage = bpf_struct_ops_image_alloc();\nkernel/bpf/bpf_struct_ops.c-665-\t\tif (IS_ERR(image))\n--\nkernel/bpf/bpf_struct_ops.c-674-\t\tif (image != *_image)\nkernel/bpf/bpf_struct_ops.c:675:\t\t\tbpf_struct_ops_image_free(image);\nkernel/bpf/bpf_struct_ops.c-676-\t\treturn size ? : -EFAULT;\n--\nkernel/bpf/bpf_struct_ops.c-683-\nkernel/bpf/bpf_struct_ops.c:684:static void bpf_struct_ops_ksym_init(const char *tname, const char *mname,\nkernel/bpf/bpf_struct_ops.c-685-\t\t\t\t     void *image, unsigned int size,\n--\nkernel/bpf/bpf_struct_ops.c-692-\nkernel/bpf/bpf_struct_ops.c:693:static void bpf_struct_ops_map_add_ksyms(struct bpf_struct_ops_map *st_map)\nkernel/bpf/bpf_struct_ops.c-694-{\n--\nkernel/bpf/bpf_struct_ops.c-703-\nkernel/bpf/bpf_struct_ops.c:704:static void bpf_struct_ops_map_del_ksyms(struct bpf_struct_ops_map *st_map)\nkernel/bpf/bpf_struct_ops.c-705-{\n--\nkernel/bpf/bpf_struct_ops.c-714-\nkernel/bpf/bpf_struct_ops.c:715:static void bpf_struct_ops_map_free_ksyms(struct bpf_struct_ops_map *st_map)\nkernel/bpf/bpf_struct_ops.c-716-{\n--\nkernel/bpf/bpf_struct_ops.c-726-\nkernel/bpf/bpf_struct_ops.c:727:static long bpf_struct_ops_map_update_elem(struct bpf_map *map, void *key,\nkernel/bpf/bpf_struct_ops.c-728-\t\t\t\t\t   void *value, u64 flags)\nkernel/bpf/bpf_struct_ops.c-729-{\nkernel/bpf/bpf_struct_ops.c:730:\tstruct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;\nkernel/bpf/bpf_struct_ops.c:731:\tconst struct bpf_struct_ops_desc *st_ops_desc = st_map-\u003est_ops_desc;\nkernel/bpf/bpf_struct_ops.c:732:\tconst struct bpf_struct_ops *st_ops = st_ops_desc-\u003est_ops;\nkernel/bpf/bpf_struct_ops.c:733:\tstruct bpf_struct_ops_value *uvalue, *kvalue;\nkernel/bpf/bpf_struct_ops.c-734-\tconst struct btf_type *module_type;\n--\nkernel/bpf/bpf_struct_ops.c-767-\nkernel/bpf/bpf_struct_ops.c:768:\tuvalue = (struct bpf_struct_ops_value *)st_map-\u003euvalue;\nkernel/bpf/bpf_struct_ops.c:769:\tkvalue = (struct bpf_struct_ops_value *)\u0026st_map-\u003ekvalue;\nkernel/bpf/bpf_struct_ops.c-770-\n--\n\n"
}

17/2 2026/10/29 02:08 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 50317
							output: 31
							thoughts: 277
						

Thoughts:
**Analyzing BPF-related Configuration for I/O Cost Accounting**

Alright, let's break this down. From looking at `kernel/bpf/Makefile`, it's clear that the presence of both `CONFIG_BPF_JIT` and `CONFIG_BPF_SYSCALL` directly results in the building of `bpf_struct_ops.o`. That's the baseline.

Now, concerning the `BLK_CGROUP_IOCOST_BPF` configuration, the dependencies are explicit: We need `BLK_CGROUP_IOCOST`, `BPF_SYSCALL`, `BPF_JIT`, and `DEBUG_INFO_BTF`. And, of course, `BLK_CGROUP_IOCOST` itself relies on `BLK_CGROUP`. So, in essence, to get this working, we need all of these:

*   `BLK_CGROUP`
*   `BLK_CGROUP_IOCOST`
*   `BLK_CGROUP_IOCOST_BPF`
*   `BPF_SYSCALL`
*   `BPF_JIT`
*   `DEBUG_INFO_BTF`

It's straightforward so far, but I'm going to double-check that this is the complete picture, especially with the block layer. I need to confirm if `BLK_CGROUP` itself has any dependencies that could trip us up. Time to check `block/Kconfig`.



18/2 2026/10/29 02:08 tool grepper
0m Error:
no matches

Args:
{
  "Expression": "config BLK_CGROUP$",
  "PathPrefixes": [
    "block/"
  ]
}

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

19/2 2026/10/29 02:08 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 50960
							output: 32
							thoughts: 13
						

Thoughts:
Okay, here's my attempt at summarizing that thought process, tailored for an expert audience:

**Hunting Down the `BLK_CGROUP` Definition**

Alright, so I need to get straight to the heart of what's going on with `BLK_CGROUP`. My initial thought is to immediately track down the definitive definition. I need to understand this kernel symbol, and the first step, as always, is to locate its authoritative source. That's likely going to be in one of the relevant kernel headers or source files. I'm thinking I need to find the declaration, associated data structures, and any relevant documentation or comments. This symbol is related to block I/O and cgroups, so I'll need to focus my search on those areas. Let's see what we can find. I anticipate a bit of digging, but it's a critical first step.



20/2 2026/10/29 02:08 tool grepper
0m Error:
no matches

Args:
{
  "Expression": "config BLK_CGROUP\\b",
  "PathPrefixes": [
    "block/"
  ]
}

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

21/2 2026/10/29 02:08 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 51205
							output: 23
							thoughts: 16
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience:

**Hunting Down BLK_CGROUP**

Alright, time to get down to brass tacks. I'm thinking, "Let's track down where `BLK_CGROUP` is being used across the entire source tree." It's not enough to just know it *exists*; I need a comprehensive understanding of its integration. I'm visualizing a full-scale code archaeology expedition. I'm not looking for a single instance but rather every occurrence, every reference, every inclusion. Think `grep -r` on steroids, but with a more nuanced understanding of the kernel's structure in mind. This means I'm looking beyond just straight string matches; I'm considering context, potential indirect references, and any relevant macros or defines that might mask its presence. Gotta find the needle, and all the haystack. This search is the foundation for understanding what the code using the constant does.



22/2 2026/10/29 02:08 tool grepper
0m Args:
{
  "Expression": "config BLK_CGROUP\\b"
}

Results:
{
  "Output": "init/Kconfig=904=config MEMCG_V1\n--\ninit/Kconfig-920-\ninit/Kconfig:921:config BLK_CGROUP\ninit/Kconfig-922-\tbool \"IO controller\"\n"
}

23/2 2026/10/29 02:08 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 51522
							output: 32
							thoughts: 17
						

Thoughts:
Okay, let's dive into this. Here's my thought process on the matter:

**Analyzing `init/Kconfig` Around Line 921**

Right, time to take a look at `init/Kconfig`, specifically around line 921. I'm assuming there's something interesting or potentially relevant to the current problem/task being discussed there. That specific line number suggests it might be a configuration option, a conditional statement, or perhaps even a comment cluster dealing with a particular feature or subsystem initialization within the kernel's configuration system. I'll need to see the context surrounding line 921 to understand its purpose and significance fully, but my immediate assumption is that there's a configuration-related detail that needs to be clarified, checked, or understood in more detail. This could inform the next step in my analysis or potentially illuminate an issue with a particular module. I'll focus on the Kconfig syntax and the surrounding code for clues.



24/2 2026/10/29 02:08 tool read-file
0m Args:
{
  "File": "init/Kconfig",
  "FirstLine": 918,
  "LineCount": 15
}

Results:
{
  "Contents": " 918:\t\n 919:\t\t  Say N if unsure.\n 920:\t\n 921:\tconfig BLK_CGROUP\n 922:\t\tbool \"IO controller\"\n 923:\t\tdepends on BLOCK\n 924:\t\tdefault n\n 925:\t\thelp\n 926:\t\tGeneric block IO controller cgroup interface. This is the common\n 927:\t\tcgroup interface which should be used by various IO controlling\n 928:\t\tpolicies.\n 929:\t\n 930:\t\tCurrently, CFQ IO scheduler uses it to recognize task groups and\n 931:\t\tcontrol disk bandwidth allocation (proportional time slice allocation)\n 932:\t\tto such task groups. It is also used by bio throttling logic in\n"
}

25/2 2026/10/29 02:08 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 51980
							output: 35
							thoughts: 1730
						

Thoughts:
**Analyzing BPF-Based I/O Cost Accounting in the Block Layer**

Okay, let's break this down systematically. My initial task is to identify the relevant kernel configurations and, crucially, pinpoint the key functions for fuzzing. First, I need to ensure the correct configs are enabled. I've confirmed that `BLK_CGROUP_IOCOST` depends on `BLK_CGROUP` and selects `BLK_RQ_ALLOC_TIME`, which sounds right. Then, `BLK_CGROUP_IOCOST_BPF` is def_bool, dependent on both `BLK_CGROUP_IOCOST` and `BPF_SYSCALL`, with the addition of `BPF_JIT` and `DEBUG_INFO_BTF`. I should probably include `BPF` because `BPF_SYSCALL` relies on it. So the configs I need are `BLK_CGROUP_IOCOST`, `BLK_CGROUP_IOCOST_BPF`, `BPF_SYSCALL`, `BPF_JIT`, `DEBUG_INFO_BTF`, and `BLK_CGROUP`.

Next, I'll go through the code changes methodically, looking for significant new symbols and altered functions. In `block/blk-iocost-bpf.c`, I see a bunch of static functions, like `ioc_bpf_deliver_iocg_callbacks`, `ioc_bpf_attach`, `ioc_bpf_detach`, `bpf_iocost_model_init`, and validation and helper functions. However, `ioc_bpf_eject` is non-static, which is an important starting point. I can see this is exported via `blk-iocost.h`. Several functions like `bpf_iocost_reg`, `bpf_iocost_unreg`, `bpf_iocost_validate`, `bpf_iocost_init_member`, `bpf_iocost_check_member` are all struct ops callbacks.

Now, in `block/blk-iocost.c`, there are modifications to existing functions like `calc_vtime_cost`, `calc_size_vtime_cost`, `ioc_rqos_done`, and `ioc_rqos_exit`. `blk_iocost_init` is now non-static, and there's a new `ioc_pd_online` function, and changes to `ioc_pd_free`, `ioc_cost_model_prfill`, `ioc_cost_model_write` and `ioc_autop_idx`, and changes to `ioc_timer_fn`. The header `block/blk-iocost.h` has inline helpers for cost calculation and locking.

Now, I'm thinking about fuzzing and syzkaller's requirements. Remember that Section 4 focuses on specific feature logic and entry points. I should avoid ubiquitous functions and target specific logic. The question is: are static functions in `.c` files targetable? Yes, it seems they have local symbols. The compiler does *not* inline non-inline static functions. So, focusing on the ones which are non-static and callbacks is key.

Focusing on the `.c` files, here are the crucial functions that I should pass to the fuzzer (the ones that are NOT static or struct_ops callbacks):
In `block/blk-iocost-bpf.c`:
*   `ioc_bpf_eject` (exported)
*   `ioc_bpf_deliver_iocg_callbacks`
*   `ioc_bpf_attach` (called by bpf_iocost_reg)
*   `ioc_bpf_detach` (called by bpf_iocost_unreg)

In `block/blk-iocost.c`:
*   `ioc_cost_model_write` (cgroup sysfs write handler for `io.cost.model`)
*   `ioc_cost_model_prfill` (cgroup sysfs read handler for `io.cost.model`)
*   `ioc_pd_online` (blkcg_policy pd_online callback)
*   `ioc_pd_free` (blkcg_policy pd_free callback)
*   `blk_iocost_init` (now non-static exported to `blk-iocost-bpf.c`)
*   `ioc_rqos_exit` (caller of `ioc_bpf_eject`)

Also, I should explore if `calc_vtime_cost` is static and where it's called.



26/2 2026/10/29 02:08 tool grepper
0m Args:
{
  "Expression": "calc_vtime_cost",
  "PathPrefixes": [
    "block/blk-iocost.c"
  ]
}

Results:
{
  "Output": "block/blk-iocost.c=2080=static u64 adjust_inuse_and_calc_cost(struct ioc_gq *iocg, u64 vtime,\n--\nblock/blk-iocost.c-2140-\nblock/blk-iocost.c:2141:static void calc_vtime_cost_builtin(struct bio *bio, struct ioc_gq *iocg,\nblock/blk-iocost.c-2142-\t\t\t\t    bool is_merge, u64 *costp)\n--\nblock/blk-iocost.c-2195-\nblock/blk-iocost.c:2196:static u64 calc_vtime_cost(struct bio *bio, struct ioc_gq *iocg, bool is_merge)\nblock/blk-iocost.c-2197-{\n--\nblock/blk-iocost.c-2200-\tif (!ioc_model_calc_cost(iocg-\u003eioc, bio, is_merge, \u0026cost))\nblock/blk-iocost.c:2201:\t\tcalc_vtime_cost_builtin(bio, iocg, is_merge, \u0026cost);\nblock/blk-iocost.c-2202-\n--\nblock/blk-iocost.c=2206=static void calc_size_vtime_cost_builtin(struct request *rq, struct ioc *ioc,\n--\nblock/blk-iocost.c-2226- * requests, where no ioc-\u003elock is held; the model pointer is read\nblock/blk-iocost.c:2227: * under RCU, matching the bio-side calc_vtime_cost().\nblock/blk-iocost.c-2228- */\n--\nblock/blk-iocost.c=2322=static void ioc_rqos_throttle(struct rq_qos *rqos, struct bio *bio)\n--\nblock/blk-iocost.c-2338-\t/* calculate the absolute vtime cost */\nblock/blk-iocost.c:2339:\tabs_cost = calc_vtime_cost(bio, iocg, false);\nblock/blk-iocost.c-2340-\tif (!abs_cost)\n--\nblock/blk-iocost.c=2413=static void ioc_rqos_merge(struct rq_qos *rqos, struct request *rq,\n--\nblock/blk-iocost.c-2426-\nblock/blk-iocost.c:2427:\tabs_cost = calc_vtime_cost(bio, iocg, true);\nblock/blk-iocost.c-2428-\tif (!abs_cost)\n"
}

27/2 2026/10/29 02:08 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 55415
							output: 374
							thoughts: 2131
						

Thoughts:
**Fuzzing Candidate Assessment: Block IO Cost with BPF Struct_Ops**

Okay, so I've been digging into this patch. It looks like it's introducing a new BPF struct_ops interface (`iocost_model_ops`) for the block I/O cost accounting, specifically within the cgroup v2 context. This allows userspace BPF programs to dictate how I/O requests are priced, which is pretty significant. The key functions I need to focus on are: `ioc_bpf_attach`, `ioc_bpf_detach`, `ioc_bpf_eject`, `ioc_bpf_deliver_iocg_callbacks`, `bpf_iocost_reg`, `bpf_iocost_unreg`, `bpf_iocost_validate`, `ioc_cost_model_write`, `ioc_pd_online`, and `ioc_pd_free`. Functions `calc_vtime_cost` and `calc_size_vtime_cost` and their call sites are also relevant.

The code's got some complex synchronization going on, specifically with multiple locks (including `rq_qos_mutex`, `blkcg_mutex`, `queue_lock`, `ioc->lock`), RCU reads with potential races, and lifecycle events such as device removal and cgroup deletion. I see `ioc_bpf_attach` and `ioc_bpf_detach` taking multiple locks, and `ioc_bpf_eject` clearing fields under a lock. There are lockdep asserts within `ioc_bpf_deliver_iocg_callbacks`, and potential deadlocks lurking between these locks. Furthermore, I'm concerned about races between the BPF link unregistration/close, disk removal, cgroup deletion, and concurrent I/O.

These are accessible via `bpf()` syscall and sysfs/cgroupfs writes (`io.cost.model`, `io.cost.qos`), and block I/O syscalls. I'm seeing a clear opening here for fuzzing: a new interface, complex locking, user-space interaction, and potential race conditions. The presence of those lockdep assertions is a big red flag – they are screaming for fuzzing coverage.

The config options I'll need to enable are: `BLK_CGROUP_IOCOST`, `BLK_CGROUP_IOCOST_BPF`, `BPF_SYSCALL`, `BPF_JIT`, `DEBUG_INFO_BTF`, and `BLK_CGROUP`.

This looks like a solid candidate for syzkaller. I'll include the suggested FocusSymbols in the config.



28/2 2026/10/29 02:08 tool set-results
0m Args:
{
  "EnableConfigs": [
    "BLK_CGROUP_IOCOST",
    "BLK_CGROUP_IOCOST_BPF",
    "BPF_SYSCALL",
    "BPF_JIT",
    "DEBUG_INFO_BTF",
    "BLK_CGROUP"
  ],
  "FocusSymbols": [
    "ioc_bpf_attach",
    "ioc_bpf_detach",
    "ioc_bpf_eject",
    "ioc_bpf_deliver_iocg_callbacks",
    "bpf_iocost_reg",
    "bpf_iocost_unreg",
    "bpf_iocost_validate",
    "ioc_cost_model_write",
    "ioc_pd_online",
    "ioc_pd_free",
    "calc_vtime_cost",
    "calc_size_vtime_cost"
  ],
  "Reasoning": "The patch adds a new BPF struct_ops type (iocost_model_ops) allowing userspace BPF programs to dynamically implement pluggable cost models for the blk-iocost cgroup IO controller. The implementation introduces attach, detach, and eject lifecycles with intricate lock orchestration across rq_qos_mutex, blkcg_mutex, queue_lock, and ioc-\u003elock, plus lockdep assertions and RCU dereferencing during I/O submission/completion pricing paths. The code is reachable through standard syscalls (bpf syscall for struct_ops link registration, cgroupfs writes to io.cost.model, block I/O, and device removal), making it well-suited for syzkaller fuzzing to identify potential deadlocks, refcounting issues, or lifecycle races.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "BLK_CGROUP_IOCOST",
    "BLK_CGROUP_IOCOST_BPF",
    "BPF_SYSCALL",
    "BPF_JIT",
    "DEBUG_INFO_BTF",
    "BLK_CGROUP"
  ],
  "FocusSymbols": [
    "ioc_bpf_attach",
    "ioc_bpf_detach",
    "ioc_bpf_eject",
    "ioc_bpf_deliver_iocg_callbacks",
    "bpf_iocost_reg",
    "bpf_iocost_unreg",
    "bpf_iocost_validate",
    "ioc_cost_model_write",
    "ioc_pd_online",
    "ioc_pd_free",
    "calc_vtime_cost",
    "calc_size_vtime_cost"
  ],
  "Reasoning": "The patch adds a new BPF struct_ops type (iocost_model_ops) allowing userspace BPF programs to dynamically implement pluggable cost models for the blk-iocost cgroup IO controller. The implementation introduces attach, detach, and eject lifecycles with intricate lock orchestration across rq_qos_mutex, blkcg_mutex, queue_lock, and ioc-\u003elock, plus lockdep assertions and RCU dereferencing during I/O submission/completion pricing paths. The code is reachable through standard syscalls (bpf syscall for struct_ops link registration, cgroupfs writes to io.cost.model, block I/O, and device removal), making it well-suited for syzkaller fuzzing to identify potential deadlocks, refcounting issues, or lifecycle races.",
  "WorthFuzzing": true
}

29/1 2026/10/29 02:08 action If
1m Args:
{
  "WorthFuzzing": true
}

Results:
null

30/2 2026/10/29 02:08 agent kmsan-evaluator
1m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch series introduces BPF struct_ops support (`iocost_model_ops`) for pluggable cost models in the blk-iocost controller, along with cgroup v2 control/query integration, queue freeze/quiesce handling, an iocost tick tracepoint (`iocost_ioc_tick`), and BPF selftests.\n\nAnalysis regarding KMSAN applicability:\n1. No uninitialized memory or info-leak risks:\n   - All newly added struct members in `struct ioc` (`attached`, `model`, `bpf_link`) and `struct ioc_gq` (`bpf_iocg_inited`) reside in structures allocated using zeroing allocators (`kzalloc_obj` in `blk_iocost_init` and `kzalloc_node` in `ioc_pd_alloc`).\n   - Local variables in modified functions (e.g., `new_model`, `model_write` in `ioc_cost_model_write`, `cost` in `calc_vtime_cost` and `calc_size_vtime_cost`, `nr_active` and `now` in `ioc_timer_fn`) are explicitly initialized before any read.\n   - The tracepoint `iocost_ioc_tick` populates each TP_STRUCT__entry field explicitly from initialized state.\n   - No kernel data structures or uninitialized paddings are copied to userspace via `copy_to_user`, `put_user`, socket options, or netlink; cgroup file readbacks use `seq_printf` with static string literals.\n2. Bugs introduced by this patch are domain-specific to locking, RCU, and object lifetimes:\n   - Complex lock hierarchy (`rq_qos_mutex`, `blkcg_mutex`, `queue_lock`, `ioc-\u003elock`), queue freezing/quiescing, reference counting (`bpf_struct_ops_get`/`put`, `blkdev_get_no_open`/`blkdev_put_no_open`), and RCU dereferencing.\n   - Any bugs here (e.g., use-after-free, deadlocks, NULL pointer dereferences, or lock order inversions) are detected by KASAN and LOCKDEP.\n\nBecause there are no uninitialized memory access or info-leak risks, a dedicated KMSAN fuzzing session is not warranted.",
  "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 4aad694db0f87849c37acd272fd8ad3abb1e16a7
Author: syz-cluster <triage@syzkaller.com>
Date:   Thu Oct 29 02:07:29 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 7e00a051382fb7..439b83dd3f6aa9 100644
--- a/Documentation/admin-guide/cgroup-v2.rst
+++ b/Documentation/admin-guide/cgroup-v2.rst
@@ -2056,8 +2056,9 @@ IO Interface Files
 	currently implements "io.weight" proportional control.  Lines
 	are keyed by $MAJ:$MIN device numbers and not ordered.  The
 	line for a given device is populated on the first write for
-	the device on "io.cost.qos" or "io.cost.model".  The following
-	nested keys are defined.
+	the device on "io.cost.qos" or "io.cost.model", or when a BPF
+	cost model is attached to it.  The following nested keys are
+	defined.
 
 	  ======	=====================================
 	  enable	Weight-based control enable
@@ -2111,13 +2112,41 @@ IO Interface Files
 	implements "io.weight" proportional control.  Lines are keyed
 	by $MAJ:$MIN device numbers and not ordered.  The line for a
 	given device is populated on the first write for the device on
-	"io.cost.qos" or "io.cost.model".  The following nested keys
-	are defined.
+	"io.cost.qos" or "io.cost.model", or when a BPF cost model is
+	attached to it.  The following nested keys are defined.
 
-	  =====		================================
+	  =====		==========================================
 	  ctrl		"auto" or "user"
-	  model		The cost model in use - "linear"
-	  =====		================================
+	  model		The cost model in use - "linear" or "bpf"
+	  =====		==========================================
+
+	When CONFIG_BLK_CGROUP_IOCOST_BPF is enabled, a BPF cost
+	model can be bound to a device by attaching an
+	"iocost_model_ops" struct_ops carrying the whole disk's
+	major:minor in its "dev" member (a partition's major:minor is
+	rejected).  Attaching creates the controller if needed, like
+	an io.cost.model write does, switches the device's pricing to
+	the model and populates the device's line in this file and in
+	"io.cost.qos" if it did not exist yet.  Attaching fails with
+	-EBUSY if the device already has a model attached.  The
+	attached model prices IOs only while the controller is
+	enabled through "io.cost.qos"; attaching does not enable it.
+
+	While a model is attached, "model" selects between it and the
+	builtin model: "model=bpf" switches to the attached model and
+	"model=linear" switches back to the builtin model, and neither
+	detaches the struct_ops.
+
+	Only detaching removes the model, after which "model=bpf"
+	fails and the device prices with the builtin model again.
+	Device removal ejects the attached model as well, while the
+	struct_ops link remains until userspace destroys it.  "ctrl"
+	accepts only "auto" and "user" and never selects a model.  It
+	keeps describing the builtin coefficients, which take effect
+	again when switched back.  The automatic profile stepping does
+	not switch profiles while the BPF model is in use; as with
+	user-set parameters, the profile selected from the device
+	class still applies.
 
 	When "ctrl" is "auto", the kernel may change all parameters
 	dynamically.  When "ctrl" is set to "user" or any other
@@ -2125,7 +2154,8 @@ IO Interface Files
 	automatic changes are disabled.
 
 	When "model" is "linear", the following model parameters are
-	defined.
+	defined.  They remain readable and writable while "model" is
+	"bpf" but take effect only after switching back to "linear".
 
 	  =============	========================================
 	  [r|w]bps	The maximum sequential IO throughput
diff --git a/MAINTAINERS b/MAINTAINERS
index 801f964899ba79..3abe3a089215a2 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -6785,10 +6785,13 @@ T:	git git://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux.git
 F:	Documentation/admin-guide/cgroup-v1/blkio-controller.rst
 F:	block/bfq-cgroup.c
 F:	block/blk-cgroup.c
+F:	block/blk-iocost-bpf.c
 F:	block/blk-iocost.c
+F:	block/blk-iocost.h
 F:	block/blk-iolatency.c
 F:	block/blk-throttle.c
 F:	include/linux/blk-cgroup.h
+F:	include/trace/events/iocost.h
 
 CONTROL GROUP - CPUSET
 M:	Waiman Long <longman@redhat.com>
diff --git a/block/Kconfig b/block/Kconfig
index 70e4a66d941ff6..8eaa2a803b6178 100644
--- a/block/Kconfig
+++ b/block/Kconfig
@@ -229,6 +229,10 @@ config BLK_ERROR_INJECTION
 
 	  See Documentation/block/error-injection.rst for details.
 
+config BLK_CGROUP_IOCOST_BPF
+	def_bool y
+	depends on BLK_CGROUP_IOCOST && BPF_SYSCALL && BPF_JIT && DEBUG_INFO_BTF
+
 source "block/Kconfig.iosched"
 
 endif # BLOCK
diff --git a/block/Makefile b/block/Makefile
index e7bd320e3d6971..ee5cebeea006fa 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-iocost-bpf.c b/block/blk-iocost-bpf.c
new file mode 100644
index 00000000000000..8ff51c26fb253d
--- /dev/null
+++ b/block/blk-iocost-bpf.c
@@ -0,0 +1,464 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * blk-iocost: BPF struct_ops plumbing for pluggable cost models.
+ *
+ * Copyright (C) 2026 KylinSoft Corporation.
+ *
+ * Registers the "iocost_model_ops" struct_ops type. Attachment is per-device:
+ * the target device is set in the ops from userspace before load, .reg
+ * attaches the model to that device, creating the ioc if needed and switching
+ * to the model with the queue frozen before rq_qos_mutex, like io.cost.qos
+ * writes, and .unreg detaches it; enabling and disabling the controller stays
+ * with io.cost.qos. The struct_ops core owns the program lifetime.
+ */
+#include <linux/init.h>
+#include <linux/kernel.h>
+#include <linux/module.h>
+#include <linux/bpf.h>
+#include <linux/bpf_verifier.h>
+#include <linux/btf.h>
+#include "blk-iocost.h"
+#include <linux/blk-mq.h>
+#include <linux/mutex.h>
+#include "blk.h"
+
+/*
+/*
+ * Deliver iocg_init()/iocg_free() to the cgroups already online on the
+ * queue: init walks q->blkg_list in reverse so parents receive it first,
+ * like blkcg_activate_policy(); free walks it forward like the blkcg
+ * policy teardown. The queue is frozen and quiesced; queue_lock
+ * serializes against blkg creation and blkcg_mutex against the delayed
+ * list removal in blkg destruction; the callbacks are called with
+ * ioc->lock held, the same lock the attachment updates take.
+ */
+static void ioc_bpf_deliver_iocg_callbacks(struct ioc *ioc,
+					   const struct iocost_model_ops *ops,
+					   bool init)
+{
+	struct request_queue *q = ioc->rqos.disk->queue;
+	struct blkcg_gq *blkg;
+
+	lockdep_assert_held(&q->blkcg_mutex);
+	lockdep_assert_held(&q->queue_lock);
+	lockdep_assert_held(&ioc->lock);
+
+	if (init) {
+		/* parents first, like blkcg_activate_policy() */
+		list_for_each_entry_reverse(blkg, &q->blkg_list, q_node) {
+			struct ioc_gq *iocg = blkg_to_iocg(blkg);
+
+			/*
+			 * A blkg which never went online never reached the
+			 * radix tree, so it must not receive an init either;
+			 * the attach runs under the same queue_lock as
+			 * blkg_create(), so pd->online is stable here. Any
+			 * previous attachment had its delivered flags cleared
+			 * before it went away, so none can still be set here.
+			 */
+			if (!iocg || !iocg->pd.online)
+				continue;
+			if (ops->iocg_init) {
+				ops->iocg_init(blkg->blkcg, q);
+				iocg->bpf_iocg_inited = true;
+			}
+		}
+	} else {
+		list_for_each_entry(blkg, &q->blkg_list, q_node) {
+			struct ioc_gq *iocg = blkg_to_iocg(blkg);
+
+			if (!iocg || !iocg->bpf_iocg_inited)
+				continue;
+			if (ops->iocg_free)
+				ops->iocg_free(blkg->blkcg, q);
+			iocg->bpf_iocg_inited = false;
+		}
+	}
+}
+
+static int ioc_bpf_attach(struct iocost_model_ops *ops, struct bpf_link *link)
+{
+	struct block_device *bdev;
+	struct request_queue *q;
+	struct gendisk *disk;
+	struct ioc *ioc;
+	unsigned int memflags;
+	int ret;
+
+	bdev = blkdev_get_no_open(new_decode_dev(ops->dev), false);
+	if (!bdev)
+		return -ENODEV;
+	q = bdev->bd_queue;
+	disk = bdev->bd_disk;
+
+	if (bdev_is_partition(bdev)) {
+		blkdev_put_no_open(bdev);
+		return -EINVAL;
+	}
+	if (!queue_is_mq(q)) {
+		blkdev_put_no_open(bdev);
+		return -EOPNOTSUPP;
+	}
+
+	/*
+	 * The freeze is taken before rq_qos_mutex like ioc_qos_write() does;
+	 * holding the mutex from the disk_live() check through the model
+	 * switch keeps the ioc from being freed under us.
+	 */
+	memflags = blk_mq_freeze_queue(q);
+
+	mutex_lock(&q->rq_qos_mutex);
+
+	if (!disk_live(disk)) {
+		mutex_unlock(&q->rq_qos_mutex);
+		blk_mq_unfreeze_queue(q, memflags);
+		blkdev_put_no_open(bdev);
+		return -ENODEV;
+	}
+	ioc = q_to_ioc(q);
+	if (!ioc) {
+		ret = blk_iocost_init(disk);
+		if (ret) {
+			mutex_unlock(&q->rq_qos_mutex);
+			blk_mq_unfreeze_queue(q, memflags);
+			blkdev_put_no_open(bdev);
+			return ret;
+		}
+		ioc = q_to_ioc(q);
+	}
+
+	blk_mq_quiesce_queue(q);
+
+	/*
+	 * Scope the mutex so the tail bdev put runs with blkcg_mutex
+	 * already released: dropping the last device reference can
+	 * reach disk_release() -> blkcg_exit_disk() ->
+	 * blkg_destroy_all(), which takes q->blkcg_mutex.
+	 */
+	{
+		guard(mutex)(&q->blkcg_mutex);
+		scoped_guard(spinlock_irqsave, &q->queue_lock) {
+			spin_lock(&ioc->lock);
+			ret = ioc_attached_model_locked(ioc) ? -EBUSY : 0;
+			if (!ret) {
+				/*
+				 * Take the map reference before the attachment
+				 * is published: the readers find the ops
+				 * through it. get() cannot fail while .reg
+				 * runs, as the core holds a map reference
+				 * then, but check it anyway; on failure leave
+				 * with no attachment set.
+				 */
+				if (!bpf_struct_ops_get(ops)) {
+					ret = -ENODEV;
+				} else {
+					rcu_assign_pointer(ioc->attached, ops);
+					rcu_assign_pointer(ioc->model, ops);
+					ioc->bpf_link = link;
+
+					/* pair iocg_init() with the cgroups online */
+					ioc_bpf_deliver_iocg_callbacks(ioc, ops,
+								       true);
+				}
+			}
+			spin_unlock(&ioc->lock);
+		}
+	}
+
+	blk_mq_unquiesce_queue(q);
+	blk_mq_unfreeze_queue(q, memflags);
+	mutex_unlock(&q->rq_qos_mutex);
+	blkdev_put_no_open(bdev);
+	return ret;
+}
+
+/*
+ * Detach a model: switch back to the builtin model when the attached model is
+ * in use, clear the attachment and deliver iocg_free() to the cgroups which
+ * still exist, under the same freeze and quiesce as the attach.
+ */
+static void ioc_bpf_detach(struct iocost_model_ops *ops, struct bpf_link *link)
+{
+	struct block_device *bdev;
+	struct request_queue *q;
+	struct ioc *ioc;
+	bool matched;
+	unsigned int memflags;
+
+	/*
+	 * A failed lookup means the device is gone; the removal ejection will
+	 * detach the model and drop the map reference when rq_qos_exit() runs,
+	 * so there is nothing to do here.
+	 */
+	bdev = blkdev_get_no_open(new_decode_dev(ops->dev), false);
+	if (!bdev)
+		return;
+	q = bdev->bd_queue;
+
+	/*
+	 * The attachment is checked under rq_qos_mutex first, so an unmatched
+	 * detach exits without freezing.
+	 */
+	mutex_lock(&q->rq_qos_mutex);
+	spin_lock_irq(&q->queue_lock);
+	ioc = q_to_ioc(q);
+	if (ioc) {
+		spin_lock(&ioc->lock);
+		matched = ioc_attached_model_locked(ioc) == ops &&
+			  ioc->bpf_link == link;
+		spin_unlock(&ioc->lock);
+	} else {
+		matched = false;
+	}
+	spin_unlock_irq(&q->queue_lock);
+	mutex_unlock(&q->rq_qos_mutex);
+	if (!matched) {
+		blkdev_put_no_open(bdev);
+		return;
+	}
+
+	/* the freeze is taken before rq_qos_mutex like ioc_qos_write() */
+	memflags = blk_mq_freeze_queue(q);
+
+	mutex_lock(&q->rq_qos_mutex);
+
+	/*
+	 * Re-check under the mutex before quiescing: the freeze itself does
+	 * not touch the tag set, and the removal ejection holds rq_qos_mutex
+	 * before the driver frees the tag set, so the check passing here means
+	 * the tag set is still alive.
+	 */
+	spin_lock_irq(&q->queue_lock);
+	ioc = q_to_ioc(q);
+	if (ioc) {
+		spin_lock(&ioc->lock);
+		matched = ioc_attached_model_locked(ioc) == ops &&
+			  ioc->bpf_link == link;
+		spin_unlock(&ioc->lock);
+	} else {
+		matched = false;
+	}
+	spin_unlock_irq(&q->queue_lock);
+	if (!matched) {
+		mutex_unlock(&q->rq_qos_mutex);
+		blk_mq_unfreeze_queue(q, memflags);
+		blkdev_put_no_open(bdev);
+		return;
+	}
+
+	blk_mq_quiesce_queue(q);
+
+	/*
+	 * Scope the mutex so the tail bdev put runs with blkcg_mutex
+	 * already released: dropping the last device reference can
+	 * reach disk_release() -> blkcg_exit_disk() ->
+	 * blkg_destroy_all(), which takes q->blkcg_mutex.
+	 */
+	{
+		guard(mutex)(&q->blkcg_mutex);
+		scoped_guard(spinlock_irqsave, &q->queue_lock) {
+			spin_lock(&ioc->lock);
+			if (ioc_bpf_model_locked(ioc) == ops)
+				rcu_assign_pointer(ioc->model, NULL);
+			rcu_assign_pointer(ioc->attached, NULL);
+			ioc->bpf_link = NULL;
+
+			ioc_bpf_deliver_iocg_callbacks(ioc, ops, false);
+			spin_unlock(&ioc->lock);
+		}
+	}
+
+	blk_mq_unquiesce_queue(q);
+	blk_mq_unfreeze_queue(q, memflags);
+	mutex_unlock(&q->rq_qos_mutex);
+
+	blkdev_put_no_open(bdev);
+	bpf_struct_ops_put(ops);
+}
+
+/*
+ * Eject the model on device removal. The caller holds rq_qos_mutex and
+ * blkcg_deactivate_policy() has already run, so every existing blkg got
+ * iocg_free() from ioc_pd_free() and no walk is needed. The ioc is freed right
+ * after, so clearing the pointers and dropping the map reference is all that
+ * is left to do.
+ */
+void ioc_bpf_eject(struct ioc *ioc)
+{
+	const struct iocost_model_ops *ops;
+	unsigned long flags;
+
+	spin_lock_irqsave(&ioc->lock, flags);
+	ops = ioc_attached_model_locked(ioc);
+	if (ops) {
+		rcu_assign_pointer(ioc->attached, NULL);
+		if (ioc_bpf_model_locked(ioc) == ops)
+			rcu_assign_pointer(ioc->model, NULL);
+		ioc->bpf_link = NULL;
+	}
+	spin_unlock_irqrestore(&ioc->lock, flags);
+
+	if (ops)
+		bpf_struct_ops_put(ops);
+}
+
+/* nothing to look up: the core finds the struct by name before calling */
+static int bpf_iocost_model_init(struct btf *btf)
+{
+	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)
+{
+	/* every callback runs under RCU read lock or a spinlock */
+	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) {
+	/*
+	 * The struct_ops core rejects a nonzero userspace value for
+	 * non-function members this callback does not claim.
+	 */
+	case offsetof(struct iocost_model_ops, dev):
+		ops->dev = uops->dev;
+		return 1;
+	case offsetof(struct iocost_model_ops, read_vtime_per_page):
+		ops->read_vtime_per_page = uops->read_vtime_per_page;
+		return 1;
+	case offsetof(struct iocost_model_ops, write_vtime_per_page):
+		ops->write_vtime_per_page = uops->write_vtime_per_page;
+		return 1;
+	}
+
+	return 0;
+}
+
+/*
+ * A complete model prices every charged IO and carries both transfer
+ * coefficients; a missing calc_cost would be a NULL call from the
+ * submission path and missing coefficients would silently zero the
+ * completion-time sizing (see ioc_rqos_done()), so the model is
+ * rejected before it can be registered. iocg_init() and iocg_free()
+ * must come in pairs too: a model implementing only one of them would
+ * build per-cgroup state that nothing ever tears down.
+ */
+static bool iocost_model_complete(const struct iocost_model_ops *ops)
+{
+	return ops->calc_cost && ops->read_vtime_per_page &&
+	       ops->write_vtime_per_page &&
+	       !!ops->iocg_init == !!ops->iocg_free;
+}
+
+/*
+ * 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, and missing coefficients read as zero. This is
+ * reached from the map-update path of both map flavors, before the model can
+ * be registered.
+ */
+static int bpf_iocost_validate(void *kdata)
+{
+	struct iocost_model_ops *ops = kdata;
+
+	/*
+	 * Bound the transfer coefficients so that coefficient * pages cannot
+	 * wrap u64 for any possible request size.
+	 */
+	if (ops->read_vtime_per_page > (VTIME_PER_SEC >> IOC_SECT_TO_PAGE_SHIFT) ||
+	    ops->write_vtime_per_page > (VTIME_PER_SEC >> IOC_SECT_TO_PAGE_SHIFT))
+		return -EINVAL;
+
+	return iocost_model_complete(ops) ? 0 : -EINVAL;
+}
+
+static int bpf_iocost_reg(void *kdata, struct bpf_link *link)
+{
+	struct iocost_model_ops *ops = kdata;
+
+	/* validate() has run by now; only the device is left to check */
+	if (!ops->dev)
+		return -EINVAL;
+
+	return ioc_bpf_attach(ops, link);
+}
+
+static void bpf_iocost_unreg(void *kdata, struct bpf_link *link)
+{
+	struct iocost_model_ops *ops = kdata;
+
+	/* a gone device is handled inside ioc_bpf_detach() */
+	ioc_bpf_detach(ops, link);
+}
+
+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(struct bio *bio, u64 flags)
+{
+	return 0;
+}
+
+static void bpf_iocost_iocg_init_stub(struct blkcg *blkcg,
+				      struct request_queue *q)
+{ }
+static void bpf_iocost_iocg_free_stub(struct blkcg *blkcg,
+				      struct request_queue *q)
+{ }
+
+static struct iocost_model_ops __bpf_ops_iocost_model_ops = {
+	.calc_cost = bpf_iocost_calc_cost_stub,
+	.iocg_init = bpf_iocost_iocg_init_stub,
+	.iocg_free = bpf_iocost_iocg_free_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 a81488c755cabf..9f7f5e5f0ebb7d 100644
--- a/block/blk-iocost.c
+++ b/block/blk-iocost.c
@@ -184,6 +184,7 @@
 #include "blk-stat.h"
 #include "blk-wbt.h"
 #include "blk-cgroup.h"
+#include "blk-iocost.h"
 
 #ifdef CONFIG_TRACEPOINTS
 
@@ -209,374 +210,6 @@ static char trace_iocg_path[TRACE_IOCG_PATH_LEN];
 #define TRACE_IOCG_PATH(type, iocg, ...)	do { } while (0)
 #endif	/* CONFIG_TRACE_POINTS */
 
-enum {
-	MILLION			= 1000000,
-
-	/* timer period is calculated from latency requirements, bound it */
-	MIN_PERIOD		= USEC_PER_MSEC,
-	MAX_PERIOD		= USEC_PER_SEC,
-
-	/*
-	 * iocg->vtime is targeted at 50% behind the device vtime, which
-	 * serves as its IO credit buffer.  Surplus weight adjustment is
-	 * immediately canceled if the vtime margin runs below 10%.
-	 */
-	MARGIN_MIN_PCT		= 10,
-	MARGIN_LOW_PCT		= 20,
-	MARGIN_TARGET_PCT	= 50,
-
-	INUSE_ADJ_STEP_PCT	= 25,
-
-	/* Have some play in timer operations */
-	TIMER_SLACK_PCT		= 1,
-
-	/* 1/64k is granular enough and can easily be handled w/ u32 */
-	WEIGHT_ONE		= 1 << 16,
-};
-
-enum {
-	/*
-	 * As vtime is used to calculate the cost of each IO, it needs to
-	 * be fairly high precision.  For example, it should be able to
-	 * represent the cost of a single page worth of discard with
-	 * suffificient accuracy.  At the same time, it should be able to
-	 * represent reasonably long enough durations to be useful and
-	 * convenient during operation.
-	 *
-	 * 1s worth of vtime is 2^37.  This gives us both sub-nanosecond
-	 * granularity and days of wrap-around time even at extreme vrates.
-	 */
-	VTIME_PER_SEC_SHIFT	= 37,
-	VTIME_PER_SEC		= 1LLU << VTIME_PER_SEC_SHIFT,
-	VTIME_PER_USEC		= VTIME_PER_SEC / USEC_PER_SEC,
-	VTIME_PER_NSEC		= VTIME_PER_SEC / NSEC_PER_SEC,
-
-	/* bound vrate adjustments within two orders of magnitude */
-	VRATE_MIN_PPM		= 10000,	/* 1% */
-	VRATE_MAX_PPM		= 100000000,	/* 10000% */
-
-	VRATE_MIN		= VTIME_PER_USEC * VRATE_MIN_PPM / MILLION,
-	VRATE_CLAMP_ADJ_PCT	= 4,
-
-	/* switch iff the conditions are met for longer than this */
-	AUTOP_CYCLE_NSEC	= 10LLU * NSEC_PER_SEC,
-};
-
-enum {
-	/* if IOs end up waiting for requests, issue less */
-	RQ_WAIT_BUSY_PCT	= 5,
-
-	/* unbusy hysterisis */
-	UNBUSY_THR_PCT		= 75,
-
-	/*
-	 * The effect of delay is indirect and non-linear and a huge amount of
-	 * future debt can accumulate abruptly while unthrottled. Linearly scale
-	 * up delay as debt is going up and then let it decay exponentially.
-	 * This gives us quick ramp ups while delay is accumulating and long
-	 * tails which can help reducing the frequency of debt explosions on
-	 * unthrottle. The parameters are experimentally determined.
-	 *
-	 * The delay mechanism provides adequate protection and behavior in many
-	 * cases. However, this is far from ideal and falls shorts on both
-	 * fronts. The debtors are often throttled too harshly costing a
-	 * significant level of fairness and possibly total work while the
-	 * protection against their impacts on the system can be choppy and
-	 * unreliable.
-	 *
-	 * The shortcoming primarily stems from the fact that, unlike for page
-	 * cache, the kernel doesn't have well-defined back-pressure propagation
-	 * mechanism and policies for anonymous memory. Fully addressing this
-	 * issue will likely require substantial improvements in the area.
-	 */
-	MIN_DELAY_THR_PCT	= 500,
-	MAX_DELAY_THR_PCT	= 25000,
-	MIN_DELAY		= 250,
-	MAX_DELAY		= 250 * USEC_PER_MSEC,
-
-	/* halve debts if avg usage over 100ms is under 50% */
-	DFGV_USAGE_PCT		= 50,
-	DFGV_PERIOD		= 100 * USEC_PER_MSEC,
-
-	/* don't let cmds which take a very long time pin lagging for too long */
-	MAX_LAGGING_PERIODS	= 10,
-
-	/*
-	 * Count IO size in 4k pages.  The 12bit shift helps keeping
-	 * size-proportional components of cost calculation in closer
-	 * numbers of digits to per-IO cost components.
-	 */
-	IOC_PAGE_SHIFT		= 12,
-	IOC_PAGE_SIZE		= 1 << IOC_PAGE_SHIFT,
-	IOC_SECT_TO_PAGE_SHIFT	= IOC_PAGE_SHIFT - SECTOR_SHIFT,
-
-	/* if apart further than 16M, consider randio for linear model */
-	LCOEF_RANDIO_PAGES	= 4096,
-};
-
-enum ioc_running {
-	IOC_IDLE,
-	IOC_RUNNING,
-	IOC_STOP,
-};
-
-/* io.cost.qos controls including per-dev enable of the whole controller */
-enum {
-	QOS_ENABLE,
-	QOS_CTRL,
-	NR_QOS_CTRL_PARAMS,
-};
-
-/* io.cost.qos params */
-enum {
-	QOS_RPPM,
-	QOS_RLAT,
-	QOS_WPPM,
-	QOS_WLAT,
-	QOS_MIN,
-	QOS_MAX,
-	NR_QOS_PARAMS,
-};
-
-/* io.cost.model controls */
-enum {
-	COST_CTRL,
-	COST_MODEL,
-	NR_COST_CTRL_PARAMS,
-};
-
-/* builtin linear cost model coefficients */
-enum {
-	I_LCOEF_RBPS,
-	I_LCOEF_RSEQIOPS,
-	I_LCOEF_RRANDIOPS,
-	I_LCOEF_WBPS,
-	I_LCOEF_WSEQIOPS,
-	I_LCOEF_WRANDIOPS,
-	I_LCOEF_FLUSHIOPS,
-	NR_I_LCOEFS,
-};
-
-enum {
-	LCOEF_RPAGE,
-	LCOEF_RSEQIO,
-	LCOEF_RRANDIO,
-	LCOEF_WPAGE,
-	LCOEF_WSEQIO,
-	LCOEF_WRANDIO,
-	LCOEF_FLUSH,
-	NR_LCOEFS,
-};
-
-enum {
-	AUTOP_INVALID,
-	AUTOP_HDD,
-	AUTOP_SSD_QD1,
-	AUTOP_SSD_DFL,
-	AUTOP_SSD_FAST,
-};
-
-struct ioc_params {
-	u32				qos[NR_QOS_PARAMS];
-	u64				i_lcoefs[NR_I_LCOEFS];
-	u64				lcoefs[NR_LCOEFS];
-	u32				too_fast_vrate_pct;
-	u32				too_slow_vrate_pct;
-};
-
-struct ioc_margins {
-	s64				min;
-	s64				low;
-	s64				target;
-};
-
-struct ioc_missed {
-	local_t				nr_met;
-	local_t				nr_missed;
-	u32				last_met;
-	u32				last_missed;
-};
-
-struct ioc_pcpu_stat {
-	struct ioc_missed		missed[2];
-
-	local64_t			rq_wait_ns;
-	u64				last_rq_wait_ns;
-};
-
-/* per device */
-struct ioc {
-	struct rq_qos			rqos;
-
-	bool				enabled;
-
-	struct ioc_params		params;
-	struct ioc_margins		margins;
-	u32				period_us;
-	u32				timer_slack_ns;
-	u64				vrate_min;
-	u64				vrate_max;
-
-	spinlock_t			lock;
-	struct timer_list		timer;
-	struct list_head		active_iocgs;	/* active cgroups */
-	struct ioc_pcpu_stat __percpu	*pcpu_stat;
-
-	enum ioc_running		running;
-	atomic64_t			vtime_rate;
-	u64				vtime_base_rate;
-	s64				vtime_err;
-
-	seqcount_spinlock_t		period_seqcount;
-	u64				period_at;	/* wallclock starttime */
-	u64				period_at_vtime; /* vtime starttime */
-
-	atomic64_t			cur_period;	/* inc'd each period */
-	int				busy_level;	/* saturation history */
-
-	bool				weights_updated;
-	atomic_t			hweight_gen;	/* for lazy hweights */
-
-	/* debt forgivness */
-	u64				dfgv_period_at;
-	u64				dfgv_period_rem;
-	u64				dfgv_usage_us_sum;
-
-	u64				autop_too_fast_at;
-	u64				autop_too_slow_at;
-	int				autop_idx;
-	bool				user_qos_params:1;
-	bool				user_cost_model:1;
-};
-
-struct iocg_pcpu_stat {
-	local64_t			abs_vusage;
-};
-
-struct iocg_stat {
-	u64				usage_us;
-	u64				wait_us;
-	u64				indebt_us;
-	u64				indelay_us;
-};
-
-/* per device-cgroup pair */
-struct ioc_gq {
-	struct blkg_policy_data		pd;
-	struct ioc			*ioc;
-
-	/*
-	 * A iocg can get its weight from two sources - an explicit
-	 * per-device-cgroup configuration or the default weight of the
-	 * cgroup.  `cfg_weight` is the explicit per-device-cgroup
-	 * configuration.  `weight` is the effective considering both
-	 * sources.
-	 *
-	 * When an idle cgroup becomes active its `active` goes from 0 to
-	 * `weight`.  `inuse` is the surplus adjusted active weight.
-	 * `active` and `inuse` are used to calculate `hweight_active` and
-	 * `hweight_inuse`.
-	 *
-	 * `last_inuse` remembers `inuse` while an iocg is idle to persist
-	 * surplus adjustments.
-	 *
-	 * `inuse` may be adjusted dynamically during period. `saved_*` are used
-	 * to determine and track adjustments.
-	 */
-	u32				cfg_weight;
-	u32				weight;
-	u32				active;
-	u32				inuse;
-
-	u32				last_inuse;
-	s64				saved_margin;
-
-	sector_t			cursor;		/* to detect randio */
-
-	/*
-	 * `vtime` is this iocg's vtime cursor which progresses as IOs are
-	 * issued.  If lagging behind device vtime, the delta represents
-	 * the currently available IO budget.  If running ahead, the
-	 * overage.
-	 *
-	 * `vtime_done` is the same but progressed on completion rather
-	 * than issue.  The delta behind `vtime` represents the cost of
-	 * currently in-flight IOs.
-	 */
-	atomic64_t			vtime;
-	atomic64_t			done_vtime;
-	u64				abs_vdebt;
-
-	/* current delay in effect and when it started */
-	u64				delay;
-	u64				delay_at;
-
-	/*
-	 * The period this iocg was last active in.  Used for deactivation
-	 * and invalidating `vtime`.
-	 */
-	atomic64_t			active_period;
-	struct list_head		active_list;
-
-	/* see __propagate_weights() and current_hweight() for details */
-	u64				child_active_sum;
-	u64				child_inuse_sum;
-	u64				child_adjusted_sum;
-	int				hweight_gen;
-	u32				hweight_active;
-	u32				hweight_inuse;
-	u32				hweight_donating;
-	u32				hweight_after_donation;
-
-	struct list_head		walk_list;
-	struct list_head		surplus_list;
-
-	struct wait_queue_head		waitq;
-	struct hrtimer			waitq_timer;
-
-	/* timestamp at the latest activation */
-	u64				activated_at;
-
-	/* statistics */
-	struct iocg_pcpu_stat __percpu	*pcpu_stat;
-	struct iocg_stat		stat;
-	struct iocg_stat		last_stat;
-	u64				last_stat_abs_vusage;
-	u64				usage_delta_us;
-	u64				wait_since;
-	u64				indebt_since;
-	u64				indelay_since;
-
-	/* this iocg's depth in the hierarchy and ancestors including self */
-	int				level;
-	struct ioc_gq			*ancestors[];
-};
-
-/* per cgroup */
-struct ioc_cgrp {
-	struct blkcg_policy_data	cpd;
-	unsigned int			dfl_weight;
-};
-
-struct ioc_now {
-	u64				now_ns;
-	u64				now;
-	u64				vnow;
-};
-
-struct iocg_wait {
-	struct wait_queue_entry		wait;
-	struct bio			*bio;
-	u64				abs_cost;
-	bool				committed;
-};
-
-struct iocg_wake_ctx {
-	struct ioc_gq			*iocg;
-	u32				hw_inuse;
-	s64				vbudget;
-};
-
 static const struct ioc_params autop[] = {
 	[AUTOP_HDD] = {
 		.qos				= {
@@ -656,49 +289,6 @@ static const u32 vrate_adj_pct[] =
 	  2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
 	  4, 4, 4, 4, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8, 16 };
 
-static struct blkcg_policy blkcg_policy_iocost;
-
-/* accessors and helpers */
-static struct ioc *rqos_to_ioc(struct rq_qos *rqos)
-{
-	return container_of(rqos, struct ioc, rqos);
-}
-
-static struct ioc *q_to_ioc(struct request_queue *q)
-{
-	return rqos_to_ioc(rq_qos_id(q, RQ_QOS_COST));
-}
-
-static const char __maybe_unused *ioc_name(struct ioc *ioc)
-{
-	struct gendisk *disk = ioc->rqos.disk;
-
-	if (!disk)
-		return "<unknown>";
-	return disk->disk_name;
-}
-
-static struct ioc_gq *pd_to_iocg(struct blkg_policy_data *pd)
-{
-	return pd ? container_of(pd, struct ioc_gq, pd) : NULL;
-}
-
-static struct ioc_gq *blkg_to_iocg(struct blkcg_gq *blkg)
-{
-	return pd_to_iocg(blkg_to_pd(blkg, &blkcg_policy_iocost));
-}
-
-static struct blkcg_gq *iocg_to_blkg(struct ioc_gq *iocg)
-{
-	return pd_to_blkg(&iocg->pd);
-}
-
-static struct ioc_cgrp *blkcg_to_iocc(struct blkcg *blkcg)
-{
-	return container_of(blkcg_to_cpd(blkcg, &blkcg_policy_iocost),
-			    struct ioc_cgrp, cpd);
-}
-
 /*
  * Scale @abs_cost to the inverse of @hw_inuse.  The lower the hierarchical
  * weight, the more expensive each IO.  Must round up.
@@ -805,8 +395,14 @@ static int ioc_autop_idx(struct ioc *ioc, struct gendisk *disk)
 	if (idx < AUTOP_SSD_DFL)
 		return AUTOP_SSD_DFL;
 
-	/* if user is overriding anything, maintain what was there */
-	if (ioc->user_qos_params || ioc->user_cost_model)
+	/*
+	 * If user is overriding anything, or a BPF model is in use, maintain
+	 * what was there: with a BPF model the builtin cost coefficients are
+	 * inert, and stepping the profile would change the builtin parameters
+	 * that apply again after switching back, for no benefit in between.
+	 */
+	if (ioc->user_qos_params || ioc->user_cost_model ||
+	    ioc_bpf_model_locked(ioc))
 		return idx;
 
 	/* step up/down based on the vrate */
@@ -2243,6 +1839,7 @@ static void ioc_timer_fn(struct timer_list *timer)
 	struct ioc_now now;
 	LIST_HEAD(surpluses);
 	int nr_debtors, nr_shortages = 0, nr_lagging = 0;
+	int nr_active = 0;
 	u64 usage_us_sum = 0;
 	u32 ppm_rthr;
 	u32 ppm_wthr;
@@ -2279,6 +1876,8 @@ static void ioc_timer_fn(struct timer_list *timer)
 		u64 vdone, vtime, usage_us;
 		u32 hw_active, hw_inuse;
 
+		nr_active++;
+
 		/*
 		 * Collect unused and wind vtime closer to vnow to prevent
 		 * iocgs from accumulating a large amount of budget.
@@ -2440,6 +2039,16 @@ static void ioc_timer_fn(struct timer_list *timer)
 
 	ioc->busy_level = clamp(ioc->busy_level, -1000, 1000);
 
+	/*
+	 * Everything the tick reports is final here: busy_level was just
+	 * computed, cur_period hasn't changed, nr_active and usage_us_sum are
+	 * complete, and vrate and period_us still hold the values this period
+	 * ran in. usage is wall time over wall time, summed over iocgs, and is
+	 * not capped at 100. Emit before the refresh below so the event reads
+	 * the completed period directly.
+	 */
+	trace_iocost_ioc_tick(ioc, &now, nr_active, usage_us_sum);
+
 	ioc_adjust_base_vrate(ioc, rq_wait_pct, nr_lagging, nr_shortages,
 			      prev_busy_level, missed_ppm);
 
@@ -2588,7 +2197,9 @@ static u64 calc_vtime_cost(struct bio *bio, struct ioc_gq *iocg, bool is_merge)
 {
 	u64 cost;
 
-	calc_vtime_cost_builtin(bio, iocg, is_merge, &cost);
+	if (!ioc_model_calc_cost(iocg->ioc, bio, is_merge, &cost))
+		calc_vtime_cost_builtin(bio, iocg, is_merge, &cost);
+
 	return cost;
 }
 
@@ -2610,11 +2221,19 @@ 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)
+/*
+ * Called from the request completion path for READ and WRITE
+ * requests, where no ioc->lock is held; the model pointer is read
+ * under RCU, matching the bio-side calc_vtime_cost().
+ */
+static u64 calc_size_vtime_cost(struct request *rq, struct ioc *ioc,
+				bool is_read)
 {
 	u64 cost;
 
-	calc_size_vtime_cost_builtin(rq, ioc, &cost);
+	if (!ioc_model_size_cost(ioc, rq, is_read, &cost))
+		calc_size_vtime_cost_builtin(rq, ioc, &cost);
+
 	return cost;
 }
 
@@ -2884,7 +2503,8 @@ static void ioc_rqos_done(struct rq_qos *rqos, struct request *rq)
 
 	on_q_ns = blk_time_get_ns() - rq->alloc_time_ns;
 	rq_wait_ns = rq->start_time_ns - rq->alloc_time_ns;
-	size_nsec = div64_u64(calc_size_vtime_cost(rq, ioc), VTIME_PER_NSEC);
+	size_nsec = div64_u64(calc_size_vtime_cost(rq, ioc, pidx == QOS_RLAT),
+			       VTIME_PER_NSEC);
 
 	ccs = get_cpu_ptr(ioc->pcpu_stat);
 
@@ -2920,6 +2540,10 @@ static void ioc_rqos_exit(struct rq_qos *rqos)
 
 	timer_shutdown_sync(&ioc->timer);
 	free_percpu(ioc->pcpu_stat);
+
+	/* eject the model on device removal */
+	ioc_bpf_eject(ioc);
+
 	kfree(ioc);
 }
 
@@ -2932,7 +2556,7 @@ static const struct rq_qos_ops ioc_rqos_ops = {
 	.exit = ioc_rqos_exit,
 };
 
-static int blk_iocost_init(struct gendisk *disk)
+int blk_iocost_init(struct gendisk *disk)
 {
 	struct ioc *ioc;
 	int i, cpu, ret;
@@ -3070,6 +2694,35 @@ static void ioc_pd_init(struct blkg_policy_data *pd)
 	spin_unlock_irqrestore(&ioc->lock, flags);
 }
 
+/*
+ * iocg_init() delivery for the attached model. blkg_create() calls this only
+ * after the blkg has been inserted into the radix tree and the queue's blkg
+ * list, so a blkg whose insertion failed is never seen here and the init/free
+ * pairing cannot be broken by a model switch in between; the caller holds
+ * queue_lock, the same lock the attachment updates are serialized with.
+ */
+static void ioc_pd_online(struct blkg_policy_data *pd)
+{
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	struct ioc_gq *iocg = pd_to_iocg(pd);
+	struct blkcg_gq *blkg = pd_to_blkg(pd);
+	struct ioc *ioc = iocg->ioc;
+	const struct iocost_model_ops *model;
+	unsigned long flags;
+
+	if (!ioc)
+		return;
+
+	spin_lock_irqsave(&ioc->lock, flags);
+	model = ioc_attached_model_locked(ioc);
+	if (model && model->iocg_init) {
+		model->iocg_init(blkg->blkcg, ioc->rqos.disk->queue);
+		iocg->bpf_iocg_inited = true;
+	}
+	spin_unlock_irqrestore(&ioc->lock, flags);
+#endif
+}
+
 static void iocg_release(struct rcu_head *rcu)
 {
 	struct blkg_policy_data *pd =
@@ -3090,6 +2743,25 @@ static void ioc_pd_free(struct blkg_policy_data *pd)
 	if (ioc) {
 		spin_lock_irqsave(&ioc->lock, flags);
 
+		/*
+		 * Gate the free on the delivered flag: a blkg which never went
+		 * online never received iocg_init(), and bios still holding
+		 * the blkg can be priced between its going offline and this
+		 * free, so iocg_free() follows pd_free() rather than
+		 * pd_offline.
+		 */
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+		if (iocg->bpf_iocg_inited) {
+			const struct iocost_model_ops *amodel =
+				ioc_attached_model_locked(ioc);
+
+			if (amodel && amodel->iocg_free)
+				amodel->iocg_free(blkg->blkcg,
+						  ioc->rqos.disk->queue);
+			iocg->bpf_iocg_inited = false;
+		}
+#endif
+
 		if (!list_empty(&iocg->active_list)) {
 			struct ioc_now now;
 
@@ -3150,7 +2822,6 @@ static u64 ioc_weight_prfill(struct seq_file *sf, struct blkg_policy_data *pd,
 	return 0;
 }
 
-
 static int ioc_weight_show(struct seq_file *sf, void *v)
 {
 	struct blkcg *blkcg = css_to_blkcg(seq_css(sf));
@@ -3453,16 +3124,19 @@ static u64 ioc_cost_model_prfill(struct seq_file *sf,
 	const char *dname = blkg_dev_name(pd->blkg);
 	struct ioc *ioc = pd_to_iocg(pd)->ioc;
 	u64 *u = ioc->params.i_lcoefs;
+	const struct iocost_model_ops *model;
 
 	if (!dname)
 		return 0;
 
 	spin_lock_irq(&ioc->lock);
-	seq_printf(sf, "%s ctrl=%s model=linear "
+	model = ioc_bpf_model_locked(ioc);
+	seq_printf(sf, "%s ctrl=%s model=%s "
 		   "rbps=%llu rseqiops=%llu rrandiops=%llu "
 		   "wbps=%llu wseqiops=%llu wrandiops=%llu "
 		   "flushiops=%llu\n",
 		   dname, ioc->user_cost_model ? "user" : "auto",
+		   model ? "bpf" : "linear",
 		   u[I_LCOEF_RBPS], u[I_LCOEF_RSEQIOPS], u[I_LCOEF_RRANDIOPS],
 		   u[I_LCOEF_WBPS], u[I_LCOEF_WSEQIOPS], u[I_LCOEF_WRANDIOPS],
 		   u[I_LCOEF_FLUSHIOPS]);
@@ -3507,6 +3181,10 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 	bool user;
 	char *body, *p;
 	int ret;
+	const struct iocost_model_ops *new_model = NULL;
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	bool model_write = false;
+#endif
 
 	blkg_conf_init(&ctx, input);
 
@@ -3559,9 +3237,30 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 			continue;
 		case COST_MODEL:
 			match_strlcpy(buf, &args[0], sizeof(buf));
-			if (strcmp(buf, "linear"))
-				goto unlock;
-			continue;
+			if (!strcmp(buf, "linear")) {
+				/*
+				 * Staged and committed below, so a parse
+				 * error later in the same write leaves the
+				 * model selection untouched.
+				 */
+				new_model = NULL;
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+				model_write = true;
+#endif
+				continue;
+			}
+			if (!strcmp(buf, "bpf")) {
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+				new_model = rcu_dereference_protected(
+						ioc->attached,
+						lockdep_is_held(&ioc->lock));
+				model_write = true;
+#endif
+				if (!new_model)
+					goto unlock;
+				continue;
+			}
+			goto unlock;
 		}
 
 		tok = match_token(p, i_lcoef_tokens, args);
@@ -3579,6 +3278,10 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
 	} else {
 		ioc->user_cost_model = false;
 	}
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	if (model_write)
+		rcu_assign_pointer(ioc->model, new_model);
+#endif
 	ioc_refresh_params(ioc, true);
 
 	ret = 0;
@@ -3616,12 +3319,13 @@ static struct cftype ioc_files[] = {
 	{}
 };
 
-static struct blkcg_policy blkcg_policy_iocost = {
+struct blkcg_policy blkcg_policy_iocost = {
 	.dfl_cftypes	= ioc_files,
 	.cpd_alloc_fn	= ioc_cpd_alloc,
 	.cpd_free_fn	= ioc_cpd_free,
 	.pd_alloc_fn	= ioc_pd_alloc,
 	.pd_init_fn	= ioc_pd_init,
+	.pd_online_fn	= ioc_pd_online,
 	.pd_free_fn	= ioc_pd_free,
 	.pd_stat_fn	= ioc_pd_stat,
 };
diff --git a/block/blk-iocost.h b/block/blk-iocost.h
new file mode 100644
index 00000000000000..6d62b4fd0c543d
--- /dev/null
+++ b/block/blk-iocost.h
@@ -0,0 +1,615 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * blk-iocost private definitions, shared between blk-iocost.c and
+ * blk-iocost-bpf.c. Not for direct inclusion by other files.
+ */
+#ifndef _BLK_IOCOST_H
+#define _BLK_IOCOST_H
+
+#include <linux/types.h>
+#include <linux/blk_types.h>
+#include <linux/blkdev.h>
+#include "blk-cgroup.h"
+#include <linux/blk-mq.h>
+#include <linux/timer.h>
+#include <linux/hrtimer.h>
+#include <linux/seqlock.h>
+#include <linux/atomic.h>
+#include <linux/minmax.h>
+#include <linux/time64.h>
+#include <linux/wait.h>
+#include <asm/local.h>
+#include <asm/local64.h>
+#include "blk-rq-qos.h"
+
+struct bpf_link;
+
+/*
+ * Pluggable cost model interface for blk-iocost.
+ *
+ * A BPF struct_ops implementation can take over the cost model of one device.
+ * The device is identified by the dev member, which is set from userspace
+ * before the program is loaded; the struct_ops core owns the program lifetime.
+ * Attaching creates the ioc if needed, like an io.cost.model write, and
+ * switches the device to the BPF model with the queue frozen before
+ * rq_qos_mutex, like an io.cost.qos write, and delivers iocg_init() to the
+ * cgroups which already exist on the device. Enabling and disabling the
+ * controller stays with io.cost.qos.
+ *
+ * While a model is attached, io.cost.model selects between it and the builtin
+ * model: "model=bpf" switches to the attached model and "model=linear" back to
+ * the builtin. Neither detaches the struct_ops; only detaching does. The
+ * builtin linear coefficients are kept while the BPF model is in use and take
+ * effect again when switched back.
+ *
+ * While in use, the BPF model prices every charged IO on the device, including
+ * flushes, from the bio charging path. calc_cost() is called from the IO
+ * submission path with RCU read lock held and must not sleep. It receives the
+ * bio itself so that the model can use what it needs (operation flags, size,
+ * sector, the issuing cgroup through bio->bi_blkg, which is guaranteed
+ * non-NULL) and returns the cost of the IO in vtime units, where 1 second
+ * of device time equals VTIME_PER_SEC (2^37,
+ * available to BPF programs through vmlinux.h). The return value is clamped to
+ * 1 second of device time per IO.
+ *
+ * The struct_ops also carries the transfer cost coefficients, vtime per page
+ * for reads and writes. While the BPF model is in use, they replace the
+ * builtin coefficients in the completion-time request sizing of READ and
+ * WRITE requests, with ZONE_APPEND counted as a write. Taking over the QoS
+ * side (latency tracking, vrate control) is left for later extensions.
+ *
+ * The cgroup callbacks are bound to the iocg policy lifetime, one (cgroup,
+ * device) pair per invocation. iocg_init() is delivered from ioc_pd_online()
+ * and on attach to the cgroups already online on the device; iocg_free() on
+ * detach to the cgroups which still exist then and at pd_free() time for the
+ * rest, so that init and free pair up exactly. iocg_free() is gated on a
+ * per-iocg delivered flag, as bios can still be priced between the blkg going
+ * offline and its free. Both callbacks are called with ioc->lock held and must
+ * not sleep; the delivery points nest inside queue_lock except for iocg_free()
+ * from ioc_pd_free() in blkg_free_workfn().
+ */
+
+/*
+ * Call metadata for calc_cost()'s model_flags; the merge indicator is not a
+ * property of the bio. An enum so that the value is exported through BTF and
+ * usable from vmlinux.h.
+ */
+enum {
+	IOCOST_COST_F_MERGE	= 1 << 0,	/* called from merge path */
+};
+
+struct iocost_model_ops {
+	/*
+	 * target device (major:minor), set from userspace before load
+	 * through the struct_ops map's initial value, in the userspace
+	 * dev_t encoding new_decode_dev() accepts
+	 */
+	dev_t dev;
+
+	/* vtime per page for the completion-time request sizing */
+	u64 read_vtime_per_page;
+	u64 write_vtime_per_page;
+
+	u64 (*calc_cost)(struct bio *bio, u64 model_flags);
+	void (*iocg_init)(struct blkcg *blkcg, struct request_queue *q);
+	void (*iocg_free)(struct blkcg *blkcg, struct request_queue *q);
+};
+
+enum {
+	MILLION			= 1000000,
+
+	/* timer period is calculated from latency requirements, bound it */
+	MIN_PERIOD		= USEC_PER_MSEC,
+	MAX_PERIOD		= USEC_PER_SEC,
+
+	/*
+	 * iocg->vtime is targeted at 50% behind the device vtime, which
+	 * serves as its IO credit buffer.  Surplus weight adjustment is
+	 * immediately canceled if the vtime margin runs below 10%.
+	 */
+	MARGIN_MIN_PCT		= 10,
+	MARGIN_LOW_PCT		= 20,
+	MARGIN_TARGET_PCT	= 50,
+
+	INUSE_ADJ_STEP_PCT	= 25,
+
+	/* Have some play in timer operations */
+	TIMER_SLACK_PCT		= 1,
+
+	/* 1/64k is granular enough and can easily be handled w/ u32 */
+	WEIGHT_ONE		= 1 << 16,
+};
+
+enum {
+	/*
+	 * As vtime is used to calculate the cost of each IO, it needs to
+	 * be fairly high precision.  For example, it should be able to
+	 * represent the cost of a single page worth of discard with
+	 * suffificient accuracy.  At the same time, it should be able to
+	 * represent reasonably long enough durations to be useful and
+	 * convenient during operation.
+	 *
+	 * 1s worth of vtime is 2^37.  This gives us both sub-nanosecond
+	 * granularity and days of wrap-around time even at extreme vrates.
+	 */
+	VTIME_PER_SEC_SHIFT	= 37,
+	VTIME_PER_SEC		= 1LLU << VTIME_PER_SEC_SHIFT,
+	VTIME_PER_USEC		= VTIME_PER_SEC / USEC_PER_SEC,
+	VTIME_PER_NSEC		= VTIME_PER_SEC / NSEC_PER_SEC,
+
+	/* bound vrate adjustments within two orders of magnitude */
+	VRATE_MIN_PPM		= 10000,	/* 1% */
+	VRATE_MAX_PPM		= 100000000,	/* 10000% */
+
+	VRATE_MIN		= VTIME_PER_USEC * VRATE_MIN_PPM / MILLION,
+	VRATE_CLAMP_ADJ_PCT	= 4,
+
+	/* switch iff the conditions are met for longer than this */
+	AUTOP_CYCLE_NSEC	= 10LLU * NSEC_PER_SEC,
+};
+
+enum {
+	/* if IOs end up waiting for requests, issue less */
+	RQ_WAIT_BUSY_PCT	= 5,
+
+	/* unbusy hysterisis */
+	UNBUSY_THR_PCT		= 75,
+
+	/*
+	 * The effect of delay is indirect and non-linear and a huge amount of
+	 * future debt can accumulate abruptly while unthrottled. Linearly scale
+	 * up delay as debt is going up and then let it decay exponentially.
+	 * This gives us quick ramp ups while delay is accumulating and long
+	 * tails which can help reducing the frequency of debt explosions on
+	 * unthrottle. The parameters are experimentally determined.
+	 *
+	 * The delay mechanism provides adequate protection and behavior in many
+	 * cases. However, this is far from ideal and falls shorts on both
+	 * fronts. The debtors are often throttled too harshly costing a
+	 * significant level of fairness and possibly total work while the
+	 * protection against their impacts on the system can be choppy and
+	 * unreliable.
+	 *
+	 * The shortcoming primarily stems from the fact that, unlike for page
+	 * cache, the kernel doesn't have well-defined back-pressure propagation
+	 * mechanism and policies for anonymous memory. Fully addressing this
+	 * issue will likely require substantial improvements in the area.
+	 */
+	MIN_DELAY_THR_PCT	= 500,
+	MAX_DELAY_THR_PCT	= 25000,
+	MIN_DELAY		= 250,
+	MAX_DELAY		= 250 * USEC_PER_MSEC,
+
+	/* halve debts if avg usage over 100ms is under 50% */
+	DFGV_USAGE_PCT		= 50,
+	DFGV_PERIOD		= 100 * USEC_PER_MSEC,
+
+	/* don't let cmds which take a very long time pin lagging for too long */
+	MAX_LAGGING_PERIODS	= 10,
+
+	/*
+	 * Count IO size in 4k pages.  The 12bit shift helps keeping
+	 * size-proportional components of cost calculation in closer
+	 * numbers of digits to per-IO cost components.
+	 */
+	IOC_PAGE_SHIFT		= 12,
+	IOC_PAGE_SIZE		= 1 << IOC_PAGE_SHIFT,
+	IOC_SECT_TO_PAGE_SHIFT	= IOC_PAGE_SHIFT - SECTOR_SHIFT,
+
+	/* if apart further than 16M, consider randio for linear model */
+	LCOEF_RANDIO_PAGES	= 4096,
+};
+
+enum ioc_running {
+	IOC_IDLE,
+	IOC_RUNNING,
+	IOC_STOP,
+};
+
+/* io.cost.qos controls including per-dev enable of the whole controller */
+enum {
+	QOS_ENABLE,
+	QOS_CTRL,
+	NR_QOS_CTRL_PARAMS,
+};
+
+/* io.cost.qos params */
+enum {
+	QOS_RPPM,
+	QOS_RLAT,
+	QOS_WPPM,
+	QOS_WLAT,
+	QOS_MIN,
+	QOS_MAX,
+	NR_QOS_PARAMS,
+};
+
+/* io.cost.model controls */
+enum {
+	COST_CTRL,
+	COST_MODEL,
+	NR_COST_CTRL_PARAMS,
+};
+
+/* builtin linear cost model coefficients */
+enum {
+	I_LCOEF_RBPS,
+	I_LCOEF_RSEQIOPS,
+	I_LCOEF_RRANDIOPS,
+	I_LCOEF_WBPS,
+	I_LCOEF_WSEQIOPS,
+	I_LCOEF_WRANDIOPS,
+	I_LCOEF_FLUSHIOPS,
+	NR_I_LCOEFS,
+};
+
+enum {
+	LCOEF_RPAGE,
+	LCOEF_RSEQIO,
+	LCOEF_RRANDIO,
+	LCOEF_WPAGE,
+	LCOEF_WSEQIO,
+	LCOEF_WRANDIO,
+	LCOEF_FLUSH,
+	NR_LCOEFS,
+};
+
+enum {
+	AUTOP_INVALID,
+	AUTOP_HDD,
+	AUTOP_SSD_QD1,
+	AUTOP_SSD_DFL,
+	AUTOP_SSD_FAST,
+};
+
+struct ioc_params {
+	u32				qos[NR_QOS_PARAMS];
+	u64				i_lcoefs[NR_I_LCOEFS];
+	u64				lcoefs[NR_LCOEFS];
+	u32				too_fast_vrate_pct;
+	u32				too_slow_vrate_pct;
+};
+
+struct ioc_margins {
+	s64				min;
+	s64				low;
+	s64				target;
+};
+
+struct ioc_missed {
+	local_t				nr_met;
+	local_t				nr_missed;
+	u32				last_met;
+	u32				last_missed;
+};
+
+struct ioc_pcpu_stat {
+	struct ioc_missed		missed[2];
+
+	local64_t			rq_wait_ns;
+	u64				last_rq_wait_ns;
+};
+
+/* per device */
+struct ioc {
+	struct rq_qos			rqos;
+
+	bool				enabled;
+
+	struct ioc_params		params;
+	struct ioc_margins		margins;
+	u32				period_us;
+	u32				timer_slack_ns;
+	u64				vrate_min;
+	u64				vrate_max;
+
+	spinlock_t			lock;
+	struct timer_list		timer;
+	struct list_head		active_iocgs;	/* active cgroups */
+	struct ioc_pcpu_stat __percpu	*pcpu_stat;
+
+	enum ioc_running		running;
+	atomic64_t			vtime_rate;
+	u64				vtime_base_rate;
+	s64				vtime_err;
+
+	seqcount_spinlock_t		period_seqcount;
+	u64				period_at;	/* wallclock starttime */
+	u64				period_at_vtime; /* vtime starttime */
+
+	atomic64_t			cur_period;	/* inc'd each period */
+	int				busy_level;	/* saturation history */
+
+	bool				weights_updated;
+	atomic_t			hweight_gen;	/* for lazy hweights */
+
+	/* debt forgivness */
+	u64				dfgv_period_at;
+	u64				dfgv_period_rem;
+	u64				dfgv_usage_us_sum;
+
+	u64				autop_too_fast_at;
+	u64				autop_too_slow_at;
+	int				autop_idx;
+	bool				user_qos_params:1;
+	bool				user_cost_model:1;
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	/* the struct_ops attached to this device, NULL = none */
+	const struct iocost_model_ops	__rcu *attached;
+	/* the link which owns the attachment, written with ioc->lock held */
+	struct bpf_link			*bpf_link;
+	/* the cost model in use, NULL = builtin linear model */
+	const struct iocost_model_ops	__rcu *model;
+#endif
+};
+
+struct iocg_pcpu_stat {
+	local64_t			abs_vusage;
+};
+
+struct iocg_stat {
+	u64				usage_us;
+	u64				wait_us;
+	u64				indebt_us;
+	u64				indelay_us;
+};
+
+/* per device-cgroup pair */
+struct ioc_gq {
+	struct blkg_policy_data		pd;
+	struct ioc			*ioc;
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	/* whether the attached model's iocg_init() was delivered */
+	bool				bpf_iocg_inited;
+#endif
+
+	/*
+	 * A iocg can get its weight from two sources - an explicit
+	 * per-device-cgroup configuration or the default weight of the
+	 * cgroup.  `cfg_weight` is the explicit per-device-cgroup
+	 * configuration.  `weight` is the effective considering both
+	 * sources.
+	 *
+	 * When an idle cgroup becomes active its `active` goes from 0 to
+	 * `weight`.  `inuse` is the surplus adjusted active weight.
+	 * `active` and `inuse` are used to calculate `hweight_active` and
+	 * `hweight_inuse`.
+	 *
+	 * `last_inuse` remembers `inuse` while an iocg is idle to persist
+	 * surplus adjustments.
+	 *
+	 * `inuse` may be adjusted dynamically during period. `saved_*` are used
+	 * to determine and track adjustments.
+	 */
+	u32				cfg_weight;
+	u32				weight;
+	u32				active;
+	u32				inuse;
+
+	u32				last_inuse;
+	s64				saved_margin;
+
+	sector_t			cursor;		/* to detect randio */
+
+	/*
+	 * `vtime` is this iocg's vtime cursor which progresses as IOs are
+	 * issued.  If lagging behind device vtime, the delta represents
+	 * the currently available IO budget.  If running ahead, the
+	 * overage.
+	 *
+	 * `vtime_done` is the same but progressed on completion rather
+	 * than issue.  The delta behind `vtime` represents the cost of
+	 * currently in-flight IOs.
+	 */
+	atomic64_t			vtime;
+	atomic64_t			done_vtime;
+	u64				abs_vdebt;
+
+	/* current delay in effect and when it started */
+	u64				delay;
+	u64				delay_at;
+
+	/*
+	 * The period this iocg was last active in.  Used for deactivation
+	 * and invalidating `vtime`.
+	 */
+	atomic64_t			active_period;
+	struct list_head		active_list;
+
+	/* see __propagate_weights() and current_hweight() for details */
+	u64				child_active_sum;
+	u64				child_inuse_sum;
+	u64				child_adjusted_sum;
+	int				hweight_gen;
+	u32				hweight_active;
+	u32				hweight_inuse;
+	u32				hweight_donating;
+	u32				hweight_after_donation;
+
+	struct list_head		walk_list;
+	struct list_head		surplus_list;
+
+	struct wait_queue_head		waitq;
+	struct hrtimer			waitq_timer;
+
+	/* timestamp at the latest activation */
+	u64				activated_at;
+
+	/* statistics */
+	struct iocg_pcpu_stat __percpu	*pcpu_stat;
+	struct iocg_stat		stat;
+	struct iocg_stat		last_stat;
+	u64				last_stat_abs_vusage;
+	u64				usage_delta_us;
+	u64				wait_since;
+	u64				indebt_since;
+	u64				indelay_since;
+
+	/* this iocg's depth in the hierarchy and ancestors including self */
+	int				level;
+	struct ioc_gq			*ancestors[];
+};
+
+/* per cgroup */
+struct ioc_cgrp {
+	struct blkcg_policy_data	cpd;
+	unsigned int			dfl_weight;
+};
+
+struct ioc_now {
+	u64				now_ns;
+	u64				now;
+	u64				vnow;
+};
+
+struct iocg_wait {
+	struct wait_queue_entry		wait;
+	struct bio			*bio;
+	u64				abs_cost;
+	bool				committed;
+};
+
+struct iocg_wake_ctx {
+	struct ioc_gq			*iocg;
+	u32				hw_inuse;
+	s64				vbudget;
+};
+
+extern struct blkcg_policy blkcg_policy_iocost;
+
+static inline struct ioc *rqos_to_ioc(struct rq_qos *rqos)
+{
+	return container_of(rqos, struct ioc, rqos);
+}
+
+static inline struct ioc *q_to_ioc(struct request_queue *q)
+{
+	return rqos_to_ioc(rq_qos_id(q, RQ_QOS_COST));
+}
+
+static inline const char __maybe_unused *ioc_name(struct ioc *ioc)
+{
+	struct gendisk *disk = ioc->rqos.disk;
+
+	if (!disk)
+		return "<unknown>";
+	return disk->disk_name;
+}
+
+static inline struct ioc_gq *pd_to_iocg(struct blkg_policy_data *pd)
+{
+	return pd ? container_of(pd, struct ioc_gq, pd) : NULL;
+}
+
+static inline struct ioc_gq *blkg_to_iocg(struct blkcg_gq *blkg)
+{
+	return pd_to_iocg(blkg_to_pd(blkg, &blkcg_policy_iocost));
+}
+
+static inline struct blkcg_gq *iocg_to_blkg(struct ioc_gq *iocg)
+{
+	return pd_to_blkg(&iocg->pd);
+}
+
+static inline struct ioc_cgrp *blkcg_to_iocc(struct blkcg *blkcg)
+{
+	return container_of(blkcg_to_cpd(blkcg, &blkcg_policy_iocost),
+			    struct ioc_cgrp, cpd);
+}
+
+/*
+ * The attached struct_ops and the model in use. The writers hold
+ * ioc->lock, the hot path readers are inside rcu_read_lock() and the
+ * map is not freed until after an RCU grace period, the slow readers
+ * hold ioc->lock.
+ */
+static inline const struct iocost_model_ops *
+ioc_attached_model_locked(struct ioc *ioc)
+{
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	return rcu_dereference_protected(ioc->attached,
+					 lockdep_is_held(&ioc->lock));
+#else
+	return NULL;
+#endif
+}
+
+static inline const struct iocost_model_ops *
+ioc_bpf_model_locked(struct ioc *ioc)
+{
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+	return rcu_dereference_protected(ioc->model,
+					 lockdep_is_held(&ioc->lock));
+#else
+	return NULL;
+#endif
+}
+
+/*
+ * Price one charged IO with the model in use into *@cost and return
+ * true, or return false when no model is in use and the builtin model
+ * must price it. The model is read under rcu_read_lock(), which the
+ * helper takes and releases itself, and the returned cost is clamped
+ * to one second of device time. calc_cost() may be invoked for a
+ * (cgroup, device) pair before iocg_init() has been delivered for
+ * it; models relying on per-pair state must tolerate that window.
+ */
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+static inline bool ioc_model_calc_cost(struct ioc *ioc, struct bio *bio,
+				       bool is_merge, u64 *cost)
+{
+	const struct iocost_model_ops *model;
+
+	rcu_read_lock();
+	model = rcu_dereference(ioc->model);
+	if (model)
+		*cost = min(model->calc_cost(bio, is_merge ?
+			    IOCOST_COST_F_MERGE : 0), VTIME_PER_SEC);
+	rcu_read_unlock();
+	return model;
+}
+#else	/* CONFIG_BLK_CGROUP_IOCOST_BPF */
+static inline bool ioc_model_calc_cost(struct ioc *ioc, struct bio *bio,
+				       bool is_merge, u64 *cost)
+{
+	return false;
+}
+#endif	/* CONFIG_BLK_CGROUP_IOCOST_BPF */
+
+/*
+ * The same for the completion-time request sizing: the transfer cost
+ * is the model's vtime per page for the request direction, and the
+ * returned cost is clamped to one second of device time.
+ */
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+static inline bool ioc_model_size_cost(struct ioc *ioc, struct request *rq,
+				       bool is_read, u64 *cost)
+{
+	const struct iocost_model_ops *model;
+
+	rcu_read_lock();
+	model = rcu_dereference(ioc->model);
+	if (model)
+		*cost = min((is_read ? model->read_vtime_per_page :
+			     model->write_vtime_per_page) *
+			    (blk_rq_stats_sectors(rq) >> IOC_SECT_TO_PAGE_SHIFT),
+			    VTIME_PER_SEC);
+	rcu_read_unlock();
+	return model;
+}
+#else	/* CONFIG_BLK_CGROUP_IOCOST_BPF */
+static inline bool ioc_model_size_cost(struct ioc *ioc, struct request *rq,
+				       bool is_read, u64 *cost)
+{
+	return false;
+}
+#endif	/* CONFIG_BLK_CGROUP_IOCOST_BPF */
+
+int blk_iocost_init(struct gendisk *disk);
+
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+void ioc_bpf_eject(struct ioc *ioc);
+#else	/* CONFIG_BLK_CGROUP_IOCOST_BPF */
+static inline void ioc_bpf_eject(struct ioc *ioc) { }
+#endif	/* CONFIG_BLK_CGROUP_IOCOST_BPF */
+#endif	/* _BLK_IOCOST_H */
diff --git a/include/trace/events/iocost.h b/include/trace/events/iocost.h
index e772b1bc60d603..39229605f499d7 100644
--- a/include/trace/events/iocost.h
+++ b/include/trace/events/iocost.h
@@ -178,6 +178,49 @@ TRACE_EVENT(iocost_ioc_vrate_adj,
 	)
 );
 
+/*
+ * Periodic per-device summary, emitted once per period before the vrate
+ * adjustment and the period transition in 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, const struct ioc_now *now,
+		 int nr_active, u64 usage_us_sum),
+
+	TP_ARGS(ioc, now, nr_active, usage_us_sum),
+
+	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)
+	),
+
+	TP_fast_assign(
+		__assign_str(devname);
+		__entry->cur_period = atomic64_read(&ioc->cur_period);
+		__entry->period_us = ioc->period_us;
+		__entry->vrate = ioc->vtime_base_rate;
+		__entry->busy_level = ioc->busy_level;
+		__entry->nr_active = nr_active;
+		__entry->usage_pct = now->now > ioc->period_at ?
+			div64_u64(usage_us_sum * 100,
+				  now->now - ioc->period_at) : 0;
+	),
+
+	TP_printk("[%s] period=%llu:%uus vrate=%llu busy=%d active=%d usage=%u%%",
+		__get_str(devname), __entry->cur_period, __entry->period_us,
+		__entry->vrate, __entry->busy_level, __entry->nr_active,
+		__entry->usage_pct
+	)
+);
+
 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 49dfe939467cc8..78ed59f83a16ac 100644
--- a/tools/testing/selftests/bpf/config
+++ b/tools/testing/selftests/bpf/config
@@ -141,3 +141,5 @@ CONFIG_SMC_HS_CTRL_BPF=y
 CONFIG_DIBS=y
 CONFIG_DIBS_LO=y
 CONFIG_PM_WAKELOCKS=y
+CONFIG_BLK_CGROUP_IOCOST=y
+CONFIG_BLK_DEV_NULL_BLK=y
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 00000000000000..5373d52d93a66a
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/iocost_model.c
@@ -0,0 +1,806 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (C) 2026 KylinSoft Corporation. */
+#define _GNU_SOURCE
+#include <test_progs.h>
+#include <fcntl.h>
+#include <sched.h>
+#include <sys/statfs.h>
+#include <linux/magic.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <sys/sysmacros.h>
+#include <unistd.h>
+#include "iocost_model.skel.h"
+#include "iocost_ms.skel.h"
+
+/*
+ * Write val to the configfs attribute at path, returning the errno of the
+ * write negated (0 on success).
+ */
+static int configfs_write(const char *path, const char *val)
+{
+	FILE *fp;
+	int err = 0;
+
+	fp = fopen(path, "w");
+	if (!fp)
+		return -errno;
+	if (fwrite(val, 1, strlen(val), fp) != strlen(val))
+		err = ferror(fp) ? -errno : -EIO;
+	if (fclose(fp) && !err)
+		err = -errno;
+	return err;
+}
+
+/*
+ * Read the first token of the file at path, for the dev attribute.
+ */
+static int read_file_token(const char *path, char *tok, size_t tok_sz)
+{
+	char fmt[16];
+	FILE *fp;
+
+	fp = fopen(path, "r");
+	if (!fp)
+		return -errno;
+	snprintf(fmt, sizeof(fmt), "%%%zus", tok_sz - 1);
+	if (fscanf(fp, fmt, tok) != 1) {
+		fclose(fp);
+		return -EIO;
+	}
+	fclose(fp);
+	return 0;
+}
+
+/*
+ * Create a null_blk instance through configfs and copy its maj:min
+ * into @dev. The device appears only once power is written, and is
+ * removed by rmdir of the instance directory; the maj:min comes from
+ * the sysfs directory of the created disk, which is named after the
+ * instance.
+ */
+static int nullb_create(const char *name, char *dev, size_t dev_sz)
+{
+	char path[128];
+	char p2[128];
+	int err;
+
+	snprintf(path, sizeof(path), "/sys/kernel/config/nullb/%s", name);
+	if (mkdir(path, 0755)) {
+		if (errno != EEXIST)
+			return -errno;
+		/*
+		 * a leftover instance from an earlier crashed run may
+		 * still be powered: tear it down before reusing the
+		 * name
+		 */
+		snprintf(p2, sizeof(p2),
+			 "/sys/kernel/config/nullb/%s/power", name);
+		configfs_write(p2, "0");
+		if (rmdir(path) && errno != ENOENT)
+			return -errno;
+		if (mkdir(path, 0755) && errno != EEXIST)
+			return -errno;
+	}
+
+	snprintf(path, sizeof(path), "/sys/kernel/config/nullb/%s/size", name);
+	err = configfs_write(path, "128");
+	if (err)
+		return err;
+
+	snprintf(path, sizeof(path), "/sys/kernel/config/nullb/%s/power", name);
+	err = configfs_write(path, "1");
+	if (err)
+		return err;
+
+	snprintf(path, sizeof(path), "/sys/block/%s/dev", name);
+	err = read_file_token(path, dev, dev_sz);
+	if (err) {
+		/* do not leave a powered instance behind */
+		snprintf(path, sizeof(path),
+			 "/sys/kernel/config/nullb/%s/power", name);
+		configfs_write(path, "0");
+		snprintf(path, sizeof(path),
+			 "/sys/kernel/config/nullb/%s", name);
+		rmdir(path);
+	}
+	return err;
+}
+
+static int nullb_remove(const char *name)
+{
+	char path[128];
+
+	/* a powered instance cannot be removed */
+	snprintf(path, sizeof(path), "/sys/kernel/config/nullb/%s/power", name);
+	configfs_write(path, "0");
+	snprintf(path, sizeof(path), "/sys/kernel/config/nullb/%s", name);
+	if (rmdir(path))
+		return -errno;
+	return 0;
+}
+
+#define IOCOST_NULLB	"iocost_model_test"
+#define IOCOST_NULLB2	"iocost_model_test2"
+
+/*
+ * The tests run against their own null_blk instance created through configfs,
+ * so they need root, configfs and the null_blk driver.
+ */
+/*
+ * The BPF cost model needs cgroup v2 at /sys/fs/cgroup and
+ * CONFIG_BLK_CGROUP_IOCOST_BPF in the running kernel; both are environment
+ * properties, so their absence is a skip.
+ */
+static bool iocost_bpf_supported(void)
+{
+	FILE *f;
+	char line[128];
+	bool any = false, on = false;
+
+	f = popen("zcat /proc/config.gz 2>/dev/null", "r");
+	if (!f)
+		return false;
+	while (fgets(line, sizeof(line), f)) {
+		if (strstr(line, "CONFIG_"))
+			any = true;
+		if (strstr(line, "CONFIG_BLK_CGROUP_IOCOST_BPF=y"))
+			on = true;
+	}
+	pclose(f);
+	return on;
+}
+
+static bool iocost_test_env(void)
+{
+	struct statfs sf;
+
+	if (geteuid() != 0) {
+		printf("%s:SKIP:needs root\n", __func__);
+		test__skip();
+		return false;
+	}
+
+	if (statfs("/sys/fs/cgroup", &sf) ||
+	    sf.f_type != CGROUP2_SUPER_MAGIC) {
+		printf("%s:SKIP:needs cgroup v2 at /sys/fs/cgroup\n",
+		       __func__);
+		test__skip();
+		return false;
+	}
+
+	if (!iocost_bpf_supported()) {
+		printf("%s:SKIP:needs CONFIG_BLK_CGROUP_IOCOST_BPF\n",
+		       __func__);
+		test__skip();
+		return false;
+	}
+
+	/* isolate the configfs and cgroup mounts from the host */
+	if (unshare(CLONE_NEWNS)) {
+		printf("%s:SKIP:unshare(CLONE_NEWNS) failed: %s\n",
+		       __func__, strerror(errno));
+		test__skip();
+		return false;
+	}
+	mkdir("/sys/kernel/config", 0755);
+	(void)mount("none", "/sys/kernel/config", "configfs", 0, NULL);
+	SYS_NOFAIL("modprobe null_blk nr_devices=0");
+	if (access("/sys/kernel/config/nullb", W_OK)) {
+		printf("%s:SKIP:needs null_blk with configfs support\n",
+		       __func__);
+		test__skip();
+		return false;
+	}
+	return true;
+}
+
+/*
+ * Read back the io.cost.model line of dev and copy the model= value into
+ * @model. Returns 0 on success.
+ */
+static int readback_model(const char *dev, char *model, size_t model_sz)
+{
+	char line[256], word[256], *m, *end;
+	FILE *fp;
+	int found = 0;
+
+	fp = fopen("/sys/fs/cgroup/io.cost.model", "r");
+	if (!fp)
+		return -1;
+	while (fgets(line, sizeof(line), fp)) {
+		if (sscanf(line, "%255s", word) == 1 && !strcmp(word, dev)) {
+			found = 1;
+			break;
+		}
+	}
+	fclose(fp);
+	if (!found)
+		return -1;
+
+	m = strstr(line, "model=");
+	if (!m)
+		return -1;
+	m += strlen("model=");
+	end = m;
+	while (*end && *end != ' ')
+		end++;
+	snprintf(model, model_sz, "%.*s", (int)(end - m), m);
+	return 0;
+}
+
+/*
+ * Read the cost.usage accumulator of dev from the cgroup's io.stat. Returns 0
+ * on success, -ENODEV when the device has no line yet (no charge recorded).
+ */
+static int read_cost_usage(const char *cgroup, const char *dev,
+			   unsigned long long *usage)
+{
+	char line[512];
+	FILE *fp;
+	int found = 0;
+
+	fp = fopen(cgroup, "r");
+	if (!fp)
+		return -EIO;
+	*usage = 0;
+	while (fgets(line, sizeof(line), fp)) {
+		char *tok = strtok(line, " \n");
+
+		if (!tok || strcmp(tok, dev))
+			continue;
+		found = 1;
+		while ((tok = strtok(NULL, " \n"))) {
+			if (!strncmp(tok, "cost.usage=", 11)) {
+				*usage = strtoull(tok + 11, NULL, 0);
+				fclose(fp);
+				return 0;
+			}
+		}
+	}
+	fclose(fp);
+	return found ? -ENOENT : -ENODEV;
+}
+
+/* mkdir, recovering from a leftover of an aborted earlier run */
+static int cgroup_mkdir(const char *path)
+{
+	if (!mkdir(path, 0755))
+		return 0;
+	if (errno == EEXIST && !rmdir(path))
+		return mkdir(path, 0755) ? -errno : 0;
+	return -errno;
+}
+
+/*
+ * Write a line to io.cost.model for dev and return the errno of the write
+ * negated (0 on success), as ASSERT_ERR() expects.
+ */
+static int write_cost_model(const char *dev, const char *what)
+{
+	char buf[128];
+	FILE *fp;
+	int err = 0;
+
+	snprintf(buf, sizeof(buf), "%s %s", dev, what);
+	fp = fopen("/sys/fs/cgroup/io.cost.model", "w");
+	if (!fp)
+		return -EACCES;
+	if (fwrite(buf, 1, strlen(buf), fp) != strlen(buf))
+		err = ferror(fp) ? -errno : -EIO;
+	if (fclose(fp) && !err)
+		err = -errno;
+	return err;
+}
+
+/*
+ * Attach the example model to the null_blk instance the test creates: the dev
+ * member is written through the struct_ops map's initial value before load,
+ * and attaching the struct_ops attaches the model to the device. Detaching the
+ * struct_ops restores the builtin model.
+ *
+ * Requires root, cgroup v2 and null_blk with configfs support.
+ */
+void serial_test_iocost_model(void)
+{
+	struct iocost_model *skel, *second, *bad;
+	unsigned int maj, min;
+	char pidbuf[16], buf[4096], path[64], qbuf[160], dev2[32];
+	int devfd, i, err, lfd;
+	char model[32], dev[32];
+	unsigned long long u1, u2, inits1;
+
+	if (!iocost_test_env())
+		return;
+	if (!ASSERT_OK(nullb_create(IOCOST_NULLB, dev, sizeof(dev)),
+		       "nullb_create"))
+		return;
+	if (sscanf(dev, "%u:%u", &maj, &min) != 2) {
+		ASSERT_TRUE(false, "dev_parse");
+		nullb_remove(IOCOST_NULLB);
+		return;
+	}
+
+	skel = iocost_model__open();
+	if (!ASSERT_OK_PTR(skel, "skel_open")) {
+		nullb_remove(IOCOST_NULLB);
+		return;
+	}
+
+	/*
+	 * a model with a zero coefficient must fail to attach instead of
+	 * silently zeroing the completion sizing (validate rejects it on
+	 * the map update the attach performs; the link form of the
+	 * struct_ops only reaches it there)
+	 */
+	bad = iocost_model__open();
+	if (!ASSERT_OK_PTR(bad, "bad_open")) {
+		iocost_model__destroy(skel);
+		nullb_remove(IOCOST_NULLB);
+		return;
+	}
+	bad->struct_ops.iocost_2x->dev = (__u32)makedev(maj, min);
+	bad->struct_ops.iocost_2x->write_vtime_per_page = 0;
+	if (ASSERT_OK(iocost_model__load(bad), "bad_load"))
+		ASSERT_EQ(iocost_model__attach(bad), -EINVAL,
+			  "attach_rejects_zero_coeff");
+	iocost_model__destroy(bad);
+
+	/* same for the read-side transfer coefficient */
+	bad = iocost_model__open();
+	if (!ASSERT_OK_PTR(bad, "bad_read_open")) {
+		iocost_model__destroy(skel);
+		nullb_remove(IOCOST_NULLB);
+		return;
+	}
+	bad->struct_ops.iocost_2x->dev = (__u32)makedev(maj, min);
+	bad->struct_ops.iocost_2x->read_vtime_per_page = 0;
+	if (ASSERT_OK(iocost_model__load(bad), "bad_read_load"))
+		ASSERT_EQ(iocost_model__attach(bad), -EINVAL,
+			  "attach_rejects_zero_read");
+	iocost_model__destroy(bad);
+
+	skel->struct_ops.iocost_2x->dev = (__u32)makedev(maj, min);
+	/*
+	 * create a cgroup for the pairing checks; its blkg comes to life
+	 * when the controller is enabled and the cgroup configured below,
+	 * exercising the iocg_init()/iocg_free() pairing end to end
+	 */
+	/*
+	 * Enable the io controller for the pairing cgroup: without it
+	 * the cgroup has no io.weight/io.stat and the iocg never
+	 * activates, so the model is consulted but nothing is charged.
+	 */
+	ASSERT_OK(configfs_write("/sys/fs/cgroup/cgroup.subtree_control",
+				 "+io"), "subtree_io");
+	if (!ASSERT_OK(cgroup_mkdir("/sys/fs/cgroup/iocost_pairing"),
+		       "mkdir_cg")) {
+		iocost_model__destroy(skel);
+		nullb_remove(IOCOST_NULLB);
+		return;
+	}
+	snprintf(pidbuf, sizeof(pidbuf), "%d", getpid());
+	ASSERT_OK(configfs_write("/sys/fs/cgroup/iocost_pairing/cgroup.procs",
+				  pidbuf), "cgroup_procs");
+	snprintf(path, sizeof(path), "/dev/%s", IOCOST_NULLB);
+	devfd = open(path, O_RDONLY);
+	if (!ASSERT_OK(devfd < 0 ? -errno : 0, "open_dev")) {
+		configfs_write("/sys/fs/cgroup/cgroup.procs", pidbuf);
+		rmdir("/sys/fs/cgroup/iocost_pairing");
+		iocost_model__destroy(skel);
+		nullb_remove(IOCOST_NULLB);
+		return;
+	}
+	for (i = 0; i < 32; i++)
+		(void)read(devfd, buf, sizeof(buf));
+	close(devfd);
+	configfs_write("/sys/fs/cgroup/cgroup.procs", pidbuf);
+
+
+	err = iocost_model__load(skel);
+	if (!ASSERT_OK(err, "skel_load")) {
+		iocost_model__destroy(skel);
+		rmdir("/sys/fs/cgroup/iocost_pairing");
+		nullb_remove(IOCOST_NULLB);
+		return;
+	}
+
+	err = iocost_model__attach(skel);
+	if (err == -EOPNOTSUPP || err == -ENODEV) {
+		printf("%s:SKIP:device is not blk-mq, has no iocost or does not exist\n",
+		       __func__);
+		iocost_model__destroy(skel);
+		rmdir("/sys/fs/cgroup/iocost_pairing");
+		nullb_remove(IOCOST_NULLB);
+		test__skip();
+		return;
+	}
+	if (ASSERT_OK(err, "attach")) {
+		/*
+		 * attached: the read path reports model=bpf until the
+		 * struct_ops is detached; ctrl keeps describing the
+		 * builtin coefficients
+		 */
+		err = readback_model(dev, model, sizeof(model));
+		if (ASSERT_OK(err, "readback"))
+			ASSERT_STREQ(model, "bpf", "model_bpf");
+
+		/*
+		 * the blkg created above was already on the blkg list
+		 * (online) when the attach walk ran, so the walk
+		 * delivered iocg_init() to it and to every other cgroup
+		 * which has a blkg on this device (the count depends on
+		 * the environment); none of them can have received
+		 * iocg_free() yet
+		 */
+		ASSERT_GT(skel->bss->iocg_inits, 0, "pair_init");
+		ASSERT_EQ(skel->bss->iocg_frees, 0, "pair_no_free");
+
+		/* a second model on the same device fails with -EBUSY */
+		second = iocost_model__open();
+		if (ASSERT_OK_PTR(second, "second_open")) {
+			second->struct_ops.iocost_2x->dev =
+				(__u32)makedev(maj, min);
+			err = iocost_model__load(second);
+			if (ASSERT_OK(err, "second_load")) {
+				struct bpf_link *l2;
+
+				/*
+				 * the kernel rejects attaching a second
+				 * model to the device with EBUSY
+				 */
+				l2 = bpf_map__attach_struct_ops(
+						second->maps.iocost_2x);
+				if (!ASSERT_ERR_PTR(l2, "second_ebusy"))
+					bpf_link__destroy(l2);
+				else
+					ASSERT_EQ(libbpf_get_error(l2), -EBUSY,
+						  "second_ebusy_errno");
+			}
+			iocost_model__destroy(second);
+		}
+
+		/*
+		 * pricing coverage: root cgroup IOs bypass the model, so
+		 * move into the pairing cgroup, enable the controller
+		 * and verify IOs actually go through calc_cost() and get
+		 * charged
+		 */
+		ASSERT_OK(configfs_write(
+				"/sys/fs/cgroup/iocost_pairing/cgroup.procs",
+				pidbuf), "procs_pairing_priced");
+		snprintf(qbuf, sizeof(qbuf), "%s 1000", dev);
+		ASSERT_OK(configfs_write(
+				"/sys/fs/cgroup/iocost_pairing/io.weight",
+				qbuf), "weight_pairing");
+		snprintf(qbuf, sizeof(qbuf),
+			 "%s enable=1 ctrl=user min=100.00 max=100.00", dev);
+		ASSERT_OK(configfs_write("/sys/fs/cgroup/io.cost.qos", qbuf),
+			  "qos_enable");
+
+		devfd = open(path, O_RDONLY);
+		if (!ASSERT_OK(devfd < 0 ? -errno : 0, "open_dev_priced")) {
+			iocost_model__destroy(skel);
+			configfs_write("/sys/fs/cgroup/cgroup.procs", pidbuf);
+			snprintf(qbuf, sizeof(qbuf), "%s enable=0", dev);
+			(void)configfs_write("/sys/fs/cgroup/io.cost.qos", qbuf);
+			if (rmdir("/sys/fs/cgroup/iocost_pairing") && errno != ENOENT)
+				printf("%s: rmdir cgroup failed: %s\n", __func__,
+				       strerror(errno));
+			nullb_remove(IOCOST_NULLB);
+			return;
+		}
+		ASSERT_OK(read_cost_usage("/sys/fs/cgroup/iocost_pairing/io.stat",
+					  dev, &u1), "cost_usage_pre");
+		for (i = 0; i < 500; i++)
+			(void)read(devfd, buf, sizeof(buf));
+		close(devfd);
+		ASSERT_GT(skel->bss->calc_costs, 0, "model_priced");
+		/*
+		 * the usage stat is flushed by the iocost timer, give
+		 * the current period a chance to end before reading
+		 */
+		sleep(3);
+		ASSERT_OK(read_cost_usage("/sys/fs/cgroup/iocost_pairing/io.stat",
+					  dev, &u2), "cost_usage_post");
+		ASSERT_GT(u2, u1, "cost_charged");
+		ASSERT_GT(skel->bss->ioc_ticks, 0, "tick_seen");
+
+		/*
+		 * a cgroup created while the model is attached gets its
+		 * iocg_init() when its first IO onlines the blkg
+		 */
+		inits1 = skel->bss->iocg_inits;
+		ASSERT_OK(cgroup_mkdir("/sys/fs/cgroup/iocost_late"),
+			  "mkdir_late");
+		ASSERT_OK(configfs_write(
+				"/sys/fs/cgroup/iocost_late/cgroup.procs",
+				pidbuf), "procs_late");
+		devfd = open(path, O_RDONLY);
+		if (ASSERT_OK(devfd < 0 ? -errno : 0, "open_dev_late")) {
+			for (i = 0; i < 32; i++)
+				(void)read(devfd, buf, sizeof(buf));
+			close(devfd);
+		}
+		ASSERT_GT(skel->bss->iocg_inits, inits1, "late_init");
+		ASSERT_OK(configfs_write("/sys/fs/cgroup/cgroup.procs",
+					 pidbuf), "procs_back");
+		rmdir("/sys/fs/cgroup/iocost_late");
+
+		/*
+		 * a second device is independent: enabling it shows
+		 * the builtin model, not the one attached to the
+		 * first
+		 */
+		if (ASSERT_OK(nullb_create(IOCOST_NULLB2, dev2,
+					   sizeof(dev2)), "nullb_create2")) {
+			snprintf(qbuf, sizeof(qbuf),
+				 "%s enable=1 ctrl=auto", dev2);
+			ASSERT_OK(configfs_write(
+					"/sys/fs/cgroup/io.cost.qos", qbuf),
+				  "qos_nullb2");
+			err = readback_model(dev2, model, sizeof(model));
+			if (ASSERT_OK(err, "readback_nullb2"))
+				ASSERT_STREQ(model, "linear",
+					     "model_linear_nullb2");
+			snprintf(qbuf, sizeof(qbuf), "%s enable=0", dev2);
+			ASSERT_OK(configfs_write(
+					"/sys/fs/cgroup/io.cost.qos", qbuf),
+				  "qos_nullb2_off");
+		}
+		nullb_remove(IOCOST_NULLB2);
+
+		/*
+		 * attachment and model selection are independent:
+		 * ctrl=bpf is never accepted, model=linear switches
+		 * back to the builtin without detaching, model=bpf
+		 * switches to the attached model again
+		 */
+		err = write_cost_model(dev, "ctrl=bpf");
+		ASSERT_ERR(err, "ctrl_bpf_rejected");
+
+		err = write_cost_model(dev, "model=linear");
+		ASSERT_OK(err, "model_linear_write");
+		err = readback_model(dev, model, sizeof(model));
+		if (ASSERT_OK(err, "readback_linear"))
+			ASSERT_STREQ(model, "linear", "model_linear");
+
+		/* still attached: the switch must not free the slot */
+		second = iocost_model__open();
+		if (ASSERT_OK_PTR(second, "second_open2")) {
+			second->struct_ops.iocost_2x->dev =
+				(__u32)makedev(maj, min);
+			err = iocost_model__load(second);
+			if (ASSERT_OK(err, "second_load2")) {
+				struct bpf_link *l2;
+
+				l2 = bpf_map__attach_struct_ops(
+						second->maps.iocost_2x);
+				if (!ASSERT_ERR_PTR(l2, "second_ebusy2"))
+					bpf_link__destroy(l2);
+				else
+					ASSERT_EQ(libbpf_get_error(l2), -EBUSY,
+						  "second_ebusy2_errno");
+			}
+			iocost_model__destroy(second);
+		}
+
+		/* still attached: switching back to the model works */
+		err = write_cost_model(dev, "model=bpf");
+		ASSERT_OK(err, "model_bpf_write");
+		err = readback_model(dev, model, sizeof(model));
+		if (ASSERT_OK(err, "readback_bpf"))
+			ASSERT_STREQ(model, "bpf", "model_bpf");
+
+		/*
+		 * detach implicitly by closing the link fd instead of
+		 * calling bpf_link__destroy() explicitly: the release
+		 * path must detach the model just like the explicit
+		 * call does
+		 */
+		lfd = bpf_link__fd(skel->links.iocost_2x);
+		bpf_link__disconnect(skel->links.iocost_2x);
+		close(lfd);
+		skel->links.iocost_2x = NULL;
+
+		/* after detach, model=bpf fails: nothing is attached */
+		err = write_cost_model(dev, "model=bpf");
+		ASSERT_ERR(err, "model_bpf_after_detach");
+
+		err = readback_model(dev, model, sizeof(model));
+		if (ASSERT_OK(err, "readback_after_detach"))
+			ASSERT_STREQ(model, "linear", "model_linear");
+
+		/* the detach walk delivered the matching iocg_free()s */
+		ASSERT_EQ(skel->bss->iocg_frees, skel->bss->iocg_inits,
+			  "pair_free");
+	}
+
+	iocost_model__destroy(skel);
+	(void)configfs_write("/sys/fs/cgroup/cgroup.procs", pidbuf);
+	snprintf(qbuf, sizeof(qbuf), "%s enable=0", dev);
+	(void)configfs_write("/sys/fs/cgroup/io.cost.qos", qbuf);
+	if (rmdir("/sys/fs/cgroup/iocost_pairing") && errno != ENOENT)
+		printf("%s: rmdir cgroup failed: %s\n", __func__,
+		       strerror(errno));
+	nullb_remove(IOCOST_NULLB);
+}
+/*
+ * Same check for the multi-stream example model. Only one model can be
+ * attached to a device at a time; each test creates its own device and
+ * attaches and detaches, so they are serial.
+ */
+void serial_test_iocost_model_streams(void)
+{
+	struct iocost_ms *skel;
+	unsigned int maj, min;
+	int err;
+	char model[32], dev[32];
+
+	if (!iocost_test_env())
+		return;
+	if (!ASSERT_OK(nullb_create(IOCOST_NULLB, dev, sizeof(dev)),
+		       "nullb_create"))
+		return;
+	if (sscanf(dev, "%u:%u", &maj, &min) != 2) {
+		ASSERT_TRUE(false, "dev_parse");
+		nullb_remove(IOCOST_NULLB);
+		return;
+	}
+
+	skel = iocost_ms__open();
+	if (!ASSERT_OK_PTR(skel, "skel_open")) {
+		nullb_remove(IOCOST_NULLB);
+		return;
+	}
+
+	skel->struct_ops.iocost_ms->dev = (__u32)makedev(maj, min);
+
+	err = iocost_ms__load(skel);
+	if (!ASSERT_OK(err, "skel_load")) {
+		iocost_ms__destroy(skel);
+		nullb_remove(IOCOST_NULLB);
+		return;
+	}
+
+	err = iocost_ms__attach(skel);
+	if (err == -EOPNOTSUPP || err == -ENODEV) {
+		printf("%s:SKIP:device is not blk-mq, has no iocost or does not exist\n",
+		       __func__);
+		iocost_ms__destroy(skel);
+		nullb_remove(IOCOST_NULLB);
+		test__skip();
+		return;
+	}
+	if (ASSERT_OK(err, "attach")) {
+		err = readback_model(dev, model, sizeof(model));
+		if (ASSERT_OK(err, "readback"))
+			ASSERT_STREQ(model, "bpf", "model_bpf");
+
+		bpf_link__destroy(skel->links.iocost_ms);
+		skel->links.iocost_ms = NULL;
+
+		err = readback_model(dev, model, sizeof(model));
+		if (ASSERT_OK(err, "readback_after_detach"))
+			ASSERT_STREQ(model, "linear", "model_linear");
+	}
+
+	iocost_ms__destroy(skel);
+	nullb_remove(IOCOST_NULLB);
+}
+
+/*
+ * Removal of the device while a model is attached: the test builds
+ * its own null_blk instance through configfs like the other tests,
+ * attaches to it, then removes the device out from under the model.
+ * The ejection must drop the device from the cgroup interface,
+ * down, and a recreated device must be attachable again.
+ */
+void serial_test_iocost_model_removal(void)
+{
+	struct iocost_model *skel, *skel2;
+	unsigned int maj, min;
+	char dev[32], model[32];
+	int err;
+
+	if (!iocost_test_env())
+		return;
+
+	skel = iocost_model__open();
+	if (!ASSERT_OK_PTR(skel, "skel_open"))
+		return;
+
+	err = nullb_create("iocost_removal", dev, sizeof(dev));
+	if (!ASSERT_OK(err, "nullb_create"))
+		goto out;
+	if (sscanf(dev, "%u:%u", &maj, &min) != 2) {
+		ASSERT_TRUE(false, "dev_parse");
+		goto out;
+	}
+
+	skel->struct_ops.iocost_2x->dev = (__u32)makedev(maj, min);
+	err = iocost_model__load(skel);
+	if (!ASSERT_OK(err, "skel_load"))
+		goto out;
+
+	err = iocost_model__attach(skel);
+	if (!ASSERT_OK(err, "attach"))
+		goto out;
+
+	err = readback_model(dev, model, sizeof(model));
+	if (ASSERT_OK(err, "readback"))
+		ASSERT_STREQ(model, "bpf", "model_bpf");
+
+	/* remove the device out from under the attached model */
+	if (!ASSERT_OK(nullb_remove("iocost_removal"), "nullb_remove"))
+		goto detach;
+
+	/* the ejection drops the device from the cgroup files */
+	err = readback_model(dev, model, sizeof(model));
+	ASSERT_ERR(err, "readback_after_removal");
+
+	err = write_cost_model(dev, "model=bpf");
+	ASSERT_ERR(err, "model_bpf_after_removal");
+
+	/*
+	 * the ejection path must deliver iocg_free() for every blkg
+	 * which was online on the removed device: pd_free() runs from
+	 * blkcg_deactivate_policy() before ioc_bpf_eject() drops the
+	 * map reference
+	 */
+	ASSERT_GT(skel->bss->iocg_inits, 0, "eject_had_inits");
+	ASSERT_EQ(skel->bss->iocg_frees, skel->bss->iocg_inits,
+		  "eject_balanced");
+
+detach:
+	/*
+	 * detaching after the device is gone must be a clean no-op;
+	 * this exercises the eject-then-detach ordering in the kernel
+	 */
+	bpf_link__destroy(skel->links.iocost_2x);
+	skel->links.iocost_2x = NULL;
+
+	/* the same attach and detach against a recreated device */
+	skel2 = iocost_model__open();
+	if (!ASSERT_OK_PTR(skel2, "skel2_open"))
+		goto out;
+
+	err = nullb_create("iocost_removal", dev, sizeof(dev));
+	if (!ASSERT_OK(err, "nullb_create_again"))
+		goto out2;
+	if (sscanf(dev, "%u:%u", &maj, &min) != 2) {
+		ASSERT_TRUE(false, "dev_parse_again");
+		goto out2;
+	}
+
+	skel2->struct_ops.iocost_2x->dev = (__u32)makedev(maj, min);
+	err = iocost_model__load(skel2);
+	if (!ASSERT_OK(err, "skel2_load"))
+		goto out2;
+
+	err = iocost_model__attach(skel2);
+	if (!ASSERT_OK(err, "attach_again"))
+		goto out2;
+
+	err = readback_model(dev, model, sizeof(model));
+	if (ASSERT_OK(err, "readback_again"))
+		ASSERT_STREQ(model, "bpf", "model_bpf_again");
+	ASSERT_GT(skel2->bss->iocg_inits, 0, "pair_init_again");
+
+	bpf_link__destroy(skel2->links.iocost_2x);
+	skel2->links.iocost_2x = NULL;
+
+	err = readback_model(dev, model, sizeof(model));
+	if (ASSERT_OK(err, "readback_after_detach_again"))
+		ASSERT_STREQ(model, "linear", "model_linear_again");
+
+	/* the re-attach walk delivered init for the recreated device */
+	ASSERT_EQ(skel2->bss->iocg_frees, skel2->bss->iocg_inits,
+		  "pair_balanced_again");
+
+out2:
+	iocost_model__destroy(skel2);
+out:
+	nullb_remove("iocost_removal");
+	iocost_model__destroy(skel);
+}
diff --git a/tools/testing/selftests/bpf/progs/iocost_model.c b/tools/testing/selftests/bpf/progs/iocost_model.c
new file mode 100644
index 00000000000000..8875fb0f441749
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/iocost_model.c
@@ -0,0 +1,201 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (C) 2026 KylinSoft Corporation. */
+/*
+ * Example iocost cost model: the builtin linear HDD formula with all costs
+ * doubled, for one device given by the dev member of the struct_ops.
+ *
+ * The constants mirror what calc_lcoefs() derives from the AUTOP_HDD defaults
+ * (rbps=174019176 rseqiops=41708 rrandiops=370, w-side analog) in vtime units
+ * where 1s == 2^37. On a rotational device still on ctrl=auto, a device with
+ * this model attached charges twice the builtin model under the same
+ * read/write workload (the builtin prices flushes as zero and adds a fixed
+ * flush term to data-bearing preflushes, which this model omits; this model
+ * prices flushes as one-page writes), 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 follows the builtin: a zero cursor means "no previous
+ * IO", and the cursor is advanced for the bios the builtin prices
+ * (READ/WRITE/ZONE_APPEND with a non-zero size), so flushes and discards leave
+ * it alone and long merged streams do not drift past the 16MB seek threshold.
+ * One known deviation, mispricing only: the builtin does not move its cursor
+ * for an IO whose cgroup fails to activate; this model does not see the
+ * activation result.
+ *
+ * The model implements the full linear formula itself, including flushes:
+ * there is no fallback to the builtin model, which prices a dataless
+ * WRITE|REQ_PREFLUSH as zero unless flushiops is configured; this model prices
+ * it as a one-page sequential write. What a flush actually costs depends on
+ * the IOs before it, which a static formula cannot express - pricing it as a
+ * small constant is a crude penalty for unnecessarily frequent flushes, and a
+ * stateful model would be the way to do better. Discards and other unpriced
+ * operations pass through at zero cost, like the builtin.
+ */
+
+#include "vmlinux.h"
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+
+/*
+ * VTIME_PER_SEC, IOC_PAGE_SIZE/SHIFT, IOC_SECT_TO_PAGE_SHIFT,
+ * LCOEF_RANDIO_PAGES (the 16MB seek threshold) and IOCOST_COST_F_MERGE
+ * come from vmlinux.h (BTF constants; the enum64 ones need pahole
+ * >= 1.23 to be emitted)
+ */
+#define IOCOST_REQ_OP_MASK	0xff		/* REQ_OP_MASK, not in BTF */
+
+/*
+ * DIV64_U64_ROUND_UP / DIV_ROUND_UP_ULL equivalents, folded at
+ * compile time
+ */
+#define RU(x, y)		((x) / (y) + (((x) % (y)) ? 1 : 0))
+
+#define RBPS	174019176ULL
+#define RSEQIOPS	41708ULL
+#define RRANDIOPS	370ULL
+#define WBPS	178075866ULL
+#define WSEQIOPS	42705ULL
+#define WRANDIOPS	378ULL
+
+#define RPAGE	(RU(VTIME_PER_SEC, RU(RBPS, IOC_PAGE_SIZE)))
+#define RSEQIO	(RU(VTIME_PER_SEC, RSEQIOPS) - RPAGE)
+#define RRANDIO	(RU(VTIME_PER_SEC, RRANDIOPS) - RPAGE)
+#define WPAGE	(RU(VTIME_PER_SEC, RU(WBPS, IOC_PAGE_SIZE)))
+#define WSEQIO	(RU(VTIME_PER_SEC, WSEQIOPS) - WPAGE)
+#define WRANDIO	(RU(VTIME_PER_SEC, WRANDIOPS) - WPAGE)
+
+/*
+ * per-cgroup cursor storage: keyed by the cgroup and freed with it,
+ * so a cgroup that comes back starts with no cursor
+ */
+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");
+
+/*
+ * cgroup callback counters: the test reads them back to verify the
+ * init/free pairing across attach, detach and device removal
+ */
+__u64 iocg_inits;
+__u64 iocg_frees;
+
+/*
+ * incremented by calc_cost(): the test asserts pricing went
+ * through the model while it is attached and the controller is
+ * enabled
+ */
+__u64 calc_costs;
+
+/* counts iocost_ioc_tick emissions observed from BPF side */
+__u64 ioc_ticks;
+
+SEC("struct_ops")
+void BPF_PROG(iocost_2x_iocg_init, struct blkcg *blkcg,
+	      struct request_queue *q)
+{
+	iocg_inits++;
+}
+
+SEC("struct_ops")
+void BPF_PROG(iocost_2x_iocg_free, struct blkcg *blkcg,
+	      struct request_queue *q)
+{
+	iocg_frees++;
+}
+
+SEC("struct_ops")
+u64 BPF_PROG(iocost_2x_calc_cost, struct bio *bio, u64 model_flags)
+{
+	u64 opf = bio->bi_opf, nbytes = bio->bi_iter.bi_size;
+	u64 sector = bio->bi_iter.bi_sector;
+	struct blkcg *blkcg = bio->bi_blkg->blkcg;
+	u64 pages, seek_pages = 0, base, coef_page, randio, cost;
+	__u64 *cursor, cur;
+	int priced;
+
+	calc_costs++;
+
+	/* builtin truncates: max(sectors >> IOC_SECT_TO_PAGE_SHIFT, 1) */
+	pages = nbytes >> IOC_PAGE_SHIFT;
+	if (!pages)
+		pages = 1;
+
+	if ((opf & IOCOST_REQ_OP_MASK) == REQ_OP_READ) {
+		base = RSEQIO; coef_page = RPAGE; randio = RRANDIO;
+	} else if ((opf & IOCOST_REQ_OP_MASK) == REQ_OP_WRITE ||
+		   (opf & IOCOST_REQ_OP_MASK) == REQ_OP_ZONE_APPEND) {
+		base = WSEQIO; coef_page = WPAGE; randio = WRANDIO;
+	} else {
+		/*
+		 * the builtin prices other operations at zero and
+		 * leaves them unthrottled; pass them through the same
+		 * way instead of inventing costs
+		 */
+		return 0;
+	}
+
+	/* mirror the builtin cursor semantics described above */
+	priced = (opf & IOCOST_REQ_OP_MASK) == REQ_OP_READ ||
+		 (opf & IOCOST_REQ_OP_MASK) == REQ_OP_WRITE ||
+		 (opf & IOCOST_REQ_OP_MASK) == REQ_OP_ZONE_APPEND;
+	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;
+	/*
+	 * a size-zero IO never moves the cursor, so it must not be
+	 * judged against it either; the builtin skips it entirely,
+	 * this model prices it as a one-page sequential write
+	 */
+	if (cur && priced && nbytes) {
+		seek_pages = sector > cur ? sector - cur
+					   : cur - sector;
+		seek_pages >>= IOC_SECT_TO_PAGE_SHIFT;
+		if (seek_pages > LCOEF_RANDIO_PAGES)
+			base = randio;
+	}
+	/*
+	 * the builtin moves the cursor unconditionally on submit, but
+	 * on a merge only for a back merge into the request ending at
+	 * it; a merged bio starts right at the cursor exactly then,
+	 * and a zero cursor means no history so it never matches
+	 */
+	if (priced && nbytes &&
+	    (!(model_flags & IOCOST_COST_F_MERGE) || (cur && cur == sector)))
+		*cursor = sector + (nbytes >> 9);
+
+	if (model_flags & IOCOST_COST_F_MERGE)
+		base = 0;
+
+	cost = 2 * (base + pages * coef_page);
+	return cost;
+}
+
+/* consumes the new iocost_ioc_tick tracepoint from BPF side */
+SEC("tp_btf/iocost_ioc_tick")
+__u64 BPF_PROG(iocost_2x_tick_count, struct ioc *ioc,
+	       const struct ioc_now *now, int nr_active, u64 usage_us_sum)
+{
+	ioc_ticks++;
+	return 0;
+}
+
+SEC(".struct_ops.link") /* detach on close */
+struct iocost_model_ops iocost_2x = {
+	.read_vtime_per_page = 2 * RPAGE,
+	.write_vtime_per_page = 2 * WPAGE,
+	.calc_cost = (void *)iocost_2x_calc_cost,
+	.iocg_init = (void *)iocost_2x_iocg_init,
+	.iocg_free = (void *)iocost_2x_iocg_free,
+};
+
+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 00000000000000..87d4abcbf69340
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/iocost_ms.c
@@ -0,0 +1,175 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (C) 2026 KylinSoft Corporation. */
+/*
+ * Example multi-stream sequentiality detection cost model.
+ *
+ * The builtin model keeps a single cursor per cgroup, so two interleaved
+ * sequential readers in one cgroup are all priced random (measured 89x
+ * overcharge, 12.9x throughput collapse), while random IO inside a hot window
+ * smaller than the 16MB seek threshold is priced sequential (measured 107x
+ * undercharge). This model replaces the single cursor with a per-cgroup table
+ * of stream slots: an IO is sequential iff its sector matches the expected
+ * next sector of any tracked stream. Interleaved streams keep their own slots,
+ * and windowed random IO rarely matches a moving expectation.
+ *
+ * Stream state lives in a CGRP_STORAGE map, so it is created and freed with
+ * the cgroup. The model implements the builtin linear formula itself; unlike
+ * the builtin it has no flush term, so preflushed IOs are priced as plain
+ * writes (mispricing only, the test never issues flushes).
+ */
+#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, struct bio *bio, u64 model_flags)
+{
+	u64 opf = bio->bi_opf, nbytes = bio->bi_iter.bi_size;
+	u64 sector = bio->bi_iter.bi_sector;
+	struct blkcg *blkcg = bio->bi_blkg->blkcg;
+	struct streams *s;
+	u64 pages, base, coef_page, randio, advance, now;
+	u32 i, victim = 0, found = 0xFFFFFFFF;
+
+	if ((opf & IOCOST_REQ_OP_MASK) == REQ_OP_READ) {
+		base = RSEQIO; coef_page = RPAGE; randio = RRANDIO;
+	} else if ((opf & IOCOST_REQ_OP_MASK) == REQ_OP_WRITE ||
+		   (opf & IOCOST_REQ_OP_MASK) == REQ_OP_ZONE_APPEND) {
+		base = WSEQIO; coef_page = WPAGE; randio = WRANDIO;
+	} else {
+		/*
+		 * the builtin prices other operations at zero and
+		 * leaves them unthrottled; pass them through the same
+		 * way instead of inventing costs
+		 */
+		return 0;
+	}
+	advance = nbytes >> 9;	/* sectors, truncated like the builtin */
+
+	/*
+	 * only bios the builtin prices participate in stream tracking;
+	 * the early return below skips the merge discount, which only
+	 * applies to tracked data bios
+	 */
+	if (!(((opf & IOCOST_REQ_OP_MASK) == REQ_OP_READ ||
+	       (opf & IOCOST_REQ_OP_MASK) == REQ_OP_WRITE ||
+	       (opf & IOCOST_REQ_OP_MASK) == REQ_OP_ZONE_APPEND) && 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 {
+		/*
+		 * a merge which matches no slot is not a new stream:
+		 * replacing a slot could evict a live stream, so merged
+		 * bios are priced without touching the table (and skip
+		 * the base cost below)
+		 */
+		if (!(model_flags & IOCOST_COST_F_MERGE)) {
+			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.link") /* detach on close */
+struct iocost_model_ops iocost_ms = {
+	.read_vtime_per_page = RPAGE,
+	.write_vtime_per_page = WPAGE,
+	.calc_cost = (void *)iocost_ms_calc_cost,
+};
+
+char LICENSE[] SEC("license") = "GPL";

31/3 2026/10/29 02:08 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 40422
							output: 28
							thoughts: 2339
						

Thoughts:
**KMSAN Evaluation for iocost BPF Patch Series**

Okay, let's break this down. The task is to determine if a dedicated KMSAN session is warranted for this patch series related to the iocost BPF (Berkeley Packet Filter) integration.  Following the guidelines, I need to look for uninitialized memory risks that *only* KMSAN would detect, keeping in mind that KASAN, LOCKDEP, and other bug detectors are sufficient for more common issues.

First, I examined the patch series and the surrounding code, focusing on potential areas of concern: kernel structures sent to user space, conditional logic involving potentially uninitialized variables, the allocation/initialization of complex data structures, and changes in bounds checks, lengths or logic that could expose uninitialized data.

The core changes involve introducing a new BPF-based iocost model, and hooking into existing structures and callbacks.  I've gone through the file changes and the introduced functions: `ioc_bpf_deliver_iocg_callbacks`, `ioc_bpf_attach`, `bpf_iocost_init_member`, and others. My attention is drawn to the areas outlined in the instructions; specifically, any data being copied to user space, new structures, and any calculations that could lead to information leaks.

I carefully scrutinized the code, starting with `ioc_cost_model_write` and `ioc_cost_model_prfill` as they involve interactions with user space through `/proc` interfaces. I checked for uninitialized variables and data races.  In `ioc_cost_model_prfill`, the `model` pointer, which can point to either the BPF model or a linear model, is compared to NULL, and the value is formatted into the output string. I saw no risk of uninitialized memory here.

In `ioc_cost_model_write`, `new_model` is initialized to NULL. The code then checks configuration options to determine if BPF model support is enabled. Regardless of the configuration, `new_model` appears to be initialized in all code paths, or it is not used in the cases that the configuration is not set.

The `trace_iocost_ioc_tick` event also received special attention because it involves transferring data. I examined the structure used to capture trace event data. Specifically, I'm checking where `struct ioc_now now;` is initialized in `ioc_timer_fn`. After the examination I saw that the `now` struct is allocated on the stack within `ioc_timer_fn`, and then, fields of `now` are assigned values before being passed to `trace_iocost_ioc_tick`.

Overall, after a thorough review of the code and the added functionality, I haven't identified any situations where uninitialized memory is introduced or exposed in a way that *only* KMSAN would detect. The code seems to handle initializations and zeroing of structures appropriately before any use or transfer. The new BPF callbacks and integration points seem to be designed with memory safety in mind. Therefore, based on the specific criteria and the current state of my analysis, I would recommend setting `NeedsKMSAN=false` for this patch series.



32/3 2026/10/29 02:09 tool grepper
0m Args:
{
  "Expression": "ioc_timer_fn",
  "PathPrefixes": [
    "block/"
  ]
}

Results:
{
  "Output": "block/blk-iocost.c=1767=static int ioc_check_iocgs(struct ioc *ioc, struct ioc_now *now)\n--\nblock/blk-iocost.c-1834-\nblock/blk-iocost.c:1835:static void ioc_timer_fn(struct timer_list *timer)\nblock/blk-iocost.c-1836-{\n--\nblock/blk-iocost.c=2559=int blk_iocost_init(struct gendisk *disk)\n--\nblock/blk-iocost.c-2584-\tspin_lock_init(\u0026ioc-\u003elock);\nblock/blk-iocost.c:2585:\ttimer_setup(\u0026ioc-\u003etimer, ioc_timer_fn, 0);\nblock/blk-iocost.c-2586-\tINIT_LIST_HEAD(\u0026ioc-\u003eactive_iocgs);\n"
}

33/3 2026/10/29 02:09 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 43698
							output: 37
							thoughts: 34
						

Thoughts:
Okay, let's dive into this. Here's my take on those lines of code:

**Analyzing `ioc_timer_fn` in `block/blk-iocost.c`**

Alright, time to get my hands dirty. I'm focusing in on `ioc_timer_fn`, specifically lines 1835 through 1880 in `block/blk-iocost.c`. From what I know about this module, this function is likely crucial for the IO cost accounting mechanism. My initial hypothesis is that it's probably the timer-driven routine responsible for periodically updating or calculating IO costs, or perhaps enforcing some sort of limit or policy. It's likely involved in sampling IO metrics over time.

I need to quickly grasp the surrounding context to understand how the timer is set up, what data it operates on, and what the implications of its execution are. I'll be looking for things like mutexes or spinlocks it acquires, what data structures it manipulates, and how it handles potential races or contention. I also will want to see which threads or processes this is executed under.

Given the length, it's probably doing something moderately complex, but hopefully not too many unrelated tasks. If it's a simple periodic sampling, I'll be pleased, and I can move on to the more interesting points. If it's doing several things at once, I'll need to figure out what those are, and why those tasks need to be done within this timer. Let's see...



34/3 2026/10/29 02:09 tool read-file
0m Args:
{
  "File": "block/blk-iocost.c",
  "FirstLine": 1835,
  "LineCount": 50
}

Results:
{
  "Contents": "1835:\tstatic void ioc_timer_fn(struct timer_list *timer)\n1836:\t{\n1837:\t\tstruct ioc *ioc = container_of(timer, struct ioc, timer);\n1838:\t\tstruct ioc_gq *iocg, *tiocg;\n1839:\t\tstruct ioc_now now;\n1840:\t\tLIST_HEAD(surpluses);\n1841:\t\tint nr_debtors, nr_shortages = 0, nr_lagging = 0;\n1842:\t\tint nr_active = 0;\n1843:\t\tu64 usage_us_sum = 0;\n1844:\t\tu32 ppm_rthr;\n1845:\t\tu32 ppm_wthr;\n1846:\t\tu32 missed_ppm[2], rq_wait_pct, nr_done;\n1847:\t\tu64 period_vtime;\n1848:\t\tint prev_busy_level;\n1849:\t\n1850:\t\t/* how were the latencies during the period? */\n1851:\t\tioc_lat_stat(ioc, missed_ppm, \u0026rq_wait_pct, \u0026nr_done);\n1852:\t\n1853:\t\t/* take care of active iocgs */\n1854:\t\tspin_lock_irq(\u0026ioc-\u003elock);\n1855:\t\n1856:\t\tppm_rthr = MILLION - ioc-\u003eparams.qos[QOS_RPPM];\n1857:\t\tppm_wthr = MILLION - ioc-\u003eparams.qos[QOS_WPPM];\n1858:\t\tioc_now(ioc, \u0026now);\n1859:\t\n1860:\t\tperiod_vtime = now.vnow - ioc-\u003eperiod_at_vtime;\n1861:\t\tif (WARN_ON_ONCE(!period_vtime)) {\n1862:\t\t\tspin_unlock_irq(\u0026ioc-\u003elock);\n1863:\t\t\treturn;\n1864:\t\t}\n1865:\t\n1866:\t\tnr_debtors = ioc_check_iocgs(ioc, \u0026now);\n1867:\t\n1868:\t\t/*\n1869:\t\t * Wait and indebt stat are flushed above and the donation calculation\n1870:\t\t * below needs updated usage stat. Let's bring stat up-to-date.\n1871:\t\t */\n1872:\t\tiocg_flush_stat(\u0026ioc-\u003eactive_iocgs, \u0026now);\n1873:\t\n1874:\t\t/* calc usage and see whether some weights need to be moved around */\n1875:\t\tlist_for_each_entry(iocg, \u0026ioc-\u003eactive_iocgs, active_list) {\n1876:\t\t\tu64 vdone, vtime, usage_us;\n1877:\t\t\tu32 hw_active, hw_inuse;\n1878:\t\n1879:\t\t\tnr_active++;\n1880:\t\n1881:\t\t\t/*\n1882:\t\t\t * Collect unused and wind vtime closer to vnow to prevent\n1883:\t\t\t * iocgs from accumulating a large amount of budget.\n1884:\t\t\t */\n"
}

35/3 2026/10/29 02:09 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 44927
							output: 28
							thoughts: 612
						

Thoughts:
**My Analysis of ioc_bpf_deliver_iocg_callbacks and Associated Initialization**

Okay, so I'm looking at this `ioc_bpf_deliver_iocg_callbacks` function and how it interacts with the `ioc_now` variable and the `iocg` structures. The code first initializes `now` using `ioc_now(ioc, &now);` *completely* before `trace_iocost_ioc_tick` is called. Got it. I need to keep that in mind as I analyze further.

Now, let's dive into `ioc_bpf_deliver_iocg_callbacks`. It appears this function is responsible for delivering callbacks related to the BPF-based iocost model during initialization (`init = true`) and freeing (`init = false`). The function iterates through the `blkg_list` of the request queue, handling the `iocg` structures associated with each `blkg`. The use of `list_for_each_entry_reverse` during init makes sense, to process parents first, similar to `blkcg_activate_policy()`. The online check is important, as an offline blkg shouldn't receive initialization. Also, clearing delivered flags before going offline is consistent.

The interesting part is the `iocg->bpf_iocg_inited` flag.  This flag controls whether `ops->iocg_init` or `ops->iocg_free` callbacks are invoked. During initialization, we call the init callback and set `iocg->bpf_iocg_inited` to `true`.  During cleanup, we call the free callback *if* `iocg->bpf_iocg_inited` is `true`, and then reset the flag to `false`. Makes sense, so only initialized structures are freed.

But wait a minute... how is `iocg->bpf_iocg_inited` initialized in the first place? It's not immediately obvious from this snippet.  The code doesn't seem to initialize it directly.  This suggests that it must be set during allocation or construction of the `iocg` structure itself.  Therefore, I'll need to look at the memory allocation functions.  Let's check `ioc_pd_alloc` and `pd_alloc_fn` to understand how `iocg` is actually brought into existence and whether the flag is initialized. Time to grep for `ioc_pd_alloc` and go from there!



36/3 2026/10/29 02:09 tool grepper
0m Args:
{
  "Expression": "ioc_pd_alloc",
  "PathPrefixes": [
    "block/"
  ]
}

Results:
{
  "Output": "block/blk-iocost.c=2636=static void ioc_cpd_free(struct blkcg_policy_data *cpd)\n--\nblock/blk-iocost.c-2640-\nblock/blk-iocost.c:2641:static struct blkg_policy_data *ioc_pd_alloc(struct gendisk *disk,\nblock/blk-iocost.c-2642-\t\tstruct blkcg *blkcg, gfp_t gfp)\n--\nblock/blk-iocost.c=3322=struct blkcg_policy blkcg_policy_iocost = {\n--\nblock/blk-iocost.c-3325-\t.cpd_free_fn\t= ioc_cpd_free,\nblock/blk-iocost.c:3326:\t.pd_alloc_fn\t= ioc_pd_alloc,\nblock/blk-iocost.c-3327-\t.pd_init_fn\t= ioc_pd_init,\n"
}

37/3 2026/10/29 02:09 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 46356
							output: 37
							thoughts: 22
						

Thoughts:
Okay, let's dive into this. I'm going to take a look at the `ioc_pd_alloc` function, specifically within the `block/blk-iocost.c` file. I need to understand how the I/O cost accounting is handled at a fundamental level. I'm interested in how it allocates and manages the persistent data structures it needs. This function is likely the linchpin in that process, which makes it crucial for understanding the overall I/O costing scheme. I anticipate I'll be looking at memory allocation, data structure initialization, and potentially some subtle aspects of resource management. Let's see how this works in practice.



38/3 2026/10/29 02:09 tool read-file
0m Args:
{
  "File": "block/blk-iocost.c",
  "FirstLine": 2640,
  "LineCount": 40
}

Results:
{
  "Contents": "2640:\t\n2641:\tstatic struct blkg_policy_data *ioc_pd_alloc(struct gendisk *disk,\n2642:\t\t\tstruct blkcg *blkcg, gfp_t gfp)\n2643:\t{\n2644:\t\tint levels = blkcg-\u003ecss.cgroup-\u003elevel + 1;\n2645:\t\tstruct ioc_gq *iocg;\n2646:\t\n2647:\t\tiocg = kzalloc_node(struct_size(iocg, ancestors, levels), gfp,\n2648:\t\t\t\t    disk-\u003enode_id);\n2649:\t\tif (!iocg)\n2650:\t\t\treturn NULL;\n2651:\t\n2652:\t\tiocg-\u003epcpu_stat = alloc_percpu_gfp(struct iocg_pcpu_stat, gfp);\n2653:\t\tif (!iocg-\u003epcpu_stat) {\n2654:\t\t\tkfree(iocg);\n2655:\t\t\treturn NULL;\n2656:\t\t}\n2657:\t\n2658:\t\treturn \u0026iocg-\u003epd;\n2659:\t}\n2660:\t\n2661:\tstatic void ioc_pd_init(struct blkg_policy_data *pd)\n2662:\t{\n2663:\t\tstruct ioc_gq *iocg = pd_to_iocg(pd);\n2664:\t\tstruct blkcg_gq *blkg = pd_to_blkg(\u0026iocg-\u003epd);\n2665:\t\tstruct ioc *ioc = q_to_ioc(blkg-\u003eq);\n2666:\t\tstruct ioc_now now;\n2667:\t\tstruct blkcg_gq *tblkg;\n2668:\t\tunsigned long flags;\n2669:\t\n2670:\t\tioc_now(ioc, \u0026now);\n2671:\t\n2672:\t\tiocg-\u003eioc = ioc;\n2673:\t\tatomic64_set(\u0026iocg-\u003evtime, now.vnow);\n2674:\t\tatomic64_set(\u0026iocg-\u003edone_vtime, now.vnow);\n2675:\t\tatomic64_set(\u0026iocg-\u003eactive_period, atomic64_read(\u0026ioc-\u003ecur_period));\n2676:\t\tINIT_LIST_HEAD(\u0026iocg-\u003eactive_list);\n2677:\t\tINIT_LIST_HEAD(\u0026iocg-\u003ewalk_list);\n2678:\t\tINIT_LIST_HEAD(\u0026iocg-\u003esurplus_list);\n2679:\t\tiocg-\u003ehweight_active = WEIGHT_ONE;\n"
}

39/3 2026/10/29 02:09 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 47237
							output: 37
							thoughts: 75
						

Thoughts:
Okay, let's break this down.

**Initial Assessment of ioc_pd_alloc and blk_iocost_init**

Right, so `ioc_pd_alloc` leverages `kzalloc_node`, which is key. That means `bpf_iocg_inited` will be guaranteed to be initialized to zero – effectively, it's starting as `false`. That's good to know, avoids some potential initial state issues.

Now, I need to see how the actual `ioc` is allocated within `blk_iocost_init`. Time to jump into `block/blk-iocost.c` and understand the initialization sequence more deeply. Let's see how things are set up at that entry point.



40/3 2026/10/29 02:09 tool read-file
0m Args:
{
  "File": "block/blk-iocost.c",
  "FirstLine": 2555,
  "LineCount": 40
}

Results:
{
  "Contents": "2555:\t\t.queue_depth_changed = ioc_rqos_queue_depth_changed,\n2556:\t\t.exit = ioc_rqos_exit,\n2557:\t};\n2558:\t\n2559:\tint blk_iocost_init(struct gendisk *disk)\n2560:\t{\n2561:\t\tstruct ioc *ioc;\n2562:\t\tint i, cpu, ret;\n2563:\t\n2564:\t\tioc = kzalloc_obj(*ioc);\n2565:\t\tif (!ioc)\n2566:\t\t\treturn -ENOMEM;\n2567:\t\n2568:\t\tioc-\u003epcpu_stat = alloc_percpu(struct ioc_pcpu_stat);\n2569:\t\tif (!ioc-\u003epcpu_stat) {\n2570:\t\t\tkfree(ioc);\n2571:\t\t\treturn -ENOMEM;\n2572:\t\t}\n2573:\t\n2574:\t\tfor_each_possible_cpu(cpu) {\n2575:\t\t\tstruct ioc_pcpu_stat *ccs = per_cpu_ptr(ioc-\u003epcpu_stat, cpu);\n2576:\t\n2577:\t\t\tfor (i = 0; i \u003c ARRAY_SIZE(ccs-\u003emissed); i++) {\n2578:\t\t\t\tlocal_set(\u0026ccs-\u003emissed[i].nr_met, 0);\n2579:\t\t\t\tlocal_set(\u0026ccs-\u003emissed[i].nr_missed, 0);\n2580:\t\t\t}\n2581:\t\t\tlocal64_set(\u0026ccs-\u003erq_wait_ns, 0);\n2582:\t\t}\n2583:\t\n2584:\t\tspin_lock_init(\u0026ioc-\u003elock);\n2585:\t\ttimer_setup(\u0026ioc-\u003etimer, ioc_timer_fn, 0);\n2586:\t\tINIT_LIST_HEAD(\u0026ioc-\u003eactive_iocgs);\n2587:\t\n2588:\t\tioc-\u003erunning = IOC_IDLE;\n2589:\t\tioc-\u003evtime_base_rate = VTIME_PER_USEC;\n2590:\t\tatomic64_set(\u0026ioc-\u003evtime_rate, VTIME_PER_USEC);\n2591:\t\tseqcount_spinlock_init(\u0026ioc-\u003eperiod_seqcount, \u0026ioc-\u003elock);\n2592:\t\tioc-\u003eperiod_at = ktime_to_us(blk_time_get());\n2593:\t\tatomic64_set(\u0026ioc-\u003ecur_period, 0);\n2594:\t\tatomic_set(\u0026ioc-\u003ehweight_gen, 0);\n"
}

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

Args:
null

Results:
null

Tokens:
							input: 48190
							output: 531
							thoughts: 3320
						

Thoughts:
**Analysis of NeedsKMSAN for Block I/O Cost Model BPF Integration**

Okay, so I'm digging into this patch set which is adding BPF struct_ops support for the iocost controller. Specifically, this allows us to plug in different cost models. We've got cgroup integration, reference counting, a tracepoint, and some selftests. The goal is to figure out if we need KMSAN enabled for this.

First, I need to make sure I understand the memory initialization. `ioc = kzalloc_obj(*ioc)` and `iocg` allocations ensure all new fields like `attached`, `model`, `bpf_link` are zeroed. Nice. Then I see how `bpf_iocost_model_ops` are used with `bpf_iocost_init_member`. This looks like a standard BPF struct_ops pattern: the kernel side (`kdata`) gets its memory via `bpf_map_kmalloc_node` or `kzalloc`, and the important thing is that `bpf_iocost_init_member` only copies initialized members from the user space (`udata`) to the kernel side and the comment in `bpf_iocost_validate` confirms that function members that are not implemented leave their pointers NULL. Local variables like `new_model`, `model_write`, `nr_active` and the `cost` variable in `calc_vtime_cost` and `calc_size_vtime_cost` are initialized before any use. Tracepoint `trace_iocost_ioc_tick` explicitly assigns *all* the fields of `TP_STRUCT__entry`. I'm going through the different code sections to verify that there are no uninitialized reads anywhere.

I need to meticulously check for potential kernel-to-userspace data leaks, especially when BPF is involved. So, for the cgroup file interfaces, it seems to be using `seq_printf` which constructs the output with pre-validated data and format strings. The `bpf_iocost_init_member` function looks clean, so there's no way to read uninitialized memory via that channel.

Now, let's go over the KMSAN rules and see if this patch is a good fit.

1.  **Kernel structures to userspace**: No new structures are copied to userspace directly that could contain uninitialized fields. The cgroup interface uses `seq_printf` safely.

2.  **Conditional logic on uninitialized data**: There's nothing that looks like it depends on uninitialized data for branching. Everything's explicitly initialized or zeroed at allocation. I've checked all variables.

3.  **Complex data structures**: No complex data structures are allocated where uninitialized fields could be read later.

4.  **Bounds checks exposing uninitialized data**: No code exposes uninitialized memory through bounds checks.

So, I'm confident there are no KMSAN risks here. Everything is properly initialized. However, there are concurrency and locking bugs that this patch is introducing: RCU dereferencing versus writer locks, potential deadlocks between freeze/quiesce and various mutexes/spinlocks, lock order issues (e.g. `blkcg_mutex` vs `queue_lock`, vs `ioc->lock`, vs `rq_qos_mutex`), lifetime issues with BPF `struct_ops`, `bdev_put`, `gendisk` and races. But all of these risks can be detected with KASAN, LOCKDEP and standard debugging tools.

So, the conclusion is clear: this patch doesn't need KMSAN because it's not exposing or introducing uninitialized memory risks. We should use KASAN and LOCKDEP to debug concurrency, memory safety, and locking. We can confidently set `NeedsKMSAN=false`!



42/3 2026/10/29 02:10 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch series introduces BPF struct_ops support (`iocost_model_ops`) for pluggable cost models in the blk-iocost controller, along with cgroup v2 control/query integration, queue freeze/quiesce handling, an iocost tick tracepoint (`iocost_ioc_tick`), and BPF selftests.\n\nAnalysis regarding KMSAN applicability:\n1. No uninitialized memory or info-leak risks:\n   - All newly added struct members in `struct ioc` (`attached`, `model`, `bpf_link`) and `struct ioc_gq` (`bpf_iocg_inited`) reside in structures allocated using zeroing allocators (`kzalloc_obj` in `blk_iocost_init` and `kzalloc_node` in `ioc_pd_alloc`).\n   - Local variables in modified functions (e.g., `new_model`, `model_write` in `ioc_cost_model_write`, `cost` in `calc_vtime_cost` and `calc_size_vtime_cost`, `nr_active` and `now` in `ioc_timer_fn`) are explicitly initialized before any read.\n   - The tracepoint `iocost_ioc_tick` populates each TP_STRUCT__entry field explicitly from initialized state.\n   - No kernel data structures or uninitialized paddings are copied to userspace via `copy_to_user`, `put_user`, socket options, or netlink; cgroup file readbacks use `seq_printf` with static string literals.\n2. Bugs introduced by this patch are domain-specific to locking, RCU, and object lifetimes:\n   - Complex lock hierarchy (`rq_qos_mutex`, `blkcg_mutex`, `queue_lock`, `ioc-\u003elock`), queue freezing/quiescing, reference counting (`bpf_struct_ops_get`/`put`, `blkdev_get_no_open`/`blkdev_put_no_open`), and RCU dereferencing.\n   - Any bugs here (e.g., use-after-free, deadlocks, NULL pointer dereferences, or lock order inversions) are detected by KASAN and LOCKDEP.\n\nBecause there are no uninitialized memory access or info-leak risks, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch series introduces BPF struct_ops support (`iocost_model_ops`) for pluggable cost models in the blk-iocost controller, along with cgroup v2 control/query integration, queue freeze/quiesce handling, an iocost tick tracepoint (`iocost_ioc_tick`), and BPF selftests.\n\nAnalysis regarding KMSAN applicability:\n1. No uninitialized memory or info-leak risks:\n   - All newly added struct members in `struct ioc` (`attached`, `model`, `bpf_link`) and `struct ioc_gq` (`bpf_iocg_inited`) reside in structures allocated using zeroing allocators (`kzalloc_obj` in `blk_iocost_init` and `kzalloc_node` in `ioc_pd_alloc`).\n   - Local variables in modified functions (e.g., `new_model`, `model_write` in `ioc_cost_model_write`, `cost` in `calc_vtime_cost` and `calc_size_vtime_cost`, `nr_active` and `now` in `ioc_timer_fn`) are explicitly initialized before any read.\n   - The tracepoint `iocost_ioc_tick` populates each TP_STRUCT__entry field explicitly from initialized state.\n   - No kernel data structures or uninitialized paddings are copied to userspace via `copy_to_user`, `put_user`, socket options, or netlink; cgroup file readbacks use `seq_printf` with static string literals.\n2. Bugs introduced by this patch are domain-specific to locking, RCU, and object lifetimes:\n   - Complex lock hierarchy (`rq_qos_mutex`, `blkcg_mutex`, `queue_lock`, `ioc-\u003elock`), queue freezing/quiescing, reference counting (`bpf_struct_ops_get`/`put`, `blkdev_get_no_open`/`blkdev_put_no_open`), and RCU dereferencing.\n   - Any bugs here (e.g., use-after-free, deadlocks, NULL pointer dereferences, or lock order inversions) are detected by KASAN and LOCKDEP.\n\nBecause there are no uninitialized memory access or info-leak risks, a dedicated KMSAN fuzzing session is not warranted.",
  "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)