| Seq | Timestamp | Type | Name | Duration |
|---|---|---|---|---|
| 0/0 | 2026/10/01 06:10 | flow | patch-triage |
3mArgs:null Results: {
"EnableConfigs": [
"BLK_CGROUP_IOCOST_BPF",
"BLK_CGROUP_IOCOST",
"BLK_CGROUP",
"CGROUPS",
"BPF_SYSCALL",
"BPF_JIT",
"DEBUG_INFO_BTF"
],
"FocusSymbols": [
"ioc_bpf_attach",
"ioc_bpf_detach",
"ioc_bpf_walk_iocgs",
"bpf_iocost_reg",
"bpf_iocost_unreg",
"bpf_iocost_init_member",
"bpf_iocost_validate",
"ioc_cost_model_write",
"blk_get_queue_rcu"
],
"KMSANReasoning": "The patch series introduces BPF struct_ops support ('iocost_model_ops') to allow pluggable cost models in the blk-iocost block I/O controller, alongside device attachment/detachment logic, RCU-protected model selection, queue reference counting (blk_get_queue_rcu), and a periodic tracepoint.\n\nAnalysis of memory safety concerns:\n1. KASAN/LOCKDEP applicability: The changes introduce concurrency and lifetime management mechanisms (synchronizing BPF struct_ops lifecycle with request_queue teardown, RCU dereferences of the attached model, mutexes across queue freezing/quiescing, and refcount management). The primary failure modes are potential race conditions, use-after-free, refcount leaks, or deadlocks, which are thoroughly covered by KASAN and LOCKDEP in standard fuzzing builds.\n2. KMSAN applicability: No uninitialized stack or heap memory is exposed or used. 'struct ioc' is allocated via kzalloc_obj, BPF struct_ops maps zero-initialize backing storage and enforce zeroed structure padding via check_zero_holes, all local variables in the new and modified functions (such as 'cost', 'now', 'model') are explicitly assigned before use, and reporting mechanisms (seq_printf in cgroup files and trace_iocost_ioc_tick) only output formatted scalar values without leaking raw kernel memory to userspace.\n\nSince there are no uninitialized memory reads or information leak risks, a dedicated KMSAN fuzzing session is not justified.",
"NeedsKMSAN": false,
"Reasoning": "The patch series introduces BPF pluggable cost model support for the block cgroup iocost controller via a new BPF struct_ops type (\"iocost_model_ops\"). It modifies core block/cgroup code to support dynamic device attachment and detachment of BPF cost models, queue freezing/quiescing, locking coordination across rq_qos_mutex, blkcg_mutex, and ioc-\u003elock, and RCU lifetime handling for block request queues. This code is fully reachable in virtualized QEMU environments via the bpf syscall and cgroup io.cost.model interfaces.",
"WorthFuzzing": true
} |
| 1/1 | 2026/10/01 06:10 | action | read-patch-diff |
0mArgs:null Results: {
"PatchDiff": "commit 417822e4805f6cd46ac79eb071e9074a04e1589c\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate: Thu Oct 1 06:10:47 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 7fe950425216c..5e780bdcf324b 100644\n--- a/Documentation/admin-guide/cgroup-v2.rst\n+++ b/Documentation/admin-guide/cgroup-v2.rst\n@@ -2117,8 +2117,27 @@ IO Interface Files\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\tor \"bpf\" while the BPF model\n+\t\t\tis in use\n \t =====\t\t================================\n \n+\tWhen CONFIG_BLK_CGROUP_IOCOST_BPF is enabled, a BPF cost model\n+\tcan be attached to a device by loading an \"iocost_model_ops\"\n+\tstruct_ops with the whole disk's major:minor in its \"dev\" member\n+\t(a partition's major:minor is rejected). Attaching creates the\n+\tcontroller if needed, like an io.cost.model write does, and\n+\tswitches the device's pricing to the model; enabling and\n+\tdisabling the controller stays with io.cost.qos. While a model\n+\tis attached, \"model\" selects between it and the builtin model:\n+\t\"model=bpf\" switches to the attached model and \"model=linear\"\n+\tswitches back to the builtin model, and neither detaches the\n+\tstruct_ops; only detaching removes the model, after which\n+\t\"model=bpf\" fails. \"ctrl\" keeps describing the builtin\n+\tcoefficients, which are kept while the BPF model is in use and\n+\ttake effect again when switched back, and the automatic profile\n+\tstepping does not switch profiles while the BPF model is in\n+\tuse.\n+\n \tWhen \"ctrl\" is \"auto\", the kernel may change all parameters\n \tdynamically. When \"ctrl\" is set to \"user\" or any other\n \tparameters are written to, \"ctrl\" become \"user\" and the\ndiff --git a/block/Kconfig b/block/Kconfig\nindex 70e4a66d941ff..1cafc1bd0dda3 100644\n--- a/block/Kconfig\n+++ b/block/Kconfig\n@@ -231,4 +231,14 @@ config BLK_ERROR_INJECTION\n \n source \"block/Kconfig.iosched\"\n \n+config BLK_CGROUP_IOCOST_BPF\n+\tbool \"Enable BPF pluggable cost model support for the cost IO controller\"\n+\tdepends on BLK_CGROUP_IOCOST \u0026\u0026 BPF_SYSCALL \u0026\u0026 BPF_JIT \u0026\u0026 DEBUG_INFO_BTF\n+\thelp\n+\t Enabling this option registers the \"iocost_model_ops\" BPF\n+\t struct_ops type, which allows a BPF program to fully replace\n+\t the builtin linear cost model on the device it is attached\n+\t to. The struct_ops is attached per device, following the\n+\t hid_bpf_ops model.\n+\n endif # BLOCK\ndiff --git a/block/Makefile b/block/Makefile\nindex e7bd320e3d697..ee5cebeea006f 100644\n--- a/block/Makefile\n+++ b/block/Makefile\n@@ -39,3 +39,4 @@ obj-$(CONFIG_BLK_INLINE_ENCRYPTION)\t+= blk-crypto.o blk-crypto-profile.o \\\n \t\t\t\t\t blk-crypto-sysfs.o\n obj-$(CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK)\t+= blk-crypto-fallback.o\n obj-$(CONFIG_BLOCK_HOLDER_DEPRECATED)\t+= holder.o\n+obj-$(CONFIG_BLK_CGROUP_IOCOST_BPF)\t+= blk-iocost-bpf.o\ndiff --git a/block/blk-core.c b/block/blk-core.c\nindex 13dc70e8f55d9..2c789b0d86ff6 100644\n--- a/block/blk-core.c\n+++ b/block/blk-core.c\n@@ -536,6 +536,23 @@ bool blk_get_queue(struct request_queue *q)\n }\n EXPORT_SYMBOL(blk_get_queue);\n \n+/**\n+ * blk_get_queue_rcu - get a queue reference regardless of the dying flag\n+ * @q: the request_queue to reference\n+ *\n+ * Unlike blk_get_queue(), this succeeds on a dying queue, so a caller\n+ * which holds the queue only through RCU (e.g. a detach path which\n+ * read the pointer locklessly) can still take a reference and touch\n+ * the queue under its own lifetime. The caller must hold\n+ * rcu_read_lock() so the memory is valid. Fails only when the\n+ * refcount already dropped to zero.\n+ */\n+bool blk_get_queue_rcu(struct request_queue *q)\n+{\n+\treturn refcount_inc_not_zero(\u0026q-\u003erefs);\n+}\n+EXPORT_SYMBOL(blk_get_queue_rcu);\n+\n #ifdef CONFIG_FAIL_MAKE_REQUEST\n \n static DECLARE_FAULT_ATTR(fail_make_request);\ndiff --git a/block/blk-iocost-bpf.c b/block/blk-iocost-bpf.c\nnew file mode 100644\nindex 0000000000000..32a5107522b5d\n--- /dev/null\n+++ b/block/blk-iocost-bpf.c\n@@ -0,0 +1,220 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/*\n+ * blk-iocost: BPF struct_ops plumbing for pluggable cost models.\n+ *\n+ * Registers the \"iocost_model_ops\" struct_ops type. Attachment is\n+ * per-device and follows the hid_bpf_ops model: the target device is\n+ * set in the ops from userspace before load, .reg attaches the model\n+ * to that device, creating the ioc if needed and switching to the\n+ * model under the same queue freeze and quiesce as io.cost.model\n+ * writes, and .unreg detaches it; enabling and disabling the\n+ * controller stays with io.cost.qos. The struct_ops core owns the\n+ * program lifetime. There is no name registry and no separate\n+ * bound-state bookkeeping.\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 \u003clinux/blk-iocost.h\u003e\n+#include \u003clinux/blk-mq.h\u003e\n+#include \u003clinux/mutex.h\u003e\n+\n+struct block_device *blkdev_get_no_open(dev_t dev, bool autoload);\n+void blkdev_put_no_open(struct block_device *bdev);\n+bool blk_get_queue_rcu(struct request_queue *q);\n+void blk_put_queue(struct request_queue *q);\n+\n+static int bpf_iocost_model_init(struct btf *btf)\n+{\n+\ts32 type_id;\n+\n+\ttype_id = btf_find_by_name_kind(btf, \"iocost_model_ops\", BTF_KIND_STRUCT);\n+\tif (type_id \u003c 0)\n+\t\treturn -EINVAL;\n+\treturn 0;\n+}\n+\n+static bool bpf_iocost_is_valid_access(int off, int size,\n+\t\t\t\t enum bpf_access_type type,\n+\t\t\t\t const struct bpf_prog *prog,\n+\t\t\t\t struct bpf_insn_access_aux *info)\n+{\n+\treturn bpf_tracing_btf_ctx_access(off, size, type, prog, info);\n+}\n+\n+/*\n+ * No iocost-specific helpers; bpf_base_func_proto already covers the\n+ * cgroup storage helpers under CONFIG_CGROUPS.\n+ */\n+static const struct bpf_func_proto *\n+bpf_iocost_get_func_proto(enum bpf_func_id func_id,\n+\t\t\t const struct bpf_prog *prog)\n+{\n+\treturn bpf_base_func_proto(func_id, prog);\n+}\n+\n+static int bpf_iocost_check_member(const struct btf_type *t,\n+\t\t\t\t const struct btf_member *member,\n+\t\t\t\t const struct bpf_prog *prog)\n+{\n+\t/* calc_cost() is called with RCU read lock held */\n+\tif (prog-\u003esleepable)\n+\t\treturn -EINVAL;\n+\treturn 0;\n+}\n+\n+static int bpf_iocost_init_member(const struct btf_type *t,\n+\t\t\t\t const struct btf_member *member,\n+\t\t\t\t void *kdata, const void *udata)\n+{\n+\tstruct iocost_model_ops *ops = kdata;\n+\tconst struct iocost_model_ops *uops = udata;\n+\tu32 moff = __btf_member_bit_offset(t, member) / 8;\n+\n+\tswitch (moff) {\n+\tcase offsetof(struct iocost_model_ops, bdev):\n+\t\t/*\n+\t\t * kernel-private: the bdev reference held while\n+\t\t * attached; reject a userspace value\n+\t\t */\n+\t\tif (uops-\u003ebdev)\n+\t\t\treturn -EINVAL;\n+\t\tops-\u003ebdev = NULL;\n+\t\treturn 1;\n+\tcase offsetof(struct iocost_model_ops, q):\n+\t\t/* kernel-private: the queue of the attached device */\n+\t\tif (uops-\u003eq)\n+\t\t\treturn -EINVAL;\n+\t\tops-\u003eq = NULL;\n+\t\treturn 1;\n+\tcase offsetof(struct iocost_model_ops, dev):\n+\t\t/*\n+\t\t * copy it and return 1 to indicate that the member is\n+\t\t * handled here, or the verifier rejects the map if the\n+\t\t * userspace value is nonzero\n+\t\t */\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+ * kvalue is zeroed at map allocation and function members are only\n+ * written when the BPF side provides a prog, so a model which did\n+ * not implement calc_cost leaves it NULL. The dispatch would call\n+ * it on every bio, so reject it here.\n+ */\n+static int bpf_iocost_validate(void *kdata)\n+{\n+\tstruct iocost_model_ops *ops = kdata;\n+\n+\treturn ops-\u003ecalc_cost ? 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+\tif (!ops-\u003edev)\n+\t\treturn -EINVAL;\n+\n+\treturn ioc_bpf_attach(ops);\n+}\n+\n+static void bpf_iocost_unreg(void *kdata, struct bpf_link *link)\n+{\n+\tstruct iocost_model_ops *ops = kdata;\n+\tstruct block_device *bdev;\n+\tstruct request_queue *q;\n+\n+\t/*\n+\t * ops-\u003eq may already have been cleared by the removal ejection;\n+\t * take a queue reference under RCU before entering the queue,\n+\t * as the queue may be dying and its memory is only guaranteed\n+\t * under rcu_read_lock()\n+\t */\n+\trcu_read_lock();\n+\tq = rcu_dereference(ops-\u003eq);\n+\tif (!q || !blk_get_queue_rcu(q)) {\n+\t\trcu_read_unlock();\n+\t\treturn;\n+\t}\n+\trcu_read_unlock();\n+\n+\t/*\n+\t * take rq_qos_mutex before touching the queue further: the\n+\t * removal ejection clears ops-\u003eq under it, inside rq_qos_exit()\n+\t * and before blk_mq_exit_queue() releases the hardware queues,\n+\t * so holding it and seeing a non-NULL ops-\u003eq guarantees the\n+\t * queue is still safe to freeze. The freeze and quiesce are\n+\t * done inside ioc_bpf_detach(), under the mutex.\n+\t */\n+\tmutex_lock(\u0026q-\u003erq_qos_mutex);\n+\tif (!ops-\u003eq) {\n+\t\t/* the removal ejection won the race; nothing to detach */\n+\t\tmutex_unlock(\u0026q-\u003erq_qos_mutex);\n+\t\tblk_put_queue(q);\n+\t\treturn;\n+\t}\n+\tbdev = ops-\u003ebdev;\n+\tioc_bpf_detach(ops);\n+\tmutex_unlock(\u0026q-\u003erq_qos_mutex);\n+\tblk_put_queue(q);\n+\n+\t/* drop the attach reference when we did the detach */\n+\tif (bdev)\n+\t\tblkdev_put_no_open(bdev);\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 2745bffcd5eef..64744266cfd30 100644\n--- a/block/blk-iocost.c\n+++ b/block/blk-iocost.c\n@@ -177,6 +177,7 @@\n #include \u003clinux/timer.h\u003e\n #include \u003clinux/time64.h\u003e\n #include \u003clinux/parser.h\u003e\n+#include \u003clinux/blk-iocost.h\u003e\n #include \u003clinux/sched/signal.h\u003e\n #include \u003casm/local.h\u003e\n #include \u003casm/local64.h\u003e\n@@ -445,6 +446,13 @@ struct ioc {\n \tint\t\t\t\tautop_idx;\n \tbool\t\t\t\tuser_qos_params:1;\n \tbool\t\t\t\tuser_cost_model:1;\n+\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\t/* the struct_ops attached to this device, NULL = none */\n+\tconst struct iocost_model_ops\t__rcu *attached;\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@@ -780,6 +788,45 @@ static void ioc_refresh_period_us(struct ioc *ioc)\n \tioc_refresh_margins(ioc);\n }\n \n+/*\n+ * The BPF model in use, or NULL when the builtin linear model prices\n+ * this device. CONFIG_BLK_CGROUP_IOCOST_BPF=n compiles to a constant\n+ * NULL so callers need no #ifdefs.\n+ */\n+static const struct iocost_model_ops *ioc_model_in_use(struct ioc *ioc)\n+{\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\treturn rcu_dereference(ioc-\u003emodel);\n+#else\n+\treturn NULL;\n+#endif\n+}\n+\n+/*\n+ * The struct_ops attached to this device, or NULL. While attachment\n+ * and model selection are independent, the cgroup callbacks follow\n+ * the attachment, not the selection.\n+ */\n+static const struct iocost_model_ops *ioc_attached_or_null(struct ioc *ioc)\n+{\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\treturn rcu_dereference(ioc-\u003eattached);\n+#else\n+\treturn NULL;\n+#endif\n+}\n+\n+static const struct iocost_model_ops *\n+ioc_model_in_use_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 * ioc-\u003erqos.disk isn't initialized when this function is called from\n * the init path.\n@@ -803,8 +850,13 @@ 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,\n+\t * maintain what was there: the builtin coefficients are inert\n+\t * then, so stepping the profile is pointless\n+\t */\n+\tif (ioc-\u003euser_qos_params || ioc-\u003euser_cost_model ||\n+\t ioc_model_in_use_locked(ioc))\n \t\treturn idx;\n \n \t/* step up/down based on the vrate */\n@@ -2238,6 +2290,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@@ -2274,6 +2327,8 @@ static void ioc_timer_fn(struct timer_list *timer)\n \t\tu64 vdone, vtime, usage_us;\n \t\tu32 hw_active, hw_inuse;\n \n+\t\tnr_active++;\n+\n \t\t/*\n \t\t * Collect unused and wind vtime closer to vnow to prevent\n \t\t * iocgs from accumulating a large amount of budget.\n@@ -2435,6 +2490,15 @@ 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, running and cur_period haven't changed, nr_active and\n+\t * usage_us_sum are complete, and vrate and period_us still hold\n+\t * the values this period ran in. Emit before the refresh below\n+\t * so the event reads 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@@ -2571,8 +2635,19 @@ static void calc_vtime_cost_builtin(struct bio *bio, struct ioc_gq *iocg,\n \n static u64 calc_vtime_cost(struct bio *bio, struct ioc_gq *iocg, bool is_merge)\n {\n+\tconst struct iocost_model_ops *model;\n \tu64 cost;\n \n+\trcu_read_lock();\n+\tmodel = ioc_model_in_use(iocg-\u003eioc);\n+\tif (model) {\n+\t\tcost = model-\u003ecalc_cost(bio,\n+\t\t\t\tis_merge ? IOCOST_COST_F_MERGE : 0);\n+\t\trcu_read_unlock();\n+\t\treturn min(cost, VTIME_PER_SEC);\n+\t}\n+\trcu_read_unlock();\n+\n \tcalc_vtime_cost_builtin(bio, iocg, is_merge, \u0026cost);\n \treturn cost;\n }\n@@ -2594,10 +2669,32 @@ static void calc_size_vtime_cost_builtin(struct request *rq, struct ioc *ioc,\n \t}\n }\n \n+/*\n+ * Called from the request completion path, where no ioc-\u003elock is\n+ * held; the model pointer is read under RCU, matching the bio-side\n+ * calc_vtime_cost().\n+ */\n static u64 calc_size_vtime_cost(struct request *rq, struct ioc *ioc)\n {\n+\tconst struct iocost_model_ops *model;\n \tu64 cost;\n \n+\trcu_read_lock();\n+\tmodel = ioc_model_in_use(ioc);\n+\tif (model \u0026\u0026 (req_op(rq) == REQ_OP_READ ||\n+\t\t req_op(rq) == REQ_OP_WRITE)) {\n+\t\tunsigned int pages =\n+\t\t\tblk_rq_stats_sectors(rq) \u003e\u003e IOC_SECT_TO_PAGE_SHIFT;\n+\t\tu64 coeff = req_op(rq) == REQ_OP_READ ?\n+\t\t\tmodel-\u003eread_vtime_per_page :\n+\t\t\tmodel-\u003ewrite_vtime_per_page;\n+\n+\t\tcost = pages * coeff;\n+\t\trcu_read_unlock();\n+\t\treturn cost;\n+\t}\n+\trcu_read_unlock();\n+\n \tcalc_size_vtime_cost_builtin(rq, ioc, \u0026cost);\n \treturn cost;\n }\n@@ -2900,6 +2997,24 @@ static void ioc_rqos_exit(struct rq_qos *rqos)\n \n \ttimer_shutdown_sync(\u0026ioc-\u003etimer);\n \tfree_percpu(ioc-\u003epcpu_stat);\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\t{\n+\t\tstruct iocost_model_ops *ops;\n+\n+\t\tspin_lock_irq(\u0026ioc-\u003elock);\n+\t\tops = (struct iocost_model_ops *)rcu_dereference_protected(\n+\t\t\t\tioc-\u003eattached, lockdep_is_held(\u0026ioc-\u003elock));\n+\t\trcu_assign_pointer(ioc-\u003eattached, NULL);\n+\t\trcu_assign_pointer(ioc-\u003emodel, NULL);\n+\t\tspin_unlock_irq(\u0026ioc-\u003elock);\n+\n+\t\t/* eject the model completely on device removal */\n+\t\tif (ops) {\n+\t\t\tWRITE_ONCE(ops-\u003eq, NULL);\n+\t\t\tblkdev_put_no_open(ops-\u003ebdev);\n+\t\t}\n+\t}\n+#endif\n \tkfree(ioc);\n }\n \n@@ -3022,6 +3137,7 @@ static void ioc_pd_init(struct blkg_policy_data *pd)\n \tstruct ioc_now now;\n \tstruct blkcg_gq *tblkg;\n \tunsigned long flags;\n+\tconst struct iocost_model_ops *model;\n \n \tioc_now(ioc, \u0026now);\n \n@@ -3048,6 +3164,18 @@ static void ioc_pd_init(struct blkg_policy_data *pd)\n \tspin_lock_irqsave(\u0026ioc-\u003elock, flags);\n \tweight_updated(iocg, \u0026now);\n \tspin_unlock_irqrestore(\u0026ioc-\u003elock, flags);\n+\n+\t/*\n+\t * the attached model is RCU-protected: a concurrent detach\n+\t * publishes NULL and the struct_ops image survives it by a\n+\t * grace period, so the callback is safe inside the read-side\n+\t * critical section\n+\t */\n+\trcu_read_lock();\n+\tmodel = ioc_attached_or_null(ioc);\n+\tif (model \u0026\u0026 model-\u003eiocg_init)\n+\t\tmodel-\u003eiocg_init(blkg-\u003eblkcg, ioc-\u003erqos.disk-\u003equeue);\n+\trcu_read_unlock();\n }\n \n static void iocg_release(struct rcu_head *rcu)\n@@ -3066,8 +3194,15 @@ static void ioc_pd_free(struct blkg_policy_data *pd)\n \tstruct blkcg_gq *blkg = pd_to_blkg(pd);\n \tstruct ioc *ioc = iocg-\u003eioc;\n \tunsigned long flags;\n+\tconst struct iocost_model_ops *model;\n \n \tif (ioc) {\n+\t\trcu_read_lock();\n+\t\tmodel = ioc_attached_or_null(ioc);\n+\t\tif (model \u0026\u0026 model-\u003eiocg_free)\n+\t\t\tmodel-\u003eiocg_free(blkg-\u003eblkcg, ioc-\u003erqos.disk-\u003equeue);\n+\t\trcu_read_unlock();\n+\n \t\tspin_lock_irqsave(\u0026ioc-\u003elock, flags);\n \n \t\tif (!list_empty(\u0026iocg-\u003eactive_list)) {\n@@ -3433,17 +3568,21 @@ 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_model_in_use_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\",\n \t\t dname, ioc-\u003euser_cost_model ? \"user\" : \"auto\",\n-\t\t u[I_LCOEF_RBPS], u[I_LCOEF_RSEQIOPS], u[I_LCOEF_RRANDIOPS],\n-\t\t u[I_LCOEF_WBPS], u[I_LCOEF_WSEQIOPS], u[I_LCOEF_WRANDIOPS]);\n+\t\t model ? \"bpf\" : \"linear\",\n+\t\t u[I_LCOEF_RBPS], u[I_LCOEF_RSEQIOPS],\n+\t\t u[I_LCOEF_RRANDIOPS], u[I_LCOEF_WBPS],\n+\t\t u[I_LCOEF_WSEQIOPS], u[I_LCOEF_WRANDIOPS]);\n \tspin_unlock_irq(\u0026ioc-\u003elock);\n \treturn 0;\n }\n@@ -3457,6 +3596,204 @@ static int ioc_cost_model_show(struct seq_file *sf, void *v)\n \treturn 0;\n }\n \n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+/*\n+ * Deliver iocg_init()/iocg_free() to the cgroups which already have a\n+ * blkg on the queue, the same q-\u003eblkg_list walk the blkcg policy\n+ * teardown uses. The queue is frozen and quiesced and blkcg_mutex\n+ * serializes against blkg creation and destruction. Cgroups without\n+ * a blkg on the device yet are not missed: their blkg is created\n+ * later and ioc_pd_init()/ioc_pd_free() deliver the callbacks then.\n+ */\n+static void ioc_bpf_walk_iocgs(struct ioc *ioc,\n+\t\t\t const struct iocost_model_ops *ops, 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+\n+\trcu_read_lock();\n+\tlist_for_each_entry(blkg, \u0026q-\u003eblkg_list, q_node) {\n+\t\tif (!blkg_to_iocg(blkg))\n+\t\t\tcontinue;\n+\t\tif (init) {\n+\t\t\tif (ops-\u003eiocg_init)\n+\t\t\t\tops-\u003eiocg_init(blkg-\u003eblkcg, q);\n+\t\t} else {\n+\t\t\tif (ops-\u003eiocg_free)\n+\t\t\t\tops-\u003eiocg_free(blkg-\u003eblkcg, q);\n+\t\t}\n+\t}\n+\trcu_read_unlock();\n+}\n+\n+int ioc_bpf_attach(struct iocost_model_ops *ops)\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+\t/* prevent multiple attach of the same struct_ops */\n+\tif (ops-\u003eq)\n+\t\treturn -EINVAL;\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\tret = -EINVAL;\n+\t\tgoto put;\n+\t}\n+\tif (!queue_is_mq(q)) {\n+\t\tret = -EOPNOTSUPP;\n+\t\tgoto put;\n+\t}\n+\n+\t/*\n+\t * check liveness and create the ioc under rq_qos_mutex, like\n+\t * blkg_conf_open_bdev() does; enabling stays with io.cost.qos\n+\t *\n+\t * the queue reference is held across the unlocked window below:\n+\t * the bdev reference does not pin the queue, bdev only holds a\n+\t * raw bd_queue pointer, and concurrent device removal may eject\n+\t * the model and free the ioc while we are off the mutex, so\n+\t * without our own reference the second mutex_lock() would touch\n+\t * a freed queue\n+\t */\n+\tmutex_lock(\u0026q-\u003erq_qos_mutex);\n+\tif (!disk_live(disk) || !blk_get_queue(q)) {\n+\t\tmutex_unlock(\u0026q-\u003erq_qos_mutex);\n+\t\tret = -ENODEV;\n+\t\tgoto put;\n+\t}\n+\tioc = q_to_ioc(q);\n+\tif (!ioc) {\n+\t\tret = blk_iocost_init(disk);\n+\t\tmutex_unlock(\u0026q-\u003erq_qos_mutex);\n+\t\tif (ret)\n+\t\t\tgoto put_q;\n+\t\tioc = q_to_ioc(q);\n+\t} else {\n+\t\tmutex_unlock(\u0026q-\u003erq_qos_mutex);\n+\t}\n+\n+\t/*\n+\t * ops-\u003ebdev is dropped by the removal ejection or by .unreg,\n+\t * whichever detaches the model first, similar to hid_bpf's\n+\t * per-ops device reference without the struct file and without\n+\t * pinning the driver module\n+\t */\n+\n+\t/*\n+\t * switch the model under the same freeze and quiesce as the\n+\t * io.cost.model writes; the freeze does not pin the ioc, so\n+\t * rq_qos_mutex has to be held across the switch - ioc_rqos_exit()\n+\t * frees the ioc under it\n+\t */\n+\tmutex_lock(\u0026q-\u003erq_qos_mutex);\n+\tioc = q_to_ioc(q);\n+\tif (!ioc) {\n+\t\tmutex_unlock(\u0026q-\u003erq_qos_mutex);\n+\t\tret = -ENODEV;\n+\t\tgoto put_q;\n+\t}\n+\tmemflags = blk_mq_freeze_queue(q);\n+\tblk_mq_quiesce_queue(q);\n+\n+\t/*\n+\t * hold blkcg_mutex across the publish and the iocg_init() walk:\n+\t * ioc_pd_init() runs under it too, so no cgroup can receive\n+\t * iocg_init() from both the walk and its own pd_init\n+\t */\n+\tmutex_lock(\u0026q-\u003eblkcg_mutex);\n+\tspin_lock_irq(\u0026ioc-\u003elock);\n+\tif (rcu_dereference_protected(ioc-\u003eattached,\n+\t\t\t\t lockdep_is_held(\u0026ioc-\u003elock))) {\n+\t\tspin_unlock_irq(\u0026ioc-\u003elock);\n+\t\tmutex_unlock(\u0026q-\u003eblkcg_mutex);\n+\t\tblk_mq_unquiesce_queue(q);\n+\t\tblk_mq_unfreeze_queue(q, memflags);\n+\t\tmutex_unlock(\u0026q-\u003erq_qos_mutex);\n+\t\tret = -EBUSY;\n+\t\tgoto put_q;\n+\t}\n+\trcu_assign_pointer(ioc-\u003eattached, ops);\n+\trcu_assign_pointer(ioc-\u003emodel, ops);\n+\tspin_unlock_irq(\u0026ioc-\u003elock);\n+\n+\tops-\u003ebdev = bdev;\n+\tWRITE_ONCE(ops-\u003eq, q);\n+\n+\t/* pair iocg_init() with the cgroups which already exist */\n+\tioc_bpf_walk_iocgs(ioc, ops, true);\n+\tmutex_unlock(\u0026q-\u003eblkcg_mutex);\n+\n+\tblk_mq_unquiesce_queue(q);\n+\tblk_mq_unfreeze_queue(q, memflags);\n+\tmutex_unlock(\u0026q-\u003erq_qos_mutex);\n+\tblk_put_queue(q);\n+\treturn 0;\n+\n+put_q:\n+\tblk_put_queue(q);\n+put:\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\n+ * model is in use, clear the attachment, and deliver iocg_free() to\n+ * the cgroups which still exist, under the same freeze and quiesce as\n+ * the attach. The caller has already checked ops-\u003eq.\n+ */\n+void ioc_bpf_detach(struct iocost_model_ops *ops)\n+{\n+\tstruct request_queue *q = ops-\u003eq;\n+\tstruct ioc *ioc;\n+\tunsigned int memflags;\n+\n+\tif (!q)\n+\t\treturn;\n+\tioc = q_to_ioc(q);\n+\tif (!ioc)\n+\t\treturn;\n+\n+\tmemflags = blk_mq_freeze_queue(q);\n+\tblk_mq_quiesce_queue(q);\n+\n+\t/*\n+\t * hold blkcg_mutex across the clearing and the iocg_free() walk:\n+\t * ioc_pd_free() runs under it too, so no cgroup can receive\n+\t * iocg_free() from both the walk and its own pd_free\n+\t */\n+\tmutex_lock(\u0026q-\u003eblkcg_mutex);\n+\tspin_lock_irq(\u0026ioc-\u003elock);\n+\tif (rcu_dereference_protected(ioc-\u003emodel,\n+\t\t\t\t lockdep_is_held(\u0026ioc-\u003elock)) == ops)\n+\t\trcu_assign_pointer(ioc-\u003emodel, NULL);\n+\trcu_assign_pointer(ioc-\u003eattached, NULL);\n+\tspin_unlock_irq(\u0026ioc-\u003elock);\n+\n+\t/* pair iocg_free() with the cgroups which still exist */\n+\tioc_bpf_walk_iocgs(ioc, ops, false);\n+\tmutex_unlock(\u0026q-\u003eblkcg_mutex);\n+\n+\tWRITE_ONCE(ops-\u003eq, NULL);\n+\n+\tblk_mq_unquiesce_queue(q);\n+\tblk_mq_unfreeze_queue(q, memflags);\n+}\n+\n+#endif\n+\n static const match_table_t cost_ctrl_tokens = {\n \t{ COST_CTRL,\t\t\"ctrl=%s\"\t},\n \t{ COST_MODEL,\t\t\"model=%s\"\t},\n@@ -3484,6 +3821,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+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\tconst struct iocost_model_ops *new_model = NULL;\n+\tbool model_write = false;\n+#endif\n \n \tblkg_conf_init(\u0026ctx, input);\n \n@@ -3536,9 +3877,28 @@ 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+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\t\t\t\t/* staged and committed below, so a parse\n+\t\t\t\t * error later in the same write leaves\n+\t\t\t\t * the model selection untouched */\n+\t\t\t\tnew_model = NULL;\n+\t\t\t\tmodel_write = true;\n+#endif\n+\t\t\t\tcontinue;\n+\t\t\t}\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\t\t\tif (!strcmp(buf, \"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\tif (!new_model)\n+\t\t\t\t\tgoto unlock;\n+\t\t\t\tmodel_write = true;\n+\t\t\t\tcontinue;\n+\t\t\t}\n+#endif\n+\t\t\tgoto unlock;\n \t\t}\n \n \t\ttok = match_token(p, i_lcoef_tokens, args);\n@@ -3556,6 +3916,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;\ndiff --git a/include/linux/blk-iocost.h b/include/linux/blk-iocost.h\nnew file mode 100644\nindex 0000000000000..03a0c7dab71fd\n--- /dev/null\n+++ b/include/linux/blk-iocost.h\n@@ -0,0 +1,110 @@\n+/* SPDX-License-Identifier: GPL-2.0 */\n+#ifndef _LINUX_BLK_IOCOST_H\n+#define _LINUX_BLK_IOCOST_H\n+\n+#include \u003clinux/types.h\u003e\n+#include \u003clinux/blk_types.h\u003e\n+#include \u003clinux/blkdev.h\u003e\n+\n+struct bio;\n+struct blkcg;\n+struct request_queue;\n+\n+/*\n+ * Pluggable cost model interface for blk-iocost.\n+ *\n+ * A BPF struct_ops implementation is attached to one device, identified\n+ * by the dev member set from userspace before load, following the\n+ * hid_bpf_ops model: the struct_ops core owns the lifetime of the\n+ * program. Attaching creates the ioc if needed, like an io.cost.model\n+ * write does, switches the device to the BPF model under the same\n+ * queue freeze and quiesce, and delivers iocg_init() to the cgroups\n+ * which already exist on the device. Enabling and disabling the\n+ * controller stays with io.cost.qos. While a model is attached,\n+ * io.cost.model selects between it and the builtin model: \"model=bpf\"\n+ * switches to the attached model, \"model=linear\" switches back to the\n+ * builtin model, and neither detaches the struct_ops; only detaching\n+ * removes the model. The builtin linear coefficients are kept while\n+ * the BPF model is in use and take effect again when switched back.\n+ *\n+ * While the BPF model is the one in use, it owns pricing for every\n+ * charged IO on the device: it prices all operations, including\n+ * flushes, from the bio charging path.\n+ *\n+ * calc_cost() is called from the IO submission path with RCU read lock\n+ * held and must not sleep. It receives the bio itself so the model\n+ * can read whatever it needs (operation flags, size, sector, the\n+ * issuing cgroup through bio-\u003ebi_blkg). It returns the cost of the\n+ * IO in vtime units, where 1 second of device time equals\n+ * VTIME_PER_SEC (2^37, available to BPF programs through vmlinux.h).\n+ * The returned value is clamped to 1 second of device time per IO.\n+ *\n+ * The struct_ops also carries the transfer cost coefficients, vtime\n+ * per page for reads and writes: while the BPF model is in use, the\n+ * builtin latency tracking and vrate adjustment use these instead of\n+ * the builtin linear coefficients for the completion-time request\n+ * sizing, so the whole controller follows the model's pricing. Letting\n+ * a model take over the QoS side entirely (latency tracking, vrate\n+ * control) is left for a later extension.\n+ *\n+ * The cgroup callbacks are bound to the iocg policy lifetime, one\n+ * (cgroup, device) pair per invocation: iocg_init() is delivered on\n+ * attach to every cgroup which already exists on the device and to\n+ * each one appearing afterwards; iocg_free() is delivered on detach to\n+ * every cgroup still existing then, and at policy deactivation time\n+ * for the rest, so init and free always pair up. Both callbacks run\n+ * inside an RCU read-side critical section and must not sleep.\n+ */\n+\n+/*\n+ * iocost-specific call metadata for calc_cost()'s model_flags\n+ * argument; the merge indicator is not a property of the bio.\n+ * An enum so the value is exported through BTF and BPF models can\n+ * use it from vmlinux.h.\n+ */\n+enum {\n+\tIOCOST_COST_F_MERGE\t= 1 \u003c\u003c 0,\t/* called from merge path */\n+};\n+\n+struct iocost_model_ops {\n+\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, used by the builtin sizing and vrate logic */\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+\t/* private: */\n+\n+\t/*\n+\t * bdev reference held while attached; dropped by the removal\n+\t * ejection or .unreg, whichever detaches the model first\n+\t */\n+\tstruct block_device\t*bdev;\n+\t/* queue of the attached device, NULL = not attached */\n+\tstruct request_queue\t*q;\n+};\n+\n+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF\n+\n+int ioc_bpf_attach(struct iocost_model_ops *ops);\n+void ioc_bpf_detach(struct iocost_model_ops *ops);\n+\n+#else\t/* CONFIG_BLK_CGROUP_IOCOST_BPF */\n+\n+static inline int ioc_bpf_attach(struct iocost_model_ops *ops)\n+{\n+\treturn -EOPNOTSUPP;\n+}\n+static inline void ioc_bpf_detach(struct iocost_model_ops *ops) { }\n+\n+#endif\t/* CONFIG_BLK_CGROUP_IOCOST_BPF */\n+#endif\t/* _LINUX_BLK_IOCOST_H */\ndiff --git a/include/trace/events/iocost.h b/include/trace/events/iocost.h\nindex e772b1bc60d60..79773e82d42cf 100644\n--- a/include/trace/events/iocost.h\n+++ b/include/trace/events/iocost.h\n@@ -178,6 +178,50 @@ TRACE_EVENT(iocost_ioc_vrate_adj,\n \t)\n );\n \n+/*\n+ * Periodic per-device summary, emitted once per period from the tail of\n+ * ioc_timer_fn(). Unlike the state-change events above, this fires every\n+ * period the controller is running, including steady states, and carries\n+ * the overall controller state so basic monitoring doesn't require drgn.\n+ */\n+TRACE_EVENT(iocost_ioc_tick,\n+\n+\tTP_PROTO(struct ioc *ioc, 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\t__field(int, running)\n+\t),\n+\n+\tTP_fast_assign(\n+\t\t__assign_str(devname);\n+\t\t__entry-\u003ecur_period = atomic64_read(\u0026ioc-\u003ecur_period);\n+\t\t__entry-\u003eperiod_us = 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\t__entry-\u003erunning = ioc-\u003erunning;\n+\t),\n+\n+\tTP_printk(\"[%s] period=%llu:%uus vrate=%llu busy=%d active=%d usage=%u%% running=%d\",\n+\t\t__get_str(devname), __entry-\u003ecur_period, __entry-\u003eperiod_us,\n+\t\t__entry-\u003evrate, __entry-\u003ebusy_level, __entry-\u003enr_active,\n+\t\t__entry-\u003eusage_pct, __entry-\u003erunning\n+\t)\n+);\n+\n TRACE_EVENT(iocost_iocg_forgive_debt,\n \n \tTP_PROTO(struct ioc_gq *iocg, const char *path, struct ioc_now *now,\ndiff --git a/tools/testing/selftests/bpf/config b/tools/testing/selftests/bpf/config\nindex 2b883b388f90c..c5634ee91e690 100644\n--- a/tools/testing/selftests/bpf/config\n+++ b/tools/testing/selftests/bpf/config\n@@ -140,3 +140,5 @@ CONFIG_SMC_HS_CTRL_BPF=y\n CONFIG_DIBS=y\n CONFIG_DIBS_LO=y\n CONFIG_PM_WAKELOCKS=y\n+CONFIG_BLK_CGROUP_IOCOST=y\n+CONFIG_BLK_CGROUP_IOCOST_BPF=y\ndiff --git a/tools/testing/selftests/bpf/prog_tests/iocost_model.c b/tools/testing/selftests/bpf/prog_tests/iocost_model.c\nnew file mode 100644\nindex 0000000000000..5b7b1282fcb74\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/prog_tests/iocost_model.c\n@@ -0,0 +1,245 @@\n+// SPDX-License-Identifier: GPL-2.0\n+#include \u003ctest_progs.h\u003e\n+#include \u003cfcntl.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+ * Read back the io.cost.model line of dev and copy the model= value\n+ * into @model. Returns 0 on success.\n+ */\n+static int readback_model(const char *dev, char *model, size_t model_sz)\n+{\n+\tchar line[256], word[256], *m, *end;\n+\tFILE *fp;\n+\tint found = 0;\n+\n+\tfp = fopen(\"/sys/fs/cgroup/io.cost.model\", \"r\");\n+\tif (!fp)\n+\t\treturn -1;\n+\twhile (fgets(line, sizeof(line), fp)) {\n+\t\tif (sscanf(line, \"%255s\", word) == 1 \u0026\u0026 !strcmp(word, dev)) {\n+\t\t\tfound = 1;\n+\t\t\tbreak;\n+\t\t}\n+\t}\n+\tfclose(fp);\n+\tif (!found)\n+\t\treturn -1;\n+\n+\tm = strstr(line, \"model=\");\n+\tif (!m)\n+\t\treturn -1;\n+\tm += strlen(\"model=\");\n+\tend = m;\n+\twhile (*end \u0026\u0026 *end != ' ')\n+\t\tend++;\n+\tsnprintf(model, model_sz, \"%.*s\", (int)(end - m), m);\n+\treturn 0;\n+}\n+\n+/*\n+ * Write a line to io.cost.model for dev and return the errno of the\n+ * write (0 on success).\n+ */\n+static int write_cost_model(const char *dev, const char *what)\n+{\n+\tchar buf[128], line[256], word[256];\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 one device, given as major:minor in\n+ * $IOCOST_TEST_DEV: the dev member is written through the struct_ops\n+ * map's initial value before load, as hid_bpf_ops does with hid_id,\n+ * and attaching the struct_ops attaches the model to the device.\n+ * Detaching the struct_ops restores the builtin model.\n+ *\n+ * Requires root, cgroup v2 and a device with iocost support.\n+ */\n+void serial_test_iocost_model(void)\n+{\n+\tstruct iocost_model *skel, *second;\n+\tunsigned int maj, min;\n+\t__u32 *ops_dev, *sdev;\n+\tint err;\n+\tchar model[32], *dev;\n+\n+\tdev = getenv(\"IOCOST_TEST_DEV\");\n+\tif (!dev || geteuid() != 0 || sscanf(dev, \"%u:%u\", \u0026maj, \u0026min) != 2) {\n+\t\tprintf(\"%s:SKIP:needs root and IOCOST_TEST_DEV=\u003cmaj\u003e:\u003cmin\u003e\\n\",\n+\t\t __func__);\n+\t\ttest__skip();\n+\t\treturn;\n+\t}\n+\n+\tskel = iocost_model__open();\n+\tif (!ASSERT_OK_PTR(skel, \"skel_open\"))\n+\t\treturn;\n+\n+\t/* dev is the first member of struct iocost_model_ops */\n+\tops_dev = bpf_map__initial_value(skel-\u003emaps.iocost_2x, NULL);\n+\tif (!ASSERT_OK_PTR(ops_dev, \"initial_value\")) {\n+\t\tiocost_model__destroy(skel);\n+\t\treturn;\n+\t}\n+\t*ops_dev = (__u32)makedev(maj, min);\n+\n+\terr = iocost_model__load(skel);\n+\tif (!ASSERT_OK(err, \"skel_load\")) {\n+\t\tiocost_model__destroy(skel);\n+\t\treturn;\n+\t}\n+\n+\terr = iocost_model__attach(skel);\n+\tif (err == -EOPNOTSUPP) {\n+\t\tprintf(\"%s: device is not blk-mq or iocost unavailable, skipping\\n\",\n+\t\t __func__);\n+\t\tiocost_model__destroy(skel);\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_EQ(strcmp(model, \"bpf\"), 0, \"model_bpf\");\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\tsdev = bpf_map__initial_value(\n+\t\t\t\t\tsecond-\u003emaps.iocost_2x, NULL);\n+\t\t\tif (!ASSERT_OK_PTR(sdev, \"second_initial_value\"))\n+\t\t\t\tgoto out_destroy;\n+\t\t\t*sdev = (__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+out_destroy:\n+\t\t\tiocost_model__destroy(second);\n+\t\t}\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_EQ(strcmp(model, \"linear\"), 0, \"model_linear\");\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_EQ(strcmp(model, \"bpf\"), 0, \"model_bpf\");\n+\n+\t\tiocost_model__detach(skel);\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_EQ(strcmp(model, \"linear\"), 0, \"model_linear\");\n+\t}\n+\n+\tiocost_model__destroy(skel);\n+}\n+/*\n+ * Same check for the multi-stream example model. Only one model can\n+ * be attached to a device at a time; both tests attach and detach, so\n+ * they are serial and independent.\n+ */\n+void serial_test_iocost_model_streams(void)\n+{\n+\tstruct iocost_ms *skel;\n+\tunsigned int maj, min;\n+\t__u32 *ops_dev;\n+\tint err;\n+\tchar model[32], *dev;\n+\n+\tdev = getenv(\"IOCOST_TEST_DEV\");\n+\tif (!dev || geteuid() != 0 || sscanf(dev, \"%u:%u\", \u0026maj, \u0026min) != 2) {\n+\t\tprintf(\"%s:SKIP:needs root and IOCOST_TEST_DEV=\u003cmaj\u003e:\u003cmin\u003e\\n\",\n+\t\t __func__);\n+\t\ttest__skip();\n+\t\treturn;\n+\t}\n+\n+\tskel = iocost_ms__open();\n+\tif (!ASSERT_OK_PTR(skel, \"skel_open\"))\n+\t\treturn;\n+\n+\tops_dev = bpf_map__initial_value(skel-\u003emaps.iocost_ms, NULL);\n+\tif (!ASSERT_OK_PTR(ops_dev, \"initial_value\")) {\n+\t\tiocost_ms__destroy(skel);\n+\t\treturn;\n+\t}\n+\t*ops_dev = (__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\treturn;\n+\t}\n+\n+\terr = iocost_ms__attach(skel);\n+\tif (err == -EOPNOTSUPP) {\n+\t\tprintf(\"%s: device is not blk-mq or iocost unavailable, skipping\\n\",\n+\t\t __func__);\n+\t\tiocost_ms__destroy(skel);\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_EQ(strcmp(model, \"bpf\"), 0, \"model_bpf\");\n+\n+\t\tiocost_ms__detach(skel);\n+\n+\t\terr = readback_model(dev, model, sizeof(model));\n+\t\tif (ASSERT_OK(err, \"readback_after_detach\"))\n+\t\t\tASSERT_EQ(strcmp(model, \"linear\"), 0, \"model_linear\");\n+\t}\n+\n+\tiocost_ms__destroy(skel);\n+}\ndiff --git a/tools/testing/selftests/bpf/progs/iocost_model.c b/tools/testing/selftests/bpf/progs/iocost_model.c\nnew file mode 100644\nindex 0000000000000..e8f222c50b39c\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/progs/iocost_model.c\n@@ -0,0 +1,140 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/*\n+ * Example iocost cost model: the builtin linear HDD formula with all\n+ * costs doubled, for one device given by the dev member of the\n+ * struct_ops.\n+ *\n+ * The constants mirror what calc_lcoefs() derives from the AUTOP_HDD\n+ * defaults (rbps=174019176 rseqiops=41708 rrandiops=370, w-side\n+ * analog) in vtime units where 1s == 2^37. On a rotational device\n+ * still on ctrl=auto, a device with this model attached charges\n+ * twice the builtin model under the same read/write workload\n+ * (the builtin prices flushes as zero; this model prices them\n+ * as one-page writes), so the\n+ * doubled cost is a direct check that accounting goes through the\n+ * BPF path. On a non-rotational device, or one with user-pinned\n+ * coefficients, the ratio to the builtin model is arbitrary.\n+ *\n+ * The cursor handling mirrors the builtin: a zero cursor means \"no\n+ * previous IO\", and the cursor is advanced for bios the builtin\n+ * prices (READ/WRITE with a non-zero size), merged ones included, so\n+ * flushes and discards leave it alone and long merged streams do not\n+ * drift past the 16MB seek threshold.\n+ *\n+ * The model implements the full linear formula itself, including\n+ * flushes: there is no fallback to the builtin model, a dataless\n+ * WRITE|REQ_PREFLUSH is priced as a one-page write.\n+ */\n+\n+#include \"vmlinux.h\"\n+#include \u003cbpf/bpf_helpers.h\u003e\n+#include \u003cbpf/bpf_tracing.h\u003e\n+\n+/*\n+ * VTIME_PER_SEC, IOC_PAGE_SIZE/SHIFT, IOC_SECT_TO_PAGE_SHIFT and\n+ * IOCOST_COST_F_MERGE come from vmlinux.h (BTF enum constants)\n+ */\n+#define LCOEF_RANDIO_PAGES\t4096\t/* 16MB seek threshold */\n+#define IOCOST_REQ_OP_MASK\t0xff\t\t/* REQ_OP_MASK, not in BTF */\n+\n+/*\n+ * DIV64_U64_ROUND_UP / DIV_ROUND_UP_ULL equivalents, folded at\n+ * compile time\n+ */\n+#define RU(x, y)\t\t((x) / (y) + (((x) % (y)) ? 1 : 0))\n+\n+#define RBPS\t174019176ULL\n+#define RSEQIOPS\t41708ULL\n+#define RRANDIOPS\t370ULL\n+#define WBPS\t178075866ULL\n+#define WSEQIOPS\t42705ULL\n+#define WRANDIOPS\t378ULL\n+\n+#define RPAGE\t(RU(VTIME_PER_SEC, RU(RBPS, IOC_PAGE_SIZE)))\n+#define RSEQIO\t(RU(VTIME_PER_SEC, RSEQIOPS) - RPAGE)\n+#define RRANDIO\t(RU(VTIME_PER_SEC, RRANDIOPS) - RPAGE)\n+#define WPAGE\t(RU(VTIME_PER_SEC, RU(WBPS, IOC_PAGE_SIZE)))\n+#define WSEQIO\t(RU(VTIME_PER_SEC, WSEQIOPS) - WPAGE)\n+#define WRANDIO\t(RU(VTIME_PER_SEC, WRANDIOPS) - WPAGE)\n+\n+/*\n+ * per-cgroup cursor storage: keyed by the cgroup 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+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+\t/* builtin truncates: max(sectors \u003e\u003e IOC_SECT_TO_PAGE_SHIFT, 1) */\n+\tpages = nbytes \u003e\u003e IOC_PAGE_SHIFT;\n+\tif (!pages)\n+\t\tpages = 1;\n+\n+\tif ((opf \u0026 IOCOST_REQ_OP_MASK) == REQ_OP_READ) {\n+\t\tbase = RSEQIO; coef_page = RPAGE; randio = RRANDIO;\n+\t} else if ((opf \u0026 IOCOST_REQ_OP_MASK) == REQ_OP_WRITE) {\n+\t\tbase = WSEQIO; coef_page = WPAGE; randio = WRANDIO;\n+\t} else {\n+\t\t/*\n+\t\t * a fully owning model must price every op; unknown\n+\t\t * ops are priced per page at the write coefficient\n+\t\t */\n+\t\tbase = 0; coef_page = WPAGE; randio = 0;\n+\t}\n+\n+\t/*\n+\t * mirror the builtin cursor semantics: seek distance is only\n+\t * computed against a non-zero cursor, and the cursor is\n+\t * advanced for bios the builtin prices (READ/WRITE with a\n+\t * non-zero size), merged ones included, so flushes and\n+\t * discards leave it alone\n+\t */\n+\tpriced = (opf \u0026 IOCOST_REQ_OP_MASK) == REQ_OP_READ ||\n+\t\t (opf \u0026 IOCOST_REQ_OP_MASK) == REQ_OP_WRITE;\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+\tif (cur \u0026\u0026 priced) {\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+\tif (priced \u0026\u0026 nbytes)\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+SEC(\".struct_ops\")\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+};\n+\n+char LICENSE[] SEC(\"license\") = \"GPL\";\ndiff --git a/tools/testing/selftests/bpf/progs/iocost_ms.c b/tools/testing/selftests/bpf/progs/iocost_ms.c\nnew file mode 100644\nindex 0000000000000..50a670edfe399\n--- /dev/null\n+++ b/tools/testing/selftests/bpf/progs/iocost_ms.c\n@@ -0,0 +1,159 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/*\n+ * Example multi-stream sequentiality detection cost model.\n+ *\n+ * The builtin model keeps a single cursor per cgroup, so two\n+ * interleaved sequential readers in one cgroup are all priced random\n+ * (measured 89x overcharge, 12.9x throughput collapse), while random\n+ * IO inside a hot window smaller than the 16MB seek threshold is\n+ * priced sequential (measured 107x undercharge). This model replaces\n+ * the single cursor with a per-cgroup table of stream slots: an IO is\n+ * sequential iff its sector matches the expected next sector of any\n+ * tracked stream. Interleaved streams keep their own slots, and\n+ * windowed random IO rarely matches a moving expectation.\n+ *\n+ * Stream state lives in a CGRP_STORAGE map, so it is created and\n+ * freed with the cgroup. The model implements the full builtin\n+ * linear formula itself, including flush pricing.\n+ */\n+#include \"vmlinux.h\"\n+#include \u003cbpf/bpf_helpers.h\u003e\n+#include \u003cbpf/bpf_tracing.h\u003e\n+\n+/*\n+ * VTIME_PER_SEC, IOC_PAGE_SIZE/SHIFT, IOC_SECT_TO_PAGE_SHIFT and\n+ * IOCOST_COST_F_MERGE come from vmlinux.h (BTF enum constants)\n+ */\n+#define IOCOST_REQ_OP_MASK\t0xff\t\t/* REQ_OP_MASK, not in BTF */\n+\n+/*\n+ * DIV64_U64_ROUND_UP / DIV_ROUND_UP_ULL equivalents, folded at\n+ * compile time\n+ */\n+#define RU(x, y)\t\t((x) / (y) + (((x) % (y)) ? 1 : 0))\n+\n+#define RBPS\t174019176ULL\n+#define RSEQIOPS\t41708ULL\n+#define RRANDIOPS\t370ULL\n+#define WBPS\t178075866ULL\n+#define WSEQIOPS\t42705ULL\n+#define WRANDIOPS\t378ULL\n+\n+#define RPAGE\t(RU(VTIME_PER_SEC, RU(RBPS, IOC_PAGE_SIZE)))\n+#define RSEQIO\t(RU(VTIME_PER_SEC, RSEQIOPS) - RPAGE)\n+#define RRANDIO\t(RU(VTIME_PER_SEC, RRANDIOPS) - RPAGE)\n+#define WPAGE\t(RU(VTIME_PER_SEC, RU(WBPS, IOC_PAGE_SIZE)))\n+#define WSEQIO\t(RU(VTIME_PER_SEC, WSEQIOPS) - WPAGE)\n+#define WRANDIO\t(RU(VTIME_PER_SEC, WRANDIOPS) - WPAGE)\n+\n+#define NSLOTS\t4\n+\n+struct streams {\n+\t__u64 expected[NSLOTS];\t/* next expected sector, per stream */\n+\t__u64 stamp[NSLOTS];\t/* LRU stamp, 0 = empty */\n+};\n+\n+/*\n+ * per-cgroup stream table: keyed by the cgroup, freed with it\n+ */\n+struct {\n+\t__uint(type, BPF_MAP_TYPE_CGRP_STORAGE);\n+\t__uint(map_flags, BPF_F_NO_PREALLOC);\n+\t__type(key, int);\n+\t__type(value, struct streams);\n+} stream_tab SEC(\".maps\");\n+\n+SEC(\"struct_ops\")\n+u64 BPF_PROG(iocost_ms_calc_cost, 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\tbase = WSEQIO; coef_page = WPAGE; randio = WRANDIO;\n+\t} else {\n+\t\t/*\n+\t\t * a fully owning model must price every op; unknown\n+\t\t * ops are priced as per-page writes\n+\t\t */\n+\t\tbase = 0; coef_page = WPAGE; randio = 0;\n+\t}\n+\tadvance = nbytes \u003e\u003e 9;\t/* sectors, truncated like the builtin */\n+\n+\t/* only bios the builtin prices participate in stream tracking */\n+\tif (!(((opf \u0026 IOCOST_REQ_OP_MASK) == REQ_OP_READ ||\n+\t (opf \u0026 IOCOST_REQ_OP_MASK) == REQ_OP_WRITE) \u0026\u0026 nbytes)) {\n+\t\tpages = nbytes \u003e\u003e IOC_PAGE_SHIFT;\n+\t\tif (!pages)\n+\t\t\tpages = 1;\n+\t\treturn base + pages * coef_page;\n+\t}\n+\n+\ts = bpf_cgrp_storage_get(\u0026stream_tab, blkcg-\u003ecss.cgroup, NULL,\n+\t\t\t\t BPF_LOCAL_STORAGE_GET_F_CREATE);\n+\tif (!s) {\n+\t\t/* no storage: price per page, truncating like the builtin */\n+\t\tpages = nbytes \u003e\u003e IOC_PAGE_SHIFT;\n+\t\tif (!pages)\n+\t\t\tpages = 1;\n+\t\treturn base + pages * coef_page;\n+\t}\n+\n+\t/*\n+\t * Slot access is lockless, mirroring the builtin single-cursor\n+\t * update in ioc_rqos_throttle(): concurrent CPUs submitting for\n+\t * the same cgroup can race on slot updates; mispricing is\n+\t * bounded and acceptable for an example model.\n+\t */\n+\tnow = bpf_ktime_get_ns();\n+\tfor (i = 0; i \u003c NSLOTS; i++) {\n+\t\tif (s-\u003eexpected[i] == sector \u0026\u0026 s-\u003estamp[i]) {\n+\t\t\tfound = i;\n+\t\t\tbreak;\n+\t\t}\n+\t}\n+\tif (found != 0xFFFFFFFF) {\n+\t\t/* sequential: keep the seq base from the op branch */\n+\t\ts-\u003eexpected[found] = sector + advance;\n+\t\ts-\u003estamp[found] = now;\n+\t} else {\n+\t\tbase = randio;\n+\t\tfor (i = 1; i \u003c NSLOTS; i++) {\n+\t\t\tif (s-\u003estamp[i] \u003c s-\u003estamp[victim])\n+\t\t\t\tvictim = i;\n+\t\t}\n+\t\ts-\u003eexpected[victim] = sector + advance;\n+\t\ts-\u003estamp[victim] = now;\n+\t}\n+\n+\t/* builtin truncates: max(sectors \u003e\u003e IOC_SECT_TO_PAGE_SHIFT, 1) */\n+\tpages = nbytes \u003e\u003e IOC_PAGE_SHIFT;\n+\tif (!pages)\n+\t\tpages = 1;\n+\tif (model_flags \u0026 IOCOST_COST_F_MERGE) {\n+\t\t/*\n+\t\t * merged bios skip the base cost but still advance\n+\t\t * the stream position above, so a merge at the\n+\t\t * expected sector does not make the following new IO\n+\t\t * look random\n+\t\t */\n+\t\tbase = 0;\n+\t}\n+\n+\treturn base + pages * coef_page;\n+}\n+\n+SEC(\".struct_ops\")\n+struct iocost_model_ops iocost_ms = {\n+\t.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/01 06:10 | agent | patch-evaluator |
0mModel:core Args: null Results: {
"EnableConfigs": [
"BLK_CGROUP_IOCOST_BPF",
"BLK_CGROUP_IOCOST",
"BLK_CGROUP",
"CGROUPS",
"BPF_SYSCALL",
"BPF_JIT",
"DEBUG_INFO_BTF"
],
"FocusSymbols": [
"ioc_bpf_attach",
"ioc_bpf_detach",
"ioc_bpf_walk_iocgs",
"bpf_iocost_reg",
"bpf_iocost_unreg",
"bpf_iocost_init_member",
"bpf_iocost_validate",
"ioc_cost_model_write",
"blk_get_queue_rcu"
],
"Reasoning": "The patch series introduces BPF pluggable cost model support for the block cgroup iocost controller via a new BPF struct_ops type (\"iocost_model_ops\"). It modifies core block/cgroup code to support dynamic device attachment and detachment of BPF cost models, queue freezing/quiescing, locking coordination across rq_qos_mutex, blkcg_mutex, and ioc-\u003elock, and RCU lifetime handling for block request queues. This code is fully reachable in virtualized QEMU environments via the bpf syscall and cgroup io.cost.model interfaces.",
"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 417822e4805f6cd46ac79eb071e9074a04e1589c
Author: syz-cluster <triage@syzkaller.com>
Date: Thu Oct 1 06:10:47 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 7fe950425216c..5e780bdcf324b 100644
--- a/Documentation/admin-guide/cgroup-v2.rst
+++ b/Documentation/admin-guide/cgroup-v2.rst
@@ -2117,8 +2117,27 @@ IO Interface Files
===== ================================
ctrl "auto" or "user"
model The cost model in use - "linear"
+ or "bpf" while the BPF model
+ is in use
===== ================================
+ When CONFIG_BLK_CGROUP_IOCOST_BPF is enabled, a BPF cost model
+ can be attached to a device by loading an "iocost_model_ops"
+ struct_ops with 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, and
+ switches the device's pricing to the model; enabling and
+ disabling the controller stays with io.cost.qos. 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. "ctrl" keeps describing the builtin
+ coefficients, which are kept while the BPF model is in use and
+ take effect again when switched back, and the automatic profile
+ stepping does not switch profiles while the BPF model is in
+ use.
+
When "ctrl" is "auto", the kernel may change all parameters
dynamically. When "ctrl" is set to "user" or any other
parameters are written to, "ctrl" become "user" and the
diff --git a/block/Kconfig b/block/Kconfig
index 70e4a66d941ff..1cafc1bd0dda3 100644
--- a/block/Kconfig
+++ b/block/Kconfig
@@ -231,4 +231,14 @@ config BLK_ERROR_INJECTION
source "block/Kconfig.iosched"
+config BLK_CGROUP_IOCOST_BPF
+ bool "Enable BPF pluggable cost model support for the cost IO controller"
+ depends on BLK_CGROUP_IOCOST && BPF_SYSCALL && BPF_JIT && DEBUG_INFO_BTF
+ help
+ Enabling this option registers the "iocost_model_ops" BPF
+ struct_ops type, which allows a BPF program to fully replace
+ the builtin linear cost model on the device it is attached
+ to. The struct_ops is attached per device, following the
+ hid_bpf_ops model.
+
endif # BLOCK
diff --git a/block/Makefile b/block/Makefile
index e7bd320e3d697..ee5cebeea006f 100644
--- a/block/Makefile
+++ b/block/Makefile
@@ -39,3 +39,4 @@ obj-$(CONFIG_BLK_INLINE_ENCRYPTION) += blk-crypto.o blk-crypto-profile.o \
blk-crypto-sysfs.o
obj-$(CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK) += blk-crypto-fallback.o
obj-$(CONFIG_BLOCK_HOLDER_DEPRECATED) += holder.o
+obj-$(CONFIG_BLK_CGROUP_IOCOST_BPF) += blk-iocost-bpf.o
diff --git a/block/blk-core.c b/block/blk-core.c
index 13dc70e8f55d9..2c789b0d86ff6 100644
--- a/block/blk-core.c
+++ b/block/blk-core.c
@@ -536,6 +536,23 @@ bool blk_get_queue(struct request_queue *q)
}
EXPORT_SYMBOL(blk_get_queue);
+/**
+ * blk_get_queue_rcu - get a queue reference regardless of the dying flag
+ * @q: the request_queue to reference
+ *
+ * Unlike blk_get_queue(), this succeeds on a dying queue, so a caller
+ * which holds the queue only through RCU (e.g. a detach path which
+ * read the pointer locklessly) can still take a reference and touch
+ * the queue under its own lifetime. The caller must hold
+ * rcu_read_lock() so the memory is valid. Fails only when the
+ * refcount already dropped to zero.
+ */
+bool blk_get_queue_rcu(struct request_queue *q)
+{
+ return refcount_inc_not_zero(&q->refs);
+}
+EXPORT_SYMBOL(blk_get_queue_rcu);
+
#ifdef CONFIG_FAIL_MAKE_REQUEST
static DECLARE_FAULT_ATTR(fail_make_request);
diff --git a/block/blk-iocost-bpf.c b/block/blk-iocost-bpf.c
new file mode 100644
index 0000000000000..32a5107522b5d
--- /dev/null
+++ b/block/blk-iocost-bpf.c
@@ -0,0 +1,220 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * blk-iocost: BPF struct_ops plumbing for pluggable cost models.
+ *
+ * Registers the "iocost_model_ops" struct_ops type. Attachment is
+ * per-device and follows the hid_bpf_ops model: 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 under the same queue freeze and quiesce as io.cost.model
+ * writes, and .unreg detaches it; enabling and disabling the
+ * controller stays with io.cost.qos. The struct_ops core owns the
+ * program lifetime. There is no name registry and no separate
+ * bound-state bookkeeping.
+ */
+#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 <linux/blk-iocost.h>
+#include <linux/blk-mq.h>
+#include <linux/mutex.h>
+
+struct block_device *blkdev_get_no_open(dev_t dev, bool autoload);
+void blkdev_put_no_open(struct block_device *bdev);
+bool blk_get_queue_rcu(struct request_queue *q);
+void blk_put_queue(struct request_queue *q);
+
+static int bpf_iocost_model_init(struct btf *btf)
+{
+ s32 type_id;
+
+ type_id = btf_find_by_name_kind(btf, "iocost_model_ops", BTF_KIND_STRUCT);
+ if (type_id < 0)
+ return -EINVAL;
+ return 0;
+}
+
+static bool bpf_iocost_is_valid_access(int off, int size,
+ enum bpf_access_type type,
+ const struct bpf_prog *prog,
+ struct bpf_insn_access_aux *info)
+{
+ return bpf_tracing_btf_ctx_access(off, size, type, prog, info);
+}
+
+/*
+ * No iocost-specific helpers; bpf_base_func_proto already covers the
+ * cgroup storage helpers under CONFIG_CGROUPS.
+ */
+static const struct bpf_func_proto *
+bpf_iocost_get_func_proto(enum bpf_func_id func_id,
+ const struct bpf_prog *prog)
+{
+ return bpf_base_func_proto(func_id, prog);
+}
+
+static int bpf_iocost_check_member(const struct btf_type *t,
+ const struct btf_member *member,
+ const struct bpf_prog *prog)
+{
+ /* calc_cost() is called with RCU read lock held */
+ if (prog->sleepable)
+ return -EINVAL;
+ return 0;
+}
+
+static int bpf_iocost_init_member(const struct btf_type *t,
+ const struct btf_member *member,
+ void *kdata, const void *udata)
+{
+ struct iocost_model_ops *ops = kdata;
+ const struct iocost_model_ops *uops = udata;
+ u32 moff = __btf_member_bit_offset(t, member) / 8;
+
+ switch (moff) {
+ case offsetof(struct iocost_model_ops, bdev):
+ /*
+ * kernel-private: the bdev reference held while
+ * attached; reject a userspace value
+ */
+ if (uops->bdev)
+ return -EINVAL;
+ ops->bdev = NULL;
+ return 1;
+ case offsetof(struct iocost_model_ops, q):
+ /* kernel-private: the queue of the attached device */
+ if (uops->q)
+ return -EINVAL;
+ ops->q = NULL;
+ return 1;
+ case offsetof(struct iocost_model_ops, dev):
+ /*
+ * copy it and return 1 to indicate that the member is
+ * handled here, or the verifier rejects the map if the
+ * userspace value is nonzero
+ */
+ 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;
+}
+
+/*
+ * kvalue is zeroed at map allocation and function members are only
+ * written when the BPF side provides a prog, so a model which did
+ * not implement calc_cost leaves it NULL. The dispatch would call
+ * it on every bio, so reject it here.
+ */
+static int bpf_iocost_validate(void *kdata)
+{
+ struct iocost_model_ops *ops = kdata;
+
+ return ops->calc_cost ? 0 : -EINVAL;
+}
+
+static int bpf_iocost_reg(void *kdata, struct bpf_link *link)
+{
+ struct iocost_model_ops *ops = kdata;
+
+ if (!ops->dev)
+ return -EINVAL;
+
+ return ioc_bpf_attach(ops);
+}
+
+static void bpf_iocost_unreg(void *kdata, struct bpf_link *link)
+{
+ struct iocost_model_ops *ops = kdata;
+ struct block_device *bdev;
+ struct request_queue *q;
+
+ /*
+ * ops->q may already have been cleared by the removal ejection;
+ * take a queue reference under RCU before entering the queue,
+ * as the queue may be dying and its memory is only guaranteed
+ * under rcu_read_lock()
+ */
+ rcu_read_lock();
+ q = rcu_dereference(ops->q);
+ if (!q || !blk_get_queue_rcu(q)) {
+ rcu_read_unlock();
+ return;
+ }
+ rcu_read_unlock();
+
+ /*
+ * take rq_qos_mutex before touching the queue further: the
+ * removal ejection clears ops->q under it, inside rq_qos_exit()
+ * and before blk_mq_exit_queue() releases the hardware queues,
+ * so holding it and seeing a non-NULL ops->q guarantees the
+ * queue is still safe to freeze. The freeze and quiesce are
+ * done inside ioc_bpf_detach(), under the mutex.
+ */
+ mutex_lock(&q->rq_qos_mutex);
+ if (!ops->q) {
+ /* the removal ejection won the race; nothing to detach */
+ mutex_unlock(&q->rq_qos_mutex);
+ blk_put_queue(q);
+ return;
+ }
+ bdev = ops->bdev;
+ ioc_bpf_detach(ops);
+ mutex_unlock(&q->rq_qos_mutex);
+ blk_put_queue(q);
+
+ /* drop the attach reference when we did the detach */
+ if (bdev)
+ blkdev_put_no_open(bdev);
+}
+
+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 2745bffcd5eef..64744266cfd30 100644
--- a/block/blk-iocost.c
+++ b/block/blk-iocost.c
@@ -177,6 +177,7 @@
#include <linux/timer.h>
#include <linux/time64.h>
#include <linux/parser.h>
+#include <linux/blk-iocost.h>
#include <linux/sched/signal.h>
#include <asm/local.h>
#include <asm/local64.h>
@@ -445,6 +446,13 @@ struct ioc {
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 cost model in use, NULL = builtin linear model */
+ const struct iocost_model_ops __rcu *model;
+#endif
};
struct iocg_pcpu_stat {
@@ -780,6 +788,45 @@ static void ioc_refresh_period_us(struct ioc *ioc)
ioc_refresh_margins(ioc);
}
+/*
+ * The BPF model in use, or NULL when the builtin linear model prices
+ * this device. CONFIG_BLK_CGROUP_IOCOST_BPF=n compiles to a constant
+ * NULL so callers need no #ifdefs.
+ */
+static const struct iocost_model_ops *ioc_model_in_use(struct ioc *ioc)
+{
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+ return rcu_dereference(ioc->model);
+#else
+ return NULL;
+#endif
+}
+
+/*
+ * The struct_ops attached to this device, or NULL. While attachment
+ * and model selection are independent, the cgroup callbacks follow
+ * the attachment, not the selection.
+ */
+static const struct iocost_model_ops *ioc_attached_or_null(struct ioc *ioc)
+{
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+ return rcu_dereference(ioc->attached);
+#else
+ return NULL;
+#endif
+}
+
+static const struct iocost_model_ops *
+ioc_model_in_use_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
+}
+
/*
* ioc->rqos.disk isn't initialized when this function is called from
* the init path.
@@ -803,8 +850,13 @@ 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: the builtin coefficients are inert
+ * then, so stepping the profile is pointless
+ */
+ if (ioc->user_qos_params || ioc->user_cost_model ||
+ ioc_model_in_use_locked(ioc))
return idx;
/* step up/down based on the vrate */
@@ -2238,6 +2290,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;
@@ -2274,6 +2327,8 @@ static void ioc_timer_fn(struct timer_list *timer)
u64 vdone, vtime, usage_us;
u32 hw_active, hw_inuse;
+ nr_active++;
+
/*
* Collect unused and wind vtime closer to vnow to prevent
* iocgs from accumulating a large amount of budget.
@@ -2435,6 +2490,15 @@ 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, running and cur_period haven't changed, nr_active and
+ * usage_us_sum are complete, and vrate and period_us still hold
+ * the values this period ran in. 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);
@@ -2571,8 +2635,19 @@ static void calc_vtime_cost_builtin(struct bio *bio, struct ioc_gq *iocg,
static u64 calc_vtime_cost(struct bio *bio, struct ioc_gq *iocg, bool is_merge)
{
+ const struct iocost_model_ops *model;
u64 cost;
+ rcu_read_lock();
+ model = ioc_model_in_use(iocg->ioc);
+ if (model) {
+ cost = model->calc_cost(bio,
+ is_merge ? IOCOST_COST_F_MERGE : 0);
+ rcu_read_unlock();
+ return min(cost, VTIME_PER_SEC);
+ }
+ rcu_read_unlock();
+
calc_vtime_cost_builtin(bio, iocg, is_merge, &cost);
return cost;
}
@@ -2594,10 +2669,32 @@ static void calc_size_vtime_cost_builtin(struct request *rq, struct ioc *ioc,
}
}
+/*
+ * Called from the request completion path, 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)
{
+ const struct iocost_model_ops *model;
u64 cost;
+ rcu_read_lock();
+ model = ioc_model_in_use(ioc);
+ if (model && (req_op(rq) == REQ_OP_READ ||
+ req_op(rq) == REQ_OP_WRITE)) {
+ unsigned int pages =
+ blk_rq_stats_sectors(rq) >> IOC_SECT_TO_PAGE_SHIFT;
+ u64 coeff = req_op(rq) == REQ_OP_READ ?
+ model->read_vtime_per_page :
+ model->write_vtime_per_page;
+
+ cost = pages * coeff;
+ rcu_read_unlock();
+ return cost;
+ }
+ rcu_read_unlock();
+
calc_size_vtime_cost_builtin(rq, ioc, &cost);
return cost;
}
@@ -2900,6 +2997,24 @@ static void ioc_rqos_exit(struct rq_qos *rqos)
timer_shutdown_sync(&ioc->timer);
free_percpu(ioc->pcpu_stat);
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+ {
+ struct iocost_model_ops *ops;
+
+ spin_lock_irq(&ioc->lock);
+ ops = (struct iocost_model_ops *)rcu_dereference_protected(
+ ioc->attached, lockdep_is_held(&ioc->lock));
+ rcu_assign_pointer(ioc->attached, NULL);
+ rcu_assign_pointer(ioc->model, NULL);
+ spin_unlock_irq(&ioc->lock);
+
+ /* eject the model completely on device removal */
+ if (ops) {
+ WRITE_ONCE(ops->q, NULL);
+ blkdev_put_no_open(ops->bdev);
+ }
+ }
+#endif
kfree(ioc);
}
@@ -3022,6 +3137,7 @@ static void ioc_pd_init(struct blkg_policy_data *pd)
struct ioc_now now;
struct blkcg_gq *tblkg;
unsigned long flags;
+ const struct iocost_model_ops *model;
ioc_now(ioc, &now);
@@ -3048,6 +3164,18 @@ static void ioc_pd_init(struct blkg_policy_data *pd)
spin_lock_irqsave(&ioc->lock, flags);
weight_updated(iocg, &now);
spin_unlock_irqrestore(&ioc->lock, flags);
+
+ /*
+ * the attached model is RCU-protected: a concurrent detach
+ * publishes NULL and the struct_ops image survives it by a
+ * grace period, so the callback is safe inside the read-side
+ * critical section
+ */
+ rcu_read_lock();
+ model = ioc_attached_or_null(ioc);
+ if (model && model->iocg_init)
+ model->iocg_init(blkg->blkcg, ioc->rqos.disk->queue);
+ rcu_read_unlock();
}
static void iocg_release(struct rcu_head *rcu)
@@ -3066,8 +3194,15 @@ static void ioc_pd_free(struct blkg_policy_data *pd)
struct blkcg_gq *blkg = pd_to_blkg(pd);
struct ioc *ioc = iocg->ioc;
unsigned long flags;
+ const struct iocost_model_ops *model;
if (ioc) {
+ rcu_read_lock();
+ model = ioc_attached_or_null(ioc);
+ if (model && model->iocg_free)
+ model->iocg_free(blkg->blkcg, ioc->rqos.disk->queue);
+ rcu_read_unlock();
+
spin_lock_irqsave(&ioc->lock, flags);
if (!list_empty(&iocg->active_list)) {
@@ -3433,17 +3568,21 @@ 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_model_in_use_locked(ioc);
+ seq_printf(sf, "%s ctrl=%s model=%s "
"rbps=%llu rseqiops=%llu rrandiops=%llu "
"wbps=%llu wseqiops=%llu wrandiops=%llu\n",
dname, ioc->user_cost_model ? "user" : "auto",
- u[I_LCOEF_RBPS], u[I_LCOEF_RSEQIOPS], u[I_LCOEF_RRANDIOPS],
- u[I_LCOEF_WBPS], u[I_LCOEF_WSEQIOPS], u[I_LCOEF_WRANDIOPS]);
+ 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]);
spin_unlock_irq(&ioc->lock);
return 0;
}
@@ -3457,6 +3596,204 @@ static int ioc_cost_model_show(struct seq_file *sf, void *v)
return 0;
}
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+/*
+ * Deliver iocg_init()/iocg_free() to the cgroups which already have a
+ * blkg on the queue, the same q->blkg_list walk the blkcg policy
+ * teardown uses. The queue is frozen and quiesced and blkcg_mutex
+ * serializes against blkg creation and destruction. Cgroups without
+ * a blkg on the device yet are not missed: their blkg is created
+ * later and ioc_pd_init()/ioc_pd_free() deliver the callbacks then.
+ */
+static void ioc_bpf_walk_iocgs(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);
+
+ rcu_read_lock();
+ list_for_each_entry(blkg, &q->blkg_list, q_node) {
+ if (!blkg_to_iocg(blkg))
+ continue;
+ if (init) {
+ if (ops->iocg_init)
+ ops->iocg_init(blkg->blkcg, q);
+ } else {
+ if (ops->iocg_free)
+ ops->iocg_free(blkg->blkcg, q);
+ }
+ }
+ rcu_read_unlock();
+}
+
+int ioc_bpf_attach(struct iocost_model_ops *ops)
+{
+ struct block_device *bdev;
+ struct request_queue *q;
+ struct gendisk *disk;
+ struct ioc *ioc;
+ unsigned int memflags;
+ int ret;
+
+ /* prevent multiple attach of the same struct_ops */
+ if (ops->q)
+ return -EINVAL;
+
+ 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)) {
+ ret = -EINVAL;
+ goto put;
+ }
+ if (!queue_is_mq(q)) {
+ ret = -EOPNOTSUPP;
+ goto put;
+ }
+
+ /*
+ * check liveness and create the ioc under rq_qos_mutex, like
+ * blkg_conf_open_bdev() does; enabling stays with io.cost.qos
+ *
+ * the queue reference is held across the unlocked window below:
+ * the bdev reference does not pin the queue, bdev only holds a
+ * raw bd_queue pointer, and concurrent device removal may eject
+ * the model and free the ioc while we are off the mutex, so
+ * without our own reference the second mutex_lock() would touch
+ * a freed queue
+ */
+ mutex_lock(&q->rq_qos_mutex);
+ if (!disk_live(disk) || !blk_get_queue(q)) {
+ mutex_unlock(&q->rq_qos_mutex);
+ ret = -ENODEV;
+ goto put;
+ }
+ ioc = q_to_ioc(q);
+ if (!ioc) {
+ ret = blk_iocost_init(disk);
+ mutex_unlock(&q->rq_qos_mutex);
+ if (ret)
+ goto put_q;
+ ioc = q_to_ioc(q);
+ } else {
+ mutex_unlock(&q->rq_qos_mutex);
+ }
+
+ /*
+ * ops->bdev is dropped by the removal ejection or by .unreg,
+ * whichever detaches the model first, similar to hid_bpf's
+ * per-ops device reference without the struct file and without
+ * pinning the driver module
+ */
+
+ /*
+ * switch the model under the same freeze and quiesce as the
+ * io.cost.model writes; the freeze does not pin the ioc, so
+ * rq_qos_mutex has to be held across the switch - ioc_rqos_exit()
+ * frees the ioc under it
+ */
+ mutex_lock(&q->rq_qos_mutex);
+ ioc = q_to_ioc(q);
+ if (!ioc) {
+ mutex_unlock(&q->rq_qos_mutex);
+ ret = -ENODEV;
+ goto put_q;
+ }
+ memflags = blk_mq_freeze_queue(q);
+ blk_mq_quiesce_queue(q);
+
+ /*
+ * hold blkcg_mutex across the publish and the iocg_init() walk:
+ * ioc_pd_init() runs under it too, so no cgroup can receive
+ * iocg_init() from both the walk and its own pd_init
+ */
+ mutex_lock(&q->blkcg_mutex);
+ spin_lock_irq(&ioc->lock);
+ if (rcu_dereference_protected(ioc->attached,
+ lockdep_is_held(&ioc->lock))) {
+ spin_unlock_irq(&ioc->lock);
+ mutex_unlock(&q->blkcg_mutex);
+ blk_mq_unquiesce_queue(q);
+ blk_mq_unfreeze_queue(q, memflags);
+ mutex_unlock(&q->rq_qos_mutex);
+ ret = -EBUSY;
+ goto put_q;
+ }
+ rcu_assign_pointer(ioc->attached, ops);
+ rcu_assign_pointer(ioc->model, ops);
+ spin_unlock_irq(&ioc->lock);
+
+ ops->bdev = bdev;
+ WRITE_ONCE(ops->q, q);
+
+ /* pair iocg_init() with the cgroups which already exist */
+ ioc_bpf_walk_iocgs(ioc, ops, true);
+ mutex_unlock(&q->blkcg_mutex);
+
+ blk_mq_unquiesce_queue(q);
+ blk_mq_unfreeze_queue(q, memflags);
+ mutex_unlock(&q->rq_qos_mutex);
+ blk_put_queue(q);
+ return 0;
+
+put_q:
+ blk_put_queue(q);
+put:
+ 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. The caller has already checked ops->q.
+ */
+void ioc_bpf_detach(struct iocost_model_ops *ops)
+{
+ struct request_queue *q = ops->q;
+ struct ioc *ioc;
+ unsigned int memflags;
+
+ if (!q)
+ return;
+ ioc = q_to_ioc(q);
+ if (!ioc)
+ return;
+
+ memflags = blk_mq_freeze_queue(q);
+ blk_mq_quiesce_queue(q);
+
+ /*
+ * hold blkcg_mutex across the clearing and the iocg_free() walk:
+ * ioc_pd_free() runs under it too, so no cgroup can receive
+ * iocg_free() from both the walk and its own pd_free
+ */
+ mutex_lock(&q->blkcg_mutex);
+ spin_lock_irq(&ioc->lock);
+ if (rcu_dereference_protected(ioc->model,
+ lockdep_is_held(&ioc->lock)) == ops)
+ rcu_assign_pointer(ioc->model, NULL);
+ rcu_assign_pointer(ioc->attached, NULL);
+ spin_unlock_irq(&ioc->lock);
+
+ /* pair iocg_free() with the cgroups which still exist */
+ ioc_bpf_walk_iocgs(ioc, ops, false);
+ mutex_unlock(&q->blkcg_mutex);
+
+ WRITE_ONCE(ops->q, NULL);
+
+ blk_mq_unquiesce_queue(q);
+ blk_mq_unfreeze_queue(q, memflags);
+}
+
+#endif
+
static const match_table_t cost_ctrl_tokens = {
{ COST_CTRL, "ctrl=%s" },
{ COST_MODEL, "model=%s" },
@@ -3484,6 +3821,10 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
bool user;
char *body, *p;
int ret;
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+ const struct iocost_model_ops *new_model = NULL;
+ bool model_write = false;
+#endif
blkg_conf_init(&ctx, input);
@@ -3536,9 +3877,28 @@ 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")) {
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+ /* staged and committed below, so a parse
+ * error later in the same write leaves
+ * the model selection untouched */
+ new_model = NULL;
+ model_write = true;
+#endif
+ continue;
+ }
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+ if (!strcmp(buf, "bpf")) {
+ new_model = rcu_dereference_protected(
+ ioc->attached,
+ lockdep_is_held(&ioc->lock));
+ if (!new_model)
+ goto unlock;
+ model_write = true;
+ continue;
+ }
+#endif
+ goto unlock;
}
tok = match_token(p, i_lcoef_tokens, args);
@@ -3556,6 +3916,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;
diff --git a/include/linux/blk-iocost.h b/include/linux/blk-iocost.h
new file mode 100644
index 0000000000000..03a0c7dab71fd
--- /dev/null
+++ b/include/linux/blk-iocost.h
@@ -0,0 +1,110 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _LINUX_BLK_IOCOST_H
+#define _LINUX_BLK_IOCOST_H
+
+#include <linux/types.h>
+#include <linux/blk_types.h>
+#include <linux/blkdev.h>
+
+struct bio;
+struct blkcg;
+struct request_queue;
+
+/*
+ * Pluggable cost model interface for blk-iocost.
+ *
+ * A BPF struct_ops implementation is attached to one device, identified
+ * by the dev member set from userspace before load, following the
+ * hid_bpf_ops model: the struct_ops core owns the lifetime of the
+ * program. Attaching creates the ioc if needed, like an io.cost.model
+ * write does, switches the device to the BPF model under the same
+ * queue freeze and quiesce, 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, "model=linear" switches back to the
+ * builtin model, and neither detaches the struct_ops; only detaching
+ * removes the model. The builtin linear coefficients are kept while
+ * the BPF model is in use and take effect again when switched back.
+ *
+ * While the BPF model is the one in use, it owns pricing for every
+ * charged IO on the device: it prices all operations, 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 the model
+ * can read whatever it needs (operation flags, size, sector, the
+ * issuing cgroup through bio->bi_blkg). It returns the cost of the
+ * IO in vtime units, where 1 second of device time equals
+ * VTIME_PER_SEC (2^37, available to BPF programs through vmlinux.h).
+ * The returned value is clamped to 1 second of device time per IO.
+ *
+ * The struct_ops also carries the transfer cost coefficients, vtime
+ * per page for reads and writes: while the BPF model is in use, the
+ * builtin latency tracking and vrate adjustment use these instead of
+ * the builtin linear coefficients for the completion-time request
+ * sizing, so the whole controller follows the model's pricing. Letting
+ * a model take over the QoS side entirely (latency tracking, vrate
+ * control) is left for a later extension.
+ *
+ * The cgroup callbacks are bound to the iocg policy lifetime, one
+ * (cgroup, device) pair per invocation: iocg_init() is delivered on
+ * attach to every cgroup which already exists on the device and to
+ * each one appearing afterwards; iocg_free() is delivered on detach to
+ * every cgroup still existing then, and at policy deactivation time
+ * for the rest, so init and free always pair up. Both callbacks run
+ * inside an RCU read-side critical section and must not sleep.
+ */
+
+/*
+ * iocost-specific call metadata for calc_cost()'s model_flags
+ * argument; the merge indicator is not a property of the bio.
+ * An enum so the value is exported through BTF and BPF models can
+ * use it from vmlinux.h.
+ */
+enum {
+ IOCOST_COST_F_MERGE = 1 << 0, /* called from merge path */
+};
+
+struct iocost_model_ops {
+ /*
+ * 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, used by the builtin sizing and vrate logic */
+ 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);
+
+ /* private: */
+
+ /*
+ * bdev reference held while attached; dropped by the removal
+ * ejection or .unreg, whichever detaches the model first
+ */
+ struct block_device *bdev;
+ /* queue of the attached device, NULL = not attached */
+ struct request_queue *q;
+};
+
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+
+int ioc_bpf_attach(struct iocost_model_ops *ops);
+void ioc_bpf_detach(struct iocost_model_ops *ops);
+
+#else /* CONFIG_BLK_CGROUP_IOCOST_BPF */
+
+static inline int ioc_bpf_attach(struct iocost_model_ops *ops)
+{
+ return -EOPNOTSUPP;
+}
+static inline void ioc_bpf_detach(struct iocost_model_ops *ops) { }
+
+#endif /* CONFIG_BLK_CGROUP_IOCOST_BPF */
+#endif /* _LINUX_BLK_IOCOST_H */
diff --git a/include/trace/events/iocost.h b/include/trace/events/iocost.h
index e772b1bc60d60..79773e82d42cf 100644
--- a/include/trace/events/iocost.h
+++ b/include/trace/events/iocost.h
@@ -178,6 +178,50 @@ TRACE_EVENT(iocost_ioc_vrate_adj,
)
);
+/*
+ * Periodic per-device summary, emitted once per period from the tail of
+ * ioc_timer_fn(). Unlike the state-change events above, this fires every
+ * period the controller is running, including steady states, and carries
+ * the overall controller state so basic monitoring doesn't require drgn.
+ */
+TRACE_EVENT(iocost_ioc_tick,
+
+ TP_PROTO(struct ioc *ioc, 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)
+ __field(int, running)
+ ),
+
+ 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;
+ __entry->running = ioc->running;
+ ),
+
+ TP_printk("[%s] period=%llu:%uus vrate=%llu busy=%d active=%d usage=%u%% running=%d",
+ __get_str(devname), __entry->cur_period, __entry->period_us,
+ __entry->vrate, __entry->busy_level, __entry->nr_active,
+ __entry->usage_pct, __entry->running
+ )
+);
+
TRACE_EVENT(iocost_iocg_forgive_debt,
TP_PROTO(struct ioc_gq *iocg, const char *path, struct ioc_now *now,
diff --git a/tools/testing/selftests/bpf/config b/tools/testing/selftests/bpf/config
index 2b883b388f90c..c5634ee91e690 100644
--- a/tools/testing/selftests/bpf/config
+++ b/tools/testing/selftests/bpf/config
@@ -140,3 +140,5 @@ CONFIG_SMC_HS_CTRL_BPF=y
CONFIG_DIBS=y
CONFIG_DIBS_LO=y
CONFIG_PM_WAKELOCKS=y
+CONFIG_BLK_CGROUP_IOCOST=y
+CONFIG_BLK_CGROUP_IOCOST_BPF=y
diff --git a/tools/testing/selftests/bpf/prog_tests/iocost_model.c b/tools/testing/selftests/bpf/prog_tests/iocost_model.c
new file mode 100644
index 0000000000000..5b7b1282fcb74
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/iocost_model.c
@@ -0,0 +1,245 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <test_progs.h>
+#include <fcntl.h>
+#include <sys/sysmacros.h>
+#include <unistd.h>
+#include "iocost_model.skel.h"
+#include "iocost_ms.skel.h"
+
+/*
+ * 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;
+}
+
+/*
+ * Write a line to io.cost.model for dev and return the errno of the
+ * write (0 on success).
+ */
+static int write_cost_model(const char *dev, const char *what)
+{
+ char buf[128], line[256], word[256];
+ 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 one device, given as major:minor in
+ * $IOCOST_TEST_DEV: the dev member is written through the struct_ops
+ * map's initial value before load, as hid_bpf_ops does with hid_id,
+ * and attaching the struct_ops attaches the model to the device.
+ * Detaching the struct_ops restores the builtin model.
+ *
+ * Requires root, cgroup v2 and a device with iocost support.
+ */
+void serial_test_iocost_model(void)
+{
+ struct iocost_model *skel, *second;
+ unsigned int maj, min;
+ __u32 *ops_dev, *sdev;
+ int err;
+ char model[32], *dev;
+
+ dev = getenv("IOCOST_TEST_DEV");
+ if (!dev || geteuid() != 0 || sscanf(dev, "%u:%u", &maj, &min) != 2) {
+ printf("%s:SKIP:needs root and IOCOST_TEST_DEV=<maj>:<min>\n",
+ __func__);
+ test__skip();
+ return;
+ }
+
+ skel = iocost_model__open();
+ if (!ASSERT_OK_PTR(skel, "skel_open"))
+ return;
+
+ /* dev is the first member of struct iocost_model_ops */
+ ops_dev = bpf_map__initial_value(skel->maps.iocost_2x, NULL);
+ if (!ASSERT_OK_PTR(ops_dev, "initial_value")) {
+ iocost_model__destroy(skel);
+ return;
+ }
+ *ops_dev = (__u32)makedev(maj, min);
+
+ err = iocost_model__load(skel);
+ if (!ASSERT_OK(err, "skel_load")) {
+ iocost_model__destroy(skel);
+ return;
+ }
+
+ err = iocost_model__attach(skel);
+ if (err == -EOPNOTSUPP) {
+ printf("%s: device is not blk-mq or iocost unavailable, skipping\n",
+ __func__);
+ iocost_model__destroy(skel);
+ 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_EQ(strcmp(model, "bpf"), 0, "model_bpf");
+
+ /* a second model on the same device fails with -EBUSY */
+ second = iocost_model__open();
+ if (ASSERT_OK_PTR(second, "second_open")) {
+ sdev = bpf_map__initial_value(
+ second->maps.iocost_2x, NULL);
+ if (!ASSERT_OK_PTR(sdev, "second_initial_value"))
+ goto out_destroy;
+ *sdev = (__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");
+ }
+out_destroy:
+ iocost_model__destroy(second);
+ }
+
+ /*
+ * 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_EQ(strcmp(model, "linear"), 0, "model_linear");
+
+ /* 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_EQ(strcmp(model, "bpf"), 0, "model_bpf");
+
+ iocost_model__detach(skel);
+
+ /* 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_EQ(strcmp(model, "linear"), 0, "model_linear");
+ }
+
+ iocost_model__destroy(skel);
+}
+/*
+ * Same check for the multi-stream example model. Only one model can
+ * be attached to a device at a time; both tests attach and detach, so
+ * they are serial and independent.
+ */
+void serial_test_iocost_model_streams(void)
+{
+ struct iocost_ms *skel;
+ unsigned int maj, min;
+ __u32 *ops_dev;
+ int err;
+ char model[32], *dev;
+
+ dev = getenv("IOCOST_TEST_DEV");
+ if (!dev || geteuid() != 0 || sscanf(dev, "%u:%u", &maj, &min) != 2) {
+ printf("%s:SKIP:needs root and IOCOST_TEST_DEV=<maj>:<min>\n",
+ __func__);
+ test__skip();
+ return;
+ }
+
+ skel = iocost_ms__open();
+ if (!ASSERT_OK_PTR(skel, "skel_open"))
+ return;
+
+ ops_dev = bpf_map__initial_value(skel->maps.iocost_ms, NULL);
+ if (!ASSERT_OK_PTR(ops_dev, "initial_value")) {
+ iocost_ms__destroy(skel);
+ return;
+ }
+ *ops_dev = (__u32)makedev(maj, min);
+
+ err = iocost_ms__load(skel);
+ if (!ASSERT_OK(err, "skel_load")) {
+ iocost_ms__destroy(skel);
+ return;
+ }
+
+ err = iocost_ms__attach(skel);
+ if (err == -EOPNOTSUPP) {
+ printf("%s: device is not blk-mq or iocost unavailable, skipping\n",
+ __func__);
+ iocost_ms__destroy(skel);
+ return;
+ }
+ if (ASSERT_OK(err, "attach")) {
+ err = readback_model(dev, model, sizeof(model));
+ if (ASSERT_OK(err, "readback"))
+ ASSERT_EQ(strcmp(model, "bpf"), 0, "model_bpf");
+
+ iocost_ms__detach(skel);
+
+ err = readback_model(dev, model, sizeof(model));
+ if (ASSERT_OK(err, "readback_after_detach"))
+ ASSERT_EQ(strcmp(model, "linear"), 0, "model_linear");
+ }
+
+ iocost_ms__destroy(skel);
+}
diff --git a/tools/testing/selftests/bpf/progs/iocost_model.c b/tools/testing/selftests/bpf/progs/iocost_model.c
new file mode 100644
index 0000000000000..e8f222c50b39c
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/iocost_model.c
@@ -0,0 +1,140 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * 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; this model prices them
+ * 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 mirrors the builtin: a zero cursor means "no
+ * previous IO", and the cursor is advanced for bios the builtin
+ * prices (READ/WRITE with a non-zero size), merged ones included, so
+ * flushes and discards leave it alone and long merged streams do not
+ * drift past the 16MB seek threshold.
+ *
+ * The model implements the full linear formula itself, including
+ * flushes: there is no fallback to the builtin model, a dataless
+ * WRITE|REQ_PREFLUSH is priced as a one-page write.
+ */
+
+#include "vmlinux.h"
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+
+/*
+ * VTIME_PER_SEC, IOC_PAGE_SIZE/SHIFT, IOC_SECT_TO_PAGE_SHIFT and
+ * IOCOST_COST_F_MERGE come from vmlinux.h (BTF enum constants)
+ */
+#define LCOEF_RANDIO_PAGES 4096 /* 16MB seek threshold */
+#define IOCOST_REQ_OP_MASK 0xff /* REQ_OP_MASK, not in BTF */
+
+/*
+ * DIV64_U64_ROUND_UP / DIV_ROUND_UP_ULL equivalents, folded at
+ * compile time
+ */
+#define RU(x, y) ((x) / (y) + (((x) % (y)) ? 1 : 0))
+
+#define RBPS 174019176ULL
+#define RSEQIOPS 41708ULL
+#define RRANDIOPS 370ULL
+#define WBPS 178075866ULL
+#define WSEQIOPS 42705ULL
+#define WRANDIOPS 378ULL
+
+#define RPAGE (RU(VTIME_PER_SEC, RU(RBPS, IOC_PAGE_SIZE)))
+#define RSEQIO (RU(VTIME_PER_SEC, RSEQIOPS) - RPAGE)
+#define RRANDIO (RU(VTIME_PER_SEC, RRANDIOPS) - RPAGE)
+#define WPAGE (RU(VTIME_PER_SEC, RU(WBPS, IOC_PAGE_SIZE)))
+#define WSEQIO (RU(VTIME_PER_SEC, WSEQIOPS) - WPAGE)
+#define WRANDIO (RU(VTIME_PER_SEC, WRANDIOPS) - WPAGE)
+
+/*
+ * per-cgroup cursor storage: keyed by the cgroup 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");
+
+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;
+
+ /* builtin truncates: max(sectors >> IOC_SECT_TO_PAGE_SHIFT, 1) */
+ pages = nbytes >> IOC_PAGE_SHIFT;
+ if (!pages)
+ pages = 1;
+
+ if ((opf & IOCOST_REQ_OP_MASK) == REQ_OP_READ) {
+ base = RSEQIO; coef_page = RPAGE; randio = RRANDIO;
+ } else if ((opf & IOCOST_REQ_OP_MASK) == REQ_OP_WRITE) {
+ base = WSEQIO; coef_page = WPAGE; randio = WRANDIO;
+ } else {
+ /*
+ * a fully owning model must price every op; unknown
+ * ops are priced per page at the write coefficient
+ */
+ base = 0; coef_page = WPAGE; randio = 0;
+ }
+
+ /*
+ * mirror the builtin cursor semantics: seek distance is only
+ * computed against a non-zero cursor, and the cursor is
+ * advanced for bios the builtin prices (READ/WRITE with a
+ * non-zero size), merged ones included, so flushes and
+ * discards leave it alone
+ */
+ priced = (opf & IOCOST_REQ_OP_MASK) == REQ_OP_READ ||
+ (opf & IOCOST_REQ_OP_MASK) == REQ_OP_WRITE;
+ cursor = bpf_cgrp_storage_get(&cursor_store,
+ blkcg->css.cgroup, NULL,
+ BPF_LOCAL_STORAGE_GET_F_CREATE);
+ if (!cursor) {
+ if (model_flags & IOCOST_COST_F_MERGE)
+ base = 0;
+ return 2 * (base + pages * coef_page);
+ }
+ cur = *cursor;
+ if (cur && priced) {
+ seek_pages = sector > cur ? sector - cur
+ : cur - sector;
+ seek_pages >>= IOC_SECT_TO_PAGE_SHIFT;
+ if (seek_pages > LCOEF_RANDIO_PAGES)
+ base = randio;
+ }
+ if (priced && nbytes)
+ *cursor = sector + (nbytes >> 9);
+
+ if (model_flags & IOCOST_COST_F_MERGE)
+ base = 0;
+
+ cost = 2 * (base + pages * coef_page);
+ return cost;
+}
+
+SEC(".struct_ops")
+struct iocost_model_ops iocost_2x = {
+ .read_vtime_per_page = 2 * RPAGE,
+ .write_vtime_per_page = 2 * WPAGE,
+ .calc_cost = (void *)iocost_2x_calc_cost,
+};
+
+char LICENSE[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/progs/iocost_ms.c b/tools/testing/selftests/bpf/progs/iocost_ms.c
new file mode 100644
index 0000000000000..50a670edfe399
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/iocost_ms.c
@@ -0,0 +1,159 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Example multi-stream sequentiality detection cost model.
+ *
+ * The builtin model keeps a single cursor per cgroup, so two
+ * interleaved sequential readers in one cgroup are all priced random
+ * (measured 89x overcharge, 12.9x throughput collapse), while random
+ * IO inside a hot window smaller than the 16MB seek threshold is
+ * priced sequential (measured 107x undercharge). This model replaces
+ * the single cursor with a per-cgroup table of stream slots: an IO is
+ * sequential iff its sector matches the expected next sector of any
+ * tracked stream. Interleaved streams keep their own slots, and
+ * windowed random IO rarely matches a moving expectation.
+ *
+ * Stream state lives in a CGRP_STORAGE map, so it is created and
+ * freed with the cgroup. The model implements the full builtin
+ * linear formula itself, including flush pricing.
+ */
+#include "vmlinux.h"
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+
+/*
+ * VTIME_PER_SEC, IOC_PAGE_SIZE/SHIFT, IOC_SECT_TO_PAGE_SHIFT and
+ * IOCOST_COST_F_MERGE come from vmlinux.h (BTF enum constants)
+ */
+#define IOCOST_REQ_OP_MASK 0xff /* REQ_OP_MASK, not in BTF */
+
+/*
+ * DIV64_U64_ROUND_UP / DIV_ROUND_UP_ULL equivalents, folded at
+ * compile time
+ */
+#define RU(x, y) ((x) / (y) + (((x) % (y)) ? 1 : 0))
+
+#define RBPS 174019176ULL
+#define RSEQIOPS 41708ULL
+#define RRANDIOPS 370ULL
+#define WBPS 178075866ULL
+#define WSEQIOPS 42705ULL
+#define WRANDIOPS 378ULL
+
+#define RPAGE (RU(VTIME_PER_SEC, RU(RBPS, IOC_PAGE_SIZE)))
+#define RSEQIO (RU(VTIME_PER_SEC, RSEQIOPS) - RPAGE)
+#define RRANDIO (RU(VTIME_PER_SEC, RRANDIOPS) - RPAGE)
+#define WPAGE (RU(VTIME_PER_SEC, RU(WBPS, IOC_PAGE_SIZE)))
+#define WSEQIO (RU(VTIME_PER_SEC, WSEQIOPS) - WPAGE)
+#define WRANDIO (RU(VTIME_PER_SEC, WRANDIOPS) - WPAGE)
+
+#define NSLOTS 4
+
+struct streams {
+ __u64 expected[NSLOTS]; /* next expected sector, per stream */
+ __u64 stamp[NSLOTS]; /* LRU stamp, 0 = empty */
+};
+
+/*
+ * per-cgroup stream table: keyed by the cgroup, freed with it
+ */
+struct {
+ __uint(type, BPF_MAP_TYPE_CGRP_STORAGE);
+ __uint(map_flags, BPF_F_NO_PREALLOC);
+ __type(key, int);
+ __type(value, struct streams);
+} stream_tab SEC(".maps");
+
+SEC("struct_ops")
+u64 BPF_PROG(iocost_ms_calc_cost, 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) {
+ base = WSEQIO; coef_page = WPAGE; randio = WRANDIO;
+ } else {
+ /*
+ * a fully owning model must price every op; unknown
+ * ops are priced as per-page writes
+ */
+ base = 0; coef_page = WPAGE; randio = 0;
+ }
+ advance = nbytes >> 9; /* sectors, truncated like the builtin */
+
+ /* only bios the builtin prices participate in stream tracking */
+ if (!(((opf & IOCOST_REQ_OP_MASK) == REQ_OP_READ ||
+ (opf & IOCOST_REQ_OP_MASK) == REQ_OP_WRITE) && nbytes)) {
+ pages = nbytes >> IOC_PAGE_SHIFT;
+ if (!pages)
+ pages = 1;
+ return base + pages * coef_page;
+ }
+
+ s = bpf_cgrp_storage_get(&stream_tab, blkcg->css.cgroup, NULL,
+ BPF_LOCAL_STORAGE_GET_F_CREATE);
+ if (!s) {
+ /* no storage: price per page, truncating like the builtin */
+ pages = nbytes >> IOC_PAGE_SHIFT;
+ if (!pages)
+ pages = 1;
+ return base + pages * coef_page;
+ }
+
+ /*
+ * Slot access is lockless, mirroring the builtin single-cursor
+ * update in ioc_rqos_throttle(): concurrent CPUs submitting for
+ * the same cgroup can race on slot updates; mispricing is
+ * bounded and acceptable for an example model.
+ */
+ now = bpf_ktime_get_ns();
+ for (i = 0; i < NSLOTS; i++) {
+ if (s->expected[i] == sector && s->stamp[i]) {
+ found = i;
+ break;
+ }
+ }
+ if (found != 0xFFFFFFFF) {
+ /* sequential: keep the seq base from the op branch */
+ s->expected[found] = sector + advance;
+ s->stamp[found] = now;
+ } else {
+ base = randio;
+ for (i = 1; i < NSLOTS; i++) {
+ if (s->stamp[i] < s->stamp[victim])
+ victim = i;
+ }
+ s->expected[victim] = sector + advance;
+ s->stamp[victim] = now;
+ }
+
+ /* builtin truncates: max(sectors >> IOC_SECT_TO_PAGE_SHIFT, 1) */
+ pages = nbytes >> IOC_PAGE_SHIFT;
+ if (!pages)
+ pages = 1;
+ if (model_flags & IOCOST_COST_F_MERGE) {
+ /*
+ * merged bios skip the base cost but still advance
+ * the stream position above, so a merge at the
+ * expected sector does not make the following new IO
+ * look random
+ */
+ base = 0;
+ }
+
+ return base + pages * coef_page;
+}
+
+SEC(".struct_ops")
+struct iocost_model_ops iocost_ms = {
+ .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/01 06:10 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 22461 output: 32 thoughts: 740 Thoughts: **Fuzzing Feasibility of BPF Pluggable Cost Model** Okay, so this patch is introducing BPF pluggable cost model support for the IO cost controller. That means we're adding a bunch of new code, specifically `block/blk-iocost-bpf.c`, and sprinkling modifications across a few other files: `block/blk-iocost.c`, `block/blk-core.c`, `include/linux/blk-iocost.h`, `include/trace/events/iocost.h`, and tests in `tools/testing/selftests/bpf/`. My immediate thought is, "Worth fuzzing?" Let's break this down. First, the reachability question. Can we actually *get* this code to execute in a standard fuzzing environment, like QEMU or GCE? Absolutely! We're talking BPF, `struct_ops`, cgroups v2, the block-iocost stuff, the block layer itself – it's all there, and it all runs in standard virtualized environments. I can use loopback or virtio block devices, or any other disk, easily. And Syzkaller, which I'm familiar with, is already equipped to handle BPF syscalls, loading and attaching `struct_ops`, cgroup filesystem operations like `io.cost.model`, and the IO submissions that drive it. I also noticed that `trace_iocost_ioc_tick` tracepoint was added, which could be really useful for tracing. Looking at the code modifications in `block/blk-iocost.c`, we've got changes to functions like `calc_vtime_cost`, `ioc_timer_fn`, `ioc_bpf_walk_iocgs`, and a bunch of new BPF-related functions: `ioc_bpf_attach`, `ioc_bpf_detach`, etc. In `block/blk-iocost-bpf.c`, we've got a whole suite of new BPF-related functions like `bpf_iocost_model_init`, `bpf_iocost_validate`, etc. And we're even touching `block/blk-core.c` with `blk_get_queue_rcu`. This is *significant* new executable code within the core block and BPF subsystems. We're talking locking, RCU lifetimes, queue freezing/quiescing, the interaction between BPF `struct_ops` and block cgroups… there are race conditions between queue exit/removal and the unregistering of `struct_ops` (`ops->q` races specifically mentioned in the comments, which raises a red flag). Given all this, the potential for bugs in these new areas is very high. **WorthFuzzing = true** is a no-brainer here. Next, let's look at the Kconfig dependencies. I'll use `grepper` or check the diff to find the Kconfig entries: ```kconfig config BLK_CGROUP_IOCOST_BPF bool "Enable BPF pluggable cost model support for the cost IO controller" depends on BLK_CGROUP_IOCOST && BPF_SYSCALL && BPF_JIT && DEBUG_INFO_BTF ``` I'll check `BLK_CGROUP_IOCOST` in `block/Kconfig`: |
| 4/2 | 2026/10/01 06:10 | tool | grepper |
0mArgs:{
"Expression": "config BLK_CGROUP_IOCOST",
"PathPrefix": "block/"
}Results: {
"Output": "block/Kconfig=145=config BLK_CGROUP_FC_APPID\n--\nblock/Kconfig-153-\nblock/Kconfig:154:config BLK_CGROUP_IOCOST\nblock/Kconfig-155-\tbool \"Enable support for cost model based cgroup IO controller\"\n--\nblock/Kconfig=232=source \"block/Kconfig.iosched\"\nblock/Kconfig-233-\nblock/Kconfig:234:config BLK_CGROUP_IOCOST_BPF\nblock/Kconfig-235-\tbool \"Enable BPF pluggable cost model support for the cost IO controller\"\n"
} |
| 5/2 | 2026/10/01 06:10 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 24129 output: 32 thoughts: 22 Thoughts: Here's a summary of my thought process: **Diving into Kconfig Dependencies** Okay, I need to understand the context of `block/Kconfig:154`. Let's assume there's a problem here, so I'm going to quickly check its dependencies. That's the best way to understand how a specific Kconfig option is influencing the broader configuration. I'll need to look at the surrounding lines in the file and see what other options are being defined or referenced nearby. This should give me a good handle on its relationships and implications. |
| 6/2 | 2026/10/01 06:11 | tool | read-file |
0mArgs:{
"File": "block/Kconfig",
"FirstLine": 150,
"LineCount": 20
}Results: {
"Contents": " 150:\t\t cgroup applications. It enables the Fabric and the storage targets to\n 151:\t\t identify, monitor, and handle FC traffic based on VM tags by inserting\n 152:\t\t application specific identification into the FC frame.\n 153:\t\n 154:\tconfig BLK_CGROUP_IOCOST\n 155:\t\tbool \"Enable support for cost model based cgroup IO controller\"\n 156:\t\tdepends on BLK_CGROUP\n 157:\t\tselect BLK_RQ_ALLOC_TIME\n 158:\t\thelp\n 159:\t\tEnabling this option enables the .weight interface for cost\n 160:\t\tmodel based proportional IO control. The IO controller\n 161:\t\tdistributes IO capacity between different groups based on\n 162:\t\ttheir share of the overall weight distribution.\n 163:\t\n 164:\tconfig BLK_CGROUP_IOPRIO\n 165:\t\tbool \"Cgroup I/O controller for assigning an I/O priority class\"\n 166:\t\tdepends on BLK_CGROUP\n 167:\t\thelp\n 168:\t\tEnable the .prio interface for assigning an I/O priority class to\n 169:\t\trequests. The I/O priority class affects the order in which an I/O\n"
} |
| 7/2 | 2026/10/01 06:11 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 24642 output: 33 thoughts: 201 Thoughts: Okay, let's break this down. **Enabling IO Cost Accounting with BPF: A Dependency Chain** Right, so to get this `BLK_CGROUP_IOCOST_BPF` feature working, it looks like I need a few things. First, `BLK_CGROUP_IOCOST_BPF` itself, of course. Then, `BLK_CGROUP_IOCOST` is a prerequisite for that, which in turn means I need `BLK_CGROUP` enabled as well. So far, so good, this is a pretty standard hierarchy for enabling features. But wait, there's more. The use of BPF in the name screams for `BPF_SYSCALL` and `BPF_JIT`, which I'll definitely need. And for useful debugging information, `DEBUG_INFO_BTF` looks like a good idea. Therefore, for the `EnableConfigs` list, I'm thinking I'll need to explicitly enable these: * `BLK_CGROUP_IOCOST_BPF` * `BLK_CGROUP_IOCOST` * `BLK_CGROUP` * `BPF_SYSCALL` * `BPF_JIT` * `DEBUG_INFO_BTF` Now, before I sign off on this, it's always worth a quick sanity check. I should double-check if there are any other related configurations that I might be missing, or if `BPF_STRUCT_OPS` is even relevant here. A quick grep of the kernel Kconfig files for `bpf_struct_ops` or `register_bpf_struct_ops` should clear that up. I don't want to overlook anything critical! |
| 8/2 | 2026/10/01 06:11 | tool | grepper |
0mArgs:{
"Expression": "register_bpf_struct_ops",
"PathPrefix": "kernel/bpf/"
}Results: {
"Output": "kernel/bpf/btf.c=10489=bpf_struct_ops_find(struct btf *btf, u32 type_id)\n--\nkernel/bpf/btf.c-10509-\nkernel/bpf/btf.c:10510:int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)\nkernel/bpf/btf.c-10511-{\n--\nkernel/bpf/btf.c-10537-}\nkernel/bpf/btf.c:10538:EXPORT_SYMBOL_GPL(__register_bpf_struct_ops);\nkernel/bpf/btf.c-10539-#endif\n"
} |
| 9/2 | 2026/10/01 06:11 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 25457 output: 39 thoughts: 32 Thoughts: Okay, let's dive into this. Here's my thought process on what I'm looking into: **Investigating the Conditional Compilation of `__register_bpf_struct_ops`** Right, I need to understand the compilation environment of the `__register_bpf_struct_ops` function in `kernel/bpf/btf.c`. Given that this is a BPF function, I suspect that its presence, or behavior, might be contingent on certain kernel build configurations. I'm going to quickly check which preprocessor directives, specifically `#ifdef` blocks, surround this function. This will tell me under what conditions this critical function will be compiled and made available. My guess is it's related to some feature flags or kernel version compatibility, but I need the precise conditional logic to understand the full picture. |
| 10/2 | 2026/10/01 06:11 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/btf.c",
"FirstLine": 10480,
"LineCount": 40
}Results: {
"Contents": "10480:\t\tfor (i = 0; i \u003c cnt; i++) {\n10481:\t\t\tif (st_ops_list[i].value_id == value_id)\n10482:\t\t\t\treturn \u0026st_ops_list[i];\n10483:\t\t}\n10484:\t\n10485:\t\treturn NULL;\n10486:\t}\n10487:\t\n10488:\tconst struct bpf_struct_ops_desc *\n10489:\tbpf_struct_ops_find(struct btf *btf, u32 type_id)\n10490:\t{\n10491:\t\tconst struct bpf_struct_ops_desc *st_ops_list;\n10492:\t\tunsigned int i;\n10493:\t\tu32 cnt;\n10494:\t\n10495:\t\tif (!type_id)\n10496:\t\t\treturn NULL;\n10497:\t\tif (!btf-\u003estruct_ops_tab)\n10498:\t\t\treturn NULL;\n10499:\t\n10500:\t\tcnt = btf-\u003estruct_ops_tab-\u003ecnt;\n10501:\t\tst_ops_list = btf-\u003estruct_ops_tab-\u003eops;\n10502:\t\tfor (i = 0; i \u003c cnt; i++) {\n10503:\t\t\tif (st_ops_list[i].type_id == type_id)\n10504:\t\t\t\treturn \u0026st_ops_list[i];\n10505:\t\t}\n10506:\t\n10507:\t\treturn NULL;\n10508:\t}\n10509:\t\n10510:\tint __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)\n10511:\t{\n10512:\t\tstruct bpf_verifier_log *log;\n10513:\t\tstruct btf *btf;\n10514:\t\tint err = 0;\n10515:\t\n10516:\t\tbtf = btf_get_module_btf(st_ops-\u003eowner);\n10517:\t\tif (!btf)\n10518:\t\t\treturn check_btf_kconfigs(st_ops-\u003eowner, \"struct_ops\");\n10519:\t\tif (IS_ERR(btf))\n"
} |
| 11/2 | 2026/10/01 06:11 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 26344 output: 39 thoughts: 24 Thoughts: Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person: **Navigating the Labyrinth: Refining My Search Parameters** Alright, I'm diving back into this dataset. It's time to zero in on a specific region, or at least narrow the scope. I need to revisit a section, and my initial recall puts it somewhere around line 10538, or possibly before line 10480. Essentially, I'm trying to triangulate the general area where I was making the notes. This isn't a precise search, but rather a strategic bracket. I'm leveraging my mental map of the document to get me back into the vicinity of the relevant material. It's a pragmatic approach – a quick-and-dirty method to start the process of scanning for specifics. That range should be a good starting point for a targeted review. From there, I can refine it once I re-engage with the content and find my place. |
| 12/2 | 2026/10/01 06:11 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/btf.c",
"FirstLine": 10440,
"LineCount": 40
}Results: {
"Contents": "10440:\t\t\t * A regular RCU grace period therefore protects both the kdata\n10441:\t\t\t * and the trampoline image, so a tasks RCU grace period is not\n10442:\t\t\t * needed.\n10443:\t\t\t */\n10444:\t\t\tif (!cgroup_bpf_is_struct_ops_atype(cgroup_atype) ||\n10445:\t\t\t st_ops-\u003ereg || st_ops-\u003eunreg || st_ops-\u003efree_after_tasks_rcu_gp) {\n10446:\t\t\t\tbpf_struct_ops_desc_release(\u0026tab-\u003eops[btf-\u003estruct_ops_tab-\u003ecnt]);\n10447:\t\t\t\treturn -EINVAL;\n10448:\t\t\t}\n10449:\t\n10450:\t\t\t/*\n10451:\t\t\t * There is no need to unregister from the cgroup when btf_free()\n10452:\t\t\t * runs. No struct_ops map or cgroup link can be created once its\n10453:\t\t\t * BTF is gone.\n10454:\t\t\t */\n10455:\t\t\tcgroup_bpf_struct_ops_register(cgroup_atype,\n10456:\t\t\t\t\t\t tab-\u003eops[btf-\u003estruct_ops_tab-\u003ecnt].type_id,\n10457:\t\t\t\t\t\t st_ops-\u003ecfi_stubs,\n10458:\t\t\t\t\t\t st_ops-\u003efree_after_mult_rcu_gp);\n10459:\t\t}\n10460:\t\n10461:\t\tbtf-\u003estruct_ops_tab-\u003ecnt++;\n10462:\t\n10463:\t\treturn 0;\n10464:\t}\n10465:\t\n10466:\tconst struct bpf_struct_ops_desc *\n10467:\tbpf_struct_ops_find_value(struct btf *btf, u32 value_id)\n10468:\t{\n10469:\t\tconst struct bpf_struct_ops_desc *st_ops_list;\n10470:\t\tunsigned int i;\n10471:\t\tu32 cnt;\n10472:\t\n10473:\t\tif (!value_id)\n10474:\t\t\treturn NULL;\n10475:\t\tif (!btf-\u003estruct_ops_tab)\n10476:\t\t\treturn NULL;\n10477:\t\n10478:\t\tcnt = btf-\u003estruct_ops_tab-\u003ecnt;\n10479:\t\tst_ops_list = btf-\u003estruct_ops_tab-\u003eops;\n"
} |
| 13/2 | 2026/10/01 06:11 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 27311 output: 34 thoughts: 20 Thoughts: Here's my take on those thoughts: **Analyzing the bpf_struct_ops Context in btf.c** Okay, so I need to understand the conditional compilation context around `bpf_struct_ops` within `btf.c`. Let's dig in and see what `#ifdef` directives control its inclusion or behavior. This is crucial for figuring out how and when the relevant structure is defined, which then informs my analysis of the larger BPF infrastructure. I anticipate that this will be contingent on the kernel version, specific configurations enabled, or perhaps the inclusion of certain modules. Understanding those flags are fundamental to interpreting the design within the broader architecture. |
| 14/2 | 2026/10/01 06:11 | tool | grepper |
0mArgs:{
"Expression": "CONFIG_BPF_",
"PathPrefix": "kernel/bpf/btf.c"
}Results: {
"Output": "kernel/bpf/btf.c=10340=bool btf_type_ids_nocast_alias(struct bpf_verifier_log *log,\n--\nkernel/bpf/btf.c-10394-\nkernel/bpf/btf.c:10395:#ifdef CONFIG_BPF_JIT\nkernel/bpf/btf.c-10396-static int\n"
} |
| 15/2 | 2026/10/01 06:11 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 27618 output: 311 thoughts: 1723 Thoughts: **Analysis of BPF-Based I/O Cost Model Implementation** Okay, let's break this down. First, I see `#ifdef CONFIG_BPF_JIT` surrounding `struct_ops` in `btf.c`, indicating this relates to BPF JIT, and it's contingent on `BLK_CGROUP_IOCOST`, `BPF_SYSCALL`, `BPF_JIT`, and `DEBUG_INFO_BTF`. Right, got it. Now, let's get into the code. My focus is on the new logic's implementation. In `block/blk-iocost-bpf.c`, I've got: `bpf_iocost_model_init`, `bpf_iocost_check_member`, `bpf_iocost_init_member`, `bpf_iocost_validate`, `bpf_iocost_reg`, and `bpf_iocost_unreg`. Over in `block/blk-iocost.c`, there's `ioc_bpf_attach`, `ioc_bpf_detach`, `ioc_bpf_walk_iocgs`, along with modifications to `calc_vtime_cost`, `calc_size_vtime_cost`, `ioc_cost_model_write`, and `ioc_rqos_exit`. Also, the `ioc_pd_init` and `ioc_pd_free` functions are changed. Lastly, in `block/blk-core.c`, I see `blk_get_queue_rcu`. Now, to refine the important entrypoints and core logic, I'm selecting: `ioc_bpf_attach`, `ioc_bpf_detach`, `ioc_bpf_walk_iocgs`, `bpf_iocost_reg`, `bpf_iocost_unreg`, `bpf_iocost_init_member`, `bpf_iocost_validate`, `ioc_cost_model_write`, `calc_vtime_cost`, and `blk_get_queue_rcu`. Let's check for ubiquity. `blk_get_queue_rcu` is new in `blk-core.c` and only called by `bpf_iocost_unreg`. `ioc_bpf_attach` and `ioc_bpf_detach` are specific to iocost BPF. The same goes for `bpf_iocost_reg`, `bpf_iocost_unreg`, `bpf_iocost_init_member`, and `bpf_iocost_validate`; they are the `struct_ops` callbacks. `ioc_cost_model_write` is the cgroup file ops write handler. `ioc_bpf_walk_iocgs` is a helper for iterating blkgs on attach/detach. Are these static or non-static? `ioc_bpf_attach` and `ioc_bpf_detach` are non-static in `blk-iocost.c`. `ioc_bpf_walk_iocgs` is static. The `bpf_iocost_` functions are static in `blk-iocost-bpf.c`. `ioc_cost_model_write` is static. `blk_get_queue_rcu` is non-static. Okay, let's quickly check the inlining. `ioc_bpf_walk_iocgs` is called from the non-static `ioc_bpf_attach` and `ioc_bpf_detach`, and the `bpf_iocost_` functions are referenced via the `bpf_iocost_model_ops` struct, so their addresses are taken. Also, `ioc_cost_model_write` has its address taken for the cgroup file ops. So, none of these are likely to be inlined. Let's quickly verify any other interesting symbols. `ioc_pd_init` and `ioc_pd_free` call `model->iocg_init` and `model->iocg_free`. `calc_vtime_cost` and `calc_size_vtime_cost` are in the IO path. Now, checking `EnableConfigs`: `BLK_CGROUP_IOCOST_BPF`, `BLK_CGROUP_IOCOST`, `BLK_CGROUP`, `BPF_SYSCALL`, `BPF_JIT`, and `DEBUG_INFO_BTF`. I'll add `CGROUPS` since `BLK_CGROUP` depends on it. Alright, double-checking the requirements: 1. **`WorthFuzzing`: True.** This patch clearly introduces new attack surface with the BPF cost models in cgroups, which |
| 16/2 | 2026/10/01 06:11 | tool | set-results |
0mArgs:{
"EnableConfigs": [
"BLK_CGROUP_IOCOST_BPF",
"BLK_CGROUP_IOCOST",
"BLK_CGROUP",
"CGROUPS",
"BPF_SYSCALL",
"BPF_JIT",
"DEBUG_INFO_BTF"
],
"FocusSymbols": [
"ioc_bpf_attach",
"ioc_bpf_detach",
"ioc_bpf_walk_iocgs",
"bpf_iocost_reg",
"bpf_iocost_unreg",
"bpf_iocost_init_member",
"bpf_iocost_validate",
"ioc_cost_model_write",
"blk_get_queue_rcu"
],
"Reasoning": "The patch series introduces BPF pluggable cost model support for the block cgroup iocost controller via a new BPF struct_ops type (\"iocost_model_ops\"). It modifies core block/cgroup code to support dynamic device attachment and detachment of BPF cost models, queue freezing/quiescing, locking coordination across rq_qos_mutex, blkcg_mutex, and ioc-\u003elock, and RCU lifetime handling for block request queues. This code is fully reachable in virtualized QEMU environments via the bpf syscall and cgroup io.cost.model interfaces.",
"WorthFuzzing": true
}Results: {
"EnableConfigs": [
"BLK_CGROUP_IOCOST_BPF",
"BLK_CGROUP_IOCOST",
"BLK_CGROUP",
"CGROUPS",
"BPF_SYSCALL",
"BPF_JIT",
"DEBUG_INFO_BTF"
],
"FocusSymbols": [
"ioc_bpf_attach",
"ioc_bpf_detach",
"ioc_bpf_walk_iocgs",
"bpf_iocost_reg",
"bpf_iocost_unreg",
"bpf_iocost_init_member",
"bpf_iocost_validate",
"ioc_cost_model_write",
"blk_get_queue_rcu"
],
"Reasoning": "The patch series introduces BPF pluggable cost model support for the block cgroup iocost controller via a new BPF struct_ops type (\"iocost_model_ops\"). It modifies core block/cgroup code to support dynamic device attachment and detachment of BPF cost models, queue freezing/quiescing, locking coordination across rq_qos_mutex, blkcg_mutex, and ioc-\u003elock, and RCU lifetime handling for block request queues. This code is fully reachable in virtualized QEMU environments via the bpf syscall and cgroup io.cost.model interfaces.",
"WorthFuzzing": true
} |
| 17/1 | 2026/10/01 06:11 | action | If |
2mArgs:{
"WorthFuzzing": true
}Results: null |
| 18/2 | 2026/10/01 06:11 | agent | kmsan-evaluator |
2mModel:core Args: null Results: {
"KMSANReasoning": "The patch series introduces BPF struct_ops support ('iocost_model_ops') to allow pluggable cost models in the blk-iocost block I/O controller, alongside device attachment/detachment logic, RCU-protected model selection, queue reference counting (blk_get_queue_rcu), and a periodic tracepoint.\n\nAnalysis of memory safety concerns:\n1. KASAN/LOCKDEP applicability: The changes introduce concurrency and lifetime management mechanisms (synchronizing BPF struct_ops lifecycle with request_queue teardown, RCU dereferences of the attached model, mutexes across queue freezing/quiescing, and refcount management). The primary failure modes are potential race conditions, use-after-free, refcount leaks, or deadlocks, which are thoroughly covered by KASAN and LOCKDEP in standard fuzzing builds.\n2. KMSAN applicability: No uninitialized stack or heap memory is exposed or used. 'struct ioc' is allocated via kzalloc_obj, BPF struct_ops maps zero-initialize backing storage and enforce zeroed structure padding via check_zero_holes, all local variables in the new and modified functions (such as 'cost', 'now', 'model') are explicitly assigned before use, and reporting mechanisms (seq_printf in cgroup files and trace_iocost_ioc_tick) only output formatted scalar values without leaking raw kernel memory to userspace.\n\nSince there are no uninitialized memory reads or information leak risks, a dedicated KMSAN fuzzing session is not justified.",
"NeedsKMSAN": false
}Instruction: You are an expert Linux kernel security engineer specializing in kernel memory
error detectors (KASAN and KMSAN). Your job is to review the provided patch series and
determine if the code changes justify spawning a dedicated KMSAN (KernelMemorySanitizer)
fuzzing session in addition to standard KASAN fuzzing.
CRITICAL DISTINCTION BETWEEN KASAN AND KMSAN:
- Standard KASAN kernel builds (upstream-apparmor-kasan.config) already enable
a comprehensive suite of debugging tools and sanitizers, including KASAN
(out-of-bounds accesses, use-after-free, double free, invalid free), LOCKDEP
(locking bugs and deadlocks), UB-sanitizers, and memory corruption checks.
- KMSAN (KernelMemorySanitizer) detects reads of UNINITIALIZED memory (stack, heap,
or page allocations) and kernel-to-user memory info-leaks.
Rule: THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN,
LOCKDEP, OR OTHER STANDARD BUG DETECTORS.
A dedicated KMSAN fuzzing session incurs significant resource costs. You must ONLY
set NeedsKMSAN=true if the code changes introduce or expose UNINITIALIZED MEMORY risks
that are detected ONLY by KMSAN.
Look holistically at the patch series and surrounding code. Even if no direct
uninitialized field accesses or new buffer allocations are added in the diff itself,
a patch may alter control flow, bounds checking, or data length calculations in ways
that change how the rest of the code operates on existing buffers (e.g. allowing
uninitialized stack/heap memory to be read, copied to user space, or used in control
flow). Do not hesitate to use your code access tools to inspect the surrounding code,
called functions, and callers.
Set NeedsKMSAN=true ONLY IF the patch introduces or modifies:
1. Kernel structures sent to user space (via copy_to_user, put_user, netlink skb
attributes, ioctl output arguments, socket options, or BPF buffers) where fields
or structure padding might not be fully initialized/zeroed.
2. Conditional logic or branching that depends on potentially uninitialized variables
or struct fields.
3. Allocation or initialization of complex data structures where uninitialized fields
could be read later in reachable code paths.
4. Bounds checks, lengths, or logic in a way that allows surrounding code to access
uninitialized bytes of existing buffers.
Set NeedsKMSAN=false IF:
- The code changes primarily risk out-of-bounds access, array overflows, NULL pointer
dereferences, locking deadlocks, or use-after-free bugs (these are already caught
by KASAN, LOCKDEP, or standard bug detectors).
- All stack/heap structures touched or introduced by the patch are fully zeroed
or initialized (e.g. using = {0}, memset, kzalloc) before being read or copied.
- The patch does not introduce any risk of uninitialized memory usage or info-leaks.
Use your code access tools to inspect the surrounding code if necessary, then provide
detailed KMSANReasoning contrasting KASAN vs KMSAN applicability for this patch.
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt: Target architecture: amd64
For your convenience, here is the diff of the changes:
commit 417822e4805f6cd46ac79eb071e9074a04e1589c
Author: syz-cluster <triage@syzkaller.com>
Date: Thu Oct 1 06:10:47 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 7fe950425216c..5e780bdcf324b 100644
--- a/Documentation/admin-guide/cgroup-v2.rst
+++ b/Documentation/admin-guide/cgroup-v2.rst
@@ -2117,8 +2117,27 @@ IO Interface Files
===== ================================
ctrl "auto" or "user"
model The cost model in use - "linear"
+ or "bpf" while the BPF model
+ is in use
===== ================================
+ When CONFIG_BLK_CGROUP_IOCOST_BPF is enabled, a BPF cost model
+ can be attached to a device by loading an "iocost_model_ops"
+ struct_ops with 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, and
+ switches the device's pricing to the model; enabling and
+ disabling the controller stays with io.cost.qos. 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. "ctrl" keeps describing the builtin
+ coefficients, which are kept while the BPF model is in use and
+ take effect again when switched back, and the automatic profile
+ stepping does not switch profiles while the BPF model is in
+ use.
+
When "ctrl" is "auto", the kernel may change all parameters
dynamically. When "ctrl" is set to "user" or any other
parameters are written to, "ctrl" become "user" and the
diff --git a/block/Kconfig b/block/Kconfig
index 70e4a66d941ff..1cafc1bd0dda3 100644
--- a/block/Kconfig
+++ b/block/Kconfig
@@ -231,4 +231,14 @@ config BLK_ERROR_INJECTION
source "block/Kconfig.iosched"
+config BLK_CGROUP_IOCOST_BPF
+ bool "Enable BPF pluggable cost model support for the cost IO controller"
+ depends on BLK_CGROUP_IOCOST && BPF_SYSCALL && BPF_JIT && DEBUG_INFO_BTF
+ help
+ Enabling this option registers the "iocost_model_ops" BPF
+ struct_ops type, which allows a BPF program to fully replace
+ the builtin linear cost model on the device it is attached
+ to. The struct_ops is attached per device, following the
+ hid_bpf_ops model.
+
endif # BLOCK
diff --git a/block/Makefile b/block/Makefile
index e7bd320e3d697..ee5cebeea006f 100644
--- a/block/Makefile
+++ b/block/Makefile
@@ -39,3 +39,4 @@ obj-$(CONFIG_BLK_INLINE_ENCRYPTION) += blk-crypto.o blk-crypto-profile.o \
blk-crypto-sysfs.o
obj-$(CONFIG_BLK_INLINE_ENCRYPTION_FALLBACK) += blk-crypto-fallback.o
obj-$(CONFIG_BLOCK_HOLDER_DEPRECATED) += holder.o
+obj-$(CONFIG_BLK_CGROUP_IOCOST_BPF) += blk-iocost-bpf.o
diff --git a/block/blk-core.c b/block/blk-core.c
index 13dc70e8f55d9..2c789b0d86ff6 100644
--- a/block/blk-core.c
+++ b/block/blk-core.c
@@ -536,6 +536,23 @@ bool blk_get_queue(struct request_queue *q)
}
EXPORT_SYMBOL(blk_get_queue);
+/**
+ * blk_get_queue_rcu - get a queue reference regardless of the dying flag
+ * @q: the request_queue to reference
+ *
+ * Unlike blk_get_queue(), this succeeds on a dying queue, so a caller
+ * which holds the queue only through RCU (e.g. a detach path which
+ * read the pointer locklessly) can still take a reference and touch
+ * the queue under its own lifetime. The caller must hold
+ * rcu_read_lock() so the memory is valid. Fails only when the
+ * refcount already dropped to zero.
+ */
+bool blk_get_queue_rcu(struct request_queue *q)
+{
+ return refcount_inc_not_zero(&q->refs);
+}
+EXPORT_SYMBOL(blk_get_queue_rcu);
+
#ifdef CONFIG_FAIL_MAKE_REQUEST
static DECLARE_FAULT_ATTR(fail_make_request);
diff --git a/block/blk-iocost-bpf.c b/block/blk-iocost-bpf.c
new file mode 100644
index 0000000000000..32a5107522b5d
--- /dev/null
+++ b/block/blk-iocost-bpf.c
@@ -0,0 +1,220 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * blk-iocost: BPF struct_ops plumbing for pluggable cost models.
+ *
+ * Registers the "iocost_model_ops" struct_ops type. Attachment is
+ * per-device and follows the hid_bpf_ops model: 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 under the same queue freeze and quiesce as io.cost.model
+ * writes, and .unreg detaches it; enabling and disabling the
+ * controller stays with io.cost.qos. The struct_ops core owns the
+ * program lifetime. There is no name registry and no separate
+ * bound-state bookkeeping.
+ */
+#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 <linux/blk-iocost.h>
+#include <linux/blk-mq.h>
+#include <linux/mutex.h>
+
+struct block_device *blkdev_get_no_open(dev_t dev, bool autoload);
+void blkdev_put_no_open(struct block_device *bdev);
+bool blk_get_queue_rcu(struct request_queue *q);
+void blk_put_queue(struct request_queue *q);
+
+static int bpf_iocost_model_init(struct btf *btf)
+{
+ s32 type_id;
+
+ type_id = btf_find_by_name_kind(btf, "iocost_model_ops", BTF_KIND_STRUCT);
+ if (type_id < 0)
+ return -EINVAL;
+ return 0;
+}
+
+static bool bpf_iocost_is_valid_access(int off, int size,
+ enum bpf_access_type type,
+ const struct bpf_prog *prog,
+ struct bpf_insn_access_aux *info)
+{
+ return bpf_tracing_btf_ctx_access(off, size, type, prog, info);
+}
+
+/*
+ * No iocost-specific helpers; bpf_base_func_proto already covers the
+ * cgroup storage helpers under CONFIG_CGROUPS.
+ */
+static const struct bpf_func_proto *
+bpf_iocost_get_func_proto(enum bpf_func_id func_id,
+ const struct bpf_prog *prog)
+{
+ return bpf_base_func_proto(func_id, prog);
+}
+
+static int bpf_iocost_check_member(const struct btf_type *t,
+ const struct btf_member *member,
+ const struct bpf_prog *prog)
+{
+ /* calc_cost() is called with RCU read lock held */
+ if (prog->sleepable)
+ return -EINVAL;
+ return 0;
+}
+
+static int bpf_iocost_init_member(const struct btf_type *t,
+ const struct btf_member *member,
+ void *kdata, const void *udata)
+{
+ struct iocost_model_ops *ops = kdata;
+ const struct iocost_model_ops *uops = udata;
+ u32 moff = __btf_member_bit_offset(t, member) / 8;
+
+ switch (moff) {
+ case offsetof(struct iocost_model_ops, bdev):
+ /*
+ * kernel-private: the bdev reference held while
+ * attached; reject a userspace value
+ */
+ if (uops->bdev)
+ return -EINVAL;
+ ops->bdev = NULL;
+ return 1;
+ case offsetof(struct iocost_model_ops, q):
+ /* kernel-private: the queue of the attached device */
+ if (uops->q)
+ return -EINVAL;
+ ops->q = NULL;
+ return 1;
+ case offsetof(struct iocost_model_ops, dev):
+ /*
+ * copy it and return 1 to indicate that the member is
+ * handled here, or the verifier rejects the map if the
+ * userspace value is nonzero
+ */
+ 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;
+}
+
+/*
+ * kvalue is zeroed at map allocation and function members are only
+ * written when the BPF side provides a prog, so a model which did
+ * not implement calc_cost leaves it NULL. The dispatch would call
+ * it on every bio, so reject it here.
+ */
+static int bpf_iocost_validate(void *kdata)
+{
+ struct iocost_model_ops *ops = kdata;
+
+ return ops->calc_cost ? 0 : -EINVAL;
+}
+
+static int bpf_iocost_reg(void *kdata, struct bpf_link *link)
+{
+ struct iocost_model_ops *ops = kdata;
+
+ if (!ops->dev)
+ return -EINVAL;
+
+ return ioc_bpf_attach(ops);
+}
+
+static void bpf_iocost_unreg(void *kdata, struct bpf_link *link)
+{
+ struct iocost_model_ops *ops = kdata;
+ struct block_device *bdev;
+ struct request_queue *q;
+
+ /*
+ * ops->q may already have been cleared by the removal ejection;
+ * take a queue reference under RCU before entering the queue,
+ * as the queue may be dying and its memory is only guaranteed
+ * under rcu_read_lock()
+ */
+ rcu_read_lock();
+ q = rcu_dereference(ops->q);
+ if (!q || !blk_get_queue_rcu(q)) {
+ rcu_read_unlock();
+ return;
+ }
+ rcu_read_unlock();
+
+ /*
+ * take rq_qos_mutex before touching the queue further: the
+ * removal ejection clears ops->q under it, inside rq_qos_exit()
+ * and before blk_mq_exit_queue() releases the hardware queues,
+ * so holding it and seeing a non-NULL ops->q guarantees the
+ * queue is still safe to freeze. The freeze and quiesce are
+ * done inside ioc_bpf_detach(), under the mutex.
+ */
+ mutex_lock(&q->rq_qos_mutex);
+ if (!ops->q) {
+ /* the removal ejection won the race; nothing to detach */
+ mutex_unlock(&q->rq_qos_mutex);
+ blk_put_queue(q);
+ return;
+ }
+ bdev = ops->bdev;
+ ioc_bpf_detach(ops);
+ mutex_unlock(&q->rq_qos_mutex);
+ blk_put_queue(q);
+
+ /* drop the attach reference when we did the detach */
+ if (bdev)
+ blkdev_put_no_open(bdev);
+}
+
+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 2745bffcd5eef..64744266cfd30 100644
--- a/block/blk-iocost.c
+++ b/block/blk-iocost.c
@@ -177,6 +177,7 @@
#include <linux/timer.h>
#include <linux/time64.h>
#include <linux/parser.h>
+#include <linux/blk-iocost.h>
#include <linux/sched/signal.h>
#include <asm/local.h>
#include <asm/local64.h>
@@ -445,6 +446,13 @@ struct ioc {
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 cost model in use, NULL = builtin linear model */
+ const struct iocost_model_ops __rcu *model;
+#endif
};
struct iocg_pcpu_stat {
@@ -780,6 +788,45 @@ static void ioc_refresh_period_us(struct ioc *ioc)
ioc_refresh_margins(ioc);
}
+/*
+ * The BPF model in use, or NULL when the builtin linear model prices
+ * this device. CONFIG_BLK_CGROUP_IOCOST_BPF=n compiles to a constant
+ * NULL so callers need no #ifdefs.
+ */
+static const struct iocost_model_ops *ioc_model_in_use(struct ioc *ioc)
+{
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+ return rcu_dereference(ioc->model);
+#else
+ return NULL;
+#endif
+}
+
+/*
+ * The struct_ops attached to this device, or NULL. While attachment
+ * and model selection are independent, the cgroup callbacks follow
+ * the attachment, not the selection.
+ */
+static const struct iocost_model_ops *ioc_attached_or_null(struct ioc *ioc)
+{
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+ return rcu_dereference(ioc->attached);
+#else
+ return NULL;
+#endif
+}
+
+static const struct iocost_model_ops *
+ioc_model_in_use_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
+}
+
/*
* ioc->rqos.disk isn't initialized when this function is called from
* the init path.
@@ -803,8 +850,13 @@ 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: the builtin coefficients are inert
+ * then, so stepping the profile is pointless
+ */
+ if (ioc->user_qos_params || ioc->user_cost_model ||
+ ioc_model_in_use_locked(ioc))
return idx;
/* step up/down based on the vrate */
@@ -2238,6 +2290,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;
@@ -2274,6 +2327,8 @@ static void ioc_timer_fn(struct timer_list *timer)
u64 vdone, vtime, usage_us;
u32 hw_active, hw_inuse;
+ nr_active++;
+
/*
* Collect unused and wind vtime closer to vnow to prevent
* iocgs from accumulating a large amount of budget.
@@ -2435,6 +2490,15 @@ 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, running and cur_period haven't changed, nr_active and
+ * usage_us_sum are complete, and vrate and period_us still hold
+ * the values this period ran in. 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);
@@ -2571,8 +2635,19 @@ static void calc_vtime_cost_builtin(struct bio *bio, struct ioc_gq *iocg,
static u64 calc_vtime_cost(struct bio *bio, struct ioc_gq *iocg, bool is_merge)
{
+ const struct iocost_model_ops *model;
u64 cost;
+ rcu_read_lock();
+ model = ioc_model_in_use(iocg->ioc);
+ if (model) {
+ cost = model->calc_cost(bio,
+ is_merge ? IOCOST_COST_F_MERGE : 0);
+ rcu_read_unlock();
+ return min(cost, VTIME_PER_SEC);
+ }
+ rcu_read_unlock();
+
calc_vtime_cost_builtin(bio, iocg, is_merge, &cost);
return cost;
}
@@ -2594,10 +2669,32 @@ static void calc_size_vtime_cost_builtin(struct request *rq, struct ioc *ioc,
}
}
+/*
+ * Called from the request completion path, 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)
{
+ const struct iocost_model_ops *model;
u64 cost;
+ rcu_read_lock();
+ model = ioc_model_in_use(ioc);
+ if (model && (req_op(rq) == REQ_OP_READ ||
+ req_op(rq) == REQ_OP_WRITE)) {
+ unsigned int pages =
+ blk_rq_stats_sectors(rq) >> IOC_SECT_TO_PAGE_SHIFT;
+ u64 coeff = req_op(rq) == REQ_OP_READ ?
+ model->read_vtime_per_page :
+ model->write_vtime_per_page;
+
+ cost = pages * coeff;
+ rcu_read_unlock();
+ return cost;
+ }
+ rcu_read_unlock();
+
calc_size_vtime_cost_builtin(rq, ioc, &cost);
return cost;
}
@@ -2900,6 +2997,24 @@ static void ioc_rqos_exit(struct rq_qos *rqos)
timer_shutdown_sync(&ioc->timer);
free_percpu(ioc->pcpu_stat);
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+ {
+ struct iocost_model_ops *ops;
+
+ spin_lock_irq(&ioc->lock);
+ ops = (struct iocost_model_ops *)rcu_dereference_protected(
+ ioc->attached, lockdep_is_held(&ioc->lock));
+ rcu_assign_pointer(ioc->attached, NULL);
+ rcu_assign_pointer(ioc->model, NULL);
+ spin_unlock_irq(&ioc->lock);
+
+ /* eject the model completely on device removal */
+ if (ops) {
+ WRITE_ONCE(ops->q, NULL);
+ blkdev_put_no_open(ops->bdev);
+ }
+ }
+#endif
kfree(ioc);
}
@@ -3022,6 +3137,7 @@ static void ioc_pd_init(struct blkg_policy_data *pd)
struct ioc_now now;
struct blkcg_gq *tblkg;
unsigned long flags;
+ const struct iocost_model_ops *model;
ioc_now(ioc, &now);
@@ -3048,6 +3164,18 @@ static void ioc_pd_init(struct blkg_policy_data *pd)
spin_lock_irqsave(&ioc->lock, flags);
weight_updated(iocg, &now);
spin_unlock_irqrestore(&ioc->lock, flags);
+
+ /*
+ * the attached model is RCU-protected: a concurrent detach
+ * publishes NULL and the struct_ops image survives it by a
+ * grace period, so the callback is safe inside the read-side
+ * critical section
+ */
+ rcu_read_lock();
+ model = ioc_attached_or_null(ioc);
+ if (model && model->iocg_init)
+ model->iocg_init(blkg->blkcg, ioc->rqos.disk->queue);
+ rcu_read_unlock();
}
static void iocg_release(struct rcu_head *rcu)
@@ -3066,8 +3194,15 @@ static void ioc_pd_free(struct blkg_policy_data *pd)
struct blkcg_gq *blkg = pd_to_blkg(pd);
struct ioc *ioc = iocg->ioc;
unsigned long flags;
+ const struct iocost_model_ops *model;
if (ioc) {
+ rcu_read_lock();
+ model = ioc_attached_or_null(ioc);
+ if (model && model->iocg_free)
+ model->iocg_free(blkg->blkcg, ioc->rqos.disk->queue);
+ rcu_read_unlock();
+
spin_lock_irqsave(&ioc->lock, flags);
if (!list_empty(&iocg->active_list)) {
@@ -3433,17 +3568,21 @@ 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_model_in_use_locked(ioc);
+ seq_printf(sf, "%s ctrl=%s model=%s "
"rbps=%llu rseqiops=%llu rrandiops=%llu "
"wbps=%llu wseqiops=%llu wrandiops=%llu\n",
dname, ioc->user_cost_model ? "user" : "auto",
- u[I_LCOEF_RBPS], u[I_LCOEF_RSEQIOPS], u[I_LCOEF_RRANDIOPS],
- u[I_LCOEF_WBPS], u[I_LCOEF_WSEQIOPS], u[I_LCOEF_WRANDIOPS]);
+ 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]);
spin_unlock_irq(&ioc->lock);
return 0;
}
@@ -3457,6 +3596,204 @@ static int ioc_cost_model_show(struct seq_file *sf, void *v)
return 0;
}
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+/*
+ * Deliver iocg_init()/iocg_free() to the cgroups which already have a
+ * blkg on the queue, the same q->blkg_list walk the blkcg policy
+ * teardown uses. The queue is frozen and quiesced and blkcg_mutex
+ * serializes against blkg creation and destruction. Cgroups without
+ * a blkg on the device yet are not missed: their blkg is created
+ * later and ioc_pd_init()/ioc_pd_free() deliver the callbacks then.
+ */
+static void ioc_bpf_walk_iocgs(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);
+
+ rcu_read_lock();
+ list_for_each_entry(blkg, &q->blkg_list, q_node) {
+ if (!blkg_to_iocg(blkg))
+ continue;
+ if (init) {
+ if (ops->iocg_init)
+ ops->iocg_init(blkg->blkcg, q);
+ } else {
+ if (ops->iocg_free)
+ ops->iocg_free(blkg->blkcg, q);
+ }
+ }
+ rcu_read_unlock();
+}
+
+int ioc_bpf_attach(struct iocost_model_ops *ops)
+{
+ struct block_device *bdev;
+ struct request_queue *q;
+ struct gendisk *disk;
+ struct ioc *ioc;
+ unsigned int memflags;
+ int ret;
+
+ /* prevent multiple attach of the same struct_ops */
+ if (ops->q)
+ return -EINVAL;
+
+ 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)) {
+ ret = -EINVAL;
+ goto put;
+ }
+ if (!queue_is_mq(q)) {
+ ret = -EOPNOTSUPP;
+ goto put;
+ }
+
+ /*
+ * check liveness and create the ioc under rq_qos_mutex, like
+ * blkg_conf_open_bdev() does; enabling stays with io.cost.qos
+ *
+ * the queue reference is held across the unlocked window below:
+ * the bdev reference does not pin the queue, bdev only holds a
+ * raw bd_queue pointer, and concurrent device removal may eject
+ * the model and free the ioc while we are off the mutex, so
+ * without our own reference the second mutex_lock() would touch
+ * a freed queue
+ */
+ mutex_lock(&q->rq_qos_mutex);
+ if (!disk_live(disk) || !blk_get_queue(q)) {
+ mutex_unlock(&q->rq_qos_mutex);
+ ret = -ENODEV;
+ goto put;
+ }
+ ioc = q_to_ioc(q);
+ if (!ioc) {
+ ret = blk_iocost_init(disk);
+ mutex_unlock(&q->rq_qos_mutex);
+ if (ret)
+ goto put_q;
+ ioc = q_to_ioc(q);
+ } else {
+ mutex_unlock(&q->rq_qos_mutex);
+ }
+
+ /*
+ * ops->bdev is dropped by the removal ejection or by .unreg,
+ * whichever detaches the model first, similar to hid_bpf's
+ * per-ops device reference without the struct file and without
+ * pinning the driver module
+ */
+
+ /*
+ * switch the model under the same freeze and quiesce as the
+ * io.cost.model writes; the freeze does not pin the ioc, so
+ * rq_qos_mutex has to be held across the switch - ioc_rqos_exit()
+ * frees the ioc under it
+ */
+ mutex_lock(&q->rq_qos_mutex);
+ ioc = q_to_ioc(q);
+ if (!ioc) {
+ mutex_unlock(&q->rq_qos_mutex);
+ ret = -ENODEV;
+ goto put_q;
+ }
+ memflags = blk_mq_freeze_queue(q);
+ blk_mq_quiesce_queue(q);
+
+ /*
+ * hold blkcg_mutex across the publish and the iocg_init() walk:
+ * ioc_pd_init() runs under it too, so no cgroup can receive
+ * iocg_init() from both the walk and its own pd_init
+ */
+ mutex_lock(&q->blkcg_mutex);
+ spin_lock_irq(&ioc->lock);
+ if (rcu_dereference_protected(ioc->attached,
+ lockdep_is_held(&ioc->lock))) {
+ spin_unlock_irq(&ioc->lock);
+ mutex_unlock(&q->blkcg_mutex);
+ blk_mq_unquiesce_queue(q);
+ blk_mq_unfreeze_queue(q, memflags);
+ mutex_unlock(&q->rq_qos_mutex);
+ ret = -EBUSY;
+ goto put_q;
+ }
+ rcu_assign_pointer(ioc->attached, ops);
+ rcu_assign_pointer(ioc->model, ops);
+ spin_unlock_irq(&ioc->lock);
+
+ ops->bdev = bdev;
+ WRITE_ONCE(ops->q, q);
+
+ /* pair iocg_init() with the cgroups which already exist */
+ ioc_bpf_walk_iocgs(ioc, ops, true);
+ mutex_unlock(&q->blkcg_mutex);
+
+ blk_mq_unquiesce_queue(q);
+ blk_mq_unfreeze_queue(q, memflags);
+ mutex_unlock(&q->rq_qos_mutex);
+ blk_put_queue(q);
+ return 0;
+
+put_q:
+ blk_put_queue(q);
+put:
+ 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. The caller has already checked ops->q.
+ */
+void ioc_bpf_detach(struct iocost_model_ops *ops)
+{
+ struct request_queue *q = ops->q;
+ struct ioc *ioc;
+ unsigned int memflags;
+
+ if (!q)
+ return;
+ ioc = q_to_ioc(q);
+ if (!ioc)
+ return;
+
+ memflags = blk_mq_freeze_queue(q);
+ blk_mq_quiesce_queue(q);
+
+ /*
+ * hold blkcg_mutex across the clearing and the iocg_free() walk:
+ * ioc_pd_free() runs under it too, so no cgroup can receive
+ * iocg_free() from both the walk and its own pd_free
+ */
+ mutex_lock(&q->blkcg_mutex);
+ spin_lock_irq(&ioc->lock);
+ if (rcu_dereference_protected(ioc->model,
+ lockdep_is_held(&ioc->lock)) == ops)
+ rcu_assign_pointer(ioc->model, NULL);
+ rcu_assign_pointer(ioc->attached, NULL);
+ spin_unlock_irq(&ioc->lock);
+
+ /* pair iocg_free() with the cgroups which still exist */
+ ioc_bpf_walk_iocgs(ioc, ops, false);
+ mutex_unlock(&q->blkcg_mutex);
+
+ WRITE_ONCE(ops->q, NULL);
+
+ blk_mq_unquiesce_queue(q);
+ blk_mq_unfreeze_queue(q, memflags);
+}
+
+#endif
+
static const match_table_t cost_ctrl_tokens = {
{ COST_CTRL, "ctrl=%s" },
{ COST_MODEL, "model=%s" },
@@ -3484,6 +3821,10 @@ static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
bool user;
char *body, *p;
int ret;
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+ const struct iocost_model_ops *new_model = NULL;
+ bool model_write = false;
+#endif
blkg_conf_init(&ctx, input);
@@ -3536,9 +3877,28 @@ 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")) {
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+ /* staged and committed below, so a parse
+ * error later in the same write leaves
+ * the model selection untouched */
+ new_model = NULL;
+ model_write = true;
+#endif
+ continue;
+ }
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+ if (!strcmp(buf, "bpf")) {
+ new_model = rcu_dereference_protected(
+ ioc->attached,
+ lockdep_is_held(&ioc->lock));
+ if (!new_model)
+ goto unlock;
+ model_write = true;
+ continue;
+ }
+#endif
+ goto unlock;
}
tok = match_token(p, i_lcoef_tokens, args);
@@ -3556,6 +3916,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;
diff --git a/include/linux/blk-iocost.h b/include/linux/blk-iocost.h
new file mode 100644
index 0000000000000..03a0c7dab71fd
--- /dev/null
+++ b/include/linux/blk-iocost.h
@@ -0,0 +1,110 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _LINUX_BLK_IOCOST_H
+#define _LINUX_BLK_IOCOST_H
+
+#include <linux/types.h>
+#include <linux/blk_types.h>
+#include <linux/blkdev.h>
+
+struct bio;
+struct blkcg;
+struct request_queue;
+
+/*
+ * Pluggable cost model interface for blk-iocost.
+ *
+ * A BPF struct_ops implementation is attached to one device, identified
+ * by the dev member set from userspace before load, following the
+ * hid_bpf_ops model: the struct_ops core owns the lifetime of the
+ * program. Attaching creates the ioc if needed, like an io.cost.model
+ * write does, switches the device to the BPF model under the same
+ * queue freeze and quiesce, 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, "model=linear" switches back to the
+ * builtin model, and neither detaches the struct_ops; only detaching
+ * removes the model. The builtin linear coefficients are kept while
+ * the BPF model is in use and take effect again when switched back.
+ *
+ * While the BPF model is the one in use, it owns pricing for every
+ * charged IO on the device: it prices all operations, 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 the model
+ * can read whatever it needs (operation flags, size, sector, the
+ * issuing cgroup through bio->bi_blkg). It returns the cost of the
+ * IO in vtime units, where 1 second of device time equals
+ * VTIME_PER_SEC (2^37, available to BPF programs through vmlinux.h).
+ * The returned value is clamped to 1 second of device time per IO.
+ *
+ * The struct_ops also carries the transfer cost coefficients, vtime
+ * per page for reads and writes: while the BPF model is in use, the
+ * builtin latency tracking and vrate adjustment use these instead of
+ * the builtin linear coefficients for the completion-time request
+ * sizing, so the whole controller follows the model's pricing. Letting
+ * a model take over the QoS side entirely (latency tracking, vrate
+ * control) is left for a later extension.
+ *
+ * The cgroup callbacks are bound to the iocg policy lifetime, one
+ * (cgroup, device) pair per invocation: iocg_init() is delivered on
+ * attach to every cgroup which already exists on the device and to
+ * each one appearing afterwards; iocg_free() is delivered on detach to
+ * every cgroup still existing then, and at policy deactivation time
+ * for the rest, so init and free always pair up. Both callbacks run
+ * inside an RCU read-side critical section and must not sleep.
+ */
+
+/*
+ * iocost-specific call metadata for calc_cost()'s model_flags
+ * argument; the merge indicator is not a property of the bio.
+ * An enum so the value is exported through BTF and BPF models can
+ * use it from vmlinux.h.
+ */
+enum {
+ IOCOST_COST_F_MERGE = 1 << 0, /* called from merge path */
+};
+
+struct iocost_model_ops {
+ /*
+ * 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, used by the builtin sizing and vrate logic */
+ 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);
+
+ /* private: */
+
+ /*
+ * bdev reference held while attached; dropped by the removal
+ * ejection or .unreg, whichever detaches the model first
+ */
+ struct block_device *bdev;
+ /* queue of the attached device, NULL = not attached */
+ struct request_queue *q;
+};
+
+#ifdef CONFIG_BLK_CGROUP_IOCOST_BPF
+
+int ioc_bpf_attach(struct iocost_model_ops *ops);
+void ioc_bpf_detach(struct iocost_model_ops *ops);
+
+#else /* CONFIG_BLK_CGROUP_IOCOST_BPF */
+
+static inline int ioc_bpf_attach(struct iocost_model_ops *ops)
+{
+ return -EOPNOTSUPP;
+}
+static inline void ioc_bpf_detach(struct iocost_model_ops *ops) { }
+
+#endif /* CONFIG_BLK_CGROUP_IOCOST_BPF */
+#endif /* _LINUX_BLK_IOCOST_H */
diff --git a/include/trace/events/iocost.h b/include/trace/events/iocost.h
index e772b1bc60d60..79773e82d42cf 100644
--- a/include/trace/events/iocost.h
+++ b/include/trace/events/iocost.h
@@ -178,6 +178,50 @@ TRACE_EVENT(iocost_ioc_vrate_adj,
)
);
+/*
+ * Periodic per-device summary, emitted once per period from the tail of
+ * ioc_timer_fn(). Unlike the state-change events above, this fires every
+ * period the controller is running, including steady states, and carries
+ * the overall controller state so basic monitoring doesn't require drgn.
+ */
+TRACE_EVENT(iocost_ioc_tick,
+
+ TP_PROTO(struct ioc *ioc, 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)
+ __field(int, running)
+ ),
+
+ 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;
+ __entry->running = ioc->running;
+ ),
+
+ TP_printk("[%s] period=%llu:%uus vrate=%llu busy=%d active=%d usage=%u%% running=%d",
+ __get_str(devname), __entry->cur_period, __entry->period_us,
+ __entry->vrate, __entry->busy_level, __entry->nr_active,
+ __entry->usage_pct, __entry->running
+ )
+);
+
TRACE_EVENT(iocost_iocg_forgive_debt,
TP_PROTO(struct ioc_gq *iocg, const char *path, struct ioc_now *now,
diff --git a/tools/testing/selftests/bpf/config b/tools/testing/selftests/bpf/config
index 2b883b388f90c..c5634ee91e690 100644
--- a/tools/testing/selftests/bpf/config
+++ b/tools/testing/selftests/bpf/config
@@ -140,3 +140,5 @@ CONFIG_SMC_HS_CTRL_BPF=y
CONFIG_DIBS=y
CONFIG_DIBS_LO=y
CONFIG_PM_WAKELOCKS=y
+CONFIG_BLK_CGROUP_IOCOST=y
+CONFIG_BLK_CGROUP_IOCOST_BPF=y
diff --git a/tools/testing/selftests/bpf/prog_tests/iocost_model.c b/tools/testing/selftests/bpf/prog_tests/iocost_model.c
new file mode 100644
index 0000000000000..5b7b1282fcb74
--- /dev/null
+++ b/tools/testing/selftests/bpf/prog_tests/iocost_model.c
@@ -0,0 +1,245 @@
+// SPDX-License-Identifier: GPL-2.0
+#include <test_progs.h>
+#include <fcntl.h>
+#include <sys/sysmacros.h>
+#include <unistd.h>
+#include "iocost_model.skel.h"
+#include "iocost_ms.skel.h"
+
+/*
+ * 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;
+}
+
+/*
+ * Write a line to io.cost.model for dev and return the errno of the
+ * write (0 on success).
+ */
+static int write_cost_model(const char *dev, const char *what)
+{
+ char buf[128], line[256], word[256];
+ 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 one device, given as major:minor in
+ * $IOCOST_TEST_DEV: the dev member is written through the struct_ops
+ * map's initial value before load, as hid_bpf_ops does with hid_id,
+ * and attaching the struct_ops attaches the model to the device.
+ * Detaching the struct_ops restores the builtin model.
+ *
+ * Requires root, cgroup v2 and a device with iocost support.
+ */
+void serial_test_iocost_model(void)
+{
+ struct iocost_model *skel, *second;
+ unsigned int maj, min;
+ __u32 *ops_dev, *sdev;
+ int err;
+ char model[32], *dev;
+
+ dev = getenv("IOCOST_TEST_DEV");
+ if (!dev || geteuid() != 0 || sscanf(dev, "%u:%u", &maj, &min) != 2) {
+ printf("%s:SKIP:needs root and IOCOST_TEST_DEV=<maj>:<min>\n",
+ __func__);
+ test__skip();
+ return;
+ }
+
+ skel = iocost_model__open();
+ if (!ASSERT_OK_PTR(skel, "skel_open"))
+ return;
+
+ /* dev is the first member of struct iocost_model_ops */
+ ops_dev = bpf_map__initial_value(skel->maps.iocost_2x, NULL);
+ if (!ASSERT_OK_PTR(ops_dev, "initial_value")) {
+ iocost_model__destroy(skel);
+ return;
+ }
+ *ops_dev = (__u32)makedev(maj, min);
+
+ err = iocost_model__load(skel);
+ if (!ASSERT_OK(err, "skel_load")) {
+ iocost_model__destroy(skel);
+ return;
+ }
+
+ err = iocost_model__attach(skel);
+ if (err == -EOPNOTSUPP) {
+ printf("%s: device is not blk-mq or iocost unavailable, skipping\n",
+ __func__);
+ iocost_model__destroy(skel);
+ 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_EQ(strcmp(model, "bpf"), 0, "model_bpf");
+
+ /* a second model on the same device fails with -EBUSY */
+ second = iocost_model__open();
+ if (ASSERT_OK_PTR(second, "second_open")) {
+ sdev = bpf_map__initial_value(
+ second->maps.iocost_2x, NULL);
+ if (!ASSERT_OK_PTR(sdev, "second_initial_value"))
+ goto out_destroy;
+ *sdev = (__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");
+ }
+out_destroy:
+ iocost_model__destroy(second);
+ }
+
+ /*
+ * 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_EQ(strcmp(model, "linear"), 0, "model_linear");
+
+ /* 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_EQ(strcmp(model, "bpf"), 0, "model_bpf");
+
+ iocost_model__detach(skel);
+
+ /* 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_EQ(strcmp(model, "linear"), 0, "model_linear");
+ }
+
+ iocost_model__destroy(skel);
+}
+/*
+ * Same check for the multi-stream example model. Only one model can
+ * be attached to a device at a time; both tests attach and detach, so
+ * they are serial and independent.
+ */
+void serial_test_iocost_model_streams(void)
+{
+ struct iocost_ms *skel;
+ unsigned int maj, min;
+ __u32 *ops_dev;
+ int err;
+ char model[32], *dev;
+
+ dev = getenv("IOCOST_TEST_DEV");
+ if (!dev || geteuid() != 0 || sscanf(dev, "%u:%u", &maj, &min) != 2) {
+ printf("%s:SKIP:needs root and IOCOST_TEST_DEV=<maj>:<min>\n",
+ __func__);
+ test__skip();
+ return;
+ }
+
+ skel = iocost_ms__open();
+ if (!ASSERT_OK_PTR(skel, "skel_open"))
+ return;
+
+ ops_dev = bpf_map__initial_value(skel->maps.iocost_ms, NULL);
+ if (!ASSERT_OK_PTR(ops_dev, "initial_value")) {
+ iocost_ms__destroy(skel);
+ return;
+ }
+ *ops_dev = (__u32)makedev(maj, min);
+
+ err = iocost_ms__load(skel);
+ if (!ASSERT_OK(err, "skel_load")) {
+ iocost_ms__destroy(skel);
+ return;
+ }
+
+ err = iocost_ms__attach(skel);
+ if (err == -EOPNOTSUPP) {
+ printf("%s: device is not blk-mq or iocost unavailable, skipping\n",
+ __func__);
+ iocost_ms__destroy(skel);
+ return;
+ }
+ if (ASSERT_OK(err, "attach")) {
+ err = readback_model(dev, model, sizeof(model));
+ if (ASSERT_OK(err, "readback"))
+ ASSERT_EQ(strcmp(model, "bpf"), 0, "model_bpf");
+
+ iocost_ms__detach(skel);
+
+ err = readback_model(dev, model, sizeof(model));
+ if (ASSERT_OK(err, "readback_after_detach"))
+ ASSERT_EQ(strcmp(model, "linear"), 0, "model_linear");
+ }
+
+ iocost_ms__destroy(skel);
+}
diff --git a/tools/testing/selftests/bpf/progs/iocost_model.c b/tools/testing/selftests/bpf/progs/iocost_model.c
new file mode 100644
index 0000000000000..e8f222c50b39c
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/iocost_model.c
@@ -0,0 +1,140 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * 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; this model prices them
+ * 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 mirrors the builtin: a zero cursor means "no
+ * previous IO", and the cursor is advanced for bios the builtin
+ * prices (READ/WRITE with a non-zero size), merged ones included, so
+ * flushes and discards leave it alone and long merged streams do not
+ * drift past the 16MB seek threshold.
+ *
+ * The model implements the full linear formula itself, including
+ * flushes: there is no fallback to the builtin model, a dataless
+ * WRITE|REQ_PREFLUSH is priced as a one-page write.
+ */
+
+#include "vmlinux.h"
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+
+/*
+ * VTIME_PER_SEC, IOC_PAGE_SIZE/SHIFT, IOC_SECT_TO_PAGE_SHIFT and
+ * IOCOST_COST_F_MERGE come from vmlinux.h (BTF enum constants)
+ */
+#define LCOEF_RANDIO_PAGES 4096 /* 16MB seek threshold */
+#define IOCOST_REQ_OP_MASK 0xff /* REQ_OP_MASK, not in BTF */
+
+/*
+ * DIV64_U64_ROUND_UP / DIV_ROUND_UP_ULL equivalents, folded at
+ * compile time
+ */
+#define RU(x, y) ((x) / (y) + (((x) % (y)) ? 1 : 0))
+
+#define RBPS 174019176ULL
+#define RSEQIOPS 41708ULL
+#define RRANDIOPS 370ULL
+#define WBPS 178075866ULL
+#define WSEQIOPS 42705ULL
+#define WRANDIOPS 378ULL
+
+#define RPAGE (RU(VTIME_PER_SEC, RU(RBPS, IOC_PAGE_SIZE)))
+#define RSEQIO (RU(VTIME_PER_SEC, RSEQIOPS) - RPAGE)
+#define RRANDIO (RU(VTIME_PER_SEC, RRANDIOPS) - RPAGE)
+#define WPAGE (RU(VTIME_PER_SEC, RU(WBPS, IOC_PAGE_SIZE)))
+#define WSEQIO (RU(VTIME_PER_SEC, WSEQIOPS) - WPAGE)
+#define WRANDIO (RU(VTIME_PER_SEC, WRANDIOPS) - WPAGE)
+
+/*
+ * per-cgroup cursor storage: keyed by the cgroup 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");
+
+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;
+
+ /* builtin truncates: max(sectors >> IOC_SECT_TO_PAGE_SHIFT, 1) */
+ pages = nbytes >> IOC_PAGE_SHIFT;
+ if (!pages)
+ pages = 1;
+
+ if ((opf & IOCOST_REQ_OP_MASK) == REQ_OP_READ) {
+ base = RSEQIO; coef_page = RPAGE; randio = RRANDIO;
+ } else if ((opf & IOCOST_REQ_OP_MASK) == REQ_OP_WRITE) {
+ base = WSEQIO; coef_page = WPAGE; randio = WRANDIO;
+ } else {
+ /*
+ * a fully owning model must price every op; unknown
+ * ops are priced per page at the write coefficient
+ */
+ base = 0; coef_page = WPAGE; randio = 0;
+ }
+
+ /*
+ * mirror the builtin cursor semantics: seek distance is only
+ * computed against a non-zero cursor, and the cursor is
+ * advanced for bios the builtin prices (READ/WRITE with a
+ * non-zero size), merged ones included, so flushes and
+ * discards leave it alone
+ */
+ priced = (opf & IOCOST_REQ_OP_MASK) == REQ_OP_READ ||
+ (opf & IOCOST_REQ_OP_MASK) == REQ_OP_WRITE;
+ cursor = bpf_cgrp_storage_get(&cursor_store,
+ blkcg->css.cgroup, NULL,
+ BPF_LOCAL_STORAGE_GET_F_CREATE);
+ if (!cursor) {
+ if (model_flags & IOCOST_COST_F_MERGE)
+ base = 0;
+ return 2 * (base + pages * coef_page);
+ }
+ cur = *cursor;
+ if (cur && priced) {
+ seek_pages = sector > cur ? sector - cur
+ : cur - sector;
+ seek_pages >>= IOC_SECT_TO_PAGE_SHIFT;
+ if (seek_pages > LCOEF_RANDIO_PAGES)
+ base = randio;
+ }
+ if (priced && nbytes)
+ *cursor = sector + (nbytes >> 9);
+
+ if (model_flags & IOCOST_COST_F_MERGE)
+ base = 0;
+
+ cost = 2 * (base + pages * coef_page);
+ return cost;
+}
+
+SEC(".struct_ops")
+struct iocost_model_ops iocost_2x = {
+ .read_vtime_per_page = 2 * RPAGE,
+ .write_vtime_per_page = 2 * WPAGE,
+ .calc_cost = (void *)iocost_2x_calc_cost,
+};
+
+char LICENSE[] SEC("license") = "GPL";
diff --git a/tools/testing/selftests/bpf/progs/iocost_ms.c b/tools/testing/selftests/bpf/progs/iocost_ms.c
new file mode 100644
index 0000000000000..50a670edfe399
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/iocost_ms.c
@@ -0,0 +1,159 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Example multi-stream sequentiality detection cost model.
+ *
+ * The builtin model keeps a single cursor per cgroup, so two
+ * interleaved sequential readers in one cgroup are all priced random
+ * (measured 89x overcharge, 12.9x throughput collapse), while random
+ * IO inside a hot window smaller than the 16MB seek threshold is
+ * priced sequential (measured 107x undercharge). This model replaces
+ * the single cursor with a per-cgroup table of stream slots: an IO is
+ * sequential iff its sector matches the expected next sector of any
+ * tracked stream. Interleaved streams keep their own slots, and
+ * windowed random IO rarely matches a moving expectation.
+ *
+ * Stream state lives in a CGRP_STORAGE map, so it is created and
+ * freed with the cgroup. The model implements the full builtin
+ * linear formula itself, including flush pricing.
+ */
+#include "vmlinux.h"
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_tracing.h>
+
+/*
+ * VTIME_PER_SEC, IOC_PAGE_SIZE/SHIFT, IOC_SECT_TO_PAGE_SHIFT and
+ * IOCOST_COST_F_MERGE come from vmlinux.h (BTF enum constants)
+ */
+#define IOCOST_REQ_OP_MASK 0xff /* REQ_OP_MASK, not in BTF */
+
+/*
+ * DIV64_U64_ROUND_UP / DIV_ROUND_UP_ULL equivalents, folded at
+ * compile time
+ */
+#define RU(x, y) ((x) / (y) + (((x) % (y)) ? 1 : 0))
+
+#define RBPS 174019176ULL
+#define RSEQIOPS 41708ULL
+#define RRANDIOPS 370ULL
+#define WBPS 178075866ULL
+#define WSEQIOPS 42705ULL
+#define WRANDIOPS 378ULL
+
+#define RPAGE (RU(VTIME_PER_SEC, RU(RBPS, IOC_PAGE_SIZE)))
+#define RSEQIO (RU(VTIME_PER_SEC, RSEQIOPS) - RPAGE)
+#define RRANDIO (RU(VTIME_PER_SEC, RRANDIOPS) - RPAGE)
+#define WPAGE (RU(VTIME_PER_SEC, RU(WBPS, IOC_PAGE_SIZE)))
+#define WSEQIO (RU(VTIME_PER_SEC, WSEQIOPS) - WPAGE)
+#define WRANDIO (RU(VTIME_PER_SEC, WRANDIOPS) - WPAGE)
+
+#define NSLOTS 4
+
+struct streams {
+ __u64 expected[NSLOTS]; /* next expected sector, per stream */
+ __u64 stamp[NSLOTS]; /* LRU stamp, 0 = empty */
+};
+
+/*
+ * per-cgroup stream table: keyed by the cgroup, freed with it
+ */
+struct {
+ __uint(type, BPF_MAP_TYPE_CGRP_STORAGE);
+ __uint(map_flags, BPF_F_NO_PREALLOC);
+ __type(key, int);
+ __type(value, struct streams);
+} stream_tab SEC(".maps");
+
+SEC("struct_ops")
+u64 BPF_PROG(iocost_ms_calc_cost, 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) {
+ base = WSEQIO; coef_page = WPAGE; randio = WRANDIO;
+ } else {
+ /*
+ * a fully owning model must price every op; unknown
+ * ops are priced as per-page writes
+ */
+ base = 0; coef_page = WPAGE; randio = 0;
+ }
+ advance = nbytes >> 9; /* sectors, truncated like the builtin */
+
+ /* only bios the builtin prices participate in stream tracking */
+ if (!(((opf & IOCOST_REQ_OP_MASK) == REQ_OP_READ ||
+ (opf & IOCOST_REQ_OP_MASK) == REQ_OP_WRITE) && nbytes)) {
+ pages = nbytes >> IOC_PAGE_SHIFT;
+ if (!pages)
+ pages = 1;
+ return base + pages * coef_page;
+ }
+
+ s = bpf_cgrp_storage_get(&stream_tab, blkcg->css.cgroup, NULL,
+ BPF_LOCAL_STORAGE_GET_F_CREATE);
+ if (!s) {
+ /* no storage: price per page, truncating like the builtin */
+ pages = nbytes >> IOC_PAGE_SHIFT;
+ if (!pages)
+ pages = 1;
+ return base + pages * coef_page;
+ }
+
+ /*
+ * Slot access is lockless, mirroring the builtin single-cursor
+ * update in ioc_rqos_throttle(): concurrent CPUs submitting for
+ * the same cgroup can race on slot updates; mispricing is
+ * bounded and acceptable for an example model.
+ */
+ now = bpf_ktime_get_ns();
+ for (i = 0; i < NSLOTS; i++) {
+ if (s->expected[i] == sector && s->stamp[i]) {
+ found = i;
+ break;
+ }
+ }
+ if (found != 0xFFFFFFFF) {
+ /* sequential: keep the seq base from the op branch */
+ s->expected[found] = sector + advance;
+ s->stamp[found] = now;
+ } else {
+ base = randio;
+ for (i = 1; i < NSLOTS; i++) {
+ if (s->stamp[i] < s->stamp[victim])
+ victim = i;
+ }
+ s->expected[victim] = sector + advance;
+ s->stamp[victim] = now;
+ }
+
+ /* builtin truncates: max(sectors >> IOC_SECT_TO_PAGE_SHIFT, 1) */
+ pages = nbytes >> IOC_PAGE_SHIFT;
+ if (!pages)
+ pages = 1;
+ if (model_flags & IOCOST_COST_F_MERGE) {
+ /*
+ * merged bios skip the base cost but still advance
+ * the stream position above, so a merge at the
+ * expected sector does not make the following new IO
+ * look random
+ */
+ base = 0;
+ }
+
+ return base + pages * coef_page;
+}
+
+SEC(".struct_ops")
+struct iocost_model_ops iocost_ms = {
+ .read_vtime_per_page = RPAGE,
+ .write_vtime_per_page = WPAGE,
+ .calc_cost = (void *)iocost_ms_calc_cost,
+};
+
+char LICENSE[] SEC("license") = "GPL";
|
| 19/3 | 2026/10/01 06:11 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 21673 output: 32 thoughts: 1663 Thoughts: **KMSAN Evaluation: blk-iocost-bpf Patch Series** Okay, let's break this down. My goal is to determine if this patch series warrants a dedicated KMSAN fuzzing session, beyond the standard KASAN fuzzing we already run. We're looking for uninitialized memory risks. First, I see the patch introduces `CONFIG_BLK_CGROUP_IOCOST_BPF`. It's enabling BPF integration for I/O cost modeling, which immediately flags my attention. BPF often involves passing data between kernel and userspace, so there's a higher potential for initialization issues. `blk_get_queue_rcu` looks safe; it's a simple refcount check. The core of the patch seems to be in `block/blk-iocost-bpf.c` and modifications to `block/blk-iocost.c`. Specifically, the introduction of a `struct iocost_model_ops` and its interactions with BPF is where I need to focus. In `block/blk-iocost-bpf.c`, the `bpf_iocost_init_member` function is crucial. It's responsible for copying data from userspace to the kernel structure, `struct iocost_model_ops`. The description states that kvalue is zeroed at map allocation, so this means that `kdata` is zeroed. `uops` is user data, and the code looks like it checks for NULL values, preventing overwrites. I'll need to double-check that this is true in all cases. However, the bigger concern is what happens *after* `bpf_iocost_init_member`. The `bpf_iocost_reg` function then calls `ioc_bpf_attach(ops)`. What is `ops` here and how are values used? I need to understand if `ops` (a pointer to `struct iocost_model_ops`) or any members in `iocost_model_ops` are passed to userspace after the init. Also I need to check how they are used, to be certain that the code is safe. Next, I need to look closely at how the `struct ioc_now now` variable is initialized inside `ioc_timer_fn` which is called in `block/blk-iocost.c`. Is `now` initialized, or are there any potential read-before-write issues? I have to confirm. This is potentially a weak point in the code. I need to know how it is used. I also need to check all the other places where `struct iocost_model_ops` fields are read or written, especially if those fields are used in BPF programs. Are we potentially exposing uninitialized memory or allowing info leaks through BPF? The introduction of the `trace_iocost_ioc_tick` tracepoint is another area to scrutinize. Tracepoints frequently expose kernel data, and if `now` or related structures aren't fully initialized before being traced, we *could* have an info-leak. Finally, those selftests in `tools/testing/selftests/bpf` might be useful. Let's see if they cover the BPF side of things completely, including the potential for uninitialized memory accesses or info-leaks. If I find any of these concerns – uninitialized `now` variable, potential info-leaks through the BPF `struct_ops`, or uninitialized memory sent to userspace – then I'll have a strong case for setting `NeedsKMSAN=true`. If everything seems properly zeroed or initialized, then the existing KASAN fuzzing should be sufficient. I will need to check how the BPF struct_ops allocates and handles members, and inspect any potentially problematic function calls. |
| 20/3 | 2026/10/01 06:11 | tool | grepper |
0mArgs:{
"Expression": "ioc_now\\(",
"PathPrefix": "block/blk-iocost.c"
}Results: {
"Output": "block/blk-iocost.c=1025=static void ioc_adjust_base_vrate(struct ioc *ioc, u32 rq_wait_pct,\n--\nblock/blk-iocost.c-1073-/* take a snapshot of the current [v]time and vrate */\nblock/blk-iocost.c:1074:static void ioc_now(struct ioc *ioc, struct ioc_now *now)\nblock/blk-iocost.c-1075-{\n--\nblock/blk-iocost.c=1300=static bool iocg_activate(struct ioc_gq *iocg, struct ioc_now *now)\n--\nblock/blk-iocost.c-1311-\tif (!list_empty(\u0026iocg-\u003eactive_list)) {\nblock/blk-iocost.c:1312:\t\tioc_now(ioc, now);\nblock/blk-iocost.c-1313-\t\tcur_period = atomic64_read(\u0026ioc-\u003ecur_period);\n--\nblock/blk-iocost.c-1324-\nblock/blk-iocost.c:1325:\tioc_now(ioc, now);\nblock/blk-iocost.c-1326-\n--\nblock/blk-iocost.c=1615=static enum hrtimer_restart iocg_waitq_timer_fn(struct hrtimer *timer)\n--\nblock/blk-iocost.c-1621-\nblock/blk-iocost.c:1622:\tioc_now(iocg-\u003eioc, \u0026now);\nblock/blk-iocost.c-1623-\n--\nblock/blk-iocost.c=2286=static void ioc_timer_fn(struct timer_list *timer)\n--\nblock/blk-iocost.c-2308-\tppm_wthr = MILLION - ioc-\u003eparams.qos[QOS_WPPM];\nblock/blk-iocost.c:2309:\tioc_now(ioc, \u0026now);\nblock/blk-iocost.c-2310-\n--\nblock/blk-iocost.c=2872=static void ioc_rqos_merge(struct rq_qos *rqos, struct request *rq,\n--\nblock/blk-iocost.c-2889-\nblock/blk-iocost.c:2890:\tioc_now(ioc, \u0026now);\nblock/blk-iocost.c-2891-\n--\nblock/blk-iocost.c=3132=static void ioc_pd_init(struct blkg_policy_data *pd)\n--\nblock/blk-iocost.c-3141-\nblock/blk-iocost.c:3142:\tioc_now(ioc, \u0026now);\nblock/blk-iocost.c-3143-\n--\nblock/blk-iocost.c=3191=static void ioc_pd_free(struct blkg_policy_data *pd)\n--\nblock/blk-iocost.c-3210-\nblock/blk-iocost.c:3211:\t\t\tioc_now(ioc, \u0026now);\nblock/blk-iocost.c-3212-\t\t\tpropagate_weights(iocg, 0, 0, false, \u0026now);\n--\nblock/blk-iocost.c=3280=static ssize_t ioc_weight_write(struct kernfs_open_file *of, char *buf,\n--\nblock/blk-iocost.c-3306-\t\t\t\tspin_lock(\u0026iocg-\u003eioc-\u003elock);\nblock/blk-iocost.c:3307:\t\t\t\tioc_now(iocg-\u003eioc, \u0026now);\nblock/blk-iocost.c-3308-\t\t\t\tweight_updated(iocg, \u0026now);\n--\nblock/blk-iocost.c-3341-\tiocg-\u003ecfg_weight = v * WEIGHT_ONE;\nblock/blk-iocost.c:3342:\tioc_now(iocg-\u003eioc, \u0026now);\nblock/blk-iocost.c-3343-\tweight_updated(iocg, \u0026now);\n"
} |
| 21/3 | 2026/10/01 06:11 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 25246 output: 37 thoughts: 45 Thoughts: Here's my analysis of the provided code snippet: **Diving into `ioc_timer_fn` - Time Check** Okay, so I'm looking at `ioc_timer_fn`. The first thing that jumps out is that at line 2309, right before the main loop, there's a call to `ioc_now(ioc, &now);`. Naturally, I need to understand what `ioc_now` is doing here. It's crucial, right at the start of the timer function, so it's setting up a baseline or initial timestamp, probably. I need to dig into the implementation of `ioc_now` to confirm my suspicion. Knowing what time it is before the main loop seems important for whatever this loop is trying to accomplish. Let's see what that function does! |
| 22/3 | 2026/10/01 06:11 | tool | read-file |
0mArgs:{
"File": "block/blk-iocost.c",
"FirstLine": 1073,
"LineCount": 20
}Results: {
"Contents": "1073:\t/* take a snapshot of the current [v]time and vrate */\n1074:\tstatic void ioc_now(struct ioc *ioc, struct ioc_now *now)\n1075:\t{\n1076:\t\tunsigned seq;\n1077:\t\tu64 vrate;\n1078:\t\n1079:\t\tnow-\u003enow_ns = blk_time_get_ns();\n1080:\t\tnow-\u003enow = ktime_to_us(now-\u003enow_ns);\n1081:\t\tvrate = atomic64_read(\u0026ioc-\u003evtime_rate);\n1082:\t\n1083:\t\t/*\n1084:\t\t * The current vtime is\n1085:\t\t *\n1086:\t\t * vtime at period start + (wallclock time since the start) * vrate\n1087:\t\t *\n1088:\t\t * As a consistent snapshot of `period_at_vtime` and `period_at` is\n1089:\t\t * needed, they're seqcount protected.\n1090:\t\t */\n1091:\t\tdo {\n1092:\t\t\tseq = read_seqcount_begin(\u0026ioc-\u003eperiod_seqcount);\n"
} |
| 23/3 | 2026/10/01 06:11 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 25827 output: 35 thoughts: 811 Thoughts: **Analyzing iocost Tracing and Cost Model Implementation** Okay, so `ioc_now` is fully initialized within `ioc_now`. That's good. And `trace_iocost_ioc_tick` just gets the pointer, and passes it to the trace event. I need to understand what `trace_iocost_ioc_tick` actually *does* with that. Looking at the code: `TP_fast_assign` assigns all the fields. It seems pretty straightforward: Device name, current period, period in microseconds, vtime base rate, busy level, number of active requests, usage percentage (calculated as a percentage of `usage_us_sum` over the period), and a running flag are all assigned in the trace event. No obvious issues there. Now, let's move on to `ioc_cost_model_prfill`. This uses `seq_printf` to write a formatted string to a `seq_file`. It locks `ioc->lock` which is good, retrieves the in-use model, and then prints the device name, control mode (user or auto), the model (bpf or linear), and various cost coefficients (in terms of bytes per second and IOPS for sequential and random read and write). The output seems clean and doesn't appear to introduce any uninitialized memory reads. Next, I'll review `ioc_cost_model_write`. This parses the input string from kernfs, checking for either "linear" or "bpf" cost models. It uses `match_strlcpy`, so potential buffer overflows are handled. It looks safe. No uninitialized memory reads in sight. Finally, `ioc_bpf_attach`. This reads the `ops->dev`, calls `blkdev_get_no_open` on the new device, and handles error returns. Looks safe. No uninitialized variables or structs that jump out at me. And now, `bpf_iocost_init_member`. This looks at the `iocost_model_ops` members: `bdev`, `q`, `dev`, `read_vtime_per_page`, and `write_vtime_per_page`. `kdata` is initialized/zeroed, thanks to the BPF struct_ops map init. Wait, I should double-check how these struct_ops maps are allocated and initialized in the BPF subsystem, just to be absolutely sure. |
| 24/3 | 2026/10/01 06:12 | tool | grepper |
0mArgs:{
"Expression": "bpf_struct_ops_map_alloc",
"PathPrefix": "kernel/bpf/"
}Results: {
"Output": "kernel/bpf/bpf_struct_ops.c=1035=static void bpf_struct_ops_map_free(struct bpf_map *map)\n--\nkernel/bpf/bpf_struct_ops.c-1055-\nkernel/bpf/bpf_struct_ops.c:1056:static int bpf_struct_ops_map_alloc_check(union bpf_attr *attr)\nkernel/bpf/bpf_struct_ops.c-1057-{\n--\nkernel/bpf/bpf_struct_ops.c=1065=static u32 count_func_ptrs(const struct btf *btf, const struct btf_type *t)\n--\nkernel/bpf/bpf_struct_ops.c-1077-\nkernel/bpf/bpf_struct_ops.c:1078:static struct bpf_map *bpf_struct_ops_map_alloc(union bpf_attr *attr)\nkernel/bpf/bpf_struct_ops.c-1079-{\n--\nkernel/bpf/bpf_struct_ops.c=1195=const struct bpf_map_ops bpf_struct_ops_map_ops = {\nkernel/bpf/bpf_struct_ops.c:1196:\t.map_alloc_check = bpf_struct_ops_map_alloc_check,\nkernel/bpf/bpf_struct_ops.c:1197:\t.map_alloc = bpf_struct_ops_map_alloc,\nkernel/bpf/bpf_struct_ops.c-1198-\t.map_free = bpf_struct_ops_map_free,\n"
} |
| 25/3 | 2026/10/01 06:12 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 27619 output: 42 thoughts: 32 Thoughts: Okay, let's dive into this. Here's my thought process on dissecting `bpf_struct_ops_map_alloc` in `kernel/bpf/bpf_struct_ops.c`. **Diving into `bpf_struct_ops_map_alloc`** Right, so I need to understand how these structure operations are allocated in the BPF world. I'm going to head straight for `bpf_struct_ops_map_alloc` within `kernel/bpf/bpf_struct_ops.c`. This function is likely the starting point for dealing with BPF-related struct operations. I want to see how these "struct ops" are defined, allocated, and hopefully, how they're associated with the BPF maps themselves. My experience tells me that allocation in BPF often means memory is set aside to hold these operations. I want to see the details of that memory, how it is tracked, and how it is later freed. Understanding the allocation process is key to preventing memory leaks and understanding the overhead this functionality incurs. I expect to see data structures defining the supported operations (load, store, etc.) that can be performed on the target data. This initial allocation is critical for the overall BPF operation lifecycle, and I need to comprehend its implications. I anticipate looking for things like mutexes or other synchronization primitives if this allocation is accessed from multiple contexts, which is common in a kernel environment. Let's see what the code reveals. |
| 26/3 | 2026/10/01 06:12 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/bpf_struct_ops.c",
"FirstLine": 1078,
"LineCount": 40
}Results: {
"Contents": "1078:\tstatic struct bpf_map *bpf_struct_ops_map_alloc(union bpf_attr *attr)\n1079:\t{\n1080:\t\tconst struct bpf_struct_ops_desc *st_ops_desc;\n1081:\t\tsize_t st_map_size;\n1082:\t\tstruct bpf_struct_ops_map *st_map;\n1083:\t\tconst struct btf_type *t, *vt;\n1084:\t\tstruct module *mod = NULL;\n1085:\t\tstruct bpf_map *map;\n1086:\t\tstruct btf *btf;\n1087:\t\tint ret;\n1088:\t\n1089:\t\tif (attr-\u003emap_flags \u0026 BPF_F_VTYPE_BTF_OBJ_FD) {\n1090:\t\t\t/* The map holds btf for its whole life time. */\n1091:\t\t\tbtf = btf_get_by_fd(attr-\u003evalue_type_btf_obj_fd);\n1092:\t\t\tif (IS_ERR(btf))\n1093:\t\t\t\treturn ERR_CAST(btf);\n1094:\t\t\tif (!btf_is_module(btf)) {\n1095:\t\t\t\tbtf_put(btf);\n1096:\t\t\t\treturn ERR_PTR(-EINVAL);\n1097:\t\t\t}\n1098:\t\n1099:\t\t\tmod = btf_try_get_module(btf);\n1100:\t\t\t/* mod holds a refcnt to btf. We don't need an extra refcnt\n1101:\t\t\t * here.\n1102:\t\t\t */\n1103:\t\t\tbtf_put(btf);\n1104:\t\t\tif (!mod)\n1105:\t\t\t\treturn ERR_PTR(-EINVAL);\n1106:\t\t} else {\n1107:\t\t\tbtf = bpf_get_btf_vmlinux();\n1108:\t\t\tif (IS_ERR(btf))\n1109:\t\t\t\treturn ERR_CAST(btf);\n1110:\t\t\tif (!btf)\n1111:\t\t\t\treturn ERR_PTR(-ENOTSUPP);\n1112:\t\t}\n1113:\t\n1114:\t\tst_ops_desc = bpf_struct_ops_find_value(btf, attr-\u003ebtf_vmlinux_value_type_id);\n1115:\t\tif (!st_ops_desc) {\n1116:\t\t\tret = -ENOTSUPP;\n1117:\t\t\tgoto errout;\n"
} |
| 27/3 | 2026/10/01 06:12 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 28676 output: 42 thoughts: 19 Thoughts: Okay, let's dive into the rest of `bpf_struct_ops_map_alloc`. I need to get a clear picture of what's happening internally, from the allocation to the final setup. Let me break it down step-by-step to really grasp the nuances of this function. I'll need to remember the key data structures and understand how they interact in the context of creating and managing BPF maps. I'm going to look for any potential areas for optimization or areas that might lead to unexpected behavior under heavy load. I want to see where any potential bottlenecks lie. I need to keep the memory footprint of this functionality in mind, so I'll be looking for any signs of inefficient allocation or data structure choices. |
| 28/3 | 2026/10/01 06:12 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/bpf_struct_ops.c",
"FirstLine": 1118,
"LineCount": 40
}Results: {
"Contents": "1118:\t\t}\n1119:\t\n1120:\t\tif (st_ops_desc-\u003est_ops-\u003ecgroup_atype \u0026\u0026 !(attr-\u003emap_flags \u0026 BPF_F_LINK)) {\n1121:\t\t\tret = -EOPNOTSUPP;\n1122:\t\t\tgoto errout;\n1123:\t\t}\n1124:\t\n1125:\t\tvt = st_ops_desc-\u003evalue_type;\n1126:\t\tif (attr-\u003evalue_size != vt-\u003esize) {\n1127:\t\t\tret = -EINVAL;\n1128:\t\t\tgoto errout;\n1129:\t\t}\n1130:\t\n1131:\t\tt = st_ops_desc-\u003etype;\n1132:\t\n1133:\t\tst_map_size = sizeof(*st_map) +\n1134:\t\t\t/* kvalue stores the\n1135:\t\t\t * struct bpf_struct_ops_tcp_congestions_ops\n1136:\t\t\t */\n1137:\t\t\t(vt-\u003esize - sizeof(struct bpf_struct_ops_value));\n1138:\t\n1139:\t\tst_map = bpf_map_area_alloc(st_map_size, NUMA_NO_NODE);\n1140:\t\tif (!st_map) {\n1141:\t\t\tret = -ENOMEM;\n1142:\t\t\tgoto errout;\n1143:\t\t}\n1144:\t\n1145:\t\tst_map-\u003est_ops_desc = st_ops_desc;\n1146:\t\tmap = \u0026st_map-\u003emap;\n1147:\t\n1148:\t\tst_map-\u003euvalue = bpf_map_area_alloc(vt-\u003esize, NUMA_NO_NODE);\n1149:\t\tst_map-\u003efuncs_cnt = count_func_ptrs(btf, t);\n1150:\t\tst_map-\u003elinks =\n1151:\t\t\tbpf_map_area_alloc(st_map-\u003efuncs_cnt * sizeof(struct bpf_link *),\n1152:\t\t\t\t\t NUMA_NO_NODE);\n1153:\t\n1154:\t\tst_map-\u003eksyms =\n1155:\t\t\tbpf_map_area_alloc(st_map-\u003efuncs_cnt * sizeof(struct bpf_ksym *),\n1156:\t\t\t\t\t NUMA_NO_NODE);\n1157:\t\tif (!st_map-\u003euvalue || !st_map-\u003elinks || !st_map-\u003eksyms) {\n"
} |
| 29/3 | 2026/10/01 06:12 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 29555 output: 33 thoughts: 41 Thoughts: Okay, here's my interpretation of that thought process, from an expert's perspective: **Diving into BPF Map Area Allocation** Right, so I'm taking a look at `bpf_map_area_alloc`. The immediate concern is the memory allocation strategy this function employs. My internal radar flags `kzalloc` or `vmalloc` being used with `GFP_USER | __GFP_ZERO`. That's a common, but potentially sensitive, combination. `kzalloc` is generally fine, especially for smaller allocations within a kernel module context, but `vmalloc` with those flags, in particular, raises a few questions in my mind, concerning fragmentation and the potential for larger continuous virtual address space mappings in the context of user-space BPF programs. I need to understand the implications of this choice for performance, memory footprint, and, crucially, security. I'm going to have to dig deeper into the code to figure out *why* these allocations are necessary and whether it's the right approach for different BPF map types and sizes. I need to assess the overall strategy, and think about alternate allocation possibilities. |
| 30/3 | 2026/10/01 06:12 | tool | grepper |
0mArgs:{
"Expression": "bpf_map_area_alloc",
"PathPrefix": "kernel/bpf/"
}Results: {
"Output": "kernel/bpf/arena.c=266=static struct bpf_map *arena_map_alloc(union bpf_attr *attr)\n--\nkernel/bpf/arena.c-299-\nkernel/bpf/arena.c:300:\tarena = bpf_map_area_alloc(sizeof(*arena), numa_node);\nkernel/bpf/arena.c-301-\tif (!arena)\n--\nkernel/bpf/arraymap.c=84=static struct bpf_map *array_map_alloc(union bpf_attr *attr)\n--\nkernel/bpf/arraymap.c-141-\t} else {\nkernel/bpf/arraymap.c:142:\t\tarray = bpf_map_area_alloc(array_size, numa_node);\nkernel/bpf/arraymap.c-143-\t}\n--\nkernel/bpf/bloom_filter.c=99=static struct bpf_map *bloom_map_alloc(union bpf_attr *attr)\n--\nkernel/bpf/bloom_filter.c-144-\tbitset_bytes = BITS_TO_LONGS((u64)bitset_mask + 1) * sizeof(unsigned long);\nkernel/bpf/bloom_filter.c:145:\tbloom = bpf_map_area_alloc(sizeof(*bloom) + bitset_bytes, numa_node);\nkernel/bpf/bloom_filter.c-146-\n--\nkernel/bpf/bpf_insn_array.c=44=static struct bpf_map *insn_array_alloc(union bpf_attr *attr)\n--\nkernel/bpf/bpf_insn_array.c-48-\nkernel/bpf/bpf_insn_array.c:49:\tinsn_array = bpf_map_area_alloc(size, NUMA_NO_NODE);\nkernel/bpf/bpf_insn_array.c-50-\tif (!insn_array)\n--\nkernel/bpf/bpf_local_storage.c=776=bpf_local_storage_map_alloc(union bpf_attr *attr,\n--\nkernel/bpf/bpf_local_storage.c-783-\nkernel/bpf/bpf_local_storage.c:784:\tsmap = bpf_map_area_alloc(sizeof(*smap), NUMA_NO_NODE);\nkernel/bpf/bpf_local_storage.c-785-\tif (!smap)\n--\nkernel/bpf/bpf_struct_ops.c=1078=static struct bpf_map *bpf_struct_ops_map_alloc(union bpf_attr *attr)\n--\nkernel/bpf/bpf_struct_ops.c-1138-\nkernel/bpf/bpf_struct_ops.c:1139:\tst_map = bpf_map_area_alloc(st_map_size, NUMA_NO_NODE);\nkernel/bpf/bpf_struct_ops.c-1140-\tif (!st_map) {\n--\nkernel/bpf/bpf_struct_ops.c-1147-\nkernel/bpf/bpf_struct_ops.c:1148:\tst_map-\u003euvalue = bpf_map_area_alloc(vt-\u003esize, NUMA_NO_NODE);\nkernel/bpf/bpf_struct_ops.c-1149-\tst_map-\u003efuncs_cnt = count_func_ptrs(btf, t);\nkernel/bpf/bpf_struct_ops.c-1150-\tst_map-\u003elinks =\nkernel/bpf/bpf_struct_ops.c:1151:\t\tbpf_map_area_alloc(st_map-\u003efuncs_cnt * sizeof(struct bpf_link *),\nkernel/bpf/bpf_struct_ops.c-1152-\t\t\t\t NUMA_NO_NODE);\n--\nkernel/bpf/bpf_struct_ops.c-1154-\tst_map-\u003eksyms =\nkernel/bpf/bpf_struct_ops.c:1155:\t\tbpf_map_area_alloc(st_map-\u003efuncs_cnt * sizeof(struct bpf_ksym *),\nkernel/bpf/bpf_struct_ops.c-1156-\t\t\t\t NUMA_NO_NODE);\n--\nkernel/bpf/cpumap.c=85=static struct bpf_map *cpu_map_alloc(union bpf_attr *attr)\n--\nkernel/bpf/cpumap.c-100-\nkernel/bpf/cpumap.c:101:\tcmap = bpf_map_area_alloc(sizeof(*cmap), NUMA_NO_NODE);\nkernel/bpf/cpumap.c-102-\tif (!cmap)\n--\nkernel/bpf/cpumap.c-107-\t/* Alloc array for possible remote \"destination\" CPUs */\nkernel/bpf/cpumap.c:108:\tcmap-\u003ecpu_map = bpf_map_area_alloc(cmap-\u003emap.max_entries *\nkernel/bpf/cpumap.c-109-\t\t\t\t\t sizeof(struct bpf_cpu_map_entry *),\n--\nkernel/bpf/devmap.c=91=static struct hlist_head *dev_map_create_hash(unsigned int entries,\n--\nkernel/bpf/devmap.c-96-\nkernel/bpf/devmap.c:97:\thash = bpf_map_area_alloc((u64) entries * sizeof(*hash), numa_node);\nkernel/bpf/devmap.c-98-\tif (hash != NULL)\n--\nkernel/bpf/devmap.c=136=static int dev_map_init_map(struct bpf_dtab *dtab, union bpf_attr *attr)\n--\nkernel/bpf/devmap.c-153-\t} else {\nkernel/bpf/devmap.c:154:\t\tdtab-\u003enetdev_map = bpf_map_area_alloc((u64) dtab-\u003emap.max_entries *\nkernel/bpf/devmap.c-155-\t\t\t\t\t\t sizeof(struct bpf_dtab_netdev *),\n--\nkernel/bpf/devmap.c=164=static struct bpf_map *dev_map_alloc(union bpf_attr *attr)\n--\nkernel/bpf/devmap.c-168-\nkernel/bpf/devmap.c:169:\tdtab = bpf_map_area_alloc(sizeof(*dtab), NUMA_NO_NODE);\nkernel/bpf/devmap.c-170-\tif (!dtab)\n--\nkernel/bpf/hashtab.c=320=static int prealloc_init(struct bpf_htab *htab)\n--\nkernel/bpf/hashtab.c-327-\nkernel/bpf/hashtab.c:328:\thtab-\u003eelems = bpf_map_area_alloc((u64)htab-\u003eelem_size * num_entries,\nkernel/bpf/hashtab.c-329-\t\t\t\t\t htab-\u003emap.numa_node);\n--\nkernel/bpf/hashtab.c=563=static struct bpf_map *htab_map_alloc(union bpf_attr *attr)\n--\nkernel/bpf/hashtab.c-576-\nkernel/bpf/hashtab.c:577:\thtab = bpf_map_area_alloc(sizeof(*htab), NUMA_NO_NODE);\nkernel/bpf/hashtab.c-578-\tif (!htab)\n--\nkernel/bpf/hashtab.c-619-\terr = -ENOMEM;\nkernel/bpf/hashtab.c:620:\thtab-\u003ebuckets = bpf_map_area_alloc(htab-\u003en_buckets *\nkernel/bpf/hashtab.c-621-\t\t\t\t\t sizeof(struct bucket),\n--\nkernel/bpf/hashtab.c=2865=static struct bpf_map *rhtab_map_alloc(union bpf_attr *attr)\n--\nkernel/bpf/hashtab.c-2870-\nkernel/bpf/hashtab.c:2871:\trhtab = bpf_map_area_alloc(sizeof(*rhtab), NUMA_NO_NODE);\nkernel/bpf/hashtab.c-2872-\tif (!rhtab)\n--\nkernel/bpf/local_storage.c=297=static struct bpf_map *cgroup_storage_map_alloc(union bpf_attr *attr)\n--\nkernel/bpf/local_storage.c-327-\nkernel/bpf/local_storage.c:328:\tmap = bpf_map_area_alloc(sizeof(struct bpf_cgroup_storage_map), numa_node);\nkernel/bpf/local_storage.c-329-\tif (!map)\n--\nkernel/bpf/lpm_trie.c=571=static struct bpf_map *trie_alloc(union bpf_attr *attr)\n--\nkernel/bpf/lpm_trie.c-587-\nkernel/bpf/lpm_trie.c:588:\ttrie = bpf_map_area_alloc(sizeof(*trie), NUMA_NO_NODE);\nkernel/bpf/lpm_trie.c-589-\tif (!trie)\n--\nkernel/bpf/offload.c=503=struct bpf_map *bpf_map_offload_map_alloc(union bpf_attr *attr)\n--\nkernel/bpf/offload.c-515-\nkernel/bpf/offload.c:516:\toffmap = bpf_map_area_alloc(sizeof(*offmap), NUMA_NO_NODE);\nkernel/bpf/offload.c-517-\tif (!offmap)\n--\nkernel/bpf/queue_stack_maps.c=68=static struct bpf_map *queue_stack_map_alloc(union bpf_attr *attr)\n--\nkernel/bpf/queue_stack_maps.c-76-\nkernel/bpf/queue_stack_maps.c:77:\tqs = bpf_map_area_alloc(queue_size, numa_node);\nkernel/bpf/queue_stack_maps.c-78-\tif (!qs)\n--\nkernel/bpf/reuseport_array.c=149=static struct bpf_map *reuseport_array_alloc(union bpf_attr *attr)\n--\nkernel/bpf/reuseport_array.c-154-\t/* allocate all map elements and zero-initialize them */\nkernel/bpf/reuseport_array.c:155:\tarray = bpf_map_area_alloc(struct_size(array, ptrs, attr-\u003emax_entries), numa_node);\nkernel/bpf/reuseport_array.c-156-\tif (!array)\n--\nkernel/bpf/ringbuf.c=93=static struct bpf_ringbuf *bpf_ringbuf_area_alloc(size_t data_sz, int numa_node)\n--\nkernel/bpf/ringbuf.c-122-\tarray_size = (nr_meta_pages + 2 * nr_data_pages) * sizeof(*pages);\nkernel/bpf/ringbuf.c:123:\tpages = bpf_map_area_alloc(array_size, numa_node);\nkernel/bpf/ringbuf.c-124-\tif (!pages)\n--\nkernel/bpf/ringbuf.c=194=static struct bpf_map *ringbuf_map_alloc(union bpf_attr *attr)\n--\nkernel/bpf/ringbuf.c-212-\nkernel/bpf/ringbuf.c:213:\trb_map = bpf_map_area_alloc(sizeof(*rb_map), NUMA_NO_NODE);\nkernel/bpf/ringbuf.c-214-\tif (!rb_map)\n--\nkernel/bpf/stackmap.c=68=static int prealloc_elems_and_freelist(struct bpf_stack_map *smap)\n--\nkernel/bpf/stackmap.c-73-\nkernel/bpf/stackmap.c:74:\tsmap-\u003eelems = bpf_map_area_alloc(elem_size * smap-\u003emap.max_entries,\nkernel/bpf/stackmap.c-75-\t\t\t\t\t smap-\u003emap.numa_node);\n--\nkernel/bpf/stackmap.c=93=static struct bpf_map *stack_map_alloc(union bpf_attr *attr)\n--\nkernel/bpf/stackmap.c-125-\tcost = n_buckets * sizeof(struct stack_map_bucket *) + sizeof(*smap);\nkernel/bpf/stackmap.c:126:\tsmap = bpf_map_area_alloc(cost, bpf_map_attr_numa_node(attr));\nkernel/bpf/stackmap.c-127-\tif (!smap)\n--\nkernel/bpf/syscall.c=308=static int bpf_map_copy_value(struct bpf_map *map, void *key, void *value,\n--\nkernel/bpf/syscall.c-371- */\nkernel/bpf/syscall.c:372:static void *__bpf_map_area_alloc(u64 size, int numa_node, bool mmapable)\nkernel/bpf/syscall.c-373-{\n--\nkernel/bpf/syscall.c-408-\nkernel/bpf/syscall.c:409:void *bpf_map_area_alloc(u64 size, int numa_node)\nkernel/bpf/syscall.c-410-{\nkernel/bpf/syscall.c:411:\treturn __bpf_map_area_alloc(size, numa_node, false);\nkernel/bpf/syscall.c-412-}\n--\nkernel/bpf/syscall.c=414=void *bpf_map_area_mmapable_alloc(u64 size, int numa_node)\nkernel/bpf/syscall.c-415-{\nkernel/bpf/syscall.c:416:\treturn __bpf_map_area_alloc(size, numa_node, true);\nkernel/bpf/syscall.c-417-}\n"
} |
| 31/3 | 2026/10/01 06:12 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 33493 output: 36 thoughts: 984 Thoughts: **Analyzing Potential Uninitialized Variable Issues in the `iocost` BPF Implementation** Alright, let's break down this `iocost` BPF code with an eye towards uninitialized variables and potential data leaks. I know that `__bpf_map_area_alloc` uses `kzalloc_node` or `bpf_map_alloc_pages` with `__GFP_ZERO`, which should zero out the entire `struct_ops` map. That's a good starting point, but we need to verify there are no other places where uninitialized data is read or copied in this patch. My focus is the `iocost_model_ops` structure. I'll go through the functions and look at: 1. `bpf_iocost_model_init`: This function looks for a "iocost\_model\_ops" struct in the BTF data. That is straightforward. 2. `bpf_iocost_is_valid_access`: Checks, likely involves some context. 3. `bpf_iocost_get_func_proto`: Uses a `bpf_base_func_proto`. 4. `bpf_iocost_check_member`: This uses `prog->sleepable`. 5. `bpf_iocost_init_member`: This is the most interesting part. I need to be careful here as it initializes members of the `iocost_model_ops` struct. Specific struct members `bdev`, `q`, `dev`, `read_vtime_per_page`, `write_vtime_per_page` are checked, if they are already initialized (non-NULL). Then, the members are initialized, from some `uops` data. 6. `bpf_iocost_validate`: Here, it checks that the `calc_cost` member is not NULL. That makes sense. 7. `bpf_iocost_reg`: Just attaches the `ops`. 8. `bpf_iocost_unreg`: I'll need to check the refcounting, mutex locking, and resource release (like `blk_put_queue`, `blkdev_put_no_open`) for any potential issues. 9. `bpf_iocost_calc_cost_stub`, `bpf_iocost_iocg_init_stub`, `bpf_iocost_iocg_free_stub`: These are stub functions, so not an immediate concern, but I might want to sanity check them in the broader context. 10. `calc_vtime_cost` and `calc_size_vtime_cost`: Here we have a key check. `calc_vtime_cost` is a function that might call some member `model->calc_cost`. If the model is not set up correctly, or is NULL, it calls `calc_vtime_cost_builtin`. I need to ensure that the fallback always correctly initializes the cost variable and doesn't rely on potentially uninitialized data. The critical part is that `calc_vtime_cost_builtin` is called when there is no `model`. I will carefully examine `calc_vtime_cost_builtin` in `block/blk-iocost.c` to be sure that `cost` is always initialized by this function, regardless of any prior state. |
| 32/3 | 2026/10/01 06:12 | tool | grepper |
0mArgs:{
"Expression": "calc_vtime_cost_builtin",
"PathPrefix": "block/blk-iocost.c"
}Results: {
"Output": "block/blk-iocost.c=2530=static u64 adjust_inuse_and_calc_cost(struct ioc_gq *iocg, u64 vtime,\n--\nblock/blk-iocost.c-2590-\nblock/blk-iocost.c:2591:static void calc_vtime_cost_builtin(struct bio *bio, struct ioc_gq *iocg,\nblock/blk-iocost.c-2592-\t\t\t\t bool is_merge, u64 *costp)\n--\nblock/blk-iocost.c=2636=static u64 calc_vtime_cost(struct bio *bio, struct ioc_gq *iocg, bool is_merge)\n--\nblock/blk-iocost.c-2650-\nblock/blk-iocost.c:2651:\tcalc_vtime_cost_builtin(bio, iocg, is_merge, \u0026cost);\nblock/blk-iocost.c-2652-\treturn cost;\n"
} |
| 33/3 | 2026/10/01 06:12 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 35501 output: 37 thoughts: 26 Thoughts: Okay, here's my take on those lines in `block/blk-iocost.c`, summarized from a first-person perspective, assuming I'm already pretty familiar with the code and its underlying principles: **Diving into blk-iocost.c: Lines 2590-2640** Alright, let's zero in on lines 2590 to 2640 in `block/blk-iocost.c`. Based on context, I'm guessing this section is probably handling a critical function related to I/O cost accounting or maybe the core calculation of some I/O metric. I expect to see the meat of how the subsystem is tracking resource usage or making some key decisions about prioritization. It's likely involved in either a scheduling decision, resource allocation, or a cost function computation. Perhaps there's an I/O accounting update or initialization going on here. I'm keen to see if they've implemented any recent research or if it's following a more established method. I'm looking for any signs of performance bottlenecks or potential areas for optimization. I need to understand how the system's making decisions about the relative "cost" of different I/O operations, especially if there's any sophisticated modeling involved. I'm ready to dig into the details and find where the actual work is being done. I’ll make sure to note any locks or synchronization primitives used, to understand the concurrency implications of this section. |
| 34/3 | 2026/10/01 06:12 | tool | read-file |
0mArgs:{
"File": "block/blk-iocost.c",
"FirstLine": 2590,
"LineCount": 45
}Results: {
"Contents": "2590:\t\n2591:\tstatic void calc_vtime_cost_builtin(struct bio *bio, struct ioc_gq *iocg,\n2592:\t\t\t\t\t bool is_merge, u64 *costp)\n2593:\t{\n2594:\t\tstruct ioc *ioc = iocg-\u003eioc;\n2595:\t\tu64 coef_seqio, coef_randio, coef_page;\n2596:\t\tu64 pages = max_t(u64, bio_sectors(bio) \u003e\u003e IOC_SECT_TO_PAGE_SHIFT, 1);\n2597:\t\tu64 seek_pages = 0;\n2598:\t\tu64 cost = 0;\n2599:\t\n2600:\t\t/* Can't calculate cost for empty bio */\n2601:\t\tif (!bio-\u003ebi_iter.bi_size)\n2602:\t\t\tgoto out;\n2603:\t\n2604:\t\tswitch (bio_op(bio)) {\n2605:\t\tcase REQ_OP_READ:\n2606:\t\t\tcoef_seqio\t= ioc-\u003eparams.lcoefs[LCOEF_RSEQIO];\n2607:\t\t\tcoef_randio\t= ioc-\u003eparams.lcoefs[LCOEF_RRANDIO];\n2608:\t\t\tcoef_page\t= ioc-\u003eparams.lcoefs[LCOEF_RPAGE];\n2609:\t\t\tbreak;\n2610:\t\tcase REQ_OP_WRITE:\n2611:\t\t\tcoef_seqio\t= ioc-\u003eparams.lcoefs[LCOEF_WSEQIO];\n2612:\t\t\tcoef_randio\t= ioc-\u003eparams.lcoefs[LCOEF_WRANDIO];\n2613:\t\t\tcoef_page\t= ioc-\u003eparams.lcoefs[LCOEF_WPAGE];\n2614:\t\t\tbreak;\n2615:\t\tdefault:\n2616:\t\t\tgoto out;\n2617:\t\t}\n2618:\t\n2619:\t\tif (iocg-\u003ecursor) {\n2620:\t\t\tseek_pages = abs(bio-\u003ebi_iter.bi_sector - iocg-\u003ecursor);\n2621:\t\t\tseek_pages \u003e\u003e= IOC_SECT_TO_PAGE_SHIFT;\n2622:\t\t}\n2623:\t\n2624:\t\tif (!is_merge) {\n2625:\t\t\tif (seek_pages \u003e LCOEF_RANDIO_PAGES) {\n2626:\t\t\t\tcost += coef_randio;\n2627:\t\t\t} else {\n2628:\t\t\t\tcost += coef_seqio;\n2629:\t\t\t}\n2630:\t\t}\n2631:\t\tcost += pages * coef_page;\n2632:\tout:\n2633:\t\t*costp = cost;\n2634:\t}\n"
} |
| 35/3 | 2026/10/01 06:12 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 36625 output: 37 thoughts: 44 Thoughts: Okay, let's break this down. **Analyzing Built-in Cost Calculation** Right, so `calc_vtime_cost_builtin` just hands off the calculated cost directly to the `*costp` pointer. No conditional checks, no nothing. Interesting... I'm assuming that means it's pretty straightforward, probably a simple calculation. Now, I need to make sure I understand the full picture, and so I should check the other built-in. Let's see what `calc_size_vtime_cost_builtin` is doing, to be sure I haven't missed a relevant nuance. I need to be sure the core logic is consistent. |
| 36/3 | 2026/10/01 06:12 | tool | read-file |
0mArgs:{
"File": "block/blk-iocost.c",
"FirstLine": 2655,
"LineCount": 45
}Results: {
"Contents": "2655:\tstatic void calc_size_vtime_cost_builtin(struct request *rq, struct ioc *ioc,\n2656:\t\t\t\t\t\t u64 *costp)\n2657:\t{\n2658:\t\tunsigned int pages = blk_rq_stats_sectors(rq) \u003e\u003e IOC_SECT_TO_PAGE_SHIFT;\n2659:\t\n2660:\t\tswitch (req_op(rq)) {\n2661:\t\tcase REQ_OP_READ:\n2662:\t\t\t*costp = pages * ioc-\u003eparams.lcoefs[LCOEF_RPAGE];\n2663:\t\t\tbreak;\n2664:\t\tcase REQ_OP_WRITE:\n2665:\t\t\t*costp = pages * ioc-\u003eparams.lcoefs[LCOEF_WPAGE];\n2666:\t\t\tbreak;\n2667:\t\tdefault:\n2668:\t\t\t*costp = 0;\n2669:\t\t}\n2670:\t}\n2671:\t\n2672:\t/*\n2673:\t * Called from the request completion path, where no ioc-\u003elock is\n2674:\t * held; the model pointer is read under RCU, matching the bio-side\n2675:\t * calc_vtime_cost().\n2676:\t */\n2677:\tstatic u64 calc_size_vtime_cost(struct request *rq, struct ioc *ioc)\n2678:\t{\n2679:\t\tconst struct iocost_model_ops *model;\n2680:\t\tu64 cost;\n2681:\t\n2682:\t\trcu_read_lock();\n2683:\t\tmodel = ioc_model_in_use(ioc);\n2684:\t\tif (model \u0026\u0026 (req_op(rq) == REQ_OP_READ ||\n2685:\t\t\t req_op(rq) == REQ_OP_WRITE)) {\n2686:\t\t\tunsigned int pages =\n2687:\t\t\t\tblk_rq_stats_sectors(rq) \u003e\u003e IOC_SECT_TO_PAGE_SHIFT;\n2688:\t\t\tu64 coeff = req_op(rq) == REQ_OP_READ ?\n2689:\t\t\t\tmodel-\u003eread_vtime_per_page :\n2690:\t\t\t\tmodel-\u003ewrite_vtime_per_page;\n2691:\t\n2692:\t\t\tcost = pages * coeff;\n2693:\t\t\trcu_read_unlock();\n2694:\t\t\treturn cost;\n2695:\t\t}\n2696:\t\trcu_read_unlock();\n2697:\t\n2698:\t\tcalc_size_vtime_cost_builtin(rq, ioc, \u0026cost);\n2699:\t\treturn cost;\n"
} |
| 37/3 | 2026/10/01 06:12 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 37571 output: 35 thoughts: 841 Thoughts: **Analyzing Potential Uninitialized Memory Reads in iocost Model Operations** Okay, so I need to make sure there aren't any sneaky uninitialized reads happening, especially with the `iocost` model. I noticed that `calc_size_vtime_cost_builtin` unconditionally sets `*costp` in all switch cases, which is good. Now, let's dive into `ioc_bpf_attach` and `ioc_bpf_detach`. I need to confirm if anything gets allocated or copied to userspace. In `ioc_bpf_attach`, I see we have `struct block_device`, `struct request_queue`, `struct gendisk`, `struct ioc`, and some basic integer flags. The critical part is that `blkdev_get_no_open` grabs an existing `block_device`, and `q_to_ioc` either reuses an existing `ioc` or initializes it with `blk_iocost_init`. `ioc_bpf_walk_iocgs` then iterates through `q->blkg_list`. So far, all pointers, no uninitialized reads that I can see. `ioc_bpf_detach` clears `ioc->model` and `ioc->attached`, walks `q->blkg_list` again (but with a different flag), and sets `ops->q` to `NULL`. Seems clean. Now, let's get serious about copies to userspace. `ioc_cost_model_prfill` writes formatted text using `seq_printf` into a `seq_buf`, which is safe. The tracepoint `trace_iocost_ioc_tick` uses `TP_fast_assign` to set all fields explicitly. The BPF subsystem handles `struct_ops`, and the core manages read/write operations on struct_ops maps. The big question is: does `iocost_model_ops` have padding? Okay, let's check `struct iocost_model_ops`. It has a `dev_t dev`, then `u64 read_vtime_per_page`, and so on. Wait a second... what is `dev_t`? On Linux amd64, it's a `u32`! And `read_vtime_per_page` is a `u64`. So that means there is a 4-byte padding between `dev` and `read_vtime_per_page`! This is important! This could be a problem. The key question is: Is `struct iocost_model_ops` ever copied to user space? I need to figure out how BPF struct_ops works to determine if this padding can cause any leakage. I need to search the kernel code for `bpf_struct_ops_map_lookup_elem` or similar functions in `kernel/bpf/bpf_struct_ops.c` to see if user space can read a struct_ops map. |
| 38/3 | 2026/10/01 06:12 | tool | grepper |
0mArgs:{
"Expression": "bpf_struct_ops_map_lookup",
"PathPrefix": "kernel/bpf/"
}Results: {
"Output": "kernel/bpf/bpf_struct_ops.c=522=int bpf_struct_ops_map_sys_lookup_elem(struct bpf_map *map, void *key,\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=1195=const struct bpf_map_ops bpf_struct_ops_map_ops = {\n--\nkernel/bpf/bpf_struct_ops.c-1200-\t.map_get_next_key = bpf_struct_ops_map_get_next_key,\nkernel/bpf/bpf_struct_ops.c:1201:\t.map_lookup_elem = bpf_struct_ops_map_lookup_elem,\nkernel/bpf/bpf_struct_ops.c-1202-\t.map_delete_elem = bpf_struct_ops_map_delete_elem,\n"
} |
| 39/3 | 2026/10/01 06:12 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 39397 output: 41 thoughts: 36 Thoughts: Okay, let's dive into this. Here's my take on examining `bpf_struct_ops_map_sys_lookup_elem` within `kernel/bpf/bpf_struct_ops.c`. **Diving Deep into bpf_struct_ops_map_sys_lookup_elem** Alright, I'm going to focus my attention on this function, `bpf_struct_ops_map_sys_lookup_elem`. It's clearly a crucial piece of the puzzle within the BPF struct operations framework, specifically related to map operations from the system call interface. I'll need to dissect its purpose and how it interacts with the broader BPF ecosystem. My initial thoughts are that it must provide a bridge between user-space BPF programs and the kernel's map data structures, allowing those programs to look up elements within a specific map using a system call. I expect it handles validation of the input key, ensures proper access rights, and then delegates the actual lookup to the underlying map implementation. I'll be looking to understand the intricacies of how this function interacts with the `bpf_map_ops` structure, how it handles potential errors (e.g., key not found, invalid key), and the overall performance implications of this lookup path. I'm keen to see if there's any clever caching or optimization to avoid unnecessary overhead in this critical code path. And from here, I can examine its relation to all other calls. |
| 40/3 | 2026/10/01 06:12 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/bpf_struct_ops.c",
"FirstLine": 520,
"LineCount": 40
}Results: {
"Contents": " 520:\t}\n 521:\t\n 522:\tint bpf_struct_ops_map_sys_lookup_elem(struct bpf_map *map, void *key,\n 523:\t\t\t\t\t void *value)\n 524:\t{\n 525:\t\tstruct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;\n 526:\t\tstruct bpf_struct_ops_value *uvalue, *kvalue;\n 527:\t\tenum bpf_struct_ops_state state;\n 528:\t\ts64 refcnt;\n 529:\t\n 530:\t\tif (unlikely(*(u32 *)key != 0))\n 531:\t\t\treturn -ENOENT;\n 532:\t\n 533:\t\tkvalue = \u0026st_map-\u003ekvalue;\n 534:\t\t/* Pair with smp_store_release() during map_update */\n 535:\t\tstate = smp_load_acquire(\u0026kvalue-\u003ecommon.state);\n 536:\t\tif (state == BPF_STRUCT_OPS_STATE_INIT) {\n 537:\t\t\tmemset(value, 0, map-\u003evalue_size);\n 538:\t\t\treturn 0;\n 539:\t\t}\n 540:\t\n 541:\t\t/* No lock is needed. state and refcnt do not need\n 542:\t\t * to be updated together under atomic context.\n 543:\t\t */\n 544:\t\tuvalue = value;\n 545:\t\tmemcpy(uvalue, st_map-\u003euvalue, map-\u003evalue_size);\n 546:\t\tuvalue-\u003ecommon.state = state;\n 547:\t\n 548:\t\t/* This value offers the user space a general estimate of how\n 549:\t\t * many sockets are still utilizing this struct_ops for TCP\n 550:\t\t * congestion control. The number might not be exact, but it\n 551:\t\t * should sufficiently meet our present goals.\n 552:\t\t */\n 553:\t\trefcnt = atomic64_read(\u0026map-\u003erefcnt) - atomic64_read(\u0026map-\u003eusercnt);\n 554:\t\trefcount_set(\u0026uvalue-\u003ecommon.refcnt, max_t(s64, refcnt, 0));\n 555:\t\n 556:\t\treturn 0;\n 557:\t}\n 558:\t\n 559:\tstatic void *bpf_struct_ops_map_lookup_elem(struct bpf_map *map, void *key)\n"
} |
| 41/3 | 2026/10/01 06:12 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 40456 output: 37 thoughts: 78 Thoughts: Here's my analysis of what I'm seeing: **Analyzing Memory Allocation and Potential Vulnerabilities in `bpf_struct_ops_map_update_elem`** Okay, I'm looking at this code and immediately keying in on `st_map->uvalue`. I see that it was allocated using `bpf_map_area_alloc(vt->size, NUMA_NO_NODE)`, and, critically, that this function *zero-initializes* the memory. That's a key observation, as we'll need to remember that the memory begins clean. Now, my mind goes to the user-space interaction. Whenever I see a map being updated, I immediately want to understand the impact of user-space input. I need to understand what potentially could be an interesting point. In this case, updating a struct_ops map seems relevant. So, I'm going to dig into `bpf_struct_ops_map_update_elem`. That's where I need to focus my attention. It's the point where user-space control intersects with the previously zero-initialized memory. This is the place to look for potential flaws. Is there something, say, in that update function, that fails to properly validate data or that copies data from user-space directly into that zeroed memory? I need to analyze how it handles the new values. Is there a race condition? Is there a memory overwrite issue? I will need to understand what this does to see if the zero-initialization can be bypassed somehow. |
| 42/3 | 2026/10/01 06:12 | tool | grepper |
0mArgs:{
"Expression": "bpf_struct_ops_map_update_elem",
"PathPrefix": "kernel/bpf/"
}Results: {
"Output": "kernel/bpf/bpf_struct_ops.c=715=static void bpf_struct_ops_map_free_ksyms(struct bpf_struct_ops_map *st_map)\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)\n--\nkernel/bpf/bpf_struct_ops.c=1195=const struct bpf_map_ops bpf_struct_ops_map_ops = {\n--\nkernel/bpf/bpf_struct_ops.c-1202-\t.map_delete_elem = bpf_struct_ops_map_delete_elem,\nkernel/bpf/bpf_struct_ops.c:1203:\t.map_update_elem = bpf_struct_ops_map_update_elem,\nkernel/bpf/bpf_struct_ops.c-1204-\t.map_seq_show_elem = bpf_struct_ops_map_seq_show_elem,\n"
} |
| 43/3 | 2026/10/01 06:12 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 41227 output: 41 thoughts: 18 Thoughts: Okay, let's dive into this `bpf_struct_ops_map_update_elem` function. I need to understand this, and quickly. Given my background, I'm assuming this is a core component within the BPF ecosystem, likely dealing with how struct operations are handled when updating elements within a BPF map. **Diving into `bpf_struct_ops_map_update_elem`** My immediate questions are: What *exactly* is it doing with these struct operations? Is it allocating new memory, copying data, applying some kind of transformation, or validating input? Does it consider potential race conditions or concurrency issues when updating map elements, particularly given the concurrent nature of BPF programs? I need to look closely at the arguments – what data types are being passed in? A key/value pair probably, but are there any operation-specific parameters that I should be aware of? Are there checks for map type compatibility or data structure alignment? The context is key here. I'll be paying close attention to any error handling. BPF is notoriously sensitive; a single misstep can lead to crashes or security vulnerabilities. What are the potential error paths? What checks are in place to ensure memory safety? Are there any return codes or error codes I need to understand? I'll probably be tracing the error codes and the checks in place and how they relate. Finally, I need to consider performance. Update operations are frequent. Is this function optimized for speed? Are there any obvious bottlenecks or opportunities for improvement? Knowing the underlying architecture, I should also compare this with other update functions - is this optimized in a manner unique to this data structure? Is there a performance analysis to consult, or benchmark information I can look at? I will need to consider the complexity of any operation it triggers, and also see how data access is optimized. I'm going to need to dig deep into the code and associated documentation. This is going to be interesting. |
| 44/3 | 2026/10/01 06:13 | tool | read-file |
0mArgs:{
"File": "kernel/bpf/bpf_struct_ops.c",
"FirstLine": 727,
"LineCount": 50
}Results: {
"Contents": " 727:\tstatic long bpf_struct_ops_map_update_elem(struct bpf_map *map, void *key,\n 728:\t\t\t\t\t\t void *value, u64 flags)\n 729:\t{\n 730:\t\tstruct bpf_struct_ops_map *st_map = (struct bpf_struct_ops_map *)map;\n 731:\t\tconst struct bpf_struct_ops_desc *st_ops_desc = st_map-\u003est_ops_desc;\n 732:\t\tconst struct bpf_struct_ops *st_ops = st_ops_desc-\u003est_ops;\n 733:\t\tstruct bpf_struct_ops_value *uvalue, *kvalue;\n 734:\t\tconst struct btf_type *module_type;\n 735:\t\tconst struct btf_member *member;\n 736:\t\tconst struct btf_type *t = st_ops_desc-\u003etype;\n 737:\t\tstruct bpf_tramp_nodes *tnodes;\n 738:\t\tvoid *udata, *kdata;\n 739:\t\tint prog_fd, err;\n 740:\t\tu32 i, trampoline_start, image_off = 0;\n 741:\t\tvoid *cur_image = NULL, *image = NULL;\n 742:\t\tstruct bpf_link **plink;\n 743:\t\tstruct bpf_ksym **pksym;\n 744:\t\tconst char *tname, *mname;\n 745:\t\n 746:\t\tif (flags)\n 747:\t\t\treturn -EINVAL;\n 748:\t\n 749:\t\tif (*(u32 *)key != 0)\n 750:\t\t\treturn -E2BIG;\n 751:\t\n 752:\t\terr = check_zero_holes(st_map-\u003ebtf, st_ops_desc-\u003evalue_type, value);\n 753:\t\tif (err)\n 754:\t\t\treturn err;\n 755:\t\n 756:\t\tuvalue = value;\n 757:\t\terr = check_zero_holes(st_map-\u003ebtf, t, uvalue-\u003edata);\n 758:\t\tif (err)\n 759:\t\t\treturn err;\n 760:\t\n 761:\t\tif (uvalue-\u003ecommon.state || refcount_read(\u0026uvalue-\u003ecommon.refcnt))\n 762:\t\t\treturn -EINVAL;\n 763:\t\n 764:\t\ttnodes = kzalloc_objs(*tnodes, BPF_TRAMP_MAX);\n 765:\t\tif (!tnodes)\n 766:\t\t\treturn -ENOMEM;\n 767:\t\n 768:\t\tuvalue = (struct bpf_struct_ops_value *)st_map-\u003euvalue;\n 769:\t\tkvalue = (struct bpf_struct_ops_value *)\u0026st_map-\u003ekvalue;\n 770:\t\n 771:\t\tmutex_lock(\u0026st_map-\u003elock);\n 772:\t\n 773:\t\tif (kvalue-\u003ecommon.state != BPF_STRUCT_OPS_STATE_INIT) {\n 774:\t\t\terr = -EBUSY;\n 775:\t\t\tgoto unlock;\n 776:\t\t}\n"
} |
| 45/3 | 2026/10/01 06:13 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 42549 output: 30 thoughts: 130 Thoughts: Okay, let me break this down. **Diving into Zero Hole Checks** Alright, I'm zeroing in on this `check_zero_holes` function. Seems like it's a key part of the validation process here, and it's catching my eye. First off, it's being used on `value` and then again on `uvalue->data`, which implies we're dealing with a multi-part structure, likely something like a union or a struct with nested fields. The interesting bit? It's actively enforcing that any "holes" or padding within these data structures *must* be initialized to zero. That level of strictness is unusual and suggests we're operating in a context where precise memory layout and zero-initialization are critical to preventing vulnerabilities or ensuring data integrity. I need to understand why this degree of paranoia is necessary. Let's see what the function actually *does*. |
| 46/3 | 2026/10/01 06:13 | tool | grepper |
0mArgs:{
"Expression": "check_zero_holes",
"PathPrefix": "kernel/bpf/"
}Results: {
"Output": "kernel/bpf/bpf_struct_ops.c=587=static void bpf_struct_ops_map_free_image(struct bpf_struct_ops_map *st_map)\n--\nkernel/bpf/bpf_struct_ops.c-595-\nkernel/bpf/bpf_struct_ops.c:596:static int check_zero_holes(const struct btf *btf, const struct btf_type *t, void *data)\nkernel/bpf/bpf_struct_ops.c-597-{\n--\nkernel/bpf/bpf_struct_ops.c=727=static long bpf_struct_ops_map_update_elem(struct bpf_map *map, void *key,\n--\nkernel/bpf/bpf_struct_ops.c-751-\nkernel/bpf/bpf_struct_ops.c:752:\terr = check_zero_holes(st_map-\u003ebtf, st_ops_desc-\u003evalue_type, value);\nkernel/bpf/bpf_struct_ops.c-753-\tif (err)\n--\nkernel/bpf/bpf_struct_ops.c-756-\tuvalue = value;\nkernel/bpf/bpf_struct_ops.c:757:\terr = check_zero_holes(st_map-\u003ebtf, t, uvalue-\u003edata);\nkernel/bpf/bpf_struct_ops.c-758-\tif (err)\n"
} |
| 47/3 | 2026/10/01 06:13 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 43283 output: 37 thoughts: 2390 Thoughts: **Analysis of the I/O Cost BPF Patch for Potential Security Issues** Alright, let's break down this patch. My primary concern is always: can this be exploited? First, I'm verifying the potential for information leaks. The padding within the `struct iocost_model_ops` (and potentially other structures used in this context) has been checked via `check_zero_holes`, ensuring these bytes are initialized to zero. The user-provided values are copied into the kernel space's `uvalue` and then into `st_map->uvalue` through `bpf_struct_ops_map_sys_lookup_elem`. Since padding is zeroed during allocation, I am confident there is no direct information leak from padding within `struct_ops`. Then, I focused on a very common vector of attack: concurrency issues. I am meticulously scanning the code for races, especially around registration and unregistration of the BPF model with `bpf_iocost_unreg`, `ioc_rqos_exit`, `ioc_bpf_detach`, and `ioc_bpf_attach`. The use of `rcu_read_lock()`/`rcu_dereference()` and `rcu_assign_pointer()` is there, but I am now cross-checking it for any violations. I also need to verify the refcounting on `request_queue` through `blk_get_queue_rcu` and `blk_put_queue`. Lockdep warnings and potential deadlocks on `q->rq_qos_mutex`, `q->blkcg_mutex`, and `ioc->lock` must be assessed. The biggest risk is a use-after-free or a NULL pointer dereference if there is a race between a queue teardown and a `struct_ops` unregistration; this is classic. I'm making sure that KASAN and LOCKDEP are fully enabled to catch any of those UAF and deadlock vulnerabilities. Next, I need to check for the use of uninitialized variables in the newly introduced or modified functions. I've gone through each function's local variables, ensuring they are all initialized before use. The code is structured to avoid common errors of uninitialized read, which I am satisfied with. I'm focusing on the `ioc_timer_fn`, `calc_vtime_cost`, and `calc_size_vtime_cost` functions. I will also be vigilant for anything which returns a value without initialization. In the functions, `ioc_rqos_exit` and `ioc_pd_init`, `ioc_pd_free`, and `ioc_cost_model_prfill`, I am carefully reviewing the use of `rcu_dereference` and the associated lock/unlock primitives. I have verified that all necessary checks and assignment are present. Now, to see if any kernel memory is leaked to userspace via information leaks. I will look for calls to `seq_printf` or trace data formatting, as those are often used to display data that might reveal internal state. Also, I am verifying that the BPF struct_ops map lookup uses `check_zero_holes` and kzalloc'ed memory. And, I need to confirm that no `copy_to_user`, `put_user`, netlink attributes, socket options, or ioctl output arguments are added or altered that could lead to information leaks. I'm also paying very close attention to potential control flow or buffer size changes that could cause surrounding code to read uninitialized memory. `calc_vtime_cost` and `calc_size_vtime_cost` compute block I/O costs, and I need to ensure the clamped or arithmetic used with `VTIME_PER_SEC` does not cause any out-of-bounds reads. Finally, I'm examining complex data structure allocations. Only pointers to `ioc->attached` and `ioc->model` have been added to the `struct ioc` so far. The `kzalloc` function is used for `struct ioc` which I'm verifying and checking for any potential field misinitialization. |
| 48/3 | 2026/10/01 06:13 | tool | grepper |
0mError:no matches Args: {
"Expression": "kzalloc.*sizeof\\(struct ioc\\)",
"PathPrefix": "block/blk-iocost.c"
}Results: {
"error": "no matches"
} |
| 49/3 | 2026/10/01 06:13 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 46593 output: 34 thoughts: 23 Thoughts: Okay, here's my attempt at summarizing the thought process, tailored for an expert audience, and written in the first person: **Finding the Allocation of `struct ioc` in `block/blk-iocost.c`** Alright, let's dive in. I need to figure out how the `struct ioc` is allocated within `block/blk-iocost.c`. Given that I'm working with a block layer module, my initial hunch is that it's likely tied to I/O requests themselves or perhaps associated with the tracking of I/O cost metrics. The way this is likely handled is that the `ioc` struct is either statically allocated as part of a larger structure, dynamically allocated using `kmalloc` or similar, or potentially embedded within another context like the `bio` structure, possibly managed via a specific allocator. My first step would be to search the codebase for direct instantiations. I'm going to look for declarations like `struct ioc` followed by a variable name, or calls to allocation functions that suggest its use. I expect to see `kmalloc` or a similar memory allocation function if it's dynamic. I'll need to pay close attention to the context of the allocation. Is it within a function that handles I/O submission? Is it associated with a particular block device? If the allocation isn't immediately obvious, I'll trace its usage. I'll search for references to fields within the `struct ioc` to see where it's being used. The use of this structure would give me better clues. I'd expect to see it used to track resource utilization, such as latency, bandwidth, and potentially cost metrics related to the I/O operations. I'll also keep in mind potential interaction with other subsystems, such as the request queue, or any io-cost accounting or scheduling mechanisms that might interface with this structure. I'll have to see where it's initialized, populated, and eventually freed. |
| 50/3 | 2026/10/01 06:13 | tool | grepper |
0mArgs:{
"Expression": "blk_iocost_init",
"PathPrefix": "block/blk-iocost.c"
}Results: {
"Output": "block/blk-iocost.c=3021=static const struct rq_qos_ops ioc_rqos_ops = {\n--\nblock/blk-iocost.c-3029-\nblock/blk-iocost.c:3030:static int blk_iocost_init(struct gendisk *disk)\nblock/blk-iocost.c-3031-{\n--\nblock/blk-iocost.c=3408=static ssize_t ioc_qos_write(struct kernfs_open_file *of, char *input,\n--\nblock/blk-iocost.c-3445-\tif (!ioc) {\nblock/blk-iocost.c:3446:\t\tret = blk_iocost_init(disk);\nblock/blk-iocost.c-3447-\t\tif (ret)\n--\nblock/blk-iocost.c=3631=int ioc_bpf_attach(struct iocost_model_ops *ops)\n--\nblock/blk-iocost.c-3677-\tif (!ioc) {\nblock/blk-iocost.c:3678:\t\tret = blk_iocost_init(disk);\nblock/blk-iocost.c-3679-\t\tmutex_unlock(\u0026q-\u003erq_qos_mutex);\n--\nblock/blk-iocost.c=3813=static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,\n--\nblock/blk-iocost.c-3843-\tif (!ioc) {\nblock/blk-iocost.c:3844:\t\tret = blk_iocost_init(ctx.bdev-\u003ebd_disk);\nblock/blk-iocost.c-3845-\t\tif (ret)\n"
} |
| 51/3 | 2026/10/01 06:13 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 47526 output: 37 thoughts: 12 Thoughts: Okay, let's dive into this `blk_iocost_init` function. **Initial Assessment of `blk_iocost_init`** Alright, so I'm looking at this `blk_iocost_init` function. It's the initialization, of course, for the I/O cost model within the block layer, and my initial thought is: what are we setting up, and how are we getting it ready to do its job? I'm expecting to see the allocation and setup of the core data structures that underpin the cost estimation – this means structs likely related to tracking resource usage and possibly calibration parameters. Given this is the _init_ function, I anticipate checks or default settings to ensure these structures start in a known, sane state. I'm also betting this will involve registration of various components or subsystem to enable functionality. This is the bedrock of the whole performance monitoring and optimization process. I need to understand this to have any chance of following the performance implications further downstream. |
| 52/3 | 2026/10/01 06:13 | tool | read-file |
0mArgs:{
"File": "block/blk-iocost.c",
"FirstLine": 3030,
"LineCount": 25
}Results: {
"Contents": "3030:\tstatic int blk_iocost_init(struct gendisk *disk)\n3031:\t{\n3032:\t\tstruct ioc *ioc;\n3033:\t\tint i, cpu, ret;\n3034:\t\n3035:\t\tioc = kzalloc_obj(*ioc);\n3036:\t\tif (!ioc)\n3037:\t\t\treturn -ENOMEM;\n3038:\t\n3039:\t\tioc-\u003epcpu_stat = alloc_percpu(struct ioc_pcpu_stat);\n3040:\t\tif (!ioc-\u003epcpu_stat) {\n3041:\t\t\tkfree(ioc);\n3042:\t\t\treturn -ENOMEM;\n3043:\t\t}\n3044:\t\n3045:\t\tfor_each_possible_cpu(cpu) {\n3046:\t\t\tstruct ioc_pcpu_stat *ccs = per_cpu_ptr(ioc-\u003epcpu_stat, cpu);\n3047:\t\n3048:\t\t\tfor (i = 0; i \u003c ARRAY_SIZE(ccs-\u003emissed); i++) {\n3049:\t\t\t\tlocal_set(\u0026ccs-\u003emissed[i].nr_met, 0);\n3050:\t\t\t\tlocal_set(\u0026ccs-\u003emissed[i].nr_missed, 0);\n3051:\t\t\t}\n3052:\t\t\tlocal64_set(\u0026ccs-\u003erq_wait_ns, 0);\n3053:\t\t}\n3054:\t\n"
} |
| 53/3 | 2026/10/01 06:13 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 48177 output: 346 thoughts: 767 Thoughts: **My Assessment: KMSAN Not Needed** Okay, let's break this down. My initial allocation of the `ioc` struct, using `kzalloc_obj`, ensures that both `ioc->attached` and `ioc->model` start as NULL. This is crucial. Looking at `struct iocost_model_ops`, I can see that all of its members are either zeroed during the allocation of the `struct_ops` map or explicitly initialized. There's no sneaky business here – no uninitialized memory being copied, no conditional branches based on uninitialized memory, and certainly no risk of information leaks due to uninitialized buffers. The core risks I'm introducing with this patch relate to concurrency: potential bugs around attach/detach operations, queue teardown, ejection, and the refcounting. I'm also thinking about the usual suspects like lock ordering, deadlocks, and the dreaded NULL-pointer dereferences or use-after-free scenarios. But, and this is the important part, KASAN, LOCKDEP, and the standard kernel debugging tools are well-equipped to catch these types of bugs. KMSAN, on the other hand, is designed to detect reads of uninitialized memory and information leaks. And, that's not what I'm introducing. All the stack and heap structures I touch, or that are introduced, are fully zeroed or initialized. There are no uninitialized local variables that are ever read. Every local variable such as `now`, `cost`, or `model`, is explicitly assigned before use. My user-facing interfaces, like `seq_printf` and trace events, are only producing formatted output. So, I'm confident there are no KMSAN issues here. I've re-read the KMSAN guidelines, and it's clear: there's no reason to waste resources on a KMSAN session if KASAN, LOCKDEP, or other standard tools can find the bugs. KMSAN is meant for those unique scenarios where a bug can *only* be caught by it. That's not the case here. To be absolutely clear, what this patch does is add BPF struct_ops (`iocost_model_ops`) support for pluggable cost models in `blk-iocost`. I've added attach/detach logic, RCU-protected model selection, queue refcounting using `blk_get_queue_rcu`, and trace events. The potential failure modes I'm concerned with relate to object lifetimes, RCU synchronization, refcounting, and locking (e.g. `rq_qos_mutex`, `blkcg_mutex`, `ioc->lock`), as well as the classic issues of use-after-free and race conditions during device removal or concurrent attach/detach operations. KASAN, LOCKDEP, and refcount tracking are precisely what I need here. No uninitialized stack or heap variables are being read or exposed. Therefore, the conclusion is straightforward: `NeedsKMSAN=false`. Let's set that result and move on. |
| 54/3 | 2026/10/01 06:13 | tool | set-results |
0mArgs:{
"KMSANReasoning": "The patch series introduces BPF struct_ops support ('iocost_model_ops') to allow pluggable cost models in the blk-iocost block I/O controller, alongside device attachment/detachment logic, RCU-protected model selection, queue reference counting (blk_get_queue_rcu), and a periodic tracepoint.\n\nAnalysis of memory safety concerns:\n1. KASAN/LOCKDEP applicability: The changes introduce concurrency and lifetime management mechanisms (synchronizing BPF struct_ops lifecycle with request_queue teardown, RCU dereferences of the attached model, mutexes across queue freezing/quiescing, and refcount management). The primary failure modes are potential race conditions, use-after-free, refcount leaks, or deadlocks, which are thoroughly covered by KASAN and LOCKDEP in standard fuzzing builds.\n2. KMSAN applicability: No uninitialized stack or heap memory is exposed or used. 'struct ioc' is allocated via kzalloc_obj, BPF struct_ops maps zero-initialize backing storage and enforce zeroed structure padding via check_zero_holes, all local variables in the new and modified functions (such as 'cost', 'now', 'model') are explicitly assigned before use, and reporting mechanisms (seq_printf in cgroup files and trace_iocost_ioc_tick) only output formatted scalar values without leaking raw kernel memory to userspace.\n\nSince there are no uninitialized memory reads or information leak risks, a dedicated KMSAN fuzzing session is not justified.",
"NeedsKMSAN": false
}Results: {
"KMSANReasoning": "The patch series introduces BPF struct_ops support ('iocost_model_ops') to allow pluggable cost models in the blk-iocost block I/O controller, alongside device attachment/detachment logic, RCU-protected model selection, queue reference counting (blk_get_queue_rcu), and a periodic tracepoint.\n\nAnalysis of memory safety concerns:\n1. KASAN/LOCKDEP applicability: The changes introduce concurrency and lifetime management mechanisms (synchronizing BPF struct_ops lifecycle with request_queue teardown, RCU dereferences of the attached model, mutexes across queue freezing/quiescing, and refcount management). The primary failure modes are potential race conditions, use-after-free, refcount leaks, or deadlocks, which are thoroughly covered by KASAN and LOCKDEP in standard fuzzing builds.\n2. KMSAN applicability: No uninitialized stack or heap memory is exposed or used. 'struct ioc' is allocated via kzalloc_obj, BPF struct_ops maps zero-initialize backing storage and enforce zeroed structure padding via check_zero_holes, all local variables in the new and modified functions (such as 'cost', 'now', 'model') are explicitly assigned before use, and reporting mechanisms (seq_printf in cgroup files and trace_iocost_ioc_tick) only output formatted scalar values without leaking raw kernel memory to userspace.\n\nSince there are no uninitialized memory reads or information leak risks, a dedicated KMSAN fuzzing session is not justified.",
"NeedsKMSAN": false
} |
| Total Calls | Total Tokens | Avg Tokens | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|
| Total Calls | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|