AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/10/11 06:40 flow patch-triage
7m Args:
null

Results:
{
  "EnableConfigs": [
    "BLK_DEV_UBLK",
    "BLK_DEV_ZONED"
  ],
  "FocusSymbols": [
    "ublk_ctrl_start_dev",
    "ublk_stop_dev",
    "ublk_ch_uring_cmd_local",
    "ublk_uring_cmd_cancel_fn",
    "ublk_ctrl_end_recovery",
    "ublk_batch_attach",
    "ublk_ch_release_work_fn",
    "ublk_report_zones"
  ],
  "KMSANReasoning": "The patch addresses synchronization, state management, and cancellation races in the ublk driver (ublk_drv.c). Specifically:\n1. It prevents NULL pointer dereferences on io-\u003ecmd and io_uring use-after-free bugs when I/O commands are canceled while starting/stopping devices or during recovery.\n2. It introduces UB_STATE_STOPPING and manages ublk device lifecycle state transitions across START_DEV, STOP_DEV, and FETCH commands.\n3. In ublk_report_zones(), it fixes a bug where the per-batch loop index 'i' was passed to disk_report_zone() instead of the cumulative 'done_zones', ensuring multi-batch zone reporting copies to the correct index in user memory. The underlying report buffer is already explicitly zeroed with memset(), and no uninitialized kernel data is copied to user space.\n4. All added/modified variables and struct fields (e.g., ch_file, canceled, cur) are properly initialized or reside within zero-allocated structures (kzalloc_flex / kzalloc_obj).\n\nThese changes primarily address race conditions, NULL pointer dereferences, and use-after-free scenarios, which are covered by standard KASAN, LOCKDEP, and kernel oops detectors. No uninitialized memory reads or information leak hazards are introduced or exposed; thus, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch modifies the userspace block device driver (ublk_drv.c), addressing concurrency bugs and state synchronization between STOP_DEV, START_DEV, recovery operations, and io_uring command cancellation. It introduces the UB_STATE_STOPPING state, updates locking around cancel_mutex, adjusts cancel-related WARN_ON_ONCE checks, and fixes zone reporting indexing in ublk_report_zones. Because ublk operates via io_uring and virtual devices accessible in standard QEMU environments without special physical hardware, this reachable and concurrency-heavy code warrants fuzzing.",
  "WorthFuzzing": true
}

1/1 2026/10/11 06:40 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit a4bb54a2d35bed452a582bea2ba85f6ce8ce5cdb\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Sun Oct 11 06:40:13 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/Documentation/block/ublk.rst b/Documentation/block/ublk.rst\nindex 28300fee22bfc..f07611b0d4895 100644\n--- a/Documentation/block/ublk.rst\n+++ b/Documentation/block/ublk.rst\n@@ -118,7 +118,11 @@ managing and controlling ublk devices with help of several control commands:\n   After the server prepares userspace resources (such as creating I/O handler\n   threads \u0026 io_uring for handling ublk IO), this command is sent to the\n   driver for allocating \u0026 exposing ``/dev/ublkb*``. Parameters set via\n-  ``UBLK_CMD_SET_PARAMS`` are applied for creating the device.\n+  ``UBLK_CMD_SET_PARAMS`` are applied for creating the device. The command\n+  fails with ``-EBUSY`` if an I/O command fetched by the current server\n+  was canceled, because its io_uring is gone. The server can't fetch it\n+  again, and the device can be started again once the server has closed\n+  ``/dev/ublkc*``.\n \n - ``UBLK_CMD_STOP_DEV``\n \n@@ -126,6 +130,13 @@ managing and controlling ublk devices with help of several control commands:\n   ublk server will release resources (such as destroying I/O handler threads \u0026\n   io_uring).\n \n+  If a server has ``/dev/ublkc*`` open, its fetched I/O commands complete with\n+  ``UBLK_IO_RES_ABORT``. Until it closes ``/dev/ublkc*``, new\n+  ``UBLK_IO_FETCH_REQ`` and ``UBLK_U_IO_PREP_IO_CMDS`` commands complete with\n+  ``UBLK_IO_RES_ABORT`` too, and ``UBLK_CMD_START_DEV`` fails with ``-EBUSY``,\n+  even if the server hadn't fetched anything. The device can be started again\n+  by a server that opens ``/dev/ublkc*`` after that.\n+\n - ``UBLK_CMD_DEL_DEV``\n \n   Remove ``/dev/ublkc*``. When this command returns, the allocated ublk device\n@@ -195,7 +206,9 @@ managing and controlling ublk devices with help of several control commands:\n   command is accepted after ublk device is quiesced and a new process has\n   opened ``/dev/ublkc*`` and get all ublk queues be ready. When this command\n   returns, ublk device is unquiesced and new I/O requests are passed to the\n-  new process.\n+  new process. It fails with ``-EBUSY`` if an I/O command of the new\n+  process was canceled already. The recovery can be started over once the\n+  new process has closed ``/dev/ublkc*``.\n \n - user recovery feature description\n \ndiff --git a/drivers/block/ublk_drv.c b/drivers/block/ublk_drv.c\nindex b32872421951d..1e84ccc68b9b0 100644\n--- a/drivers/block/ublk_drv.c\n+++ b/drivers/block/ublk_drv.c\n@@ -321,6 +321,8 @@ struct ublk_device {\n #define UB_STATE_OPEN\t\t0\n #define UB_STATE_USED\t\t1\n #define UB_STATE_DELETED\t2\n+/* STOP_DEV canceled the server's commands, until its release */\n+#define UB_STATE_STOPPING\t3\n \tunsigned long\t\tstate;\n \tint\t\t\tub_number;\n \n@@ -334,6 +336,13 @@ struct ublk_device {\n \tu16\t\t\tnr_queue_ready;\n \tbool \t\t\tunprivileged_daemons;\n \tstruct mutex cancel_mutex;\n+\t/* the open /dev/ublkcN, protected by cancel_mutex */\n+\tstruct file *ch_file;\n+\t/*\n+\t * A cancel started in this FETCH round. Set by ublk_set_canceling(),\n+\t * cleared only by ublk_reset_ch_dev() when a new round starts. While\n+\t * it is set, no queue clears its -\u003ecanceling.\n+\t */\n \tbool canceling;\n \tpid_t \tublksrv_tgid;\n \tstruct delayed_work\texit_work;\n@@ -687,7 +696,7 @@ static int ublk_report_zones(struct gendisk *disk, sector_t sector,\n \t\t\tif (!zone-\u003elen)\n \t\t\t\tbreak;\n \n-\t\t\tret = disk_report_zone(disk, zone, i, args);\n+\t\t\tret = disk_report_zone(disk, zone, done_zones, args);\n \t\t\tif (ret)\n \t\t\t\tgoto out;\n \n@@ -810,6 +819,8 @@ ublk_batch_alloc_fcmd(struct io_uring_cmd *cmd)\n \tif (fcmd) {\n \t\tfcmd-\u003ecmd = cmd;\n \t\tfcmd-\u003ebuf_group = READ_ONCE(cmd-\u003esqe-\u003ebuf_index);\n+\t\t/* a cancel may look at it before it is linked */\n+\t\tINIT_LIST_HEAD(\u0026fcmd-\u003enode);\n \t}\n \treturn fcmd;\n }\n@@ -2399,6 +2410,9 @@ static int ublk_ch_open(struct inode *inode, struct file *filp)\n \t\treturn -EBUSY;\n \tfilp-\u003eprivate_data = ub;\n \tub-\u003eublksrv_tgid = current-\u003etgid;\n+\tmutex_lock(\u0026ub-\u003ecancel_mutex);\n+\tub-\u003ech_file = filp;\n+\tmutex_unlock(\u0026ub-\u003ecancel_mutex);\n \treturn 0;\n }\n \n@@ -2415,11 +2429,17 @@ static void ublk_reset_ch_dev(struct ublk_device *ub)\n \t\tspin_unlock(\u0026ubq-\u003ecancel_lock);\n \t}\n \n+\t/* a new FETCH round starts, the queues stay canceling until ready */\n+\tmutex_lock(\u0026ub-\u003ecancel_mutex);\n+\tub-\u003ecanceling = false;\n+\tmutex_unlock(\u0026ub-\u003ecancel_mutex);\n+\n \t/* set to NULL, otherwise new tasks cannot mmap io_cmd_buf */\n \tub-\u003emm = NULL;\n \tub-\u003enr_queue_ready = 0;\n \tub-\u003eunprivileged_daemons = false;\n \tub-\u003eublksrv_tgid = -1;\n+\tclear_bit(UB_STATE_STOPPING, \u0026ub-\u003estate);\n }\n \n static struct gendisk *ublk_get_disk(struct ublk_device *ub)\n@@ -2539,12 +2559,15 @@ static void ublk_ch_release_work_fn(struct work_struct *work)\n \t}\n \n \t/*\n-\t * disk isn't attached yet, either device isn't live, or it has\n-\t * been removed already, so we needn't to do anything\n+\t * No disk: the device isn't live, or it has been removed already.\n+\t * There are no requests to abort, but the round still has to be\n+\t * reset, so that a new server can fetch and start the device.\n \t */\n \tdisk = ublk_get_disk(ub);\n-\tif (!disk)\n-\t\tgoto out;\n+\tif (!disk) {\n+\t\tmutex_lock(\u0026ub-\u003emutex);\n+\t\tgoto reset;\n+\t}\n \n \t/*\n \t * All uring_cmd are done now, so abort any request outstanding to\n@@ -2576,7 +2599,7 @@ static void ublk_ch_release_work_fn(struct work_struct *work)\n \n \t/* double check after grabbing lock */\n \tif (!ub-\u003eub_disk)\n-\t\tgoto unlock;\n+\t\tgoto reset;\n \n \t/*\n \t * Transition the device to the nosrv state. What exactly this\n@@ -2602,13 +2625,14 @@ static void ublk_ch_release_work_fn(struct work_struct *work)\n \t\t\t\tWRITE_ONCE(ublk_get_queue(ub, i)-\u003efail_io, true);\n \t\t}\n \t}\n-unlock:\n+reset:\n+\t/*\n+\t * All uring_cmd has been done now, reset device \u0026 ubq. Under\n+\t * ub-\u003emutex, so START_DEV sees the round either ready or reset.\n+\t */\n+\tublk_reset_ch_dev(ub);\n \tmutex_unlock(\u0026ub-\u003emutex);\n \tublk_put_disk(disk);\n-\n-\t/* all uring_cmd has been done now, reset device \u0026 ubq */\n-\tublk_reset_ch_dev(ub);\n-out:\n \tclear_bit(UB_STATE_OPEN, \u0026ub-\u003estate);\n \n \t/* put the reference grabbed in ublk_ch_release() */\n@@ -2619,6 +2643,9 @@ static int ublk_ch_release(struct inode *inode, struct file *filp)\n {\n \tstruct ublk_device *ub = filp-\u003eprivate_data;\n \n+\tmutex_lock(\u0026ub-\u003ecancel_mutex);\n+\tub-\u003ech_file = NULL;\n+\tmutex_unlock(\u0026ub-\u003ecancel_mutex);\n \t/*\n \t * Grab ublk device reference, so it won't be gone until we are\n \t * really released from work function.\n@@ -2732,9 +2759,11 @@ static void ublk_abort_queue(struct ublk_device *ub, struct ublk_queue *ubq)\n \n static void ublk_start_cancel(struct ublk_device *ub)\n {\n-\tstruct gendisk *disk = ublk_get_disk(ub);\n+\tstruct gendisk *disk;\n \n+\t/* sync with ublk_ctrl_start_dev() publishing the disk */\n \tmutex_lock(\u0026ub-\u003ecancel_mutex);\n+\tdisk = ublk_get_disk(ub);\n \tif (ub-\u003ecanceling)\n \t\tgoto out;\n \n@@ -2790,7 +2819,8 @@ static void ublk_cancel_cmd(struct ublk_queue *ubq, u16 tag,\n \tdone = !!(io-\u003eflags \u0026 UBLK_IO_FLAG_CANCELED);\n \tif (!done) {\n \t\tio-\u003eflags |= UBLK_IO_FLAG_CANCELED;\n-\t\tcmd = io-\u003ecmd;\n+\t\t/* dependency ordered against smp_wmb() in ublk_prep_cancel() */\n+\t\tcmd = READ_ONCE(io-\u003ecmd);\n \t\tio-\u003ecmd = NULL;\n \t}\n \tspin_unlock(\u0026ubq-\u003ecancel_lock);\n@@ -2879,6 +2909,7 @@ static void ublk_uring_cmd_cancel_fn(struct io_uring_cmd *cmd,\n {\n \tstruct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);\n \tstruct ublk_queue *ubq = pdu-\u003eubq;\n+\tstruct io_uring_cmd *cur;\n \tstruct task_struct *task;\n \tstruct ublk_io *io;\n \n@@ -2895,7 +2926,9 @@ static void ublk_uring_cmd_cancel_fn(struct io_uring_cmd *cmd,\n \n \tublk_start_cancel(ubq-\u003edev);\n \n-\tWARN_ON_ONCE(io-\u003ecmd != cmd);\n+\t/* NULL if a cancel from the control path took it meanwhile */\n+\tcur = READ_ONCE(io-\u003ecmd);\n+\tWARN_ON_ONCE(cur \u0026\u0026 cur != cmd);\n \tublk_cancel_cmd(ubq, pdu-\u003etag, issue_flags);\n }\n \n@@ -3006,13 +3039,54 @@ static void ublk_stop_dev_unlocked(struct ublk_device *ub)\n \tput_disk(disk);\n }\n \n+static struct file *ublk_get_ch_file(struct ublk_device *ub)\n+{\n+\tstruct file *file;\n+\n+\tmutex_lock(\u0026ub-\u003ecancel_mutex);\n+\tfile = ub-\u003ech_file;\n+\tif (file \u0026\u0026 !file_ref_get(\u0026file-\u003ef_ref))\n+\t\tfile = NULL;\n+\tmutex_unlock(\u0026ub-\u003ecancel_mutex);\n+\treturn file;\n+}\n+\n static void ublk_stop_dev(struct ublk_device *ub)\n {\n+\tstruct file *file;\n+\n+\t/*\n+\t * FETCH, PREP and START_DEV take ub-\u003emutex. If a server has\n+\t * /dev/ublkcN open, set STOPPING, which turns it away, and hold a\n+\t * reference on the file: the server's release, whose reset clears\n+\t * STOPPING and lets a new server attach, can't run before we drop it.\n+\t * So the cancel can run after the unlock and only meets this server's\n+\t * commands; it has to: io_uring_cmd_done() may take uring_lock, under\n+\t * which FETCH takes ub-\u003emutex.\n+\t */\n \tmutex_lock(\u0026ub-\u003emutex);\n \tublk_stop_dev_unlocked(ub);\n-\tmutex_unlock(\u0026ub-\u003emutex);\n \tcancel_work_sync(\u0026ub-\u003epartition_scan_work);\n+\tfile = ublk_get_ch_file(ub);\n+\tif (file) {\n+\t\t/*\n+\t\t * The server has to close /dev/ublkcN before this device can\n+\t\t * be started again: the reset in its release clears STOPPING.\n+\t\t */\n+\t\tset_bit(UB_STATE_STOPPING, \u0026ub-\u003estate);\n+\t\t/* for wake_up_var() below, see wake_up_bit() */\n+\t\tsmp_mb__after_atomic();\n+\t}\n+\tmutex_unlock(\u0026ub-\u003emutex);\n+\n+\t/* no server: nothing to cancel */\n+\tif (!file)\n+\t\treturn;\n+\n+\t/* wake a START_DEV waiting for the device to get ready */\n+\twake_up_var(\u0026ub-\u003enr_queue_ready);\n \tublk_cancel_dev(ub);\n+\t__fput_sync(file);\n }\n \n static void ublk_reset_io_flags(struct ublk_queue *ubq, struct ublk_io *io)\n@@ -3024,11 +3098,19 @@ static void ublk_reset_io_flags(struct ublk_queue *ubq, struct ublk_io *io)\n }\n \n /* reset per-queue io flags */\n-static void ublk_queue_reset_io_flags(struct ublk_queue *ubq)\n+static void ublk_queue_reset_io_flags(struct ublk_device *ub,\n+\t\t\t\t      struct ublk_queue *ubq)\n {\n-\tspin_lock(\u0026ubq-\u003ecancel_lock);\n-\tubq-\u003ecanceling = false;\n-\tspin_unlock(\u0026ubq-\u003ecancel_lock);\n+\t/*\n+\t * A cancel in this FETCH round took a command which still counts as\n+\t * ready, so the queue has to stay canceling. ub-\u003ecanceling is set\n+\t * under cancel_mutex before any command is taken: either we see it\n+\t * here, or the cancel marks this queue again later.\n+\t */\n+\tmutex_lock(\u0026ub-\u003ecancel_mutex);\n+\tif (!ub-\u003ecanceling)\n+\t\tubq-\u003ecanceling = false;\n+\tmutex_unlock(\u0026ub-\u003ecancel_mutex);\n \tubq-\u003efail_io = false;\n }\n \n@@ -3050,24 +3132,17 @@ static void ublk_mark_io_ready(struct ublk_device *ub, u16 q_id,\n \t\tub-\u003enr_queue_ready++;\n \n \t\t/*\n-\t\t * Reset queue flags as soon as this queue is ready.\n-\t\t * This clears the canceling flag, allowing batch FETCH commands\n-\t\t * to succeed during recovery without waiting for all queues.\n+\t\t * Reset queue flags as soon as this queue is ready. Unless\n+\t\t * this round saw a cancel, this clears the canceling flag,\n+\t\t * allowing batch FETCH commands to succeed during recovery\n+\t\t * without waiting for all queues.\n \t\t */\n-\t\tublk_queue_reset_io_flags(ubq);\n+\t\tublk_queue_reset_io_flags(ub, ubq);\n \t}\n \n-\t/* Check if all queues are ready */\n-\tif (ublk_dev_ready(ub)) {\n-\t\t/*\n-\t\t * All queues ready - clear device-level canceling flag\n-\t\t * and wake ublk_dev_ready() waiters.\n-\t\t */\n-\t\tmutex_lock(\u0026ub-\u003ecancel_mutex);\n-\t\tub-\u003ecanceling = false;\n-\t\tmutex_unlock(\u0026ub-\u003ecancel_mutex);\n+\t/* All queues ready - wake ublk_dev_ready() waiters */\n+\tif (ublk_dev_ready(ub))\n \t\twake_up_var(\u0026ub-\u003enr_queue_ready);\n-\t}\n }\n \n static inline int ublk_check_cmd_op(u32 cmd_op)\n@@ -3151,6 +3226,12 @@ ublk_fill_io_cmd(struct ublk_io *io, struct io_uring_cmd *cmd)\n \treturn req;\n }\n \n+/*\n+ * Call before ublk_fill_io_cmd() publishes @cmd in io-\u003ecmd: a control-path\n+ * cancel may complete any command found there, and io_uring_cmd_done() only\n+ * takes it off the cancelable list if it is marked already. The handlers\n+ * hold uring_lock, so marking takes no lock.\n+ */\n static inline void ublk_prep_cancel(struct io_uring_cmd *cmd,\n \t\t\t\t    unsigned int issue_flags,\n \t\t\t\t    struct ublk_queue *ubq, u16 tag)\n@@ -3164,6 +3245,8 @@ static inline void ublk_prep_cancel(struct io_uring_cmd *cmd,\n \tpdu-\u003eubq = ubq;\n \tpdu-\u003etag = tag;\n \tio_uring_cmd_mark_cancelable(cmd, issue_flags);\n+\t/* pairs with the cancel loading cmd from io-\u003ecmd, then cmd-\u003eflags */\n+\tsmp_wmb();\n }\n \n static void ublk_io_release(void *priv)\n@@ -3268,6 +3351,9 @@ static int ublk_check_fetch_buf(const struct ublk_device *ub, __u64 buf_addr)\n static int __ublk_fetch(struct io_uring_cmd *cmd, struct ublk_device *ub,\n \t\t\tstruct ublk_io *io, u16 q_id)\n {\n+\tif (test_bit(UB_STATE_STOPPING, \u0026ub-\u003estate))\n+\t\treturn UBLK_IO_RES_ABORT;\n+\n \t/* UBLK_IO_FETCH_REQ is only allowed before dev is setup */\n \tif (ublk_dev_ready(ub))\n \t\treturn -EBUSY;\n@@ -3411,11 +3497,11 @@ static int ublk_ch_uring_cmd_local(struct io_uring_cmd *cmd,\n \t\tret = ublk_check_fetch_buf(ub, addr);\n \t\tif (ret)\n \t\t\tgoto out;\n+\t\t/* before ublk_fetch() publishes io-\u003ecmd, see ublk_prep_cancel() */\n+\t\tublk_prep_cancel(cmd, issue_flags, ubq, tag);\n \t\tret = ublk_fetch(cmd, ub, io, addr, q_id);\n \t\tif (ret)\n-\t\t\tgoto out;\n-\n-\t\tublk_prep_cancel(cmd, issue_flags, ubq, tag);\n+\t\t\tgoto out_done;\n \t\treturn -EIOCBQUEUED;\n \t}\n \n@@ -3459,6 +3545,7 @@ static int ublk_ch_uring_cmd_local(struct io_uring_cmd *cmd,\n \t\tif (ret)\n \t\t\tgoto out;\n \t\tio-\u003eres = result;\n+\t\tublk_prep_cancel(cmd, issue_flags, ubq, tag);\n \t\treq = ublk_fill_io_cmd(io, cmd);\n \t\tublk_apply_io_buf(ub, io, cmd, addr, \u0026auto_buf, \u0026buf_idx);\n \t\tif (buf_idx != UBLK_INVALID_BUF_IDX)\n@@ -3477,19 +3564,24 @@ static int ublk_ch_uring_cmd_local(struct io_uring_cmd *cmd,\n \t\t * uring_cmd active first and prepare for handling new requeued\n \t\t * request\n \t\t */\n+\t\tublk_prep_cancel(cmd, issue_flags, ubq, tag);\n \t\treq = ublk_fill_io_cmd(io, cmd);\n \t\tio-\u003ebuf.addr = addr;\n \t\tif (likely(ublk_get_data(ubq, io, req))) {\n \t\t\t__ublk_prep_compl_io_cmd(io, req);\n-\t\t\treturn UBLK_IO_RES_OK;\n+\t\t\tret = UBLK_IO_RES_OK;\n+\t\t\tgoto out_done;\n \t\t}\n \t\tbreak;\n \tdefault:\n \t\tgoto out;\n \t}\n-\tublk_prep_cancel(cmd, issue_flags, ubq, tag);\n \treturn -EIOCBQUEUED;\n \n+ out_done:\n+\t/* marked cancelable: complete through io_uring_cmd_done() */\n+\tio_uring_cmd_done(cmd, ret, issue_flags);\n+\treturn -EIOCBQUEUED;\n  out:\n \tpr_devel(\"%s: complete: cmd op %d, tag %d ret %x io_flags %x\\n\",\n \t\t\t__func__, cmd_op, tag, ret, io ? io-\u003eflags : 0);\n@@ -3888,6 +3980,15 @@ static int ublk_batch_attach(struct ublk_queue *ubq,\n \tbool free = false;\n \tstruct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(data-\u003ecmd);\n \n+\t/*\n+\t * Mark it cancelable before linking it into fcmd_head, where a cancel\n+\t * from the control path can take and complete it: see\n+\t * ublk_prep_cancel(). evts_lock orders the mark before the link.\n+\t */\n+\tpdu-\u003eubq = ubq;\n+\tpdu-\u003efcmd = fcmd;\n+\tio_uring_cmd_mark_cancelable(fcmd-\u003ecmd, data-\u003eissue_flags);\n+\n \tspin_lock(\u0026ubq-\u003eevts_lock);\n \tif (unlikely(ubq-\u003eforce_abort || ubq-\u003ecanceling)) {\n \t\tfree = true;\n@@ -3898,14 +3999,12 @@ static int ublk_batch_attach(struct ublk_queue *ubq,\n \tspin_unlock(\u0026ubq-\u003eevts_lock);\n \n \tif (unlikely(free)) {\n+\t\t/* off the cancelable list first, then nothing can see fcmd */\n+\t\tio_uring_cmd_done(data-\u003ecmd, -ENODEV, data-\u003eissue_flags);\n \t\tublk_batch_free_fcmd(fcmd);\n-\t\treturn -ENODEV;\n+\t\treturn -EIOCBQUEUED;\n \t}\n \n-\tpdu-\u003eubq = ubq;\n-\tpdu-\u003efcmd = fcmd;\n-\tio_uring_cmd_mark_cancelable(fcmd-\u003ecmd, data-\u003eissue_flags);\n-\n \tif (!new_fcmd)\n \t\tgoto out;\n \n@@ -3913,9 +4012,12 @@ static int ublk_batch_attach(struct ublk_queue *ubq,\n \t * If the two fetch commands are originated from same io_ring_ctx,\n \t * run batch dispatch directly. Otherwise, schedule task work for\n \t * doing it.\n+\t *\n+\t * Use data-\u003ecmd, not fcmd-\u003ecmd: once fcmd is linked and not active,\n+\t * a cancel from the control path may complete and free it.\n \t */\n \tif (io_uring_cmd_ctx_handle(new_fcmd-\u003ecmd) ==\n-\t\t\tio_uring_cmd_ctx_handle(fcmd-\u003ecmd)) {\n+\t\t\tio_uring_cmd_ctx_handle(data-\u003ecmd)) {\n \t\tdata-\u003ecmd = new_fcmd-\u003ecmd;\n \t\tublk_batch_dispatch(ubq, data, new_fcmd);\n \t} else {\n@@ -4431,21 +4533,27 @@ static bool ublk_validate_user_pid(struct ublk_device *ub, pid_t ublksrv_pid)\n \treturn ub-\u003eublksrv_tgid == ublksrv_pid;\n }\n \n+static bool ublk_dev_ready_or_stopping(const struct ublk_device *ub)\n+{\n+\treturn ublk_dev_ready(ub) || test_bit(UB_STATE_STOPPING, \u0026ub-\u003estate);\n+}\n+\n /*\n- * Wait until all queues have fetched their I/O commands, and return with\n- * ub-\u003emutex held and readiness guaranteed: then every queue's -\u003ecanceling\n- * is cleared. Ready may regress between wakeup and mutex_lock() (F_BATCH\n- * UNPREP, daemon death), so re-check it under the mutex and wait again.\n+ * Wait until all queues have fetched their I/O commands, or STOP_DEV set\n+ * UB_STATE_STOPPING, and return with ub-\u003emutex held. The queues stay\n+ * canceling if this round saw a cancel, see ublk_queue_reset_io_flags().\n+ * Ready may regress between wakeup and mutex_lock() (F_BATCH UNPREP,\n+ * daemon death), so re-check it under the mutex and wait again.\n  */\n static int ublk_wait_dev_ready_and_lock(struct ublk_device *ub)\n {\n \twhile (true) {\n \t\tif (wait_var_event_interruptible(\u0026ub-\u003enr_queue_ready,\n-\t\t\t\t\t\t ublk_dev_ready(ub)))\n+\t\t\t\t\t\t ublk_dev_ready_or_stopping(ub)))\n \t\t\treturn -EINTR;\n \n \t\tmutex_lock(\u0026ub-\u003emutex);\n-\t\tif (ublk_dev_ready(ub))\n+\t\tif (ublk_dev_ready_or_stopping(ub))\n \t\t\treturn 0;\n \t\tmutex_unlock(\u0026ub-\u003emutex);\n \t}\n@@ -4469,6 +4577,7 @@ static int ublk_ctrl_start_dev(struct ublk_device *ub,\n \t\t.dma_alignment\t\t= 3,\n \t};\n \tstruct gendisk *disk;\n+\tbool canceled;\n \tint ret = -EINVAL;\n \n \tif (ublksrv_pid \u003c= 0)\n@@ -4545,6 +4654,10 @@ static int ublk_ctrl_start_dev(struct ublk_device *ub,\n \t\tret = -EEXIST;\n \t\tgoto out_unlock;\n \t}\n+\tif (test_bit(UB_STATE_STOPPING, \u0026ub-\u003estate)) {\n+\t\tret = -EBUSY;\n+\t\tgoto out_unlock;\n+\t}\n \n \tdisk = blk_mq_alloc_disk(\u0026ub-\u003etag_set, \u0026lim, NULL);\n \tif (IS_ERR(disk)) {\n@@ -4555,8 +4668,24 @@ static int ublk_ctrl_start_dev(struct ublk_device *ub,\n \tdisk-\u003efops = \u0026ub_fops;\n \tdisk-\u003eprivate_data = ub;\n \n+\t/*\n+\t * A command of this FETCH round was canceled and can't be fetched\n+\t * again, don't bring up a disk over it.  Check and publish the disk\n+\t * in one cancel_mutex section: either this sees ub-\u003ecanceling, or\n+\t * ublk_start_cancel() sees the disk and quiesces it before marking\n+\t * the queues.\n+\t */\n+\tmutex_lock(\u0026ub-\u003ecancel_mutex);\n+\tcanceled = ub-\u003ecanceling;\n+\tif (!canceled)\n+\t\tub-\u003eub_disk = disk;\n+\tmutex_unlock(\u0026ub-\u003ecancel_mutex);\n+\tif (canceled) {\n+\t\tput_disk(disk);\n+\t\tret = -EBUSY;\n+\t\tgoto out_unlock;\n+\t}\n \tub-\u003edev_info.ublksrv_pid = ub-\u003eublksrv_tgid;\n-\tub-\u003eub_disk = disk;\n \n \tublk_apply_params(ub);\n \n@@ -5133,6 +5262,7 @@ static int ublk_ctrl_end_recovery(struct ublk_device *ub,\n \t\tconst struct ublksrv_ctrl_cmd *header)\n {\n \tint ublksrv_pid = (int)header-\u003edata[0];\n+\tbool canceled;\n \tint ret = -EINVAL;\n \n \tpr_devel(\"%s: Waiting for all FETCH_REQs, dev id %d...\\n\", __func__,\n@@ -5156,6 +5286,20 @@ static int ublk_ctrl_end_recovery(struct ublk_device *ub,\n \t\tret = -EBUSY;\n \t\tgoto out_unlock;\n \t}\n+\n+\t/*\n+\t * As in ublk_ctrl_start_dev(), a canceled command can't be fetched\n+\t * again.  Best effort: the disk exists here, and a cancel after this\n+\t * check is the ordinary death of the new server, which\n+\t * ublk_start_cancel() handles by quiescing and marking.\n+\t */\n+\tmutex_lock(\u0026ub-\u003ecancel_mutex);\n+\tcanceled = ub-\u003ecanceling;\n+\tmutex_unlock(\u0026ub-\u003ecancel_mutex);\n+\tif (canceled) {\n+\t\tret = -EBUSY;\n+\t\tgoto out_unlock;\n+\t}\n \tub-\u003edev_info.ublksrv_pid = ub-\u003eublksrv_tgid;\n \tub-\u003edev_info.state = UBLK_S_DEV_LIVE;\n \tpr_devel(\"%s: new ublksrv_pid %d, dev id %d\\n\",\ndiff --git a/tools/testing/selftests/ublk/.gitignore b/tools/testing/selftests/ublk/.gitignore\nindex e17bd28f27e04..d8e93fef7fcd3 100644\n--- a/tools/testing/selftests/ublk/.gitignore\n+++ b/tools/testing/selftests/ublk/.gitignore\n@@ -3,3 +3,4 @@\n /tools\n kublk\n metadata_size\n+ublk_cancel_ready\ndiff --git a/tools/testing/selftests/ublk/Makefile b/tools/testing/selftests/ublk/Makefile\nindex 5daf36c6c36c4..0d7c3dd9812ed 100644\n--- a/tools/testing/selftests/ublk/Makefile\n+++ b/tools/testing/selftests/ublk/Makefile\n@@ -19,6 +19,7 @@ TEST_PROGS += test_generic_12.sh\n TEST_PROGS += test_generic_13.sh\n TEST_PROGS += test_generic_16.sh\n TEST_PROGS += test_generic_17.sh\n+TEST_PROGS += test_generic_18.sh\n \n TEST_PROGS += test_batch_01.sh\n TEST_PROGS += test_batch_02.sh\n@@ -74,13 +75,14 @@ TEST_PROGS += test_stress_09.sh\n \n TEST_FILES := settings\n \n-TEST_GEN_PROGS_EXTENDED = kublk metadata_size\n-STANDALONE_UTILS := metadata_size.c\n+TEST_GEN_PROGS_EXTENDED = kublk metadata_size ublk_cancel_ready\n+STANDALONE_UTILS := metadata_size.c ublk_cancel_ready.c\n \n LOCAL_HDRS += $(wildcard *.h)\n include ../lib.mk\n \n $(OUTPUT)/kublk: $(filter-out $(STANDALONE_UTILS),$(wildcard *.c))\n+$(OUTPUT)/ublk_cancel_ready: ublk_cancel_ready.c ctrl.c\n \n check:\n \tshellcheck -x -f gcc *.sh\ndiff --git a/tools/testing/selftests/ublk/batch.c b/tools/testing/selftests/ublk/batch.c\nindex d8d9ebed5979f..dfc81ee17d076 100644\n--- a/tools/testing/selftests/ublk/batch.c\n+++ b/tools/testing/selftests/ublk/batch.c\n@@ -410,9 +410,16 @@ static void ublk_batch_compl_commit_cmd(struct ublk_thread *t,\n {\n \tunsigned short buf_idx = user_data_to_tag(cqe-\u003euser_data);\n \n-\tif (op == _IOC_NR(UBLK_U_IO_PREP_IO_CMDS))\n-\t\tublk_assert(cqe-\u003eres == 0);\n-\telse if (op == _IOC_NR(UBLK_U_IO_COMMIT_IO_CMDS)) {\n+\tif (op == _IOC_NR(UBLK_U_IO_PREP_IO_CMDS)) {\n+\t\t/* e.g. UBLK_IO_RES_ABORT after STOP_DEV: stop like a FETCH */\n+\t\tif (cqe-\u003eres \u003c 0) {\n+\t\t\tublk_dbg(UBLK_DBG_IO_CMD, \"%s: prep failed %d\\n\",\n+\t\t\t\t __func__, cqe-\u003eres);\n+\t\t\tt-\u003estate |= UBLKS_T_STOPPING;\n+\t\t} else {\n+\t\t\tublk_assert(cqe-\u003eres == 0);\n+\t\t}\n+\t} else if (op == _IOC_NR(UBLK_U_IO_COMMIT_IO_CMDS)) {\n \t\tint nr_elem = user_data_to_tgt_data(cqe-\u003euser_data);\n \n \t\tublk_assert(cqe-\u003eres == t-\u003ecommit_buf_elem_size * nr_elem);\ndiff --git a/tools/testing/selftests/ublk/ctrl.c b/tools/testing/selftests/ublk/ctrl.c\nnew file mode 100644\nindex 0000000000000..53d54799f9097\n--- /dev/null\n+++ b/tools/testing/selftests/ublk/ctrl.c\n@@ -0,0 +1,268 @@\n+// SPDX-License-Identifier: GPL-2.0\n+\n+/* ublk control commands, shared by kublk and ublk_cancel_ready */\n+\n+#include \"kublk.h\"\n+\n+static void ublk_ctrl_init_cmd(struct ublk_dev *dev,\n+\t\tstruct io_uring_sqe *sqe,\n+\t\tstruct ublk_ctrl_cmd_data *data)\n+{\n+\tstruct ublksrv_ctrl_dev_info *info = \u0026dev-\u003edev_info;\n+\tstruct ublksrv_ctrl_cmd *cmd = (struct ublksrv_ctrl_cmd *)ublk_get_sqe_cmd(sqe);\n+\n+\tsqe-\u003efd = dev-\u003ectrl_fd;\n+\tsqe-\u003eopcode = IORING_OP_URING_CMD;\n+\tsqe-\u003eioprio = 0;\n+\n+\tif (data-\u003eflags \u0026 CTRL_CMD_HAS_BUF) {\n+\t\tcmd-\u003eaddr = data-\u003eaddr;\n+\t\tcmd-\u003elen = data-\u003elen;\n+\t}\n+\n+\tif (data-\u003eflags \u0026 CTRL_CMD_HAS_DATA)\n+\t\tcmd-\u003edata[0] = data-\u003edata[0];\n+\n+\tcmd-\u003edev_id = info-\u003edev_id;\n+\tcmd-\u003equeue_id = -1;\n+\n+\tublk_set_sqe_cmd_op(sqe, data-\u003ecmd_op);\n+\n+\tio_uring_sqe_set_data(sqe, cmd);\n+}\n+\n+int __ublk_ctrl_cmd(struct ublk_dev *dev,\n+\t\tstruct ublk_ctrl_cmd_data *data)\n+{\n+\tstruct io_uring_sqe *sqe;\n+\tstruct io_uring_cqe *cqe;\n+\tint ret = -EINVAL;\n+\n+\tsqe = io_uring_get_sqe(\u0026dev-\u003ering);\n+\tif (!sqe) {\n+\t\tublk_err(\"%s: can't get sqe ret %d\\n\", __func__, ret);\n+\t\treturn ret;\n+\t}\n+\n+\tublk_ctrl_init_cmd(dev, sqe, data);\n+\n+\tret = io_uring_submit(\u0026dev-\u003ering);\n+\tif (ret \u003c 0) {\n+\t\tublk_err(\"uring submit ret %d\\n\", ret);\n+\t\treturn ret;\n+\t}\n+\n+\tret = io_uring_wait_cqe(\u0026dev-\u003ering, \u0026cqe);\n+\tif (ret \u003c 0) {\n+\t\tublk_err(\"wait cqe: %s\\n\", strerror(-ret));\n+\t\treturn ret;\n+\t}\n+\tio_uring_cqe_seen(\u0026dev-\u003ering, cqe);\n+\n+\treturn cqe-\u003eres;\n+}\n+\n+void ublk_ctrl_deinit(struct ublk_dev *dev)\n+{\n+\tio_uring_queue_exit(\u0026dev-\u003ering);\n+\tclose(dev-\u003ectrl_fd);\n+\tfree(dev);\n+}\n+\n+struct ublk_dev *ublk_ctrl_init(void)\n+{\n+\tstruct ublk_dev *dev = (struct ublk_dev *)calloc(1, sizeof(*dev));\n+\tstruct ublksrv_ctrl_dev_info *info;\n+\tint ret;\n+\n+\tif (!dev)\n+\t\treturn NULL;\n+\tinfo = \u0026dev-\u003edev_info;\n+\tdev-\u003ectrl_fd = open(CTRL_DEV, O_RDWR);\n+\tif (dev-\u003ectrl_fd \u003c 0) {\n+\t\tfree(dev);\n+\t\treturn NULL;\n+\t}\n+\n+\tinfo-\u003emax_io_buf_bytes = UBLK_IO_MAX_BYTES;\n+\n+\tret = ublk_setup_ring(\u0026dev-\u003ering, UBLK_CTRL_RING_DEPTH,\n+\t\t\tUBLK_CTRL_RING_DEPTH, IORING_SETUP_SQE128);\n+\tif (ret \u003c 0) {\n+\t\tublk_err(\"queue_init: %s\\n\", strerror(-ret));\n+\t\tclose(dev-\u003ectrl_fd);\n+\t\tfree(dev);\n+\t\treturn NULL;\n+\t}\n+\tdev-\u003enr_fds = 1;\n+\n+\treturn dev;\n+}\n+\n+int ublk_ctrl_stop_dev(struct ublk_dev *dev)\n+{\n+\tstruct ublk_ctrl_cmd_data data = {\n+\t\t.cmd_op\t= UBLK_U_CMD_STOP_DEV,\n+\t};\n+\n+\treturn __ublk_ctrl_cmd(dev, \u0026data);\n+}\n+\n+int ublk_ctrl_try_stop_dev(struct ublk_dev *dev)\n+{\n+\tstruct ublk_ctrl_cmd_data data = {\n+\t\t.cmd_op\t= UBLK_U_CMD_TRY_STOP_DEV,\n+\t};\n+\n+\treturn __ublk_ctrl_cmd(dev, \u0026data);\n+}\n+\n+int ublk_ctrl_start_dev(struct ublk_dev *dev,\n+\t\tint daemon_pid)\n+{\n+\tstruct ublk_ctrl_cmd_data data = {\n+\t\t.cmd_op\t= UBLK_U_CMD_START_DEV,\n+\t\t.flags\t= CTRL_CMD_HAS_DATA,\n+\t};\n+\n+\tdev-\u003edev_info.ublksrv_pid = data.data[0] = daemon_pid;\n+\n+\treturn __ublk_ctrl_cmd(dev, \u0026data);\n+}\n+\n+int ublk_ctrl_start_user_recovery(struct ublk_dev *dev)\n+{\n+\tstruct ublk_ctrl_cmd_data data = {\n+\t\t.cmd_op\t= UBLK_U_CMD_START_USER_RECOVERY,\n+\t};\n+\n+\treturn __ublk_ctrl_cmd(dev, \u0026data);\n+}\n+\n+int ublk_ctrl_end_user_recovery(struct ublk_dev *dev, int daemon_pid)\n+{\n+\tstruct ublk_ctrl_cmd_data data = {\n+\t\t.cmd_op\t= UBLK_U_CMD_END_USER_RECOVERY,\n+\t\t.flags\t= CTRL_CMD_HAS_DATA,\n+\t};\n+\n+\tdev-\u003edev_info.ublksrv_pid = data.data[0] = daemon_pid;\n+\n+\treturn __ublk_ctrl_cmd(dev, \u0026data);\n+}\n+\n+int ublk_ctrl_add_dev(struct ublk_dev *dev)\n+{\n+\tstruct ublk_ctrl_cmd_data data = {\n+\t\t.cmd_op\t= UBLK_U_CMD_ADD_DEV,\n+\t\t.flags\t= CTRL_CMD_HAS_BUF,\n+\t\t.addr = (__u64) (uintptr_t) \u0026dev-\u003edev_info,\n+\t\t.len = sizeof(struct ublksrv_ctrl_dev_info),\n+\t};\n+\n+\treturn __ublk_ctrl_cmd(dev, \u0026data);\n+}\n+\n+int ublk_ctrl_del_dev(struct ublk_dev *dev)\n+{\n+\tstruct ublk_ctrl_cmd_data data = {\n+\t\t.cmd_op = UBLK_U_CMD_DEL_DEV,\n+\t\t.flags = 0,\n+\t};\n+\n+\treturn __ublk_ctrl_cmd(dev, \u0026data);\n+}\n+\n+int ublk_ctrl_get_info(struct ublk_dev *dev)\n+{\n+\tstruct ublk_ctrl_cmd_data data = {\n+\t\t.cmd_op\t= UBLK_U_CMD_GET_DEV_INFO,\n+\t\t.flags\t= CTRL_CMD_HAS_BUF,\n+\t\t.addr = (__u64) (uintptr_t) \u0026dev-\u003edev_info,\n+\t\t.len = sizeof(struct ublksrv_ctrl_dev_info),\n+\t};\n+\n+\treturn __ublk_ctrl_cmd(dev, \u0026data);\n+}\n+\n+int ublk_ctrl_set_params(struct ublk_dev *dev,\n+\t\tstruct ublk_params *params)\n+{\n+\tstruct ublk_ctrl_cmd_data data = {\n+\t\t.cmd_op\t= UBLK_U_CMD_SET_PARAMS,\n+\t\t.flags\t= CTRL_CMD_HAS_BUF,\n+\t\t.addr = (__u64) (uintptr_t) params,\n+\t\t.len = sizeof(*params),\n+\t};\n+\tparams-\u003elen = sizeof(*params);\n+\treturn __ublk_ctrl_cmd(dev, \u0026data);\n+}\n+\n+int ublk_ctrl_get_params(struct ublk_dev *dev,\n+\t\tstruct ublk_params *params)\n+{\n+\tstruct ublk_ctrl_cmd_data data = {\n+\t\t.cmd_op\t= UBLK_U_CMD_GET_PARAMS,\n+\t\t.flags\t= CTRL_CMD_HAS_BUF,\n+\t\t.addr = (__u64)params,\n+\t\t.len = sizeof(*params),\n+\t};\n+\n+\tparams-\u003elen = sizeof(*params);\n+\n+\treturn __ublk_ctrl_cmd(dev, \u0026data);\n+}\n+\n+int ublk_ctrl_get_features(struct ublk_dev *dev,\n+\t\t__u64 *features)\n+{\n+\tstruct ublk_ctrl_cmd_data data = {\n+\t\t.cmd_op\t= UBLK_U_CMD_GET_FEATURES,\n+\t\t.flags\t= CTRL_CMD_HAS_BUF,\n+\t\t.addr = (__u64) (uintptr_t) features,\n+\t\t.len = sizeof(*features),\n+\t};\n+\n+\treturn __ublk_ctrl_cmd(dev, \u0026data);\n+}\n+\n+int ublk_ctrl_update_size(struct ublk_dev *dev,\n+\t\t__u64 nr_sects)\n+{\n+\tstruct ublk_ctrl_cmd_data data = {\n+\t\t.cmd_op\t= UBLK_U_CMD_UPDATE_SIZE,\n+\t\t.flags\t= CTRL_CMD_HAS_DATA,\n+\t};\n+\n+\tdata.data[0] = nr_sects;\n+\treturn __ublk_ctrl_cmd(dev, \u0026data);\n+}\n+\n+int ublk_ctrl_quiesce_dev(struct ublk_dev *dev, unsigned int timeout_ms)\n+{\n+\tstruct ublk_ctrl_cmd_data data = {\n+\t\t.cmd_op\t= UBLK_U_CMD_QUIESCE_DEV,\n+\t\t.flags\t= CTRL_CMD_HAS_DATA,\n+\t};\n+\n+\tdata.data[0] = timeout_ms;\n+\treturn __ublk_ctrl_cmd(dev, \u0026data);\n+}\n+\n+int ublk_ctrl_reg_buf(struct ublk_dev *dev, void *addr, size_t size,\n+\t\t      __u32 flags)\n+{\n+\tstruct ublk_shmem_buf_reg buf_reg = {\n+\t\t.addr = (unsigned long)addr,\n+\t\t.len = size,\n+\t\t.flags = flags,\n+\t};\n+\tstruct ublk_ctrl_cmd_data data = {\n+\t\t.cmd_op = UBLK_U_CMD_REG_BUF,\n+\t\t.flags = CTRL_CMD_HAS_BUF,\n+\t\t.addr = (unsigned long)\u0026buf_reg,\n+\t\t.len = sizeof(buf_reg),\n+\t};\n+\n+\treturn __ublk_ctrl_cmd(dev, \u0026data);\n+}\ndiff --git a/tools/testing/selftests/ublk/kublk.c b/tools/testing/selftests/ublk/kublk.c\nindex 2400b46157664..15ba060ce7a3c 100644\n--- a/tools/testing/selftests/ublk/kublk.c\n+++ b/tools/testing/selftests/ublk/kublk.c\n@@ -37,203 +37,6 @@ static const struct ublk_tgt_ops *ublk_find_tgt(const char *name)\n \treturn NULL;\n }\n \n-static inline int ublk_setup_ring(struct io_uring *r, int depth,\n-\t\tint cq_depth, unsigned flags)\n-{\n-\tstruct io_uring_params p;\n-\n-\tmemset(\u0026p, 0, sizeof(p));\n-\tp.flags = flags | IORING_SETUP_CQSIZE;\n-\tp.cq_entries = cq_depth;\n-\n-\treturn io_uring_queue_init_params(depth, r, \u0026p);\n-}\n-\n-static void ublk_ctrl_init_cmd(struct ublk_dev *dev,\n-\t\tstruct io_uring_sqe *sqe,\n-\t\tstruct ublk_ctrl_cmd_data *data)\n-{\n-\tstruct ublksrv_ctrl_dev_info *info = \u0026dev-\u003edev_info;\n-\tstruct ublksrv_ctrl_cmd *cmd = (struct ublksrv_ctrl_cmd *)ublk_get_sqe_cmd(sqe);\n-\n-\tsqe-\u003efd = dev-\u003ectrl_fd;\n-\tsqe-\u003eopcode = IORING_OP_URING_CMD;\n-\tsqe-\u003eioprio = 0;\n-\n-\tif (data-\u003eflags \u0026 CTRL_CMD_HAS_BUF) {\n-\t\tcmd-\u003eaddr = data-\u003eaddr;\n-\t\tcmd-\u003elen = data-\u003elen;\n-\t}\n-\n-\tif (data-\u003eflags \u0026 CTRL_CMD_HAS_DATA)\n-\t\tcmd-\u003edata[0] = data-\u003edata[0];\n-\n-\tcmd-\u003edev_id = info-\u003edev_id;\n-\tcmd-\u003equeue_id = -1;\n-\n-\tublk_set_sqe_cmd_op(sqe, data-\u003ecmd_op);\n-\n-\tio_uring_sqe_set_data(sqe, cmd);\n-}\n-\n-static int __ublk_ctrl_cmd(struct ublk_dev *dev,\n-\t\tstruct ublk_ctrl_cmd_data *data)\n-{\n-\tstruct io_uring_sqe *sqe;\n-\tstruct io_uring_cqe *cqe;\n-\tint ret = -EINVAL;\n-\n-\tsqe = io_uring_get_sqe(\u0026dev-\u003ering);\n-\tif (!sqe) {\n-\t\tublk_err(\"%s: can't get sqe ret %d\\n\", __func__, ret);\n-\t\treturn ret;\n-\t}\n-\n-\tublk_ctrl_init_cmd(dev, sqe, data);\n-\n-\tret = io_uring_submit(\u0026dev-\u003ering);\n-\tif (ret \u003c 0) {\n-\t\tublk_err(\"uring submit ret %d\\n\", ret);\n-\t\treturn ret;\n-\t}\n-\n-\tret = io_uring_wait_cqe(\u0026dev-\u003ering, \u0026cqe);\n-\tif (ret \u003c 0) {\n-\t\tublk_err(\"wait cqe: %s\\n\", strerror(-ret));\n-\t\treturn ret;\n-\t}\n-\tio_uring_cqe_seen(\u0026dev-\u003ering, cqe);\n-\n-\treturn cqe-\u003eres;\n-}\n-\n-static int ublk_ctrl_stop_dev(struct ublk_dev *dev)\n-{\n-\tstruct ublk_ctrl_cmd_data data = {\n-\t\t.cmd_op\t= UBLK_U_CMD_STOP_DEV,\n-\t};\n-\n-\treturn __ublk_ctrl_cmd(dev, \u0026data);\n-}\n-\n-static int ublk_ctrl_try_stop_dev(struct ublk_dev *dev)\n-{\n-\tstruct ublk_ctrl_cmd_data data = {\n-\t\t.cmd_op\t= UBLK_U_CMD_TRY_STOP_DEV,\n-\t};\n-\n-\treturn __ublk_ctrl_cmd(dev, \u0026data);\n-}\n-\n-static int ublk_ctrl_start_dev(struct ublk_dev *dev,\n-\t\tint daemon_pid)\n-{\n-\tstruct ublk_ctrl_cmd_data data = {\n-\t\t.cmd_op\t= UBLK_U_CMD_START_DEV,\n-\t\t.flags\t= CTRL_CMD_HAS_DATA,\n-\t};\n-\n-\tdev-\u003edev_info.ublksrv_pid = data.data[0] = daemon_pid;\n-\n-\treturn __ublk_ctrl_cmd(dev, \u0026data);\n-}\n-\n-static int ublk_ctrl_start_user_recovery(struct ublk_dev *dev)\n-{\n-\tstruct ublk_ctrl_cmd_data data = {\n-\t\t.cmd_op\t= UBLK_U_CMD_START_USER_RECOVERY,\n-\t};\n-\n-\treturn __ublk_ctrl_cmd(dev, \u0026data);\n-}\n-\n-static int ublk_ctrl_end_user_recovery(struct ublk_dev *dev, int daemon_pid)\n-{\n-\tstruct ublk_ctrl_cmd_data data = {\n-\t\t.cmd_op\t= UBLK_U_CMD_END_USER_RECOVERY,\n-\t\t.flags\t= CTRL_CMD_HAS_DATA,\n-\t};\n-\n-\tdev-\u003edev_info.ublksrv_pid = data.data[0] = daemon_pid;\n-\n-\treturn __ublk_ctrl_cmd(dev, \u0026data);\n-}\n-\n-static int ublk_ctrl_add_dev(struct ublk_dev *dev)\n-{\n-\tstruct ublk_ctrl_cmd_data data = {\n-\t\t.cmd_op\t= UBLK_U_CMD_ADD_DEV,\n-\t\t.flags\t= CTRL_CMD_HAS_BUF,\n-\t\t.addr = (__u64) (uintptr_t) \u0026dev-\u003edev_info,\n-\t\t.len = sizeof(struct ublksrv_ctrl_dev_info),\n-\t};\n-\n-\treturn __ublk_ctrl_cmd(dev, \u0026data);\n-}\n-\n-static int ublk_ctrl_del_dev(struct ublk_dev *dev)\n-{\n-\tstruct ublk_ctrl_cmd_data data = {\n-\t\t.cmd_op = UBLK_U_CMD_DEL_DEV,\n-\t\t.flags = 0,\n-\t};\n-\n-\treturn __ublk_ctrl_cmd(dev, \u0026data);\n-}\n-\n-static int ublk_ctrl_get_info(struct ublk_dev *dev)\n-{\n-\tstruct ublk_ctrl_cmd_data data = {\n-\t\t.cmd_op\t= UBLK_U_CMD_GET_DEV_INFO,\n-\t\t.flags\t= CTRL_CMD_HAS_BUF,\n-\t\t.addr = (__u64) (uintptr_t) \u0026dev-\u003edev_info,\n-\t\t.len = sizeof(struct ublksrv_ctrl_dev_info),\n-\t};\n-\n-\treturn __ublk_ctrl_cmd(dev, \u0026data);\n-}\n-\n-static int ublk_ctrl_set_params(struct ublk_dev *dev,\n-\t\tstruct ublk_params *params)\n-{\n-\tstruct ublk_ctrl_cmd_data data = {\n-\t\t.cmd_op\t= UBLK_U_CMD_SET_PARAMS,\n-\t\t.flags\t= CTRL_CMD_HAS_BUF,\n-\t\t.addr = (__u64) (uintptr_t) params,\n-\t\t.len = sizeof(*params),\n-\t};\n-\tparams-\u003elen = sizeof(*params);\n-\treturn __ublk_ctrl_cmd(dev, \u0026data);\n-}\n-\n-static int ublk_ctrl_get_params(struct ublk_dev *dev,\n-\t\tstruct ublk_params *params)\n-{\n-\tstruct ublk_ctrl_cmd_data data = {\n-\t\t.cmd_op\t= UBLK_U_CMD_GET_PARAMS,\n-\t\t.flags\t= CTRL_CMD_HAS_BUF,\n-\t\t.addr = (__u64)params,\n-\t\t.len = sizeof(*params),\n-\t};\n-\n-\tparams-\u003elen = sizeof(*params);\n-\n-\treturn __ublk_ctrl_cmd(dev, \u0026data);\n-}\n-\n-static int ublk_ctrl_get_features(struct ublk_dev *dev,\n-\t\t__u64 *features)\n-{\n-\tstruct ublk_ctrl_cmd_data data = {\n-\t\t.cmd_op\t= UBLK_U_CMD_GET_FEATURES,\n-\t\t.flags\t= CTRL_CMD_HAS_BUF,\n-\t\t.addr = (__u64) (uintptr_t) features,\n-\t\t.len = sizeof(*features),\n-\t};\n-\n-\treturn __ublk_ctrl_cmd(dev, \u0026data);\n-}\n-\n static int parse_param_types(const char *arg, __u32 *types)\n {\n \tchar buf[128], *save = NULL, *tok;\n@@ -283,30 +86,6 @@ static void ublk_init_params_from_ctx(const struct dev_ctx *ctx,\n \t};\n }\n \n-static int ublk_ctrl_update_size(struct ublk_dev *dev,\n-\t\t__u64 nr_sects)\n-{\n-\tstruct ublk_ctrl_cmd_data data = {\n-\t\t.cmd_op\t= UBLK_U_CMD_UPDATE_SIZE,\n-\t\t.flags\t= CTRL_CMD_HAS_DATA,\n-\t};\n-\n-\tdata.data[0] = nr_sects;\n-\treturn __ublk_ctrl_cmd(dev, \u0026data);\n-}\n-\n-static int ublk_ctrl_quiesce_dev(struct ublk_dev *dev,\n-\t\t\t\t unsigned int timeout_ms)\n-{\n-\tstruct ublk_ctrl_cmd_data data = {\n-\t\t.cmd_op\t= UBLK_U_CMD_QUIESCE_DEV,\n-\t\t.flags\t= CTRL_CMD_HAS_DATA,\n-\t};\n-\n-\tdata.data[0] = timeout_ms;\n-\treturn __ublk_ctrl_cmd(dev, \u0026data);\n-}\n-\n static const char *ublk_dev_state_desc(struct ublk_dev *dev)\n {\n \tswitch (dev-\u003edev_info.state) {\n@@ -426,38 +205,6 @@ static void ublk_ctrl_dump(struct ublk_dev *dev)\n \tfflush(stdout);\n }\n \n-static void ublk_ctrl_deinit(struct ublk_dev *dev)\n-{\n-\tclose(dev-\u003ectrl_fd);\n-\tfree(dev);\n-}\n-\n-static struct ublk_dev *ublk_ctrl_init(void)\n-{\n-\tstruct ublk_dev *dev = (struct ublk_dev *)calloc(1, sizeof(*dev));\n-\tstruct ublksrv_ctrl_dev_info *info = \u0026dev-\u003edev_info;\n-\tint ret;\n-\n-\tdev-\u003ectrl_fd = open(CTRL_DEV, O_RDWR);\n-\tif (dev-\u003ectrl_fd \u003c 0) {\n-\t\tfree(dev);\n-\t\treturn NULL;\n-\t}\n-\n-\tinfo-\u003emax_io_buf_bytes = UBLK_IO_MAX_BYTES;\n-\n-\tret = ublk_setup_ring(\u0026dev-\u003ering, UBLK_CTRL_RING_DEPTH,\n-\t\t\tUBLK_CTRL_RING_DEPTH, IORING_SETUP_SQE128);\n-\tif (ret \u003c 0) {\n-\t\tublk_err(\"queue_init: %s\\n\", strerror(-ret));\n-\t\tfree(dev);\n-\t\treturn NULL;\n-\t}\n-\tdev-\u003enr_fds = 1;\n-\n-\treturn dev;\n-}\n-\n static size_t __ublk_queue_cmd_buf_sz(const struct ublk_queue *q, __u16 depth)\n {\n \tsize_t size = depth * (size_t)q-\u003eio_desc_size;\n@@ -1283,24 +1030,6 @@ static void ublk_shmem_unregister_all(void)\n \tshmem_count = 0;\n }\n \n-static int ublk_ctrl_reg_buf(struct ublk_dev *dev, void *addr, size_t size,\n-\t\t\t     __u32 flags)\n-{\n-\tstruct ublk_shmem_buf_reg buf_reg = {\n-\t\t.addr = (unsigned long)addr,\n-\t\t.len = size,\n-\t\t.flags = flags,\n-\t};\n-\tstruct ublk_ctrl_cmd_data data = {\n-\t\t.cmd_op = UBLK_U_CMD_REG_BUF,\n-\t\t.flags = CTRL_CMD_HAS_BUF,\n-\t\t.addr = (unsigned long)\u0026buf_reg,\n-\t\t.len = sizeof(buf_reg),\n-\t};\n-\n-\treturn __ublk_ctrl_cmd(dev, \u0026data);\n-}\n-\n /*\n  * Handle one client connection: receive memfd, mmap it, register\n  * the VA range with kernel, send back the assigned index.\ndiff --git a/tools/testing/selftests/ublk/kublk.h b/tools/testing/selftests/ublk/kublk.h\nindex d98f3d612d888..99b8ceff853cb 100644\n--- a/tools/testing/selftests/ublk/kublk.h\n+++ b/tools/testing/selftests/ublk/kublk.h\n@@ -294,6 +294,38 @@ struct ublk_dev {\n \n extern int ublk_queue_io_cmd(struct ublk_thread *t, struct ublk_io *io);\n \n+static inline int ublk_setup_ring(struct io_uring *r, int depth,\n+\t\tint cq_depth, unsigned int flags)\n+{\n+\tstruct io_uring_params p;\n+\n+\tmemset(\u0026p, 0, sizeof(p));\n+\tp.flags = flags | IORING_SETUP_CQSIZE;\n+\tp.cq_entries = cq_depth;\n+\n+\treturn io_uring_queue_init_params(depth, r, \u0026p);\n+}\n+\n+/* ctrl.c: control commands */\n+struct ublk_dev *ublk_ctrl_init(void);\n+void ublk_ctrl_deinit(struct ublk_dev *dev);\n+int __ublk_ctrl_cmd(struct ublk_dev *dev, struct ublk_ctrl_cmd_data *data);\n+int ublk_ctrl_add_dev(struct ublk_dev *dev);\n+int ublk_ctrl_del_dev(struct ublk_dev *dev);\n+int ublk_ctrl_get_info(struct ublk_dev *dev);\n+int ublk_ctrl_set_params(struct ublk_dev *dev, struct ublk_params *params);\n+int ublk_ctrl_get_params(struct ublk_dev *dev, struct ublk_params *params);\n+int ublk_ctrl_get_features(struct ublk_dev *dev, __u64 *features);\n+int ublk_ctrl_start_dev(struct ublk_dev *dev, int daemon_pid);\n+int ublk_ctrl_stop_dev(struct ublk_dev *dev);\n+int ublk_ctrl_try_stop_dev(struct ublk_dev *dev);\n+int ublk_ctrl_start_user_recovery(struct ublk_dev *dev);\n+int ublk_ctrl_end_user_recovery(struct ublk_dev *dev, int daemon_pid);\n+int ublk_ctrl_update_size(struct ublk_dev *dev, __u64 nr_sects);\n+int ublk_ctrl_quiesce_dev(struct ublk_dev *dev, unsigned int timeout_ms);\n+int ublk_ctrl_reg_buf(struct ublk_dev *dev, void *addr, size_t size,\n+\t\t      __u32 flags);\n+\n static inline int __ublk_use_batch_io(__u64 flags)\n {\n \treturn flags \u0026 UBLK_F_BATCH_IO;\ndiff --git a/tools/testing/selftests/ublk/test_generic_18.sh b/tools/testing/selftests/ublk/test_generic_18.sh\nnew file mode 100755\nindex 0000000000000..2dbb59e238a41\n--- /dev/null\n+++ b/tools/testing/selftests/ublk/test_generic_18.sh\n@@ -0,0 +1,69 @@\n+#!/bin/bash\n+# SPDX-License-Identifier: GPL-2.0\n+\n+. \"$(cd \"$(dirname \"$0\")\" \u0026\u0026 pwd)\"/test_common.sh\n+\n+ERR_CODE=0\n+CANCEL_PROG=\"$(_ublk_test_top_dir)/ublk_cancel_ready\"\n+\n+_prep_test \"generic\" \"start device over canceled io commands\"\n+\n+# STOP_DEV while kublk's UBLK_F_BATCH_IO server prepares and fetches: the\n+# server has to fail cleanly when PREP or FETCH is aborted, so `kublk add`\n+# must return either way.\n+race_batch_stop()\n+{\n+\tlocal id=9999 i res started=0\n+\n+\t_have_feature \"BATCH_IO\" || return \"$UBLK_SKIP_CODE\"\n+\tfor i in $(seq 1 20); do\n+\t\ttimeout 20 \"$UBLK_PROG\" add -t null -q 2 -b -n \"$id\" \u003e /dev/null 2\u003e\u00261 \u0026\n+\t\tlocal pid=$!\n+\t\t# vary where STOP_DEV lands relative to the batch PREP and FETCH\n+\t\tsleep \"0.$((i % 10))\"\n+\t\t\"$UBLK_PROG\" stop -n \"$id\" \u003e /dev/null 2\u003e\u00261\n+\t\twait \"$pid\"\n+\t\tres=$?\n+\t\t\"$UBLK_PROG\" del -n \"$id\" \u003e /dev/null 2\u003e\u00261\n+\t\tif [ \"$res\" -eq 124 ]; then\n+\t\t\techo \"run $i: kublk add -b hung after STOP_DEV\"\n+\t\t\treturn 255\n+\t\tfi\n+\t\t[ \"$res\" -eq 0 ] \u0026\u0026 started=$((started + 1))\n+\tdone\n+\techo \"20 runs: started $started, stopped before start $((20 - started))\"\n+}\n+\n+# race_batch_stop is above, the other modes are described in\n+# ublk_cancel_ready.c\n+for mode in stop_start partial_fetch recovery stop_restart stop_attached \\\n+\t\tstop_live_restart race_start race_fetch race_async_fetch \\\n+\t\trace_batch_stop; do\n+\tdmesg_before=$(dmesg | wc -l)\n+\tif [ \"$mode\" = race_batch_stop ]; then\n+\t\trace_batch_stop \u003e \"$UBLK_TMP\" 2\u003e\u00261\n+\telse\n+\t\ttimeout 60 \"$CANCEL_PROG\" \"$mode\" \u003e \"$UBLK_TMP\" 2\u003e\u00261\n+\tfi\n+\tres=$?\n+\tmsg=\"\"\n+\n+\tif dmesg | tail -n +\"$((dmesg_before + 1))\" | \\\n+\t\t\tgrep -q -e \"BUG:\" -e \"Oops\" -e \"WARNING:\"; then\n+\t\tmsg=\"$mode: kernel oops/warning\"\n+\t\tERR_CODE=255\n+\telif [ \"$res\" -eq \"$UBLK_SKIP_CODE\" ]; then\n+\t\t[ \"$ERR_CODE\" -eq 0 ] \u0026\u0026 ERR_CODE=$UBLK_SKIP_CODE\n+\telif [ \"$res\" -ne 0 ]; then\n+\t\tmsg=\"$mode: failed ($res)\"\n+\t\tERR_CODE=255\n+\tfi\n+\t# the output once: on failure, or always when not quiet\n+\t[ -n \"$msg\" ] \u0026\u0026 echo \"$msg\"\n+\tif [ -n \"$msg\" ] || [ \"$UBLK_TEST_QUIET\" -eq 0 ]; then\n+\t\tcat \"$UBLK_TMP\"\n+\tfi\n+done\n+\n+_cleanup_test\n+_show_result $TID $ERR_CODE\ndiff --git a/tools/testing/selftests/ublk/ublk_cancel_ready.c b/tools/testing/selftests/ublk/ublk_cancel_ready.c\nnew file mode 100644\nindex 0000000000000..23071babc0e4c\n--- /dev/null\n+++ b/tools/testing/selftests/ublk/ublk_cancel_ready.c\n@@ -0,0 +1,957 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/*\n+ * Bring a ublk device live while some of its fetched io commands are\n+ * canceled.\n+ *\n+ * A cancel completes a fetched command and clears io-\u003ecmd, but the io\n+ * still counts as ready. Only ubq-\u003ecanceling keeps ublk_queue_rq() away\n+ * from the NULL io-\u003ecmd. Each mode below loses -\u003ecanceling in another way:\n+ *\n+ * stop_start:    fetch every tag, STOP_DEV before START_DEV, START_DEV.\n+ *                STOP_DEV cancels the commands of the attached server,\n+ *                so START_DEV must get -EBUSY until that server is gone.\n+ *                An unfixed kernel starts the device over them.\n+ *\n+ * partial_fetch: task A fetches tags 0..depth-2 and dies, so its\n+ *                commands are canceled. Task B fetches the last tag, and\n+ *                an unfixed kernel clears -\u003ecanceling when the queue gets\n+ *                ready. /dev/ublkcN stays open all the time, so\n+ *                ublk_ch_release() never resets the queue.\n+ *\n+ * recovery:      a UBLK_F_USER_RECOVERY device with two queues loses its\n+ *                server. During recovery task Q0 fetches queue 0, which\n+ *                clears q0-\u003ecanceling, then dies. An unfixed kernel still\n+ *                has ub-\u003ecanceling set because queue 1 is not ready, so\n+ *                ublk_start_cancel() does not mark queue 0 again. Reads\n+ *                are issued on a CPU mapped to queue 0.\n+ *\n+ * In partial_fetch and recovery, START_DEV / END_USER_RECOVERY must refuse\n+ * with -EBUSY. An unfixed kernel oopses in ublk_queue_cmd() on a NULL\n+ * io-\u003ecmd.\n+ *\n+ * stop_restart:  control mode. STOP_DEV on a new device, before any\n+ *                server opened it, takes no command. A server started\n+ *                afterwards has to start the device and serve I/O.\n+ *\n+ * stop_attached: STOP_DEV on a device whose server opened it but fetched\n+ *                nothing stops that server too: FETCH gets ABORT and\n+ *                START_DEV -EBUSY, until a new server opens the device.\n+ *\n+ * stop_live_restart: STOP_DEV on a live device; once its server is gone,\n+ *                a new server has to fetch and start it again. An unfixed\n+ *                ublk_ch_release() skips the reset once the disk is gone,\n+ *                so the new FETCH gets -EBUSY.\n+ *\n+ * race_start:    STOP_DEV and START_DEV at the same time on a device whose\n+ *                server fetched every tag. START_DEV either wins, and\n+ *                reads complete (they fail once STOP_DEV removes the\n+ *                disk), or gets -EBUSY. An unfixed kernel cancels the\n+ *                commands of the live disk.\n+ *\n+ * race_fetch:    STOP_DEV while a server opens the device and fetches,\n+ *                then START_DEV. If STOP_DEV came before the open, it must\n+ *                not take any command, so START_DEV works and every read\n+ *                succeeds; otherwise START_DEV gets -EBUSY. An unfixed\n+ *                kernel takes commands fetched after its unlock and goes\n+ *                live over them.\n+ *\n+ * race_async_fetch: FETCH with IOSQE_ASYNC while STOP_DEV cancels,\n+ *                then close the ring. An unfixed FETCH marks its command\n+ *                cancelable only after publishing it and dropping\n+ *                ub-\u003emutex; a cancel in between completes a command which\n+ *                is then put on io_uring's cancelable list. Closing the\n+ *                ring walks that list: KASAN reports a use after free.\n+ *                Needs a KASAN kernel to see the bug; otherwise it must\n+ *                just not crash.\n+ *\n+ * A dying task is a child process which fetches and then calls exec().\n+ * exec() cancels the task's uring_cmds before it returns, so the cancel\n+ * is done once the child is reaped. A thread exit does not cancel them,\n+ * and closing the ring cancels them later, from io_ring_exit_work().\n+ */\n+#include \u003csched.h\u003e\n+\n+#include \"kublk.h\"\n+#include \"../kselftest.h\"\n+\n+#define NR_QUEUES\t2\n+#define DEPTH\t\t4\n+#define BUF_SIZE\t(64 \u003c\u003c 10)\n+#define DEV_SECTORS\t(64 \u003c\u003c 11)\t/* 64MB */\n+#define NR_READS\t(DEPTH * 2)\n+#define SERVE_DELAY_US\t200000\n+#define RACE_LOOPS\t50\n+#define ASYNC_LOOPS\t300\n+\n+/* one control handle per thread, the race modes send commands from two */\n+static __thread struct ublk_dev *ctrl_dev;\n+static int cdev_fd = -1;\n+static int dev_id = -1;\n+static int nr_queues;\n+static void *bufs[NR_QUEUES][DEPTH];\n+static const struct ublksrv_io_desc *iods[NR_QUEUES];\n+static size_t iods_len;\n+\n+static struct io_uring_sqe *get_sqe(struct io_uring *ring)\n+{\n+\tstruct io_uring_sqe *sqe = io_uring_get_sqe(ring);\n+\n+\tif (!sqe) {\n+\t\tfprintf(stderr, \"out of sqes\\n\");\n+\t\texit(KSFT_FAIL);\n+\t}\n+\treturn sqe;\n+}\n+\n+static struct ublk_dev *ctrl(void)\n+{\n+\tif (!ctrl_dev) {\n+\t\tctrl_dev = ublk_ctrl_init();\n+\t\tif (!ctrl_dev) {\n+\t\t\tfprintf(stderr, \"ublk_ctrl_init failed\\n\");\n+\t\t\texit(KSFT_FAIL);\n+\t\t}\n+\t}\n+\tctrl_dev-\u003edev_info.dev_id = dev_id;\n+\treturn ctrl_dev;\n+}\n+\n+static void ctrl_put(void)\n+{\n+\tif (ctrl_dev)\n+\t\tublk_ctrl_deinit(ctrl_dev);\n+\tctrl_dev = NULL;\n+}\n+\n+static int dev_state(void)\n+{\n+\tstruct ublk_dev *dev = ctrl();\n+\tint ret = ublk_ctrl_get_info(dev);\n+\n+\treturn ret ? ret : dev-\u003edev_info.state;\n+}\n+\n+static int open_cdev(void)\n+{\n+\tsize_t max_len = UBLK_MAX_QUEUE_DEPTH * sizeof(struct ublksrv_io_desc);\n+\tint pg = getpagesize();\n+\tchar path[64];\n+\n+\tsnprintf(path, sizeof(path), \"/dev/ublkc%d\", dev_id);\n+\tfor (int i = 0; i \u003c 100 \u0026\u0026 cdev_fd \u003c 0; i++) {\n+\t\tcdev_fd = open(path, O_RDWR);\n+\t\tif (cdev_fd \u003c 0)\n+\t\t\tusleep(50000);\n+\t}\n+\tif (cdev_fd \u003c 0)\n+\t\treturn -errno;\n+\n+\t/* queue q's descriptors start at q * the size for the max depth */\n+\tmax_len = (max_len + pg - 1) \u0026 ~(size_t)(pg - 1);\n+\tiods_len = (DEPTH * sizeof(struct ublksrv_io_desc) + pg - 1) \u0026\n+\t\t~(size_t)(pg - 1);\n+\tfor (int q = 0; q \u003c nr_queues; q++) {\n+\t\tvoid *p = mmap(NULL, iods_len, PROT_READ,\n+\t\t\t       MAP_SHARED | MAP_POPULATE, cdev_fd,\n+\t\t\t       UBLKSRV_CMD_BUF_OFFSET + q * max_len);\n+\n+\t\tif (p == MAP_FAILED)\n+\t\t\treturn -errno;\n+\t\tiods[q] = p;\n+\t}\n+\treturn 0;\n+}\n+\n+/* the last reference to /dev/ublkcN runs ublk_ch_release() */\n+static void close_cdev(void)\n+{\n+\tfor (int q = 0; q \u003c nr_queues; q++) {\n+\t\tif (iods[q])\n+\t\t\tmunmap((void *)iods[q], iods_len);\n+\t\tiods[q] = NULL;\n+\t}\n+\tif (cdev_fd \u003e= 0)\n+\t\tclose(cdev_fd);\n+\tcdev_fd = -1;\n+}\n+\n+/* ADD_DEV and SET_PARAMS, without opening /dev/ublkcN */\n+static int add_dev_noopen(int queues, __u64 flags)\n+{\n+\tstruct ublk_dev *dev = ctrl();\n+\tstruct ublksrv_ctrl_dev_info info = {\n+\t\t.nr_hw_queues\t= queues,\n+\t\t.queue_depth\t= DEPTH,\n+\t\t.max_io_buf_bytes = BUF_SIZE,\n+\t\t.dev_id\t\t= -1,\n+\t\t.flags\t\t= UBLK_F_NO_AUTO_PART_SCAN | flags,\n+\t};\n+\tstruct ublk_params p = {\n+\t\t.types\t= UBLK_PARAM_TYPE_BASIC,\n+\t\t.basic\t= {\n+\t\t\t.logical_bs_shift\t= 9,\n+\t\t\t.physical_bs_shift\t= 12,\n+\t\t\t.io_opt_shift\t\t= 12,\n+\t\t\t.io_min_shift\t\t= 9,\n+\t\t\t.max_sectors\t\t= BUF_SIZE \u003e\u003e 9,\n+\t\t\t.dev_sectors\t\t= DEV_SECTORS,\n+\t\t},\n+\t};\n+\tint ret;\n+\n+\tnr_queues = queues;\n+\tdev-\u003edev_info = info;\n+\tret = ublk_ctrl_add_dev(dev);\n+\tif (ret)\n+\t\treturn ret;\n+\tdev_id = dev-\u003edev_info.dev_id;\n+\n+\tret = ublk_ctrl_set_params(ctrl(), \u0026p);\n+\tif (ret)\n+\t\treturn ret;\n+\n+\tfor (int q = 0; q \u003c queues; q++)\n+\t\tfor (int i = 0; i \u003c DEPTH; i++)\n+\t\t\tif (!bufs[q][i] \u0026\u0026\n+\t\t\t    posix_memalign(\u0026bufs[q][i], getpagesize(), BUF_SIZE))\n+\t\t\t\treturn -ENOMEM;\n+\treturn 0;\n+}\n+\n+static int add_dev(int queues, __u64 flags)\n+{\n+\treturn add_dev_noopen(queues, flags) ?: open_cdev();\n+}\n+\n+static void cleanup(void)\n+{\n+\tif (dev_id \u003c 0)\n+\t\treturn;\n+\tublk_ctrl_stop_dev(ctrl());\n+\tclose_cdev();\n+\tublk_ctrl_del_dev(ctrl());\n+\tdev_id = -1;\n+}\n+\n+/* race_async_fetch sets IOSQE_ASYNC on the io commands */\n+static int io_cmd_sqe_flags;\n+\n+static void queue_io_cmd(struct io_uring *ring, __u32 op, int q, int tag,\n+\t\t\t int res)\n+{\n+\tstruct io_uring_sqe *sqe = get_sqe(ring);\n+\tstruct ublksrv_io_cmd *cmd = (struct ublksrv_io_cmd *)sqe-\u003ecmd;\n+\n+\tmemset(sqe, 0, sizeof(*sqe));\n+\tsqe-\u003efd = cdev_fd;\n+\tsqe-\u003eopcode = IORING_OP_URING_CMD;\n+\tsqe-\u003eflags = io_cmd_sqe_flags;\n+\tublk_set_sqe_cmd_op(sqe, op);\n+\tcmd-\u003eq_id = q;\n+\tcmd-\u003etag = tag;\n+\tcmd-\u003eresult = res;\n+\tcmd-\u003eaddr = (__u64)(uintptr_t)bufs[q][tag];\n+\tio_uring_sqe_set_data64(sqe, (q \u003c\u003c 16) | tag);\n+}\n+\n+struct async_arg {\n+\tpthread_barrier_t go, stopped;\n+};\n+\n+/*\n+ * FETCH every tag with IOSQE_ASYNC, racing STOP_DEV, then close the ring once\n+ * STOP_DEV returned: that walks io_uring's list of cancelable commands.\n+ */\n+static void *race_async_fn(void *data)\n+{\n+\tstruct async_arg *a = data;\n+\tstruct io_uring ring;\n+\tint ok = !io_uring_queue_init(DEPTH, \u0026ring, 0);\n+\n+\tif (ok)\n+\t\tfor (int tag = 0; tag \u003c DEPTH; tag++)\n+\t\t\tqueue_io_cmd(\u0026ring, UBLK_U_IO_FETCH_REQ, 0, tag, 0);\n+\tpthread_barrier_wait(\u0026a-\u003ego);\n+\tif (ok)\n+\t\tio_uring_submit(\u0026ring);\n+\tpthread_barrier_wait(\u0026a-\u003estopped);\n+\tif (ok)\n+\t\tio_uring_queue_exit(\u0026ring);\n+\treturn NULL;\n+}\n+\n+/* reap @nr completions of canceled fetch commands, return how many */\n+static int reap_aborts(struct io_uring *ring, int nr)\n+{\n+\tstruct __kernel_timespec ts = { .tv_sec = 2 };\n+\tstruct io_uring_cqe *cqe;\n+\tint aborted = 0;\n+\n+\twhile (nr--) {\n+\t\tif (io_uring_wait_cqe_timeout(ring, \u0026cqe, \u0026ts))\n+\t\t\tbreak;\n+\t\tif (cqe-\u003eres == UBLK_IO_RES_ABORT)\n+\t\t\taborted++;\n+\t\tio_uring_cqe_seen(ring, cqe);\n+\t}\n+\treturn aborted;\n+}\n+\n+/*\n+ * A server thread fetches @nr_tags tags of queue @q, then completes each\n+ * request after @delay_us, until its commands are aborted.\n+ */\n+struct server {\n+\tint q, first_tag, nr_tags, delay_us;\n+\tint failed;\t/* result which ended the serve loop, 0 if none */\n+\tpthread_t thread;\n+\tpthread_barrier_t fetched;\n+\t/* race_fetch: wait for @go and @race_delay_us, open, fetch one by one */\n+\tpthread_barrier_t go;\n+\tint race, race_delay_us;\n+};\n+\n+static void *server_fn(void *data)\n+{\n+\tstruct server *s = data;\n+\tstruct io_uring ring;\n+\tstruct io_uring_cqe *cqe;\n+\n+\tif (io_uring_queue_init(DEPTH, \u0026ring, 0)) {\n+\t\tpthread_barrier_wait(\u0026s-\u003efetched);\n+\t\treturn NULL;\n+\t}\n+\tif (s-\u003erace) {\n+\t\tpthread_barrier_wait(\u0026s-\u003ego);\n+\t\tusleep(s-\u003erace_delay_us);\n+\t\tif (open_cdev()) {\n+\t\t\tpthread_barrier_wait(\u0026s-\u003efetched);\n+\t\t\tio_uring_queue_exit(\u0026ring);\n+\t\t\treturn NULL;\n+\t\t}\n+\t}\n+\tfor (int tag = s-\u003efirst_tag; tag \u003c s-\u003efirst_tag + s-\u003enr_tags; tag++) {\n+\t\tqueue_io_cmd(\u0026ring, UBLK_U_IO_FETCH_REQ, s-\u003eq, tag, 0);\n+\t\tif (s-\u003erace)\n+\t\t\tio_uring_submit(\u0026ring);\n+\t}\n+\tio_uring_submit(\u0026ring);\n+\tpthread_barrier_wait(\u0026s-\u003efetched);\n+\n+\twhile (!io_uring_wait_cqe(\u0026ring, \u0026cqe)) {\n+\t\tint tag = cqe-\u003euser_data \u0026 0xffff;\n+\t\tconst struct ublksrv_io_desc *iod = \u0026iods[s-\u003eq][tag];\n+\t\tint res = cqe-\u003eres;\n+\n+\t\tio_uring_cqe_seen(\u0026ring, cqe);\n+\t\tif (res != UBLK_IO_RES_OK) {\n+\t\t\t__atomic_store_n(\u0026s-\u003efailed, res, __ATOMIC_RELEASE);\n+\t\t\tbreak;\n+\t\t}\n+\t\tusleep(s-\u003edelay_us);\n+\t\tres = ublksrv_get_op(iod) \u003c= UBLK_IO_OP_WRITE ?\n+\t\t\tiod-\u003enr_sectors \u003c\u003c 9 : 0;\n+\t\tqueue_io_cmd(\u0026ring, UBLK_U_IO_COMMIT_AND_FETCH_REQ, s-\u003eq, tag,\n+\t\t\t     res);\n+\t\tio_uring_submit(\u0026ring);\n+\t}\n+\tio_uring_queue_exit(\u0026ring);\n+\treturn NULL;\n+}\n+\n+/* returns once the fetch commands are issued; with @race, call race_go() */\n+static void server_start(struct server *s)\n+{\n+\tpthread_barrier_init(\u0026s-\u003efetched, NULL, 2);\n+\tpthread_barrier_init(\u0026s-\u003ego, NULL, 2);\n+\tpthread_create(\u0026s-\u003ethread, NULL, server_fn, s);\n+\tif (!s-\u003erace)\n+\t\tpthread_barrier_wait(\u0026s-\u003efetched);\n+}\n+\n+/* wait up to 5s for the serve loop of @s to end, return its result */\n+static int server_wait_failed(struct server *s)\n+{\n+\tint res = 0;\n+\n+\tfor (int i = 0; i \u003c 500 \u0026\u0026 !res; i++) {\n+\t\tres = __atomic_load_n(\u0026s-\u003efailed, __ATOMIC_ACQUIRE);\n+\t\tif (!res)\n+\t\t\tusleep(10000);\n+\t}\n+\treturn res;\n+}\n+\n+/*\n+ * A task fetches @nr_tags tags of queue @q and dies. Returns once its\n+ * commands are canceled, see the top of this file.\n+ */\n+static int fetch_and_die(int q, int first_tag, int nr_tags)\n+{\n+\tint status;\n+\tpid_t pid = fork();\n+\n+\tif (pid \u003c 0)\n+\t\treturn -1;\n+\tif (!pid) {\n+\t\tstruct io_uring ring;\n+\n+\t\tif (io_uring_queue_init(DEPTH, \u0026ring, 0))\n+\t\t\t_exit(1);\n+\t\tfor (int tag = first_tag; tag \u003c first_tag + nr_tags; tag++)\n+\t\t\tqueue_io_cmd(\u0026ring, UBLK_U_IO_FETCH_REQ, q, tag, 0);\n+\t\tif (io_uring_submit(\u0026ring) != nr_tags)\n+\t\t\t_exit(1);\n+\t\texeclp(\"true\", \"true\", NULL);\n+\t\t_exit(1);\n+\t}\n+\tif (waitpid(pid, \u0026status, 0) != pid || !WIFEXITED(status) ||\n+\t    WEXITSTATUS(status))\n+\t\treturn -1;\n+\tprintf(\"q%d: task died with %d fetch cmds in flight\\n\", q, nr_tags);\n+\treturn 0;\n+}\n+\n+struct reads {\n+\tstruct io_uring ring;\n+\tvoid *buf;\n+\tint fd, done, ok, eio, other;\n+};\n+\n+/*\n+ * Issue NR_READS reads at once, from @cpu if it is not negative: blk-mq\n+ * maps the submitting CPU to the hw queue. A server holding its live\n+ * tags for a while makes the other reads take the canceled tags.\n+ */\n+static int open_tries = 100;\t/* 50ms each */\n+\n+static int reads_submit(struct reads *r, int cpu)\n+{\n+\tchar path[64];\n+\tcpu_set_t set, old;\n+\n+\tsnprintf(path, sizeof(path), \"/dev/ublkb%d\", dev_id);\n+\tr-\u003efd = -1;\n+\tfor (int i = 0; i \u003c open_tries \u0026\u0026 r-\u003efd \u003c 0; i++) {\n+\t\tr-\u003efd = open(path, O_RDONLY | O_DIRECT);\n+\t\tif (r-\u003efd \u003c 0)\n+\t\t\tusleep(50000);\n+\t}\n+\tif (r-\u003efd \u003c 0) {\n+\t\tfprintf(stderr, \"open %s: %s\\n\", path, strerror(errno));\n+\t\treturn -1;\n+\t}\n+\tif (posix_memalign(\u0026r-\u003ebuf, 4096, NR_READS * 4096) ||\n+\t    io_uring_queue_init(NR_READS, \u0026r-\u003ering, 0))\n+\t\treturn -1;\n+\n+\tfor (int i = 0; i \u003c NR_READS; i++)\n+\t\tio_uring_prep_read(get_sqe(\u0026r-\u003ering), r-\u003efd,\n+\t\t\t\t   r-\u003ebuf + i * 4096, 4096, i * 4096);\n+\n+\tif (cpu \u003e= 0) {\n+\t\tsched_getaffinity(0, sizeof(old), \u0026old);\n+\t\tCPU_ZERO(\u0026set);\n+\t\tCPU_SET(cpu, \u0026set);\n+\t\tsched_setaffinity(0, sizeof(set), \u0026set);\n+\t}\n+\tio_uring_submit(\u0026r-\u003ering);\n+\tif (cpu \u003e= 0)\n+\t\tsched_setaffinity(0, sizeof(old), \u0026old);\n+\treturn 0;\n+}\n+\n+static void reads_reap(struct reads *r, int timeout_s)\n+{\n+\tstruct __kernel_timespec ts = { .tv_sec = timeout_s };\n+\tstruct io_uring_cqe *cqe;\n+\n+\twhile (r-\u003edone \u003c NR_READS \u0026\u0026\n+\t       !io_uring_wait_cqe_timeout(\u0026r-\u003ering, \u0026cqe, \u0026ts)) {\n+\t\tif (cqe-\u003eres == 4096)\n+\t\t\tr-\u003eok++;\n+\t\telse if (cqe-\u003eres == -EIO)\n+\t\t\tr-\u003eeio++;\n+\t\telse\n+\t\t\tr-\u003eother++;\n+\t\tr-\u003edone++;\n+\t\tio_uring_cqe_seen(\u0026r-\u003ering, cqe);\n+\t}\n+}\n+\n+static void reads_put(struct reads *r)\n+{\n+\tio_uring_queue_exit(\u0026r-\u003ering);\n+\tclose(r-\u003efd);\n+\tfree(r-\u003ebuf);\n+}\n+\n+static int reads_result(struct reads *r)\n+{\n+\tprintf(\"reads: %d ok, %d -EIO, %d other, %d not completed\\n\",\n+\t       r-\u003eok, r-\u003eeio, r-\u003eother, NR_READS - r-\u003edone);\n+\treads_put(r);\n+\treturn r-\u003eother || r-\u003edone \u003c NR_READS ? KSFT_FAIL : KSFT_PASS;\n+}\n+\n+static int start_dev(void)\n+{\n+\tint ret = ublk_ctrl_start_dev(ctrl(), getpid());\n+\n+\tprintf(\"START_DEV: %d\\n\", ret);\n+\treturn ret;\n+}\n+\n+static int expect_err(const char *what, int ret, int want)\n+{\n+\tif (ret == want)\n+\t\treturn KSFT_PASS;\n+\tfprintf(stderr, \"%s: %d, expected %d\\n\", what, ret, want);\n+\treturn KSFT_FAIL;\n+}\n+\n+/* START_DEV must fail with @want; if it went live, show what a read does */\n+static int start_dev_expect(int want)\n+{\n+\tstruct reads r = {};\n+\tint ret = start_dev();\n+\n+\tif (!ret \u0026\u0026 !reads_submit(\u0026r, -1)) {\n+\t\treads_reap(\u0026r, 10);\n+\t\treads_result(\u0026r);\n+\t}\n+\treturn expect_err(\"START_DEV\", ret, want);\n+}\n+\n+static int test_stop_start(void)\n+{\n+\tstruct io_uring ring;\n+\tint ret;\n+\n+\tif (add_dev(1, 0))\n+\t\treturn KSFT_FAIL;\n+\tif (io_uring_queue_init(DEPTH, \u0026ring, 0))\n+\t\treturn KSFT_FAIL;\n+\tfor (int tag = 0; tag \u003c DEPTH; tag++)\n+\t\tqueue_io_cmd(\u0026ring, UBLK_U_IO_FETCH_REQ, 0, tag, 0);\n+\tio_uring_submit(\u0026ring);\n+\n+\t/* device is ready but not started: state is UBLK_S_DEV_DEAD */\n+\tret = ublk_ctrl_stop_dev(ctrl());\n+\tprintf(\"STOP_DEV: %d, canceled fetch cmds: %d/%d\\n\", ret,\n+\t       reap_aborts(\u0026ring, DEPTH), DEPTH);\n+\n+\t/* STOP_DEV canceled the attached server: no start until it exits */\n+\tret = start_dev_expect(-EBUSY);\n+\tio_uring_queue_exit(\u0026ring);\n+\treturn ret;\n+}\n+\n+static int test_partial_fetch(void)\n+{\n+\tstruct server b = { .q = 0, .first_tag = DEPTH - 1, .nr_tags = 1,\n+\t\t\t    .delay_us = SERVE_DELAY_US };\n+\tint ret;\n+\n+\tif (add_dev(1, 0) || fetch_and_die(0, 0, DEPTH - 1))\n+\t\treturn KSFT_FAIL;\n+\n+\t/* the last FETCH makes the queue ready and clears -\u003ecanceling */\n+\tserver_start(\u0026b);\n+\n+\tret = start_dev_expect(-EBUSY);\n+\n+\tcleanup();\n+\tpthread_join(b.thread, NULL);\n+\treturn ret;\n+}\n+\n+static int test_stop_restart(void)\n+{\n+\tstruct server s = { .q = 0, .nr_tags = DEPTH };\n+\tstruct reads r = {};\n+\tint ret;\n+\n+\tif (add_dev_noopen(1, 0))\n+\t\treturn KSFT_FAIL;\n+\n+\t/* no server is attached, so there is nothing to cancel */\n+\tret = ublk_ctrl_stop_dev(ctrl());\n+\tprintf(\"STOP_DEV: %d\\n\", ret);\n+\tif (open_cdev())\n+\t\treturn KSFT_FAIL;\n+\n+\tserver_start(\u0026s);\n+\tif (start_dev()) {\n+\t\tret = KSFT_FAIL;\n+\t} else if (reads_submit(\u0026r, -1)) {\n+\t\tret = KSFT_FAIL;\n+\t} else {\n+\t\treads_reap(\u0026r, 10);\n+\t\tret = reads_result(\u0026r);\n+\t\tif (r.ok != NR_READS)\n+\t\t\tret = KSFT_FAIL;\n+\t}\n+\n+\tcleanup();\n+\tpthread_join(s.thread, NULL);\n+\treturn ret;\n+}\n+\n+struct start_arg {\n+\tpthread_barrier_t go;\n+\tint ret, reads_ok;\n+};\n+\n+static void *race_start_fn(void *data)\n+{\n+\tstruct start_arg *a = data;\n+\tstruct reads r = {};\n+\n+\tpthread_barrier_wait(\u0026a-\u003ego);\n+\ta-\u003eret = ublk_ctrl_start_dev(ctrl(), getpid());\n+\ta-\u003ereads_ok = 1;\n+\t/*\n+\t * The disk may be gone already if STOP_DEV came right after, and\n+\t * reads may fail then: they only have to complete.\n+\t */\n+\tif (!a-\u003eret \u0026\u0026 !reads_submit(\u0026r, -1)) {\n+\t\treads_reap(\u0026r, 5);\n+\t\ta-\u003ereads_ok = r.done == NR_READS;\n+\t\tif (a-\u003ereads_ok)\n+\t\t\treads_put(\u0026r);\n+\t\telse\n+\t\t\treads_result(\u0026r);\n+\t}\n+\tctrl_put();\n+\treturn NULL;\n+}\n+\n+static int test_race_start(void)\n+{\n+\tint live = 0, ebusy = 0;\n+\n+\topen_tries = 4;\n+\tfor (int i = 0; i \u003c RACE_LOOPS; i++) {\n+\t\tstruct server s = { .q = 0, .nr_tags = DEPTH };\n+\t\tstruct start_arg a = {};\n+\t\tpthread_t t;\n+\n+\t\tif (add_dev(1, 0))\n+\t\t\treturn KSFT_FAIL;\n+\t\tserver_start(\u0026s);\n+\t\tpthread_barrier_init(\u0026a.go, NULL, 2);\n+\t\tpthread_create(\u0026t, NULL, race_start_fn, \u0026a);\n+\t\tpthread_barrier_wait(\u0026a.go);\n+\t\tublk_ctrl_stop_dev(ctrl());\n+\t\tpthread_join(t, NULL);\n+\t\tcleanup();\n+\t\tpthread_join(s.thread, NULL);\n+\n+\t\tif (a.ret == 0)\n+\t\t\tlive++;\n+\t\telse if (a.ret == -EBUSY)\n+\t\t\tebusy++;\n+\t\tif ((a.ret \u0026\u0026 a.ret != -EBUSY) || !a.reads_ok) {\n+\t\t\tfprintf(stderr, \"loop %d: START_DEV %d, reads %s\\n\",\n+\t\t\t\ti, a.ret, a.reads_ok ? \"ok\" : \"failed\");\n+\t\t\treturn KSFT_FAIL;\n+\t\t}\n+\t}\n+\tprintf(\"%d loops: START_DEV won %d, got -EBUSY %d\\n\", RACE_LOOPS,\n+\t       live, ebusy);\n+\treturn KSFT_PASS;\n+}\n+\n+static int test_race_fetch(void)\n+{\n+\tint live = 0, ebusy = 0;\n+\n+\tfor (int i = 0; i \u003c RACE_LOOPS; i++) {\n+\t\t/* vary who goes first: STOP_DEV, or the server's open */\n+\t\tstruct server s = { .q = 0, .nr_tags = DEPTH, .race = 1,\n+\t\t\t\t    .race_delay_us = (i % 10) * 50 };\n+\t\tstruct reads r = {};\n+\t\tint ret;\n+\n+\t\tif (add_dev_noopen(1, 0))\n+\t\t\treturn KSFT_FAIL;\n+\t\tserver_start(\u0026s);\n+\t\tpthread_barrier_wait(\u0026s.go);\n+\t\tublk_ctrl_stop_dev(ctrl());\n+\t\tpthread_barrier_wait(\u0026s.fetched);\n+\n+\t\tret = ublk_ctrl_start_dev(ctrl(), getpid());\n+\t\tif (!ret) {\n+\t\t\t/* nothing was taken, so every read has to succeed */\n+\t\t\tlive++;\n+\t\t\tif (reads_submit(\u0026r, -1))\n+\t\t\t\treturn KSFT_FAIL;\n+\t\t\treads_reap(\u0026r, 5);\n+\t\t\tif (r.ok != NR_READS) {\n+\t\t\t\tfprintf(stderr, \"loop %d: live, but \", i);\n+\t\t\t\treads_result(\u0026r);\n+\t\t\t\treturn KSFT_FAIL;\n+\t\t\t}\n+\t\t\treads_put(\u0026r);\n+\t\t} else if (ret == -EBUSY) {\n+\t\t\tebusy++;\n+\t\t} else {\n+\t\t\tfprintf(stderr, \"loop %d: START_DEV %d\\n\", i, ret);\n+\t\t\treturn KSFT_FAIL;\n+\t\t}\n+\t\tcleanup();\n+\t\tpthread_join(s.thread, NULL);\n+\t}\n+\tprintf(\"%d loops: START_DEV worked %d, got -EBUSY %d\\n\", RACE_LOOPS,\n+\t       live, ebusy);\n+\treturn KSFT_PASS;\n+}\n+\n+static int test_race_async_fetch(void)\n+{\n+\tio_cmd_sqe_flags = IOSQE_ASYNC;\n+\tfor (int i = 0; i \u003c ASYNC_LOOPS; i++) {\n+\t\tstruct async_arg a;\n+\t\tpthread_t t;\n+\n+\t\tif (add_dev(1, 0))\n+\t\t\treturn KSFT_FAIL;\n+\t\tpthread_barrier_init(\u0026a.go, NULL, 2);\n+\t\tpthread_barrier_init(\u0026a.stopped, NULL, 2);\n+\t\tpthread_create(\u0026t, NULL, race_async_fn, \u0026a);\n+\t\tpthread_barrier_wait(\u0026a.go);\n+\t\t/* vary where STOP_DEV lands relative to the FETCHes */\n+\t\tusleep((i % 5) * 1000);\n+\t\tublk_ctrl_stop_dev(ctrl());\n+\t\tpthread_barrier_wait(\u0026a.stopped);\n+\t\tpthread_join(t, NULL);\n+\t\tcleanup();\n+\t}\n+\tprintf(\"%d loops done\\n\", ASYNC_LOOPS);\n+\treturn KSFT_PASS;\n+}\n+\n+/*\n+ * The stopped server is gone: reopen /dev/ublkcN, start a new server and\n+ * the device, and read from it.\n+ */\n+static int restart_server(void)\n+{\n+\tstruct server s = { .q = 0, .nr_tags = DEPTH };\n+\tstruct reads r = {};\n+\tint ret;\n+\n+\tclose_cdev();\n+\tif (open_cdev())\n+\t\treturn KSFT_FAIL;\n+\tserver_start(\u0026s);\n+\tusleep(200000);\n+\tif (s.failed) {\n+\t\tfprintf(stderr, \"new server: FETCH failed %d\\n\", s.failed);\n+\t\tcleanup();\n+\t\tpthread_join(s.thread, NULL);\n+\t\treturn KSFT_FAIL;\n+\t}\n+\t/* -EEXIST until the old disk is freed, e.g. after a udev probe */\n+\tfor (int i = 0; i \u003c 100; i++) {\n+\t\tret = start_dev();\n+\t\tif (ret != -EEXIST)\n+\t\t\tbreak;\n+\t\tusleep(50000);\n+\t}\n+\tif (ret || reads_submit(\u0026r, -1)) {\n+\t\tfprintf(stderr, \"new server: START_DEV %d\\n\", ret);\n+\t\tret = KSFT_FAIL;\n+\t} else {\n+\t\treads_reap(\u0026r, 10);\n+\t\tret = reads_result(\u0026r);\n+\t\tif (r.ok != NR_READS)\n+\t\t\tret = KSFT_FAIL;\n+\t}\n+\tcleanup();\n+\tpthread_join(s.thread, NULL);\n+\treturn ret;\n+}\n+\n+/*\n+ * stop_attached: STOP_DEV while a server has the device open but has\n+ * fetched nothing stops that server too: its FETCH gets ABORT and\n+ * START_DEV -EBUSY. Once it is gone, a new server can start the device.\n+ */\n+static int test_stop_attached(void)\n+{\n+\tstruct server s = { .q = 0, .nr_tags = DEPTH };\n+\tint ret;\n+\n+\tif (add_dev(1, 0))\n+\t\treturn KSFT_FAIL;\n+\tret = ublk_ctrl_stop_dev(ctrl());\n+\tprintf(\"STOP_DEV: %d\\n\", ret);\n+\n+\tserver_start(\u0026s);\n+\tret = server_wait_failed(\u0026s);\n+\tprintf(\"FETCH after STOP_DEV: %d\\n\", ret);\n+\tif (ret != UBLK_IO_RES_ABORT) {\n+\t\tcleanup();\n+\t\tpthread_join(s.thread, NULL);\n+\t\treturn KSFT_FAIL;\n+\t}\n+\tpthread_join(s.thread, NULL);\n+\tif (expect_err(\"START_DEV\", start_dev(), -EBUSY))\n+\t\treturn KSFT_FAIL;\n+\treturn restart_server();\n+}\n+\n+/*\n+ * stop_live_restart: STOP_DEV on a live device; once its server is gone,\n+ * a new server has to fetch and start it again.\n+ */\n+static int test_stop_live_restart(void)\n+{\n+\tstruct server s = { .q = 0, .nr_tags = DEPTH };\n+\tint ret;\n+\n+\tif (add_dev(1, 0))\n+\t\treturn KSFT_FAIL;\n+\tserver_start(\u0026s);\n+\tif (expect_err(\"START_DEV\", start_dev(), 0))\n+\t\treturn KSFT_FAIL;\n+\tret = ublk_ctrl_stop_dev(ctrl());\n+\tprintf(\"STOP_DEV: %d\\n\", ret);\n+\tpthread_join(s.thread, NULL);\n+\treturn restart_server();\n+}\n+\n+/* first CPU which blk-mq maps to hw queue @q */\n+static int queue_cpu(int q)\n+{\n+\tchar path[96];\n+\tFILE *f;\n+\tint cpu = -1;\n+\n+\tsnprintf(path, sizeof(path), \"/sys/block/ublkb%d/mq/%d/cpu_list\",\n+\t\t dev_id, q);\n+\tfor (int i = 0; i \u003c 100 \u0026\u0026 !(f = fopen(path, \"r\")); i++)\n+\t\tusleep(50000);\n+\tif (!f)\n+\t\treturn -1;\n+\tif (fscanf(f, \"%d\", \u0026cpu) != 1)\n+\t\tcpu = -1;\n+\tfclose(f);\n+\treturn cpu;\n+}\n+\n+static int test_recovery(void)\n+{\n+\tstruct server q1 = { .q = 1, .nr_tags = DEPTH };\n+\tstruct io_uring ring;\n+\tstruct reads r = {};\n+\tint ret, cpu;\n+\n+\tif (add_dev(NR_QUEUES, UBLK_F_USER_RECOVERY))\n+\t\treturn KSFT_FAIL;\n+\n+\t/* the first server: fetch everything, start, then die */\n+\tif (io_uring_queue_init(NR_QUEUES * DEPTH, \u0026ring, 0))\n+\t\treturn KSFT_FAIL;\n+\tfor (int q = 0; q \u003c NR_QUEUES; q++)\n+\t\tfor (int tag = 0; tag \u003c DEPTH; tag++)\n+\t\t\tqueue_io_cmd(\u0026ring, UBLK_U_IO_FETCH_REQ, q, tag, 0);\n+\tio_uring_submit(\u0026ring);\n+\tif (start_dev())\n+\t\treturn KSFT_FAIL;\n+\tcpu = queue_cpu(0);\n+\tif (cpu \u003c 0) {\n+\t\tprintf(\"no CPU maps to queue 0, can't aim the reads\\n\");\n+\t\treturn KSFT_SKIP;\n+\t}\n+\n+\tio_uring_queue_exit(\u0026ring);\n+\tclose_cdev();\n+\tfor (int i = 0; i \u003c 100 \u0026\u0026 dev_state() != UBLK_S_DEV_QUIESCED; i++)\n+\t\tusleep(50000);\n+\tprintf(\"server exited, state %d (QUIESCED is %d)\\n\", dev_state(),\n+\t       UBLK_S_DEV_QUIESCED);\n+\n+\tfor (int i = 0; i \u003c 100; i++) {\n+\t\tret = ublk_ctrl_start_user_recovery(ctrl());\n+\t\tif (ret != -EBUSY)\n+\t\t\tbreak;\n+\t\tusleep(50000);\n+\t}\n+\tprintf(\"START_USER_RECOVERY: %d\\n\", ret);\n+\tif (ret || open_cdev())\n+\t\treturn KSFT_FAIL;\n+\n+\t/* queue 0 gets ready, then its task dies before queue 1 is ready */\n+\tif (fetch_and_die(0, 0, DEPTH))\n+\t\treturn KSFT_FAIL;\n+\n+\tprintf(\"reads on cpu %d, which maps to queue 0\\n\", cpu);\n+\tif (reads_submit(\u0026r, cpu))\n+\t\treturn KSFT_FAIL;\n+\n+\tserver_start(\u0026q1);\n+\tret = ublk_ctrl_end_user_recovery(ctrl(), getpid());\n+\tprintf(\"END_USER_RECOVERY: %d\\n\", ret);\n+\tret = expect_err(\"END_USER_RECOVERY\", ret, -EBUSY);\n+\n+\t/*\n+\t * Requests held back on queue 0 wait for STOP_DEV to fail them.\n+\t * Close the disk before DEL_DEV, which waits for its last reference.\n+\t */\n+\treads_reap(\u0026r, 1);\n+\tublk_ctrl_stop_dev(ctrl());\n+\treads_reap(\u0026r, 5);\n+\tif (reads_result(\u0026r))\n+\t\tret = KSFT_FAIL;\n+\tcleanup();\n+\tpthread_join(q1.thread, NULL);\n+\treturn ret;\n+}\n+\n+static const struct {\n+\tconst char *name;\n+\tint (*fn)(void);\n+} modes[] = {\n+\t{ \"stop_start\",\t\ttest_stop_start },\n+\t{ \"partial_fetch\",\ttest_partial_fetch },\n+\t{ \"recovery\",\t\ttest_recovery },\n+\t{ \"stop_restart\",\ttest_stop_restart },\n+\t{ \"race_start\",\t\ttest_race_start },\n+\t{ \"race_fetch\",\t\ttest_race_fetch },\n+\t{ \"race_async_fetch\",\ttest_race_async_fetch },\n+\t{ \"stop_attached\",\ttest_stop_attached },\n+\t{ \"stop_live_restart\",\ttest_stop_live_restart },\n+};\n+\n+int main(int argc, char **argv)\n+{\n+\tint (*fn)(void) = NULL;\n+\tint ret;\n+\n+\tfor (int i = 0; argc == 2 \u0026\u0026 i \u003c ARRAY_SIZE(modes); i++)\n+\t\tif (!strcmp(argv[1], modes[i].name))\n+\t\t\tfn = modes[i].fn;\n+\tif (!fn) {\n+\t\tfprintf(stderr, \"usage: %s MODE, modes:\", argv[0]);\n+\t\tfor (int i = 0; i \u003c ARRAY_SIZE(modes); i++)\n+\t\t\tfprintf(stderr, \" %s\", modes[i].name);\n+\t\tfprintf(stderr, \"\\n\");\n+\t\treturn KSFT_FAIL;\n+\t}\n+\n+\t/* keep the output of a run that ends in an oops */\n+\tsetvbuf(stdout, NULL, _IOLBF, 0);\n+\n+\tif (access(CTRL_DEV, F_OK)) {\n+\t\tperror(CTRL_DEV);\n+\t\treturn KSFT_SKIP;\n+\t}\n+\tprintf(\"%s\\n\", argv[1]);\n+\tret = fn();\n+\tcleanup();\n+\tctrl_put();\n+\treturn ret;\n+}\n"
}

2/1 2026/10/11 06:40 agent patch-evaluator
3m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "BLK_DEV_UBLK",
    "BLK_DEV_ZONED"
  ],
  "FocusSymbols": [
    "ublk_ctrl_start_dev",
    "ublk_stop_dev",
    "ublk_ch_uring_cmd_local",
    "ublk_uring_cmd_cancel_fn",
    "ublk_ctrl_end_recovery",
    "ublk_batch_attach",
    "ublk_ch_release_work_fn",
    "ublk_report_zones"
  ],
  "Reasoning": "The patch modifies the userspace block device driver (ublk_drv.c), addressing concurrency bugs and state synchronization between STOP_DEV, START_DEV, recovery operations, and io_uring command cancellation. It introduces the UB_STATE_STOPPING state, updates locking around cancel_mutex, adjusts cancel-related WARN_ON_ONCE checks, and fixes zone reporting indexing in ublk_report_zones. Because ublk operates via io_uring and virtual devices accessible in standard QEMU environments without special physical hardware, this reachable and concurrency-heavy code warrants fuzzing.",
  "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 a4bb54a2d35bed452a582bea2ba85f6ce8ce5cdb
Author: syz-cluster <triage@syzkaller.com>
Date:   Sun Oct 11 06:40:13 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/block/ublk.rst b/Documentation/block/ublk.rst
index 28300fee22bfc..f07611b0d4895 100644
--- a/Documentation/block/ublk.rst
+++ b/Documentation/block/ublk.rst
@@ -118,7 +118,11 @@ managing and controlling ublk devices with help of several control commands:
   After the server prepares userspace resources (such as creating I/O handler
   threads & io_uring for handling ublk IO), this command is sent to the
   driver for allocating & exposing ``/dev/ublkb*``. Parameters set via
-  ``UBLK_CMD_SET_PARAMS`` are applied for creating the device.
+  ``UBLK_CMD_SET_PARAMS`` are applied for creating the device. The command
+  fails with ``-EBUSY`` if an I/O command fetched by the current server
+  was canceled, because its io_uring is gone. The server can't fetch it
+  again, and the device can be started again once the server has closed
+  ``/dev/ublkc*``.
 
 - ``UBLK_CMD_STOP_DEV``
 
@@ -126,6 +130,13 @@ managing and controlling ublk devices with help of several control commands:
   ublk server will release resources (such as destroying I/O handler threads &
   io_uring).
 
+  If a server has ``/dev/ublkc*`` open, its fetched I/O commands complete with
+  ``UBLK_IO_RES_ABORT``. Until it closes ``/dev/ublkc*``, new
+  ``UBLK_IO_FETCH_REQ`` and ``UBLK_U_IO_PREP_IO_CMDS`` commands complete with
+  ``UBLK_IO_RES_ABORT`` too, and ``UBLK_CMD_START_DEV`` fails with ``-EBUSY``,
+  even if the server hadn't fetched anything. The device can be started again
+  by a server that opens ``/dev/ublkc*`` after that.
+
 - ``UBLK_CMD_DEL_DEV``
 
   Remove ``/dev/ublkc*``. When this command returns, the allocated ublk device
@@ -195,7 +206,9 @@ managing and controlling ublk devices with help of several control commands:
   command is accepted after ublk device is quiesced and a new process has
   opened ``/dev/ublkc*`` and get all ublk queues be ready. When this command
   returns, ublk device is unquiesced and new I/O requests are passed to the
-  new process.
+  new process. It fails with ``-EBUSY`` if an I/O command of the new
+  process was canceled already. The recovery can be started over once the
+  new process has closed ``/dev/ublkc*``.
 
 - user recovery feature description
 
diff --git a/drivers/block/ublk_drv.c b/drivers/block/ublk_drv.c
index b32872421951d..1e84ccc68b9b0 100644
--- a/drivers/block/ublk_drv.c
+++ b/drivers/block/ublk_drv.c
@@ -321,6 +321,8 @@ struct ublk_device {
 #define UB_STATE_OPEN		0
 #define UB_STATE_USED		1
 #define UB_STATE_DELETED	2
+/* STOP_DEV canceled the server's commands, until its release */
+#define UB_STATE_STOPPING	3
 	unsigned long		state;
 	int			ub_number;
 
@@ -334,6 +336,13 @@ struct ublk_device {
 	u16			nr_queue_ready;
 	bool 			unprivileged_daemons;
 	struct mutex cancel_mutex;
+	/* the open /dev/ublkcN, protected by cancel_mutex */
+	struct file *ch_file;
+	/*
+	 * A cancel started in this FETCH round. Set by ublk_set_canceling(),
+	 * cleared only by ublk_reset_ch_dev() when a new round starts. While
+	 * it is set, no queue clears its ->canceling.
+	 */
 	bool canceling;
 	pid_t 	ublksrv_tgid;
 	struct delayed_work	exit_work;
@@ -687,7 +696,7 @@ static int ublk_report_zones(struct gendisk *disk, sector_t sector,
 			if (!zone->len)
 				break;
 
-			ret = disk_report_zone(disk, zone, i, args);
+			ret = disk_report_zone(disk, zone, done_zones, args);
 			if (ret)
 				goto out;
 
@@ -810,6 +819,8 @@ ublk_batch_alloc_fcmd(struct io_uring_cmd *cmd)
 	if (fcmd) {
 		fcmd->cmd = cmd;
 		fcmd->buf_group = READ_ONCE(cmd->sqe->buf_index);
+		/* a cancel may look at it before it is linked */
+		INIT_LIST_HEAD(&fcmd->node);
 	}
 	return fcmd;
 }
@@ -2399,6 +2410,9 @@ static int ublk_ch_open(struct inode *inode, struct file *filp)
 		return -EBUSY;
 	filp->private_data = ub;
 	ub->ublksrv_tgid = current->tgid;
+	mutex_lock(&ub->cancel_mutex);
+	ub->ch_file = filp;
+	mutex_unlock(&ub->cancel_mutex);
 	return 0;
 }
 
@@ -2415,11 +2429,17 @@ static void ublk_reset_ch_dev(struct ublk_device *ub)
 		spin_unlock(&ubq->cancel_lock);
 	}
 
+	/* a new FETCH round starts, the queues stay canceling until ready */
+	mutex_lock(&ub->cancel_mutex);
+	ub->canceling = false;
+	mutex_unlock(&ub->cancel_mutex);
+
 	/* set to NULL, otherwise new tasks cannot mmap io_cmd_buf */
 	ub->mm = NULL;
 	ub->nr_queue_ready = 0;
 	ub->unprivileged_daemons = false;
 	ub->ublksrv_tgid = -1;
+	clear_bit(UB_STATE_STOPPING, &ub->state);
 }
 
 static struct gendisk *ublk_get_disk(struct ublk_device *ub)
@@ -2539,12 +2559,15 @@ static void ublk_ch_release_work_fn(struct work_struct *work)
 	}
 
 	/*
-	 * disk isn't attached yet, either device isn't live, or it has
-	 * been removed already, so we needn't to do anything
+	 * No disk: the device isn't live, or it has been removed already.
+	 * There are no requests to abort, but the round still has to be
+	 * reset, so that a new server can fetch and start the device.
 	 */
 	disk = ublk_get_disk(ub);
-	if (!disk)
-		goto out;
+	if (!disk) {
+		mutex_lock(&ub->mutex);
+		goto reset;
+	}
 
 	/*
 	 * All uring_cmd are done now, so abort any request outstanding to
@@ -2576,7 +2599,7 @@ static void ublk_ch_release_work_fn(struct work_struct *work)
 
 	/* double check after grabbing lock */
 	if (!ub->ub_disk)
-		goto unlock;
+		goto reset;
 
 	/*
 	 * Transition the device to the nosrv state. What exactly this
@@ -2602,13 +2625,14 @@ static void ublk_ch_release_work_fn(struct work_struct *work)
 				WRITE_ONCE(ublk_get_queue(ub, i)->fail_io, true);
 		}
 	}
-unlock:
+reset:
+	/*
+	 * All uring_cmd has been done now, reset device & ubq. Under
+	 * ub->mutex, so START_DEV sees the round either ready or reset.
+	 */
+	ublk_reset_ch_dev(ub);
 	mutex_unlock(&ub->mutex);
 	ublk_put_disk(disk);
-
-	/* all uring_cmd has been done now, reset device & ubq */
-	ublk_reset_ch_dev(ub);
-out:
 	clear_bit(UB_STATE_OPEN, &ub->state);
 
 	/* put the reference grabbed in ublk_ch_release() */
@@ -2619,6 +2643,9 @@ static int ublk_ch_release(struct inode *inode, struct file *filp)
 {
 	struct ublk_device *ub = filp->private_data;
 
+	mutex_lock(&ub->cancel_mutex);
+	ub->ch_file = NULL;
+	mutex_unlock(&ub->cancel_mutex);
 	/*
 	 * Grab ublk device reference, so it won't be gone until we are
 	 * really released from work function.
@@ -2732,9 +2759,11 @@ static void ublk_abort_queue(struct ublk_device *ub, struct ublk_queue *ubq)
 
 static void ublk_start_cancel(struct ublk_device *ub)
 {
-	struct gendisk *disk = ublk_get_disk(ub);
+	struct gendisk *disk;
 
+	/* sync with ublk_ctrl_start_dev() publishing the disk */
 	mutex_lock(&ub->cancel_mutex);
+	disk = ublk_get_disk(ub);
 	if (ub->canceling)
 		goto out;
 
@@ -2790,7 +2819,8 @@ static void ublk_cancel_cmd(struct ublk_queue *ubq, u16 tag,
 	done = !!(io->flags & UBLK_IO_FLAG_CANCELED);
 	if (!done) {
 		io->flags |= UBLK_IO_FLAG_CANCELED;
-		cmd = io->cmd;
+		/* dependency ordered against smp_wmb() in ublk_prep_cancel() */
+		cmd = READ_ONCE(io->cmd);
 		io->cmd = NULL;
 	}
 	spin_unlock(&ubq->cancel_lock);
@@ -2879,6 +2909,7 @@ static void ublk_uring_cmd_cancel_fn(struct io_uring_cmd *cmd,
 {
 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
 	struct ublk_queue *ubq = pdu->ubq;
+	struct io_uring_cmd *cur;
 	struct task_struct *task;
 	struct ublk_io *io;
 
@@ -2895,7 +2926,9 @@ static void ublk_uring_cmd_cancel_fn(struct io_uring_cmd *cmd,
 
 	ublk_start_cancel(ubq->dev);
 
-	WARN_ON_ONCE(io->cmd != cmd);
+	/* NULL if a cancel from the control path took it meanwhile */
+	cur = READ_ONCE(io->cmd);
+	WARN_ON_ONCE(cur && cur != cmd);
 	ublk_cancel_cmd(ubq, pdu->tag, issue_flags);
 }
 
@@ -3006,13 +3039,54 @@ static void ublk_stop_dev_unlocked(struct ublk_device *ub)
 	put_disk(disk);
 }
 
+static struct file *ublk_get_ch_file(struct ublk_device *ub)
+{
+	struct file *file;
+
+	mutex_lock(&ub->cancel_mutex);
+	file = ub->ch_file;
+	if (file && !file_ref_get(&file->f_ref))
+		file = NULL;
+	mutex_unlock(&ub->cancel_mutex);
+	return file;
+}
+
 static void ublk_stop_dev(struct ublk_device *ub)
 {
+	struct file *file;
+
+	/*
+	 * FETCH, PREP and START_DEV take ub->mutex. If a server has
+	 * /dev/ublkcN open, set STOPPING, which turns it away, and hold a
+	 * reference on the file: the server's release, whose reset clears
+	 * STOPPING and lets a new server attach, can't run before we drop it.
+	 * So the cancel can run after the unlock and only meets this server's
+	 * commands; it has to: io_uring_cmd_done() may take uring_lock, under
+	 * which FETCH takes ub->mutex.
+	 */
 	mutex_lock(&ub->mutex);
 	ublk_stop_dev_unlocked(ub);
-	mutex_unlock(&ub->mutex);
 	cancel_work_sync(&ub->partition_scan_work);
+	file = ublk_get_ch_file(ub);
+	if (file) {
+		/*
+		 * The server has to close /dev/ublkcN before this device can
+		 * be started again: the reset in its release clears STOPPING.
+		 */
+		set_bit(UB_STATE_STOPPING, &ub->state);
+		/* for wake_up_var() below, see wake_up_bit() */
+		smp_mb__after_atomic();
+	}
+	mutex_unlock(&ub->mutex);
+
+	/* no server: nothing to cancel */
+	if (!file)
+		return;
+
+	/* wake a START_DEV waiting for the device to get ready */
+	wake_up_var(&ub->nr_queue_ready);
 	ublk_cancel_dev(ub);
+	__fput_sync(file);
 }
 
 static void ublk_reset_io_flags(struct ublk_queue *ubq, struct ublk_io *io)
@@ -3024,11 +3098,19 @@ static void ublk_reset_io_flags(struct ublk_queue *ubq, struct ublk_io *io)
 }
 
 /* reset per-queue io flags */
-static void ublk_queue_reset_io_flags(struct ublk_queue *ubq)
+static void ublk_queue_reset_io_flags(struct ublk_device *ub,
+				      struct ublk_queue *ubq)
 {
-	spin_lock(&ubq->cancel_lock);
-	ubq->canceling = false;
-	spin_unlock(&ubq->cancel_lock);
+	/*
+	 * A cancel in this FETCH round took a command which still counts as
+	 * ready, so the queue has to stay canceling. ub->canceling is set
+	 * under cancel_mutex before any command is taken: either we see it
+	 * here, or the cancel marks this queue again later.
+	 */
+	mutex_lock(&ub->cancel_mutex);
+	if (!ub->canceling)
+		ubq->canceling = false;
+	mutex_unlock(&ub->cancel_mutex);
 	ubq->fail_io = false;
 }
 
@@ -3050,24 +3132,17 @@ static void ublk_mark_io_ready(struct ublk_device *ub, u16 q_id,
 		ub->nr_queue_ready++;
 
 		/*
-		 * Reset queue flags as soon as this queue is ready.
-		 * This clears the canceling flag, allowing batch FETCH commands
-		 * to succeed during recovery without waiting for all queues.
+		 * Reset queue flags as soon as this queue is ready. Unless
+		 * this round saw a cancel, this clears the canceling flag,
+		 * allowing batch FETCH commands to succeed during recovery
+		 * without waiting for all queues.
 		 */
-		ublk_queue_reset_io_flags(ubq);
+		ublk_queue_reset_io_flags(ub, ubq);
 	}
 
-	/* Check if all queues are ready */
-	if (ublk_dev_ready(ub)) {
-		/*
-		 * All queues ready - clear device-level canceling flag
-		 * and wake ublk_dev_ready() waiters.
-		 */
-		mutex_lock(&ub->cancel_mutex);
-		ub->canceling = false;
-		mutex_unlock(&ub->cancel_mutex);
+	/* All queues ready - wake ublk_dev_ready() waiters */
+	if (ublk_dev_ready(ub))
 		wake_up_var(&ub->nr_queue_ready);
-	}
 }
 
 static inline int ublk_check_cmd_op(u32 cmd_op)
@@ -3151,6 +3226,12 @@ ublk_fill_io_cmd(struct ublk_io *io, struct io_uring_cmd *cmd)
 	return req;
 }
 
+/*
+ * Call before ublk_fill_io_cmd() publishes @cmd in io->cmd: a control-path
+ * cancel may complete any command found there, and io_uring_cmd_done() only
+ * takes it off the cancelable list if it is marked already. The handlers
+ * hold uring_lock, so marking takes no lock.
+ */
 static inline void ublk_prep_cancel(struct io_uring_cmd *cmd,
 				    unsigned int issue_flags,
 				    struct ublk_queue *ubq, u16 tag)
@@ -3164,6 +3245,8 @@ static inline void ublk_prep_cancel(struct io_uring_cmd *cmd,
 	pdu->ubq = ubq;
 	pdu->tag = tag;
 	io_uring_cmd_mark_cancelable(cmd, issue_flags);
+	/* pairs with the cancel loading cmd from io->cmd, then cmd->flags */
+	smp_wmb();
 }
 
 static void ublk_io_release(void *priv)
@@ -3268,6 +3351,9 @@ static int ublk_check_fetch_buf(const struct ublk_device *ub, __u64 buf_addr)
 static int __ublk_fetch(struct io_uring_cmd *cmd, struct ublk_device *ub,
 			struct ublk_io *io, u16 q_id)
 {
+	if (test_bit(UB_STATE_STOPPING, &ub->state))
+		return UBLK_IO_RES_ABORT;
+
 	/* UBLK_IO_FETCH_REQ is only allowed before dev is setup */
 	if (ublk_dev_ready(ub))
 		return -EBUSY;
@@ -3411,11 +3497,11 @@ static int ublk_ch_uring_cmd_local(struct io_uring_cmd *cmd,
 		ret = ublk_check_fetch_buf(ub, addr);
 		if (ret)
 			goto out;
+		/* before ublk_fetch() publishes io->cmd, see ublk_prep_cancel() */
+		ublk_prep_cancel(cmd, issue_flags, ubq, tag);
 		ret = ublk_fetch(cmd, ub, io, addr, q_id);
 		if (ret)
-			goto out;
-
-		ublk_prep_cancel(cmd, issue_flags, ubq, tag);
+			goto out_done;
 		return -EIOCBQUEUED;
 	}
 
@@ -3459,6 +3545,7 @@ static int ublk_ch_uring_cmd_local(struct io_uring_cmd *cmd,
 		if (ret)
 			goto out;
 		io->res = result;
+		ublk_prep_cancel(cmd, issue_flags, ubq, tag);
 		req = ublk_fill_io_cmd(io, cmd);
 		ublk_apply_io_buf(ub, io, cmd, addr, &auto_buf, &buf_idx);
 		if (buf_idx != UBLK_INVALID_BUF_IDX)
@@ -3477,19 +3564,24 @@ static int ublk_ch_uring_cmd_local(struct io_uring_cmd *cmd,
 		 * uring_cmd active first and prepare for handling new requeued
 		 * request
 		 */
+		ublk_prep_cancel(cmd, issue_flags, ubq, tag);
 		req = ublk_fill_io_cmd(io, cmd);
 		io->buf.addr = addr;
 		if (likely(ublk_get_data(ubq, io, req))) {
 			__ublk_prep_compl_io_cmd(io, req);
-			return UBLK_IO_RES_OK;
+			ret = UBLK_IO_RES_OK;
+			goto out_done;
 		}
 		break;
 	default:
 		goto out;
 	}
-	ublk_prep_cancel(cmd, issue_flags, ubq, tag);
 	return -EIOCBQUEUED;
 
+ out_done:
+	/* marked cancelable: complete through io_uring_cmd_done() */
+	io_uring_cmd_done(cmd, ret, issue_flags);
+	return -EIOCBQUEUED;
  out:
 	pr_devel("%s: complete: cmd op %d, tag %d ret %x io_flags %x\n",
 			__func__, cmd_op, tag, ret, io ? io->flags : 0);
@@ -3888,6 +3980,15 @@ static int ublk_batch_attach(struct ublk_queue *ubq,
 	bool free = false;
 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(data->cmd);
 
+	/*
+	 * Mark it cancelable before linking it into fcmd_head, where a cancel
+	 * from the control path can take and complete it: see
+	 * ublk_prep_cancel(). evts_lock orders the mark before the link.
+	 */
+	pdu->ubq = ubq;
+	pdu->fcmd = fcmd;
+	io_uring_cmd_mark_cancelable(fcmd->cmd, data->issue_flags);
+
 	spin_lock(&ubq->evts_lock);
 	if (unlikely(ubq->force_abort || ubq->canceling)) {
 		free = true;
@@ -3898,14 +3999,12 @@ static int ublk_batch_attach(struct ublk_queue *ubq,
 	spin_unlock(&ubq->evts_lock);
 
 	if (unlikely(free)) {
+		/* off the cancelable list first, then nothing can see fcmd */
+		io_uring_cmd_done(data->cmd, -ENODEV, data->issue_flags);
 		ublk_batch_free_fcmd(fcmd);
-		return -ENODEV;
+		return -EIOCBQUEUED;
 	}
 
-	pdu->ubq = ubq;
-	pdu->fcmd = fcmd;
-	io_uring_cmd_mark_cancelable(fcmd->cmd, data->issue_flags);
-
 	if (!new_fcmd)
 		goto out;
 
@@ -3913,9 +4012,12 @@ static int ublk_batch_attach(struct ublk_queue *ubq,
 	 * If the two fetch commands are originated from same io_ring_ctx,
 	 * run batch dispatch directly. Otherwise, schedule task work for
 	 * doing it.
+	 *
+	 * Use data->cmd, not fcmd->cmd: once fcmd is linked and not active,
+	 * a cancel from the control path may complete and free it.
 	 */
 	if (io_uring_cmd_ctx_handle(new_fcmd->cmd) ==
-			io_uring_cmd_ctx_handle(fcmd->cmd)) {
+			io_uring_cmd_ctx_handle(data->cmd)) {
 		data->cmd = new_fcmd->cmd;
 		ublk_batch_dispatch(ubq, data, new_fcmd);
 	} else {
@@ -4431,21 +4533,27 @@ static bool ublk_validate_user_pid(struct ublk_device *ub, pid_t ublksrv_pid)
 	return ub->ublksrv_tgid == ublksrv_pid;
 }
 
+static bool ublk_dev_ready_or_stopping(const struct ublk_device *ub)
+{
+	return ublk_dev_ready(ub) || test_bit(UB_STATE_STOPPING, &ub->state);
+}
+
 /*
- * Wait until all queues have fetched their I/O commands, and return with
- * ub->mutex held and readiness guaranteed: then every queue's ->canceling
- * is cleared. Ready may regress between wakeup and mutex_lock() (F_BATCH
- * UNPREP, daemon death), so re-check it under the mutex and wait again.
+ * Wait until all queues have fetched their I/O commands, or STOP_DEV set
+ * UB_STATE_STOPPING, and return with ub->mutex held. The queues stay
+ * canceling if this round saw a cancel, see ublk_queue_reset_io_flags().
+ * Ready may regress between wakeup and mutex_lock() (F_BATCH UNPREP,
+ * daemon death), so re-check it under the mutex and wait again.
  */
 static int ublk_wait_dev_ready_and_lock(struct ublk_device *ub)
 {
 	while (true) {
 		if (wait_var_event_interruptible(&ub->nr_queue_ready,
-						 ublk_dev_ready(ub)))
+						 ublk_dev_ready_or_stopping(ub)))
 			return -EINTR;
 
 		mutex_lock(&ub->mutex);
-		if (ublk_dev_ready(ub))
+		if (ublk_dev_ready_or_stopping(ub))
 			return 0;
 		mutex_unlock(&ub->mutex);
 	}
@@ -4469,6 +4577,7 @@ static int ublk_ctrl_start_dev(struct ublk_device *ub,
 		.dma_alignment		= 3,
 	};
 	struct gendisk *disk;
+	bool canceled;
 	int ret = -EINVAL;
 
 	if (ublksrv_pid <= 0)
@@ -4545,6 +4654,10 @@ static int ublk_ctrl_start_dev(struct ublk_device *ub,
 		ret = -EEXIST;
 		goto out_unlock;
 	}
+	if (test_bit(UB_STATE_STOPPING, &ub->state)) {
+		ret = -EBUSY;
+		goto out_unlock;
+	}
 
 	disk = blk_mq_alloc_disk(&ub->tag_set, &lim, NULL);
 	if (IS_ERR(disk)) {
@@ -4555,8 +4668,24 @@ static int ublk_ctrl_start_dev(struct ublk_device *ub,
 	disk->fops = &ub_fops;
 	disk->private_data = ub;
 
+	/*
+	 * A command of this FETCH round was canceled and can't be fetched
+	 * again, don't bring up a disk over it.  Check and publish the disk
+	 * in one cancel_mutex section: either this sees ub->canceling, or
+	 * ublk_start_cancel() sees the disk and quiesces it before marking
+	 * the queues.
+	 */
+	mutex_lock(&ub->cancel_mutex);
+	canceled = ub->canceling;
+	if (!canceled)
+		ub->ub_disk = disk;
+	mutex_unlock(&ub->cancel_mutex);
+	if (canceled) {
+		put_disk(disk);
+		ret = -EBUSY;
+		goto out_unlock;
+	}
 	ub->dev_info.ublksrv_pid = ub->ublksrv_tgid;
-	ub->ub_disk = disk;
 
 	ublk_apply_params(ub);
 
@@ -5133,6 +5262,7 @@ static int ublk_ctrl_end_recovery(struct ublk_device *ub,
 		const struct ublksrv_ctrl_cmd *header)
 {
 	int ublksrv_pid = (int)header->data[0];
+	bool canceled;
 	int ret = -EINVAL;
 
 	pr_devel("%s: Waiting for all FETCH_REQs, dev id %d...\n", __func__,
@@ -5156,6 +5286,20 @@ static int ublk_ctrl_end_recovery(struct ublk_device *ub,
 		ret = -EBUSY;
 		goto out_unlock;
 	}
+
+	/*
+	 * As in ublk_ctrl_start_dev(), a canceled command can't be fetched
+	 * again.  Best effort: the disk exists here, and a cancel after this
+	 * check is the ordinary death of the new server, which
+	 * ublk_start_cancel() handles by quiescing and marking.
+	 */
+	mutex_lock(&ub->cancel_mutex);
+	canceled = ub->canceling;
+	mutex_unlock(&ub->cancel_mutex);
+	if (canceled) {
+		ret = -EBUSY;
+		goto out_unlock;
+	}
 	ub->dev_info.ublksrv_pid = ub->ublksrv_tgid;
 	ub->dev_info.state = UBLK_S_DEV_LIVE;
 	pr_devel("%s: new ublksrv_pid %d, dev id %d\n",
diff --git a/tools/testing/selftests/ublk/.gitignore b/tools/testing/selftests/ublk/.gitignore
index e17bd28f27e04..d8e93fef7fcd3 100644
--- a/tools/testing/selftests/ublk/.gitignore
+++ b/tools/testing/selftests/ublk/.gitignore
@@ -3,3 +3,4 @@
 /tools
 kublk
 metadata_size
+ublk_cancel_ready
diff --git a/tools/testing/selftests/ublk/Makefile b/tools/testing/selftests/ublk/Makefile
index 5daf36c6c36c4..0d7c3dd9812ed 100644
--- a/tools/testing/selftests/ublk/Makefile
+++ b/tools/testing/selftests/ublk/Makefile
@@ -19,6 +19,7 @@ TEST_PROGS += test_generic_12.sh
 TEST_PROGS += test_generic_13.sh
 TEST_PROGS += test_generic_16.sh
 TEST_PROGS += test_generic_17.sh
+TEST_PROGS += test_generic_18.sh
 
 TEST_PROGS += test_batch_01.sh
 TEST_PROGS += test_batch_02.sh
@@ -74,13 +75,14 @@ TEST_PROGS += test_stress_09.sh
 
 TEST_FILES := settings
 
-TEST_GEN_PROGS_EXTENDED = kublk metadata_size
-STANDALONE_UTILS := metadata_size.c
+TEST_GEN_PROGS_EXTENDED = kublk metadata_size ublk_cancel_ready
+STANDALONE_UTILS := metadata_size.c ublk_cancel_ready.c
 
 LOCAL_HDRS += $(wildcard *.h)
 include ../lib.mk
 
 $(OUTPUT)/kublk: $(filter-out $(STANDALONE_UTILS),$(wildcard *.c))
+$(OUTPUT)/ublk_cancel_ready: ublk_cancel_ready.c ctrl.c
 
 check:
 	shellcheck -x -f gcc *.sh
diff --git a/tools/testing/selftests/ublk/batch.c b/tools/testing/selftests/ublk/batch.c
index d8d9ebed5979f..dfc81ee17d076 100644
--- a/tools/testing/selftests/ublk/batch.c
+++ b/tools/testing/selftests/ublk/batch.c
@@ -410,9 +410,16 @@ static void ublk_batch_compl_commit_cmd(struct ublk_thread *t,
 {
 	unsigned short buf_idx = user_data_to_tag(cqe->user_data);
 
-	if (op == _IOC_NR(UBLK_U_IO_PREP_IO_CMDS))
-		ublk_assert(cqe->res == 0);
-	else if (op == _IOC_NR(UBLK_U_IO_COMMIT_IO_CMDS)) {
+	if (op == _IOC_NR(UBLK_U_IO_PREP_IO_CMDS)) {
+		/* e.g. UBLK_IO_RES_ABORT after STOP_DEV: stop like a FETCH */
+		if (cqe->res < 0) {
+			ublk_dbg(UBLK_DBG_IO_CMD, "%s: prep failed %d\n",
+				 __func__, cqe->res);
+			t->state |= UBLKS_T_STOPPING;
+		} else {
+			ublk_assert(cqe->res == 0);
+		}
+	} else if (op == _IOC_NR(UBLK_U_IO_COMMIT_IO_CMDS)) {
 		int nr_elem = user_data_to_tgt_data(cqe->user_data);
 
 		ublk_assert(cqe->res == t->commit_buf_elem_size * nr_elem);
diff --git a/tools/testing/selftests/ublk/ctrl.c b/tools/testing/selftests/ublk/ctrl.c
new file mode 100644
index 0000000000000..53d54799f9097
--- /dev/null
+++ b/tools/testing/selftests/ublk/ctrl.c
@@ -0,0 +1,268 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/* ublk control commands, shared by kublk and ublk_cancel_ready */
+
+#include "kublk.h"
+
+static void ublk_ctrl_init_cmd(struct ublk_dev *dev,
+		struct io_uring_sqe *sqe,
+		struct ublk_ctrl_cmd_data *data)
+{
+	struct ublksrv_ctrl_dev_info *info = &dev->dev_info;
+	struct ublksrv_ctrl_cmd *cmd = (struct ublksrv_ctrl_cmd *)ublk_get_sqe_cmd(sqe);
+
+	sqe->fd = dev->ctrl_fd;
+	sqe->opcode = IORING_OP_URING_CMD;
+	sqe->ioprio = 0;
+
+	if (data->flags & CTRL_CMD_HAS_BUF) {
+		cmd->addr = data->addr;
+		cmd->len = data->len;
+	}
+
+	if (data->flags & CTRL_CMD_HAS_DATA)
+		cmd->data[0] = data->data[0];
+
+	cmd->dev_id = info->dev_id;
+	cmd->queue_id = -1;
+
+	ublk_set_sqe_cmd_op(sqe, data->cmd_op);
+
+	io_uring_sqe_set_data(sqe, cmd);
+}
+
+int __ublk_ctrl_cmd(struct ublk_dev *dev,
+		struct ublk_ctrl_cmd_data *data)
+{
+	struct io_uring_sqe *sqe;
+	struct io_uring_cqe *cqe;
+	int ret = -EINVAL;
+
+	sqe = io_uring_get_sqe(&dev->ring);
+	if (!sqe) {
+		ublk_err("%s: can't get sqe ret %d\n", __func__, ret);
+		return ret;
+	}
+
+	ublk_ctrl_init_cmd(dev, sqe, data);
+
+	ret = io_uring_submit(&dev->ring);
+	if (ret < 0) {
+		ublk_err("uring submit ret %d\n", ret);
+		return ret;
+	}
+
+	ret = io_uring_wait_cqe(&dev->ring, &cqe);
+	if (ret < 0) {
+		ublk_err("wait cqe: %s\n", strerror(-ret));
+		return ret;
+	}
+	io_uring_cqe_seen(&dev->ring, cqe);
+
+	return cqe->res;
+}
+
+void ublk_ctrl_deinit(struct ublk_dev *dev)
+{
+	io_uring_queue_exit(&dev->ring);
+	close(dev->ctrl_fd);
+	free(dev);
+}
+
+struct ublk_dev *ublk_ctrl_init(void)
+{
+	struct ublk_dev *dev = (struct ublk_dev *)calloc(1, sizeof(*dev));
+	struct ublksrv_ctrl_dev_info *info;
+	int ret;
+
+	if (!dev)
+		return NULL;
+	info = &dev->dev_info;
+	dev->ctrl_fd = open(CTRL_DEV, O_RDWR);
+	if (dev->ctrl_fd < 0) {
+		free(dev);
+		return NULL;
+	}
+
+	info->max_io_buf_bytes = UBLK_IO_MAX_BYTES;
+
+	ret = ublk_setup_ring(&dev->ring, UBLK_CTRL_RING_DEPTH,
+			UBLK_CTRL_RING_DEPTH, IORING_SETUP_SQE128);
+	if (ret < 0) {
+		ublk_err("queue_init: %s\n", strerror(-ret));
+		close(dev->ctrl_fd);
+		free(dev);
+		return NULL;
+	}
+	dev->nr_fds = 1;
+
+	return dev;
+}
+
+int ublk_ctrl_stop_dev(struct ublk_dev *dev)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op	= UBLK_U_CMD_STOP_DEV,
+	};
+
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_try_stop_dev(struct ublk_dev *dev)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op	= UBLK_U_CMD_TRY_STOP_DEV,
+	};
+
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_start_dev(struct ublk_dev *dev,
+		int daemon_pid)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op	= UBLK_U_CMD_START_DEV,
+		.flags	= CTRL_CMD_HAS_DATA,
+	};
+
+	dev->dev_info.ublksrv_pid = data.data[0] = daemon_pid;
+
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_start_user_recovery(struct ublk_dev *dev)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op	= UBLK_U_CMD_START_USER_RECOVERY,
+	};
+
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_end_user_recovery(struct ublk_dev *dev, int daemon_pid)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op	= UBLK_U_CMD_END_USER_RECOVERY,
+		.flags	= CTRL_CMD_HAS_DATA,
+	};
+
+	dev->dev_info.ublksrv_pid = data.data[0] = daemon_pid;
+
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_add_dev(struct ublk_dev *dev)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op	= UBLK_U_CMD_ADD_DEV,
+		.flags	= CTRL_CMD_HAS_BUF,
+		.addr = (__u64) (uintptr_t) &dev->dev_info,
+		.len = sizeof(struct ublksrv_ctrl_dev_info),
+	};
+
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_del_dev(struct ublk_dev *dev)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op = UBLK_U_CMD_DEL_DEV,
+		.flags = 0,
+	};
+
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_get_info(struct ublk_dev *dev)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op	= UBLK_U_CMD_GET_DEV_INFO,
+		.flags	= CTRL_CMD_HAS_BUF,
+		.addr = (__u64) (uintptr_t) &dev->dev_info,
+		.len = sizeof(struct ublksrv_ctrl_dev_info),
+	};
+
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_set_params(struct ublk_dev *dev,
+		struct ublk_params *params)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op	= UBLK_U_CMD_SET_PARAMS,
+		.flags	= CTRL_CMD_HAS_BUF,
+		.addr = (__u64) (uintptr_t) params,
+		.len = sizeof(*params),
+	};
+	params->len = sizeof(*params);
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_get_params(struct ublk_dev *dev,
+		struct ublk_params *params)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op	= UBLK_U_CMD_GET_PARAMS,
+		.flags	= CTRL_CMD_HAS_BUF,
+		.addr = (__u64)params,
+		.len = sizeof(*params),
+	};
+
+	params->len = sizeof(*params);
+
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_get_features(struct ublk_dev *dev,
+		__u64 *features)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op	= UBLK_U_CMD_GET_FEATURES,
+		.flags	= CTRL_CMD_HAS_BUF,
+		.addr = (__u64) (uintptr_t) features,
+		.len = sizeof(*features),
+	};
+
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_update_size(struct ublk_dev *dev,
+		__u64 nr_sects)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op	= UBLK_U_CMD_UPDATE_SIZE,
+		.flags	= CTRL_CMD_HAS_DATA,
+	};
+
+	data.data[0] = nr_sects;
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_quiesce_dev(struct ublk_dev *dev, unsigned int timeout_ms)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op	= UBLK_U_CMD_QUIESCE_DEV,
+		.flags	= CTRL_CMD_HAS_DATA,
+	};
+
+	data.data[0] = timeout_ms;
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_reg_buf(struct ublk_dev *dev, void *addr, size_t size,
+		      __u32 flags)
+{
+	struct ublk_shmem_buf_reg buf_reg = {
+		.addr = (unsigned long)addr,
+		.len = size,
+		.flags = flags,
+	};
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op = UBLK_U_CMD_REG_BUF,
+		.flags = CTRL_CMD_HAS_BUF,
+		.addr = (unsigned long)&buf_reg,
+		.len = sizeof(buf_reg),
+	};
+
+	return __ublk_ctrl_cmd(dev, &data);
+}
diff --git a/tools/testing/selftests/ublk/kublk.c b/tools/testing/selftests/ublk/kublk.c
index 2400b46157664..15ba060ce7a3c 100644
--- a/tools/testing/selftests/ublk/kublk.c
+++ b/tools/testing/selftests/ublk/kublk.c
@@ -37,203 +37,6 @@ static const struct ublk_tgt_ops *ublk_find_tgt(const char *name)
 	return NULL;
 }
 
-static inline int ublk_setup_ring(struct io_uring *r, int depth,
-		int cq_depth, unsigned flags)
-{
-	struct io_uring_params p;
-
-	memset(&p, 0, sizeof(p));
-	p.flags = flags | IORING_SETUP_CQSIZE;
-	p.cq_entries = cq_depth;
-
-	return io_uring_queue_init_params(depth, r, &p);
-}
-
-static void ublk_ctrl_init_cmd(struct ublk_dev *dev,
-		struct io_uring_sqe *sqe,
-		struct ublk_ctrl_cmd_data *data)
-{
-	struct ublksrv_ctrl_dev_info *info = &dev->dev_info;
-	struct ublksrv_ctrl_cmd *cmd = (struct ublksrv_ctrl_cmd *)ublk_get_sqe_cmd(sqe);
-
-	sqe->fd = dev->ctrl_fd;
-	sqe->opcode = IORING_OP_URING_CMD;
-	sqe->ioprio = 0;
-
-	if (data->flags & CTRL_CMD_HAS_BUF) {
-		cmd->addr = data->addr;
-		cmd->len = data->len;
-	}
-
-	if (data->flags & CTRL_CMD_HAS_DATA)
-		cmd->data[0] = data->data[0];
-
-	cmd->dev_id = info->dev_id;
-	cmd->queue_id = -1;
-
-	ublk_set_sqe_cmd_op(sqe, data->cmd_op);
-
-	io_uring_sqe_set_data(sqe, cmd);
-}
-
-static int __ublk_ctrl_cmd(struct ublk_dev *dev,
-		struct ublk_ctrl_cmd_data *data)
-{
-	struct io_uring_sqe *sqe;
-	struct io_uring_cqe *cqe;
-	int ret = -EINVAL;
-
-	sqe = io_uring_get_sqe(&dev->ring);
-	if (!sqe) {
-		ublk_err("%s: can't get sqe ret %d\n", __func__, ret);
-		return ret;
-	}
-
-	ublk_ctrl_init_cmd(dev, sqe, data);
-
-	ret = io_uring_submit(&dev->ring);
-	if (ret < 0) {
-		ublk_err("uring submit ret %d\n", ret);
-		return ret;
-	}
-
-	ret = io_uring_wait_cqe(&dev->ring, &cqe);
-	if (ret < 0) {
-		ublk_err("wait cqe: %s\n", strerror(-ret));
-		return ret;
-	}
-	io_uring_cqe_seen(&dev->ring, cqe);
-
-	return cqe->res;
-}
-
-static int ublk_ctrl_stop_dev(struct ublk_dev *dev)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op	= UBLK_U_CMD_STOP_DEV,
-	};
-
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
-static int ublk_ctrl_try_stop_dev(struct ublk_dev *dev)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op	= UBLK_U_CMD_TRY_STOP_DEV,
-	};
-
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
-static int ublk_ctrl_start_dev(struct ublk_dev *dev,
-		int daemon_pid)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op	= UBLK_U_CMD_START_DEV,
-		.flags	= CTRL_CMD_HAS_DATA,
-	};
-
-	dev->dev_info.ublksrv_pid = data.data[0] = daemon_pid;
-
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
-static int ublk_ctrl_start_user_recovery(struct ublk_dev *dev)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op	= UBLK_U_CMD_START_USER_RECOVERY,
-	};
-
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
-static int ublk_ctrl_end_user_recovery(struct ublk_dev *dev, int daemon_pid)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op	= UBLK_U_CMD_END_USER_RECOVERY,
-		.flags	= CTRL_CMD_HAS_DATA,
-	};
-
-	dev->dev_info.ublksrv_pid = data.data[0] = daemon_pid;
-
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
-static int ublk_ctrl_add_dev(struct ublk_dev *dev)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op	= UBLK_U_CMD_ADD_DEV,
-		.flags	= CTRL_CMD_HAS_BUF,
-		.addr = (__u64) (uintptr_t) &dev->dev_info,
-		.len = sizeof(struct ublksrv_ctrl_dev_info),
-	};
-
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
-static int ublk_ctrl_del_dev(struct ublk_dev *dev)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op = UBLK_U_CMD_DEL_DEV,
-		.flags = 0,
-	};
-
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
-static int ublk_ctrl_get_info(struct ublk_dev *dev)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op	= UBLK_U_CMD_GET_DEV_INFO,
-		.flags	= CTRL_CMD_HAS_BUF,
-		.addr = (__u64) (uintptr_t) &dev->dev_info,
-		.len = sizeof(struct ublksrv_ctrl_dev_info),
-	};
-
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
-static int ublk_ctrl_set_params(struct ublk_dev *dev,
-		struct ublk_params *params)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op	= UBLK_U_CMD_SET_PARAMS,
-		.flags	= CTRL_CMD_HAS_BUF,
-		.addr = (__u64) (uintptr_t) params,
-		.len = sizeof(*params),
-	};
-	params->len = sizeof(*params);
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
-static int ublk_ctrl_get_params(struct ublk_dev *dev,
-		struct ublk_params *params)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op	= UBLK_U_CMD_GET_PARAMS,
-		.flags	= CTRL_CMD_HAS_BUF,
-		.addr = (__u64)params,
-		.len = sizeof(*params),
-	};
-
-	params->len = sizeof(*params);
-
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
-static int ublk_ctrl_get_features(struct ublk_dev *dev,
-		__u64 *features)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op	= UBLK_U_CMD_GET_FEATURES,
-		.flags	= CTRL_CMD_HAS_BUF,
-		.addr = (__u64) (uintptr_t) features,
-		.len = sizeof(*features),
-	};
-
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
 static int parse_param_types(const char *arg, __u32 *types)
 {
 	char buf[128], *save = NULL, *tok;
@@ -283,30 +86,6 @@ static void ublk_init_params_from_ctx(const struct dev_ctx *ctx,
 	};
 }
 
-static int ublk_ctrl_update_size(struct ublk_dev *dev,
-		__u64 nr_sects)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op	= UBLK_U_CMD_UPDATE_SIZE,
-		.flags	= CTRL_CMD_HAS_DATA,
-	};
-
-	data.data[0] = nr_sects;
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
-static int ublk_ctrl_quiesce_dev(struct ublk_dev *dev,
-				 unsigned int timeout_ms)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op	= UBLK_U_CMD_QUIESCE_DEV,
-		.flags	= CTRL_CMD_HAS_DATA,
-	};
-
-	data.data[0] = timeout_ms;
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
 static const char *ublk_dev_state_desc(struct ublk_dev *dev)
 {
 	switch (dev->dev_info.state) {
@@ -426,38 +205,6 @@ static void ublk_ctrl_dump(struct ublk_dev *dev)
 	fflush(stdout);
 }
 
-static void ublk_ctrl_deinit(struct ublk_dev *dev)
-{
-	close(dev->ctrl_fd);
-	free(dev);
-}
-
-static struct ublk_dev *ublk_ctrl_init(void)
-{
-	struct ublk_dev *dev = (struct ublk_dev *)calloc(1, sizeof(*dev));
-	struct ublksrv_ctrl_dev_info *info = &dev->dev_info;
-	int ret;
-
-	dev->ctrl_fd = open(CTRL_DEV, O_RDWR);
-	if (dev->ctrl_fd < 0) {
-		free(dev);
-		return NULL;
-	}
-
-	info->max_io_buf_bytes = UBLK_IO_MAX_BYTES;
-
-	ret = ublk_setup_ring(&dev->ring, UBLK_CTRL_RING_DEPTH,
-			UBLK_CTRL_RING_DEPTH, IORING_SETUP_SQE128);
-	if (ret < 0) {
-		ublk_err("queue_init: %s\n", strerror(-ret));
-		free(dev);
-		return NULL;
-	}
-	dev->nr_fds = 1;
-
-	return dev;
-}
-
 static size_t __ublk_queue_cmd_buf_sz(const struct ublk_queue *q, __u16 depth)
 {
 	size_t size = depth * (size_t)q->io_desc_size;
@@ -1283,24 +1030,6 @@ static void ublk_shmem_unregister_all(void)
 	shmem_count = 0;
 }
 
-static int ublk_ctrl_reg_buf(struct ublk_dev *dev, void *addr, size_t size,
-			     __u32 flags)
-{
-	struct ublk_shmem_buf_reg buf_reg = {
-		.addr = (unsigned long)addr,
-		.len = size,
-		.flags = flags,
-	};
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op = UBLK_U_CMD_REG_BUF,
-		.flags = CTRL_CMD_HAS_BUF,
-		.addr = (unsigned long)&buf_reg,
-		.len = sizeof(buf_reg),
-	};
-
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
 /*
  * Handle one client connection: receive memfd, mmap it, register
  * the VA range with kernel, send back the assigned index.
diff --git a/tools/testing/selftests/ublk/kublk.h b/tools/testing/selftests/ublk/kublk.h
index d98f3d612d888..99b8ceff853cb 100644
--- a/tools/testing/selftests/ublk/kublk.h
+++ b/tools/testing/selftests/ublk/kublk.h
@@ -294,6 +294,38 @@ struct ublk_dev {
 
 extern int ublk_queue_io_cmd(struct ublk_thread *t, struct ublk_io *io);
 
+static inline int ublk_setup_ring(struct io_uring *r, int depth,
+		int cq_depth, unsigned int flags)
+{
+	struct io_uring_params p;
+
+	memset(&p, 0, sizeof(p));
+	p.flags = flags | IORING_SETUP_CQSIZE;
+	p.cq_entries = cq_depth;
+
+	return io_uring_queue_init_params(depth, r, &p);
+}
+
+/* ctrl.c: control commands */
+struct ublk_dev *ublk_ctrl_init(void);
+void ublk_ctrl_deinit(struct ublk_dev *dev);
+int __ublk_ctrl_cmd(struct ublk_dev *dev, struct ublk_ctrl_cmd_data *data);
+int ublk_ctrl_add_dev(struct ublk_dev *dev);
+int ublk_ctrl_del_dev(struct ublk_dev *dev);
+int ublk_ctrl_get_info(struct ublk_dev *dev);
+int ublk_ctrl_set_params(struct ublk_dev *dev, struct ublk_params *params);
+int ublk_ctrl_get_params(struct ublk_dev *dev, struct ublk_params *params);
+int ublk_ctrl_get_features(struct ublk_dev *dev, __u64 *features);
+int ublk_ctrl_start_dev(struct ublk_dev *dev, int daemon_pid);
+int ublk_ctrl_stop_dev(struct ublk_dev *dev);
+int ublk_ctrl_try_stop_dev(struct ublk_dev *dev);
+int ublk_ctrl_start_user_recovery(struct ublk_dev *dev);
+int ublk_ctrl_end_user_recovery(struct ublk_dev *dev, int daemon_pid);
+int ublk_ctrl_update_size(struct ublk_dev *dev, __u64 nr_sects);
+int ublk_ctrl_quiesce_dev(struct ublk_dev *dev, unsigned int timeout_ms);
+int ublk_ctrl_reg_buf(struct ublk_dev *dev, void *addr, size_t size,
+		      __u32 flags);
+
 static inline int __ublk_use_batch_io(__u64 flags)
 {
 	return flags & UBLK_F_BATCH_IO;
diff --git a/tools/testing/selftests/ublk/test_generic_18.sh b/tools/testing/selftests/ublk/test_generic_18.sh
new file mode 100755
index 0000000000000..2dbb59e238a41
--- /dev/null
+++ b/tools/testing/selftests/ublk/test_generic_18.sh
@@ -0,0 +1,69 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+
+. "$(cd "$(dirname "$0")" && pwd)"/test_common.sh
+
+ERR_CODE=0
+CANCEL_PROG="$(_ublk_test_top_dir)/ublk_cancel_ready"
+
+_prep_test "generic" "start device over canceled io commands"
+
+# STOP_DEV while kublk's UBLK_F_BATCH_IO server prepares and fetches: the
+# server has to fail cleanly when PREP or FETCH is aborted, so `kublk add`
+# must return either way.
+race_batch_stop()
+{
+	local id=9999 i res started=0
+
+	_have_feature "BATCH_IO" || return "$UBLK_SKIP_CODE"
+	for i in $(seq 1 20); do
+		timeout 20 "$UBLK_PROG" add -t null -q 2 -b -n "$id" > /dev/null 2>&1 &
+		local pid=$!
+		# vary where STOP_DEV lands relative to the batch PREP and FETCH
+		sleep "0.$((i % 10))"
+		"$UBLK_PROG" stop -n "$id" > /dev/null 2>&1
+		wait "$pid"
+		res=$?
+		"$UBLK_PROG" del -n "$id" > /dev/null 2>&1
+		if [ "$res" -eq 124 ]; then
+			echo "run $i: kublk add -b hung after STOP_DEV"
+			return 255
+		fi
+		[ "$res" -eq 0 ] && started=$((started + 1))
+	done
+	echo "20 runs: started $started, stopped before start $((20 - started))"
+}
+
+# race_batch_stop is above, the other modes are described in
+# ublk_cancel_ready.c
+for mode in stop_start partial_fetch recovery stop_restart stop_attached \
+		stop_live_restart race_start race_fetch race_async_fetch \
+		race_batch_stop; do
+	dmesg_before=$(dmesg | wc -l)
+	if [ "$mode" = race_batch_stop ]; then
+		race_batch_stop > "$UBLK_TMP" 2>&1
+	else
+		timeout 60 "$CANCEL_PROG" "$mode" > "$UBLK_TMP" 2>&1
+	fi
+	res=$?
+	msg=""
+
+	if dmesg | tail -n +"$((dmesg_before + 1))" | \
+			grep -q -e "BUG:" -e "Oops" -e "WARNING:"; then
+		msg="$mode: kernel oops/warning"
+		ERR_CODE=255
+	elif [ "$res" -eq "$UBLK_SKIP_CODE" ]; then
+		[ "$ERR_CODE" -eq 0 ] && ERR_CODE=$UBLK_SKIP_CODE
+	elif [ "$res" -ne 0 ]; then
+		msg="$mode: failed ($res)"
+		ERR_CODE=255
+	fi
+	# the output once: on failure, or always when not quiet
+	[ -n "$msg" ] && echo "$msg"
+	if [ -n "$msg" ] || [ "$UBLK_TEST_QUIET" -eq 0 ]; then
+		cat "$UBLK_TMP"
+	fi
+done
+
+_cleanup_test
+_show_result $TID $ERR_CODE
diff --git a/tools/testing/selftests/ublk/ublk_cancel_ready.c b/tools/testing/selftests/ublk/ublk_cancel_ready.c
new file mode 100644
index 0000000000000..23071babc0e4c
--- /dev/null
+++ b/tools/testing/selftests/ublk/ublk_cancel_ready.c
@@ -0,0 +1,957 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Bring a ublk device live while some of its fetched io commands are
+ * canceled.
+ *
+ * A cancel completes a fetched command and clears io->cmd, but the io
+ * still counts as ready. Only ubq->canceling keeps ublk_queue_rq() away
+ * from the NULL io->cmd. Each mode below loses ->canceling in another way:
+ *
+ * stop_start:    fetch every tag, STOP_DEV before START_DEV, START_DEV.
+ *                STOP_DEV cancels the commands of the attached server,
+ *                so START_DEV must get -EBUSY until that server is gone.
+ *                An unfixed kernel starts the device over them.
+ *
+ * partial_fetch: task A fetches tags 0..depth-2 and dies, so its
+ *                commands are canceled. Task B fetches the last tag, and
+ *                an unfixed kernel clears ->canceling when the queue gets
+ *                ready. /dev/ublkcN stays open all the time, so
+ *                ublk_ch_release() never resets the queue.
+ *
+ * recovery:      a UBLK_F_USER_RECOVERY device with two queues loses its
+ *                server. During recovery task Q0 fetches queue 0, which
+ *                clears q0->canceling, then dies. An unfixed kernel still
+ *                has ub->canceling set because queue 1 is not ready, so
+ *                ublk_start_cancel() does not mark queue 0 again. Reads
+ *                are issued on a CPU mapped to queue 0.
+ *
+ * In partial_fetch and recovery, START_DEV / END_USER_RECOVERY must refuse
+ * with -EBUSY. An unfixed kernel oopses in ublk_queue_cmd() on a NULL
+ * io->cmd.
+ *
+ * stop_restart:  control mode. STOP_DEV on a new device, before any
+ *                server opened it, takes no command. A server started
+ *                afterwards has to start the device and serve I/O.
+ *
+ * stop_attached: STOP_DEV on a device whose server opened it but fetched
+ *                nothing stops that server too: FETCH gets ABORT and
+ *                START_DEV -EBUSY, until a new server opens the device.
+ *
+ * stop_live_restart: STOP_DEV on a live device; once its server is gone,
+ *                a new server has to fetch and start it again. An unfixed
+ *                ublk_ch_release() skips the reset once the disk is gone,
+ *                so the new FETCH gets -EBUSY.
+ *
+ * race_start:    STOP_DEV and START_DEV at the same time on a device whose
+ *                server fetched every tag. START_DEV either wins, and
+ *                reads complete (they fail once STOP_DEV removes the
+ *                disk), or gets -EBUSY. An unfixed kernel cancels the
+ *                commands of the live disk.
+ *
+ * race_fetch:    STOP_DEV while a server opens the device and fetches,
+ *                then START_DEV. If STOP_DEV came before the open, it must
+ *                not take any command, so START_DEV works and every read
+ *                succeeds; otherwise START_DEV gets -EBUSY. An unfixed
+ *                kernel takes commands fetched after its unlock and goes
+ *                live over them.
+ *
+ * race_async_fetch: FETCH with IOSQE_ASYNC while STOP_DEV cancels,
+ *                then close the ring. An unfixed FETCH marks its command
+ *                cancelable only after publishing it and dropping
+ *                ub->mutex; a cancel in between completes a command which
+ *                is then put on io_uring's cancelable list. Closing the
+ *                ring walks that list: KASAN reports a use after free.
+ *                Needs a KASAN kernel to see the bug; otherwise it must
+ *                just not crash.
+ *
+ * A dying task is a child process which fetches and then calls exec().
+ * exec() cancels the task's uring_cmds before it returns, so the cancel
+ * is done once the child is reaped. A thread exit does not cancel them,
+ * and closing the ring cancels them later, from io_ring_exit_work().
+ */
+#include <sched.h>
+
+#include "kublk.h"
+#include "../kselftest.h"
+
+#define NR_QUEUES	2
+#define DEPTH		4
+#define BUF_SIZE	(64 << 10)
+#define DEV_SECTORS	(64 << 11)	/* 64MB */
+#define NR_READS	(DEPTH * 2)
+#define SERVE_DELAY_US	200000
+#define RACE_LOOPS	50
+#define ASYNC_LOOPS	300
+
+/* one control handle per thread, the race modes send commands from two */
+static __thread struct ublk_dev *ctrl_dev;
+static int cdev_fd = -1;
+static int dev_id = -1;
+static int nr_queues;
+static void *bufs[NR_QUEUES][DEPTH];
+static const struct ublksrv_io_desc *iods[NR_QUEUES];
+static size_t iods_len;
+
+static struct io_uring_sqe *get_sqe(struct io_uring *ring)
+{
+	struct io_uring_sqe *sqe = io_uring_get_sqe(ring);
+
+	if (!sqe) {
+		fprintf(stderr, "out of sqes\n");
+		exit(KSFT_FAIL);
+	}
+	return sqe;
+}
+
+static struct ublk_dev *ctrl(void)
+{
+	if (!ctrl_dev) {
+		ctrl_dev = ublk_ctrl_init();
+		if (!ctrl_dev) {
+			fprintf(stderr, "ublk_ctrl_init failed\n");
+			exit(KSFT_FAIL);
+		}
+	}
+	ctrl_dev->dev_info.dev_id = dev_id;
+	return ctrl_dev;
+}
+
+static void ctrl_put(void)
+{
+	if (ctrl_dev)
+		ublk_ctrl_deinit(ctrl_dev);
+	ctrl_dev = NULL;
+}
+
+static int dev_state(void)
+{
+	struct ublk_dev *dev = ctrl();
+	int ret = ublk_ctrl_get_info(dev);
+
+	return ret ? ret : dev->dev_info.state;
+}
+
+static int open_cdev(void)
+{
+	size_t max_len = UBLK_MAX_QUEUE_DEPTH * sizeof(struct ublksrv_io_desc);
+	int pg = getpagesize();
+	char path[64];
+
+	snprintf(path, sizeof(path), "/dev/ublkc%d", dev_id);
+	for (int i = 0; i < 100 && cdev_fd < 0; i++) {
+		cdev_fd = open(path, O_RDWR);
+		if (cdev_fd < 0)
+			usleep(50000);
+	}
+	if (cdev_fd < 0)
+		return -errno;
+
+	/* queue q's descriptors start at q * the size for the max depth */
+	max_len = (max_len + pg - 1) & ~(size_t)(pg - 1);
+	iods_len = (DEPTH * sizeof(struct ublksrv_io_desc) + pg - 1) &
+		~(size_t)(pg - 1);
+	for (int q = 0; q < nr_queues; q++) {
+		void *p = mmap(NULL, iods_len, PROT_READ,
+			       MAP_SHARED | MAP_POPULATE, cdev_fd,
+			       UBLKSRV_CMD_BUF_OFFSET + q * max_len);
+
+		if (p == MAP_FAILED)
+			return -errno;
+		iods[q] = p;
+	}
+	return 0;
+}
+
+/* the last reference to /dev/ublkcN runs ublk_ch_release() */
+static void close_cdev(void)
+{
+	for (int q = 0; q < nr_queues; q++) {
+		if (iods[q])
+			munmap((void *)iods[q], iods_len);
+		iods[q] = NULL;
+	}
+	if (cdev_fd >= 0)
+		close(cdev_fd);
+	cdev_fd = -1;
+}
+
+/* ADD_DEV and SET_PARAMS, without opening /dev/ublkcN */
+static int add_dev_noopen(int queues, __u64 flags)
+{
+	struct ublk_dev *dev = ctrl();
+	struct ublksrv_ctrl_dev_info info = {
+		.nr_hw_queues	= queues,
+		.queue_depth	= DEPTH,
+		.max_io_buf_bytes = BUF_SIZE,
+		.dev_id		= -1,
+		.flags		= UBLK_F_NO_AUTO_PART_SCAN | flags,
+	};
+	struct ublk_params p = {
+		.types	= UBLK_PARAM_TYPE_BASIC,
+		.basic	= {
+			.logical_bs_shift	= 9,
+			.physical_bs_shift	= 12,
+			.io_opt_shift		= 12,
+			.io_min_shift		= 9,
+			.max_sectors		= BUF_SIZE >> 9,
+			.dev_sectors		= DEV_SECTORS,
+		},
+	};
+	int ret;
+
+	nr_queues = queues;
+	dev->dev_info = info;
+	ret = ublk_ctrl_add_dev(dev);
+	if (ret)
+		return ret;
+	dev_id = dev->dev_info.dev_id;
+
+	ret = ublk_ctrl_set_params(ctrl(), &p);
+	if (ret)
+		return ret;
+
+	for (int q = 0; q < queues; q++)
+		for (int i = 0; i < DEPTH; i++)
+			if (!bufs[q][i] &&
+			    posix_memalign(&bufs[q][i], getpagesize(), BUF_SIZE))
+				return -ENOMEM;
+	return 0;
+}
+
+static int add_dev(int queues, __u64 flags)
+{
+	return add_dev_noopen(queues, flags) ?: open_cdev();
+}
+
+static void cleanup(void)
+{
+	if (dev_id < 0)
+		return;
+	ublk_ctrl_stop_dev(ctrl());
+	close_cdev();
+	ublk_ctrl_del_dev(ctrl());
+	dev_id = -1;
+}
+
+/* race_async_fetch sets IOSQE_ASYNC on the io commands */
+static int io_cmd_sqe_flags;
+
+static void queue_io_cmd(struct io_uring *ring, __u32 op, int q, int tag,
+			 int res)
+{
+	struct io_uring_sqe *sqe = get_sqe(ring);
+	struct ublksrv_io_cmd *cmd = (struct ublksrv_io_cmd *)sqe->cmd;
+
+	memset(sqe, 0, sizeof(*sqe));
+	sqe->fd = cdev_fd;
+	sqe->opcode = IORING_OP_URING_CMD;
+	sqe->flags = io_cmd_sqe_flags;
+	ublk_set_sqe_cmd_op(sqe, op);
+	cmd->q_id = q;
+	cmd->tag = tag;
+	cmd->result = res;
+	cmd->addr = (__u64)(uintptr_t)bufs[q][tag];
+	io_uring_sqe_set_data64(sqe, (q << 16) | tag);
+}
+
+struct async_arg {
+	pthread_barrier_t go, stopped;
+};
+
+/*
+ * FETCH every tag with IOSQE_ASYNC, racing STOP_DEV, then close the ring once
+ * STOP_DEV returned: that walks io_uring's list of cancelable commands.
+ */
+static void *race_async_fn(void *data)
+{
+	struct async_arg *a = data;
+	struct io_uring ring;
+	int ok = !io_uring_queue_init(DEPTH, &ring, 0);
+
+	if (ok)
+		for (int tag = 0; tag < DEPTH; tag++)
+			queue_io_cmd(&ring, UBLK_U_IO_FETCH_REQ, 0, tag, 0);
+	pthread_barrier_wait(&a->go);
+	if (ok)
+		io_uring_submit(&ring);
+	pthread_barrier_wait(&a->stopped);
+	if (ok)
+		io_uring_queue_exit(&ring);
+	return NULL;
+}
+
+/* reap @nr completions of canceled fetch commands, return how many */
+static int reap_aborts(struct io_uring *ring, int nr)
+{
+	struct __kernel_timespec ts = { .tv_sec = 2 };
+	struct io_uring_cqe *cqe;
+	int aborted = 0;
+
+	while (nr--) {
+		if (io_uring_wait_cqe_timeout(ring, &cqe, &ts))
+			break;
+		if (cqe->res == UBLK_IO_RES_ABORT)
+			aborted++;
+		io_uring_cqe_seen(ring, cqe);
+	}
+	return aborted;
+}
+
+/*
+ * A server thread fetches @nr_tags tags of queue @q, then completes each
+ * request after @delay_us, until its commands are aborted.
+ */
+struct server {
+	int q, first_tag, nr_tags, delay_us;
+	int failed;	/* result which ended the serve loop, 0 if none */
+	pthread_t thread;
+	pthread_barrier_t fetched;
+	/* race_fetch: wait for @go and @race_delay_us, open, fetch one by one */
+	pthread_barrier_t go;
+	int race, race_delay_us;
+};
+
+static void *server_fn(void *data)
+{
+	struct server *s = data;
+	struct io_uring ring;
+	struct io_uring_cqe *cqe;
+
+	if (io_uring_queue_init(DEPTH, &ring, 0)) {
+		pthread_barrier_wait(&s->fetched);
+		return NULL;
+	}
+	if (s->race) {
+		pthread_barrier_wait(&s->go);
+		usleep(s->race_delay_us);
+		if (open_cdev()) {
+			pthread_barrier_wait(&s->fetched);
+			io_uring_queue_exit(&ring);
+			return NULL;
+		}
+	}
+	for (int tag = s->first_tag; tag < s->first_tag + s->nr_tags; tag++) {
+		queue_io_cmd(&ring, UBLK_U_IO_FETCH_REQ, s->q, tag, 0);
+		if (s->race)
+			io_uring_submit(&ring);
+	}
+	io_uring_submit(&ring);
+	pthread_barrier_wait(&s->fetched);
+
+	while (!io_uring_wait_cqe(&ring, &cqe)) {
+		int tag = cqe->user_data & 0xffff;
+		const struct ublksrv_io_desc *iod = &iods[s->q][tag];
+		int res = cqe->res;
+
+		io_uring_cqe_seen(&ring, cqe);
+		if (res != UBLK_IO_RES_OK) {
+			__atomic_store_n(&s->failed, res, __ATOMIC_RELEASE);
+			break;
+		}
+		usleep(s->delay_us);
+		res = ublksrv_get_op(iod) <= UBLK_IO_OP_WRITE ?
+			iod->nr_sectors << 9 : 0;
+		queue_io_cmd(&ring, UBLK_U_IO_COMMIT_AND_FETCH_REQ, s->q, tag,
+			     res);
+		io_uring_submit(&ring);
+	}
+	io_uring_queue_exit(&ring);
+	return NULL;
+}
+
+/* returns once the fetch commands are issued; with @race, call race_go() */
+static void server_start(struct server *s)
+{
+	pthread_barrier_init(&s->fetched, NULL, 2);
+	pthread_barrier_init(&s->go, NULL, 2);
+	pthread_create(&s->thread, NULL, server_fn, s);
+	if (!s->race)
+		pthread_barrier_wait(&s->fetched);
+}
+
+/* wait up to 5s for the serve loop of @s to end, return its result */
+static int server_wait_failed(struct server *s)
+{
+	int res = 0;
+
+	for (int i = 0; i < 500 && !res; i++) {
+		res = __atomic_load_n(&s->failed, __ATOMIC_ACQUIRE);
+		if (!res)
+			usleep(10000);
+	}
+	return res;
+}
+
+/*
+ * A task fetches @nr_tags tags of queue @q and dies. Returns once its
+ * commands are canceled, see the top of this file.
+ */
+static int fetch_and_die(int q, int first_tag, int nr_tags)
+{
+	int status;
+	pid_t pid = fork();
+
+	if (pid < 0)
+		return -1;
+	if (!pid) {
+		struct io_uring ring;
+
+		if (io_uring_queue_init(DEPTH, &ring, 0))
+			_exit(1);
+		for (int tag = first_tag; tag < first_tag + nr_tags; tag++)
+			queue_io_cmd(&ring, UBLK_U_IO_FETCH_REQ, q, tag, 0);
+		if (io_uring_submit(&ring) != nr_tags)
+			_exit(1);
+		execlp("true", "true", NULL);
+		_exit(1);
+	}
+	if (waitpid(pid, &status, 0) != pid || !WIFEXITED(status) ||
+	    WEXITSTATUS(status))
+		return -1;
+	printf("q%d: task died with %d fetch cmds in flight\n", q, nr_tags);
+	return 0;
+}
+
+struct reads {
+	struct io_uring ring;
+	void *buf;
+	int fd, done, ok, eio, other;
+};
+
+/*
+ * Issue NR_READS reads at once, from @cpu if it is not negative: blk-mq
+ * maps the submitting CPU to the hw queue. A server holding its live
+ * tags for a while makes the other reads take the canceled tags.
+ */
+static int open_tries = 100;	/* 50ms each */
+
+static int reads_submit(struct reads *r, int cpu)
+{
+	char path[64];
+	cpu_set_t set, old;
+
+	snprintf(path, sizeof(path), "/dev/ublkb%d", dev_id);
+	r->fd = -1;
+	for (int i = 0; i < open_tries && r->fd < 0; i++) {
+		r->fd = open(path, O_RDONLY | O_DIRECT);
+		if (r->fd < 0)
+			usleep(50000);
+	}
+	if (r->fd < 0) {
+		fprintf(stderr, "open %s: %s\n", path, strerror(errno));
+		return -1;
+	}
+	if (posix_memalign(&r->buf, 4096, NR_READS * 4096) ||
+	    io_uring_queue_init(NR_READS, &r->ring, 0))
+		return -1;
+
+	for (int i = 0; i < NR_READS; i++)
+		io_uring_prep_read(get_sqe(&r->ring), r->fd,
+				   r->buf + i * 4096, 4096, i * 4096);
+
+	if (cpu >= 0) {
+		sched_getaffinity(0, sizeof(old), &old);
+		CPU_ZERO(&set);
+		CPU_SET(cpu, &set);
+		sched_setaffinity(0, sizeof(set), &set);
+	}
+	io_uring_submit(&r->ring);
+	if (cpu >= 0)
+		sched_setaffinity(0, sizeof(old), &old);
+	return 0;
+}
+
+static void reads_reap(struct reads *r, int timeout_s)
+{
+	struct __kernel_timespec ts = { .tv_sec = timeout_s };
+	struct io_uring_cqe *cqe;
+
+	while (r->done < NR_READS &&
+	       !io_uring_wait_cqe_timeout(&r->ring, &cqe, &ts)) {
+		if (cqe->res == 4096)
+			r->ok++;
+		else if (cqe->res == -EIO)
+			r->eio++;
+		else
+			r->other++;
+		r->done++;
+		io_uring_cqe_seen(&r->ring, cqe);
+	}
+}
+
+static void reads_put(struct reads *r)
+{
+	io_uring_queue_exit(&r->ring);
+	close(r->fd);
+	free(r->buf);
+}
+
+static int reads_result(struct reads *r)
+{
+	printf("reads: %d ok, %d -EIO, %d other, %d not completed\n",
+	       r->ok, r->eio, r->other, NR_READS - r->done);
+	reads_put(r);
+	return r->other || r->done < NR_READS ? KSFT_FAIL : KSFT_PASS;
+}
+
+static int start_dev(void)
+{
+	int ret = ublk_ctrl_start_dev(ctrl(), getpid());
+
+	printf("START_DEV: %d\n", ret);
+	return ret;
+}
+
+static int expect_err(const char *what, int ret, int want)
+{
+	if (ret == want)
+		return KSFT_PASS;
+	fprintf(stderr, "%s: %d, expected %d\n", what, ret, want);
+	return KSFT_FAIL;
+}
+
+/* START_DEV must fail with @want; if it went live, show what a read does */
+static int start_dev_expect(int want)
+{
+	struct reads r = {};
+	int ret = start_dev();
+
+	if (!ret && !reads_submit(&r, -1)) {
+		reads_reap(&r, 10);
+		reads_result(&r);
+	}
+	return expect_err("START_DEV", ret, want);
+}
+
+static int test_stop_start(void)
+{
+	struct io_uring ring;
+	int ret;
+
+	if (add_dev(1, 0))
+		return KSFT_FAIL;
+	if (io_uring_queue_init(DEPTH, &ring, 0))
+		return KSFT_FAIL;
+	for (int tag = 0; tag < DEPTH; tag++)
+		queue_io_cmd(&ring, UBLK_U_IO_FETCH_REQ, 0, tag, 0);
+	io_uring_submit(&ring);
+
+	/* device is ready but not started: state is UBLK_S_DEV_DEAD */
+	ret = ublk_ctrl_stop_dev(ctrl());
+	printf("STOP_DEV: %d, canceled fetch cmds: %d/%d\n", ret,
+	       reap_aborts(&ring, DEPTH), DEPTH);
+
+	/* STOP_DEV canceled the attached server: no start until it exits */
+	ret = start_dev_expect(-EBUSY);
+	io_uring_queue_exit(&ring);
+	return ret;
+}
+
+static int test_partial_fetch(void)
+{
+	struct server b = { .q = 0, .first_tag = DEPTH - 1, .nr_tags = 1,
+			    .delay_us = SERVE_DELAY_US };
+	int ret;
+
+	if (add_dev(1, 0) || fetch_and_die(0, 0, DEPTH - 1))
+		return KSFT_FAIL;
+
+	/* the last FETCH makes the queue ready and clears ->canceling */
+	server_start(&b);
+
+	ret = start_dev_expect(-EBUSY);
+
+	cleanup();
+	pthread_join(b.thread, NULL);
+	return ret;
+}
+
+static int test_stop_restart(void)
+{
+	struct server s = { .q = 0, .nr_tags = DEPTH };
+	struct reads r = {};
+	int ret;
+
+	if (add_dev_noopen(1, 0))
+		return KSFT_FAIL;
+
+	/* no server is attached, so there is nothing to cancel */
+	ret = ublk_ctrl_stop_dev(ctrl());
+	printf("STOP_DEV: %d\n", ret);
+	if (open_cdev())
+		return KSFT_FAIL;
+
+	server_start(&s);
+	if (start_dev()) {
+		ret = KSFT_FAIL;
+	} else if (reads_submit(&r, -1)) {
+		ret = KSFT_FAIL;
+	} else {
+		reads_reap(&r, 10);
+		ret = reads_result(&r);
+		if (r.ok != NR_READS)
+			ret = KSFT_FAIL;
+	}
+
+	cleanup();
+	pthread_join(s.thread, NULL);
+	return ret;
+}
+
+struct start_arg {
+	pthread_barrier_t go;
+	int ret, reads_ok;
+};
+
+static void *race_start_fn(void *data)
+{
+	struct start_arg *a = data;
+	struct reads r = {};
+
+	pthread_barrier_wait(&a->go);
+	a->ret = ublk_ctrl_start_dev(ctrl(), getpid());
+	a->reads_ok = 1;
+	/*
+	 * The disk may be gone already if STOP_DEV came right after, and
+	 * reads may fail then: they only have to complete.
+	 */
+	if (!a->ret && !reads_submit(&r, -1)) {
+		reads_reap(&r, 5);
+		a->reads_ok = r.done == NR_READS;
+		if (a->reads_ok)
+			reads_put(&r);
+		else
+			reads_result(&r);
+	}
+	ctrl_put();
+	return NULL;
+}
+
+static int test_race_start(void)
+{
+	int live = 0, ebusy = 0;
+
+	open_tries = 4;
+	for (int i = 0; i < RACE_LOOPS; i++) {
+		struct server s = { .q = 0, .nr_tags = DEPTH };
+		struct start_arg a = {};
+		pthread_t t;
+
+		if (add_dev(1, 0))
+			return KSFT_FAIL;
+		server_start(&s);
+		pthread_barrier_init(&a.go, NULL, 2);
+		pthread_create(&t, NULL, race_start_fn, &a);
+		pthread_barrier_wait(&a.go);
+		ublk_ctrl_stop_dev(ctrl());
+		pthread_join(t, NULL);
+		cleanup();
+		pthread_join(s.thread, NULL);
+
+		if (a.ret == 0)
+			live++;
+		else if (a.ret == -EBUSY)
+			ebusy++;
+		if ((a.ret && a.ret != -EBUSY) || !a.reads_ok) {
+			fprintf(stderr, "loop %d: START_DEV %d, reads %s\n",
+				i, a.ret, a.reads_ok ? "ok" : "failed");
+			return KSFT_FAIL;
+		}
+	}
+	printf("%d loops: START_DEV won %d, got -EBUSY %d\n", RACE_LOOPS,
+	       live, ebusy);
+	return KSFT_PASS;
+}
+
+static int test_race_fetch(void)
+{
+	int live = 0, ebusy = 0;
+
+	for (int i = 0; i < RACE_LOOPS; i++) {
+		/* vary who goes first: STOP_DEV, or the server's open */
+		struct server s = { .q = 0, .nr_tags = DEPTH, .race = 1,
+				    .race_delay_us = (i % 10) * 50 };
+		struct reads r = {};
+		int ret;
+
+		if (add_dev_noopen(1, 0))
+			return KSFT_FAIL;
+		server_start(&s);
+		pthread_barrier_wait(&s.go);
+		ublk_ctrl_stop_dev(ctrl());
+		pthread_barrier_wait(&s.fetched);
+
+		ret = ublk_ctrl_start_dev(ctrl(), getpid());
+		if (!ret) {
+			/* nothing was taken, so every read has to succeed */
+			live++;
+			if (reads_submit(&r, -1))
+				return KSFT_FAIL;
+			reads_reap(&r, 5);
+			if (r.ok != NR_READS) {
+				fprintf(stderr, "loop %d: live, but ", i);
+				reads_result(&r);
+				return KSFT_FAIL;
+			}
+			reads_put(&r);
+		} else if (ret == -EBUSY) {
+			ebusy++;
+		} else {
+			fprintf(stderr, "loop %d: START_DEV %d\n", i, ret);
+			return KSFT_FAIL;
+		}
+		cleanup();
+		pthread_join(s.thread, NULL);
+	}
+	printf("%d loops: START_DEV worked %d, got -EBUSY %d\n", RACE_LOOPS,
+	       live, ebusy);
+	return KSFT_PASS;
+}
+
+static int test_race_async_fetch(void)
+{
+	io_cmd_sqe_flags = IOSQE_ASYNC;
+	for (int i = 0; i < ASYNC_LOOPS; i++) {
+		struct async_arg a;
+		pthread_t t;
+
+		if (add_dev(1, 0))
+			return KSFT_FAIL;
+		pthread_barrier_init(&a.go, NULL, 2);
+		pthread_barrier_init(&a.stopped, NULL, 2);
+		pthread_create(&t, NULL, race_async_fn, &a);
+		pthread_barrier_wait(&a.go);
+		/* vary where STOP_DEV lands relative to the FETCHes */
+		usleep((i % 5) * 1000);
+		ublk_ctrl_stop_dev(ctrl());
+		pthread_barrier_wait(&a.stopped);
+		pthread_join(t, NULL);
+		cleanup();
+	}
+	printf("%d loops done\n", ASYNC_LOOPS);
+	return KSFT_PASS;
+}
+
+/*
+ * The stopped server is gone: reopen /dev/ublkcN, start a new server and
+ * the device, and read from it.
+ */
+static int restart_server(void)
+{
+	struct server s = { .q = 0, .nr_tags = DEPTH };
+	struct reads r = {};
+	int ret;
+
+	close_cdev();
+	if (open_cdev())
+		return KSFT_FAIL;
+	server_start(&s);
+	usleep(200000);
+	if (s.failed) {
+		fprintf(stderr, "new server: FETCH failed %d\n", s.failed);
+		cleanup();
+		pthread_join(s.thread, NULL);
+		return KSFT_FAIL;
+	}
+	/* -EEXIST until the old disk is freed, e.g. after a udev probe */
+	for (int i = 0; i < 100; i++) {
+		ret = start_dev();
+		if (ret != -EEXIST)
+			break;
+		usleep(50000);
+	}
+	if (ret || reads_submit(&r, -1)) {
+		fprintf(stderr, "new server: START_DEV %d\n", ret);
+		ret = KSFT_FAIL;
+	} else {
+		reads_reap(&r, 10);
+		ret = reads_result(&r);
+		if (r.ok != NR_READS)
+			ret = KSFT_FAIL;
+	}
+	cleanup();
+	pthread_join(s.thread, NULL);
+	return ret;
+}
+
+/*
+ * stop_attached: STOP_DEV while a server has the device open but has
+ * fetched nothing stops that server too: its FETCH gets ABORT and
+ * START_DEV -EBUSY. Once it is gone, a new server can start the device.
+ */
+static int test_stop_attached(void)
+{
+	struct server s = { .q = 0, .nr_tags = DEPTH };
+	int ret;
+
+	if (add_dev(1, 0))
+		return KSFT_FAIL;
+	ret = ublk_ctrl_stop_dev(ctrl());
+	printf("STOP_DEV: %d\n", ret);
+
+	server_start(&s);
+	ret = server_wait_failed(&s);
+	printf("FETCH after STOP_DEV: %d\n", ret);
+	if (ret != UBLK_IO_RES_ABORT) {
+		cleanup();
+		pthread_join(s.thread, NULL);
+		return KSFT_FAIL;
+	}
+	pthread_join(s.thread, NULL);
+	if (expect_err("START_DEV", start_dev(), -EBUSY))
+		return KSFT_FAIL;
+	return restart_server();
+}
+
+/*
+ * stop_live_restart: STOP_DEV on a live device; once its server is gone,
+ * a new server has to fetch and start it again.
+ */
+static int test_stop_live_restart(void)
+{
+	struct server s = { .q = 0, .nr_tags = DEPTH };
+	int ret;
+
+	if (add_dev(1, 0))
+		return KSFT_FAIL;
+	server_start(&s);
+	if (expect_err("START_DEV", start_dev(), 0))
+		return KSFT_FAIL;
+	ret = ublk_ctrl_stop_dev(ctrl());
+	printf("STOP_DEV: %d\n", ret);
+	pthread_join(s.thread, NULL);
+	return restart_server();
+}
+
+/* first CPU which blk-mq maps to hw queue @q */
+static int queue_cpu(int q)
+{
+	char path[96];
+	FILE *f;
+	int cpu = -1;
+
+	snprintf(path, sizeof(path), "/sys/block/ublkb%d/mq/%d/cpu_list",
+		 dev_id, q);
+	for (int i = 0; i < 100 && !(f = fopen(path, "r")); i++)
+		usleep(50000);
+	if (!f)
+		return -1;
+	if (fscanf(f, "%d", &cpu) != 1)
+		cpu = -1;
+	fclose(f);
+	return cpu;
+}
+
+static int test_recovery(void)
+{
+	struct server q1 = { .q = 1, .nr_tags = DEPTH };
+	struct io_uring ring;
+	struct reads r = {};
+	int ret, cpu;
+
+	if (add_dev(NR_QUEUES, UBLK_F_USER_RECOVERY))
+		return KSFT_FAIL;
+
+	/* the first server: fetch everything, start, then die */
+	if (io_uring_queue_init(NR_QUEUES * DEPTH, &ring, 0))
+		return KSFT_FAIL;
+	for (int q = 0; q < NR_QUEUES; q++)
+		for (int tag = 0; tag < DEPTH; tag++)
+			queue_io_cmd(&ring, UBLK_U_IO_FETCH_REQ, q, tag, 0);
+	io_uring_submit(&ring);
+	if (start_dev())
+		return KSFT_FAIL;
+	cpu = queue_cpu(0);
+	if (cpu < 0) {
+		printf("no CPU maps to queue 0, can't aim the reads\n");
+		return KSFT_SKIP;
+	}
+
+	io_uring_queue_exit(&ring);
+	close_cdev();
+	for (int i = 0; i < 100 && dev_state() != UBLK_S_DEV_QUIESCED; i++)
+		usleep(50000);
+	printf("server exited, state %d (QUIESCED is %d)\n", dev_state(),
+	       UBLK_S_DEV_QUIESCED);
+
+	for (int i = 0; i < 100; i++) {
+		ret = ublk_ctrl_start_user_recovery(ctrl());
+		if (ret != -EBUSY)
+			break;
+		usleep(50000);
+	}
+	printf("START_USER_RECOVERY: %d\n", ret);
+	if (ret || open_cdev())
+		return KSFT_FAIL;
+
+	/* queue 0 gets ready, then its task dies before queue 1 is ready */
+	if (fetch_and_die(0, 0, DEPTH))
+		return KSFT_FAIL;
+
+	printf("reads on cpu %d, which maps to queue 0\n", cpu);
+	if (reads_submit(&r, cpu))
+		return KSFT_FAIL;
+
+	server_start(&q1);
+	ret = ublk_ctrl_end_user_recovery(ctrl(), getpid());
+	printf("END_USER_RECOVERY: %d\n", ret);
+	ret = expect_err("END_USER_RECOVERY", ret, -EBUSY);
+
+	/*
+	 * Requests held back on queue 0 wait for STOP_DEV to fail them.
+	 * Close the disk before DEL_DEV, which waits for its last reference.
+	 */
+	reads_reap(&r, 1);
+	ublk_ctrl_stop_dev(ctrl());
+	reads_reap(&r, 5);
+	if (reads_result(&r))
+		ret = KSFT_FAIL;
+	cleanup();
+	pthread_join(q1.thread, NULL);
+	return ret;
+}
+
+static const struct {
+	const char *name;
+	int (*fn)(void);
+} modes[] = {
+	{ "stop_start",		test_stop_start },
+	{ "partial_fetch",	test_partial_fetch },
+	{ "recovery",		test_recovery },
+	{ "stop_restart",	test_stop_restart },
+	{ "race_start",		test_race_start },
+	{ "race_fetch",		test_race_fetch },
+	{ "race_async_fetch",	test_race_async_fetch },
+	{ "stop_attached",	test_stop_attached },
+	{ "stop_live_restart",	test_stop_live_restart },
+};
+
+int main(int argc, char **argv)
+{
+	int (*fn)(void) = NULL;
+	int ret;
+
+	for (int i = 0; argc == 2 && i < ARRAY_SIZE(modes); i++)
+		if (!strcmp(argv[1], modes[i].name))
+			fn = modes[i].fn;
+	if (!fn) {
+		fprintf(stderr, "usage: %s MODE, modes:", argv[0]);
+		for (int i = 0; i < ARRAY_SIZE(modes); i++)
+			fprintf(stderr, " %s", modes[i].name);
+		fprintf(stderr, "\n");
+		return KSFT_FAIL;
+	}
+
+	/* keep the output of a run that ends in an oops */
+	setvbuf(stdout, NULL, _IOLBF, 0);
+
+	if (access(CTRL_DEV, F_OK)) {
+		perror(CTRL_DEV);
+		return KSFT_SKIP;
+	}
+	printf("%s\n", argv[1]);
+	ret = fn();
+	cleanup();
+	ctrl_put();
+	return ret;
+}

3/2 2026/10/11 06:40 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 30272
							output: 33
							thoughts: 220
						

Thoughts:
**Kernel Patch Review - Ublk Driver**

Okay, so I've got a kernel patch review request. My goal here is to determine a few key things about this patch. First, I need to figure out if this patch is **WorthFuzzing** – a "true" or "false" value here is the end result. Then, I need to document my **Reasoning** behind that determination. Finally, I'll identify any relevant **EnableConfigs** and **FocusSymbols** that relate to it.

Let's dive in and read this patch carefully. I see the changes are touching: `Documentation/block/ublk.rst`, `drivers/block/ublk_drv.c`, and a directory full of selftests: `tools/testing/selftests/ublk/*`. That’s interesting. A documentation update, the driver source, and some self tests. That already looks promising.

Now, let's focus on `drivers/block/ublk_drv.c`. Okay, ublk...right, it's the userspace block device, enabled by `CONFIG_BLK_DEV_UBLK`. That's an important configuration. Is it reachable in standard virtualized environments like QEMU or GCE? Yes! ublk is a virtual block device driver and it uses IO_uring and char/block devices. Specifically, it uses `/dev/ublk-control`, `/dev/ublkc*`, and `/dev/ublkb*` so this has an interesting user interface. Excellent, and good news: I remember Syzkaller is actively fuzzing ublk. This is definitely a prime candidate for fuzzing! So, I need to make sure I confirm the Kconfig option that enables `ublk_drv.c`, but this looks like a good one.



4/2 2026/10/11 06:40 tool grepper
0m Args:
{
  "Expression": "CONFIG_BLK_DEV_UBLK",
  "PathPrefixes": [
    "drivers/block/"
  ]
}

Results:
{
  "Output": "drivers/block/Makefile=38=obj-$(CONFIG_BLK_DEV_RUST_NULL) += rnull/\ndrivers/block/Makefile-39-\ndrivers/block/Makefile:40:obj-$(CONFIG_BLK_DEV_UBLK)\t\t\t+= ublk_drv.o\ndrivers/block/Makefile-41-obj-$(CONFIG_BLK_DEV_ZONED_LOOP) += zloop.o\n"
}

5/2 2026/10/11 06:40 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 31018
							output: 33
							thoughts: 16
						

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

**Diving into the ublk Kconfig**

Alright, time to get my hands dirty. My mind immediately zeroes in on the `BLK_DEV_UBLK` Kconfig option. I need to understand its current state and how it's configured within the broader block device subsystem. I want to quickly ascertain if there are any obvious dependencies, default values, or potential conflicts that I should be aware of. I'll be looking for clues on whether it's enabled by default, if there are any specific hardware requirements tied to it, or if it's dependent on any other features that might influence its behaviour. I will then cross reference any new or important information with any current problems I have noticed.



6/2 2026/10/11 06:40 tool grepper
0m Args:
{
  "Expression": "config BLK_DEV_UBLK",
  "PathPrefixes": [
    "drivers/block/"
  ]
}

Results:
{
  "Output": "drivers/block/Kconfig=315=config BLK_DEV_RBD\n--\ndrivers/block/Kconfig-327-\ndrivers/block/Kconfig:328:config BLK_DEV_UBLK\ndrivers/block/Kconfig-329-\ttristate \"Userspace block driver (Experimental)\"\n"
}

7/2 2026/10/11 06:40 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 31323
							output: 34
							thoughts: 24
						

Thoughts:
Okay, here's my interpretation of that thought process, assuming I'm an expert in this field, presented as a first-person summary:

**Digging into Block Device Driver Configuration**

Right, let's get down to brass tacks. I need to understand the configuration options and dependencies for block device drivers, specifically. My initial hunch is that the key to this information resides in the `drivers/block/Kconfig` file. And, if memory serves, line 328 should be a good starting point. I suspect that's where I'll find the core definitions, any conditional logic, and the dependencies on other kernel subsystems or features. Let's get to it and see what it reveals.



8/2 2026/10/11 06:40 tool read-file
0m Args:
{
  "File": "drivers/block/Kconfig",
  "FirstLine": 325,
  "LineCount": 25
}

Results:
{
  "Contents": " 325:\t\n 326:\t\t  If unsure, say N.\n 327:\t\n 328:\tconfig BLK_DEV_UBLK\n 329:\t\ttristate \"Userspace block driver (Experimental)\"\n 330:\t\tselect IO_URING\n 331:\t\thelp\n 332:\t\t  io_uring based userspace block driver. Together with ublk server, ublk\n 333:\t\t  has been working well, but interface with userspace or command data\n 334:\t\t  definition isn't finalized yet, and might change according to future\n 335:\t\t  requirement, so mark is as experimental now.\n 336:\t\n 337:\tconfig BLKDEV_UBLK_LEGACY_OPCODES\n 338:\t\tbool \"Support legacy command opcode\"\n 339:\t\tdepends on BLK_DEV_UBLK\n 340:\t\tdefault y\n 341:\t\thelp\n 342:\t\t  ublk driver started to take plain command encoding, which turns out\n 343:\t\t  one bad way. The traditional ioctl command opcode encodes more\n 344:\t\t  info and basically defines each code uniquely, so opcode conflict\n 345:\t\t  is avoided, and driver can handle wrong command easily, meantime it\n 346:\t\t  may help security subsystem to audit io_uring command.\n 347:\t\n 348:\t\t  Say Y if your application still uses legacy command opcode.\n 349:\t\n"
}

9/2 2026/10/11 06:40 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 31916
							output: 107
							thoughts: 1638
						

Thoughts:
**Analysis of ublk_drv.c Changes for Fuzzing**

Okay, so I've been digging into the recent changes in `drivers/block/ublk_drv.c`, and it's clear this is a significant refactor to address some nasty concurrency issues related to command cancellation, device stopping/starting, and io_uring interaction. This kind of work is *always* a high-value target for fuzzing, especially when it involves locking, state transitions, and asynchronous operations.

Let's break down my thought process:

First, the changes are pretty extensive. We've got:

*   New state (`UB_STATE_STOPPING`) and associated logic, which is a red flag for race conditions if not handled carefully.
*   Changes to locking using `cancel_mutex`, `mutex`, and other locks, especially around device state checks. I see instances of `READ_ONCE` and `smp_wmb()`, which tells me the developers are aware of memory ordering issues, but that makes it all the more important to verify the correctness.
*   Modification to command cancel logic in multiple functions: `ublk_cancel_cmd`, `ublk_uring_cmd_cancel_fn`, and various other functions.
*   Updates to `io_uring` command handling, notably around the `ublk_ch_uring_cmd_local` and batch attach.

The focus here seems to be on preventing races and ensuring data consistency during device stop/start cycles and command cancellations. This area is notoriously tricky and a perfect breeding ground for subtle bugs that fuzzing can uncover.

Reachability is key. Since this is a block driver, it's easily reachable via `/dev/ublk-control` and `/dev/ublkc*` char devices. The integration with io_uring makes it accessible to both privileged and unprivileged userspace, which is perfect for fuzzing in a standard QEMU environment. The fact that it's a virtual device driver also makes it much easier to isolate and test.

Now, let's identify the specific functions that are worth focusing on. Since I'm limited on time, I'll go for:
1. `ublk_ch_open`: This opens the communication channel, so it's key.
2. `ublk_stop_dev`: An entrypoint in the stop process.
3. `ublk_uring_cmd_cancel_fn`: The core of the io\_uring command cancel mechanism.
4. `ublk_ch_uring_cmd_local`: This and the batch functions must be tested to ensure the io\_uring implementation is not flawed.
5. `ublk_ctrl_start_dev` and `ublk_ctrl_end_recovery`: As control entrypoints, they are likely involved in various races.
6. `ublk_batch_alloc_fcmd` and `ublk_batch_attach` : Important in the batch process.
7. `ublk_dev_ready_or_stopping`: Helper is worth looking at.

I need to dig deeper into the call graphs of these functions to ensure I'm not missing any critical dependencies or entry points. But based on this initial assessment, I'm confident that this code is worth fuzzing and should be a priority.



10/2 2026/10/11 06:41 tool grepper
0m Args:
{
  "Expression": "(ublk_ch_open|ublk_ch_release|ublk_stop_dev|ublk_uring_cmd_cancel_fn|ublk_ch_uring_cmd_local|ublk_batch_attach|ublk_ctrl_start_dev|ublk_ctrl_end_recovery|ublk_report_zones)",
  "PathPrefixes": [
    "drivers/block/ublk_drv.c"
  ]
}

Results:
{
  "Output": "drivers/block/ublk_drv.c=366=static void ublk_io_release(void *priv);\ndrivers/block/ublk_drv.c:367:static void ublk_stop_dev_unlocked(struct ublk_device *ub);\ndrivers/block/ublk_drv.c-368-static bool ublk_try_buf_match(struct ublk_device *ub, struct request *rq,\n--\ndrivers/block/ublk_drv.c=609=static void *ublk_alloc_report_buffer(struct ublk_device *ublk,\n--\ndrivers/block/ublk_drv.c-635-\ndrivers/block/ublk_drv.c:636:static int ublk_report_zones(struct gendisk *disk, sector_t sector,\ndrivers/block/ublk_drv.c-637-\t\t      unsigned int nr_zones, struct blk_report_zones_args *args)\n--\ndrivers/block/ublk_drv.c=733=static void ublk_setup_iod_zoned(struct ublk_queue *ubq, struct request *req)\n--\ndrivers/block/ublk_drv.c-771-\ndrivers/block/ublk_drv.c:772:#define ublk_report_zones (NULL)\ndrivers/block/ublk_drv.c-773-\n--\ndrivers/block/ublk_drv.c=1382=static const struct block_device_operations ub_fops = {\n--\ndrivers/block/ublk_drv.c-1385-\t.free_disk =\tublk_free_disk,\ndrivers/block/ublk_drv.c:1386:\t.report_zones =\tublk_report_zones,\ndrivers/block/ublk_drv.c-1387-};\n--\ndrivers/block/ublk_drv.c=2152=static blk_status_t ublk_prep_req(struct ublk_queue *ubq, struct request *rq,\n--\ndrivers/block/ublk_drv.c-2158-\t/* With recovery feature enabled, force_abort is set in\ndrivers/block/ublk_drv.c:2159:\t * ublk_stop_dev() before calling del_gendisk(). We have to\ndrivers/block/ublk_drv.c-2160-\t * abort all requeued and new rqs here to let del_gendisk()\n--\ndrivers/block/ublk_drv.c=2371=static void ublk_queue_reinit(struct ublk_device *ub, struct ublk_queue *ubq)\n--\ndrivers/block/ublk_drv.c-2403-\ndrivers/block/ublk_drv.c:2404:static int ublk_ch_open(struct inode *inode, struct file *filp)\ndrivers/block/ublk_drv.c-2405-{\n--\ndrivers/block/ublk_drv.c=2506=static bool ublk_check_and_reset_active_ref(struct ublk_device *ub)\n--\ndrivers/block/ublk_drv.c-2535-\ndrivers/block/ublk_drv.c:2536:static void ublk_ch_release_work_fn(struct work_struct *work)\ndrivers/block/ublk_drv.c-2537-{\n--\ndrivers/block/ublk_drv.c-2616-\ndrivers/block/ublk_drv.c:2617:\t\tublk_stop_dev_unlocked(ub);\ndrivers/block/ublk_drv.c-2618-\t} else {\n--\ndrivers/block/ublk_drv.c-2637-\ndrivers/block/ublk_drv.c:2638:\t/* put the reference grabbed in ublk_ch_release() */\ndrivers/block/ublk_drv.c-2639-\tublk_put_device(ub);\n--\ndrivers/block/ublk_drv.c-2641-\ndrivers/block/ublk_drv.c:2642:static int ublk_ch_release(struct inode *inode, struct file *filp)\ndrivers/block/ublk_drv.c-2643-{\n--\ndrivers/block/ublk_drv.c-2654-\ndrivers/block/ublk_drv.c:2655:\tINIT_DELAYED_WORK(\u0026ub-\u003eexit_work, ublk_ch_release_work_fn);\ndrivers/block/ublk_drv.c-2656-\tschedule_delayed_work(\u0026ub-\u003eexit_work, 0);\n--\ndrivers/block/ublk_drv.c=2760=static void ublk_start_cancel(struct ublk_device *ub)\n--\ndrivers/block/ublk_drv.c-2763-\ndrivers/block/ublk_drv.c:2764:\t/* sync with ublk_ctrl_start_dev() publishing the disk */\ndrivers/block/ublk_drv.c-2765-\tmutex_lock(\u0026ub-\u003ecancel_mutex);\n--\ndrivers/block/ublk_drv.c-2779-\t\t/*\ndrivers/block/ublk_drv.c:2780:\t\t * Disk not yet allocated by ublk_ctrl_start_dev(), so\ndrivers/block/ublk_drv.c-2781-\t\t * there is no request queue and ublk_queue_rq() cannot\n--\ndrivers/block/ublk_drv.c=2880=static void ublk_batch_cancel_fn(struct io_uring_cmd *cmd,\n--\ndrivers/block/ublk_drv.c-2906- */\ndrivers/block/ublk_drv.c:2907:static void ublk_uring_cmd_cancel_fn(struct io_uring_cmd *cmd,\ndrivers/block/ublk_drv.c-2908-\t\tunsigned int issue_flags)\n--\ndrivers/block/ublk_drv.c=3012=static struct gendisk *ublk_detach_disk(struct ublk_device *ub)\n--\ndrivers/block/ublk_drv.c-3026-\ndrivers/block/ublk_drv.c:3027:static void ublk_stop_dev_unlocked(struct ublk_device *ub)\ndrivers/block/ublk_drv.c-3028-\t__must_hold(\u0026ub-\u003emutex)\n--\ndrivers/block/ublk_drv.c=3042=static struct file *ublk_get_ch_file(struct ublk_device *ub)\n--\ndrivers/block/ublk_drv.c-3053-\ndrivers/block/ublk_drv.c:3054:static void ublk_stop_dev(struct ublk_device *ub)\ndrivers/block/ublk_drv.c-3055-{\n--\ndrivers/block/ublk_drv.c-3067-\tmutex_lock(\u0026ub-\u003emutex);\ndrivers/block/ublk_drv.c:3068:\tublk_stop_dev_unlocked(ub);\ndrivers/block/ublk_drv.c-3069-\tcancel_work_sync(\u0026ub-\u003epartition_scan_work);\n--\ndrivers/block/ublk_drv.c=3432=static bool ublk_get_data(const struct ublk_queue *ubq, struct ublk_io *io,\n--\ndrivers/block/ublk_drv.c-3449-\ndrivers/block/ublk_drv.c:3450:static int ublk_ch_uring_cmd_local(struct io_uring_cmd *cmd,\ndrivers/block/ublk_drv.c-3451-\t\tunsigned int issue_flags)\n--\ndrivers/block/ublk_drv.c=3619=static void ublk_ch_uring_cmd_cb(struct io_tw_req tw_req, io_tw_token_t tw)\n--\ndrivers/block/ublk_drv.c-3625-\tif (!tw.cancel)\ndrivers/block/ublk_drv.c:3626:\t\tret = ublk_ch_uring_cmd_local(cmd, issue_flags);\ndrivers/block/ublk_drv.c-3627-\tif (ret != -EIOCBQUEUED)\n--\ndrivers/block/ublk_drv.c=3631=static int ublk_ch_uring_cmd(struct io_uring_cmd *cmd, unsigned int issue_flags)\n--\ndrivers/block/ublk_drv.c-3633-\tif (unlikely(issue_flags \u0026 IO_URING_F_CANCEL)) {\ndrivers/block/ublk_drv.c:3634:\t\tublk_uring_cmd_cancel_fn(cmd, issue_flags);\ndrivers/block/ublk_drv.c-3635-\t\treturn 0;\n--\ndrivers/block/ublk_drv.c-3643-\ndrivers/block/ublk_drv.c:3644:\treturn ublk_ch_uring_cmd_local(cmd, issue_flags);\ndrivers/block/ublk_drv.c-3645-}\n--\ndrivers/block/ublk_drv.c=3950=static int ublk_check_batch_cmd(const struct ublk_batch_io_data *data)\n--\ndrivers/block/ublk_drv.c-3974-\ndrivers/block/ublk_drv.c:3975:static int ublk_batch_attach(struct ublk_queue *ubq,\ndrivers/block/ublk_drv.c-3976-\t\t\t     struct ublk_batch_io_data *data,\n--\ndrivers/block/ublk_drv.c=4031=static int ublk_handle_batch_fetch_cmd(struct ublk_batch_io_data *data)\n--\ndrivers/block/ublk_drv.c-4038-\ndrivers/block/ublk_drv.c:4039:\treturn ublk_batch_attach(ubq, data, fcmd);\ndrivers/block/ublk_drv.c-4040-}\n--\ndrivers/block/ublk_drv.c=4252=static const struct file_operations ublk_ch_fops = {\ndrivers/block/ublk_drv.c-4253-\t.owner = THIS_MODULE,\ndrivers/block/ublk_drv.c:4254:\t.open = ublk_ch_open,\ndrivers/block/ublk_drv.c:4255:\t.release = ublk_ch_release,\ndrivers/block/ublk_drv.c-4256-\t.read_iter = ublk_ch_read_iter,\n--\ndrivers/block/ublk_drv.c=4262=static const struct file_operations ublk_ch_batch_io_fops = {\ndrivers/block/ublk_drv.c-4263-\t.owner = THIS_MODULE,\ndrivers/block/ublk_drv.c:4264:\t.open = ublk_ch_open,\ndrivers/block/ublk_drv.c:4265:\t.release = ublk_ch_release,\ndrivers/block/ublk_drv.c-4266-\t.read_iter = ublk_ch_read_iter,\n--\ndrivers/block/ublk_drv.c=4498=static void ublk_remove(struct ublk_device *ub)\n--\ndrivers/block/ublk_drv.c-4501-\ndrivers/block/ublk_drv.c:4502:\tublk_stop_dev(ub);\ndrivers/block/ublk_drv.c-4503-\tcdev_device_del(\u0026ub-\u003ecdev, \u0026ub-\u003ecdev_dev);\n--\ndrivers/block/ublk_drv.c=4548=static int ublk_wait_dev_ready_and_lock(struct ublk_device *ub)\n--\ndrivers/block/ublk_drv.c-4561-\ndrivers/block/ublk_drv.c:4562:static int ublk_ctrl_start_dev(struct ublk_device *ub,\ndrivers/block/ublk_drv.c-4563-\t\tconst struct ublksrv_ctrl_cmd *header)\n--\ndrivers/block/ublk_drv.c=5070=static void ublk_ctrl_stop_dev(struct ublk_device *ub)\ndrivers/block/ublk_drv.c-5071-{\ndrivers/block/ublk_drv.c:5072:\tublk_stop_dev(ub);\ndrivers/block/ublk_drv.c-5073-}\n--\ndrivers/block/ublk_drv.c=5225=static int ublk_ctrl_start_recovery(struct ublk_device *ub)\n--\ndrivers/block/ublk_drv.c-5260-\ndrivers/block/ublk_drv.c:5261:static int ublk_ctrl_end_recovery(struct ublk_device *ub,\ndrivers/block/ublk_drv.c-5262-\t\tconst struct ublksrv_ctrl_cmd *header)\n--\ndrivers/block/ublk_drv.c-5290-\t/*\ndrivers/block/ublk_drv.c:5291:\t * As in ublk_ctrl_start_dev(), a canceled command can't be fetched\ndrivers/block/ublk_drv.c-5292-\t * again.  Best effort: the disk exists here, and a cancel after this\n--\ndrivers/block/ublk_drv.c=5464=static int ublk_char_dev_permission(struct ublk_device *ub,\n--\ndrivers/block/ublk_drv.c-5494- *\ndrivers/block/ublk_drv.c:5495: * This ordering (mutex -\u003e freeze) is safe because ublk_stop_dev_unlocked()\ndrivers/block/ublk_drv.c-5496- * already holds ub-\u003emutex when calling del_gendisk() which freezes the queue.\n--\ndrivers/block/ublk_drv.c=5916=static int ublk_ctrl_uring_cmd(struct io_uring_cmd *cmd,\n--\ndrivers/block/ublk_drv.c-5963-\tcase UBLK_CMD_START_DEV:\ndrivers/block/ublk_drv.c:5964:\t\tret = ublk_ctrl_start_dev(ub, \u0026header);\ndrivers/block/ublk_drv.c-5965-\t\tbreak;\n--\ndrivers/block/ublk_drv.c-5995-\tcase UBLK_CMD_END_USER_RECOVERY:\ndrivers/block/ublk_drv.c:5996:\t\tret = ublk_ctrl_end_recovery(ub, \u0026header);\ndrivers/block/ublk_drv.c-5997-\t\tbreak;\n"
}

11/2 2026/10/11 06:41 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 38103
							output: 37
							thoughts: 1048
						

Thoughts:
**Focus Symbol Identification for UBLK Driver**

Okay, let's break this down. My goal here is to identify the most suitable functions within the UBLK driver for use with FocusSymbols, specifically targeting our fuzzing efforts. I need to make sure I pick the right entry points, the ones that are specific to the features being modified and not ubiquitous lifecycle functions.

First, I'm going to look at what `ublk_ch_uring_cmd` and `ublk_ctrl_uring_cmd` actually call. `ublk_ctrl_uring_cmd` seems to be the command handler, dealing with things like starting and stopping the device (`UBLK_CMD_START_DEV`, `UBLK_CMD_STOP_DEV`), ending recovery, and `ublk_ch_uring_cmd` handles the local uring execution, the cancellation function, and other related functions. I need to keep in mind, of course, that these functions might be inlined. I need to figure out which of them are exported or have distinct symbols.

So, I need to check: are `ublk_ctrl_start_dev`, `ublk_stop_dev`, `ublk_ch_uring_cmd_local`, `ublk_batch_attach`, `ublk_uring_cmd_cancel_fn`, `ublk_ctrl_end_recovery`, `ublk_ch_release_work_fn`, and `ublk_report_zones` good candidates?

Now, can syzkaller actually target static functions? Syzkaller uses kcov to track addresses, which it then maps to functions in the vmlinux symbol table. Static functions *can* have symbols, but that depends on whether the compiler inlines them. Static functions declared in .c files will generally have symbols in kallsyms or vmlinux unless the compiler decides to inline them.

The documentation is clear: I need to avoid lifecycle hotpaths (generic functions called by nearly every program) and instead target specific feature logic and entrypoints. If changes are primarily in static inline helpers, I need to find the non-static caller functions in .c files that *exercise* those helpers.

Alright, the core modifications are in `drivers/block/ublk_drv.c`. So let's look at `ublk_ctrl_start_dev`, `ublk_stop_dev`, `ublk_ch_uring_cmd_local`, `ublk_uring_cmd_cancel_fn`, `ublk_ctrl_end_recovery`, `ublk_batch_attach`, `ublk_ch_release_work_fn`, and `ublk_report_zones` in that file.

Let's check the size and their non-inlined nature.
*   `ublk_ctrl_start_dev`: This one's reasonably large, looks like it handles the device start process.
*   `ublk_stop_dev`: This one is modified to deal with stopping, cancellation, and file closing.
*   `ublk_ch_uring_cmd_local`: Handles the actual execution of the io\_uring command on the character device.
*   `ublk_uring_cmd_cancel_fn`: The callback function for canceling io\_uring commands.
*   `ublk_ctrl_end_recovery`: This is for the recovery command.
*   `ublk_batch_attach`: This has the batch fetching logic.
*   `ublk_ch_release_work_fn`: The function in the release workqueue.
*   `ublk_report_zones`: For zone reporting.

Finally, I need to check the Kconfig options. Does `CONFIG_BLK_DEV_UBLK` depend on anything? Let me check `drivers/block/Kconfig`. It's a tristate option and *selects* `IO_URING`, and it has no dependencies! This is good. It is declared as experimental, so that is an important detail. But does `ublk_report_zones` require `BLK_DEV_ZONED`? Let's check the code itself, at line 772 of `drivers/block/ublk_drv.c`.



12/2 2026/10/11 06:41 tool grepper
0m Args:
{
  "Expression": "ublk_report_zones",
  "PathPrefixes": [
    "drivers/block/ublk_drv.c"
  ]
}

Results:
{
  "Output": "drivers/block/ublk_drv.c=609=static void *ublk_alloc_report_buffer(struct ublk_device *ublk,\n--\ndrivers/block/ublk_drv.c-635-\ndrivers/block/ublk_drv.c:636:static int ublk_report_zones(struct gendisk *disk, sector_t sector,\ndrivers/block/ublk_drv.c-637-\t\t      unsigned int nr_zones, struct blk_report_zones_args *args)\n--\ndrivers/block/ublk_drv.c=733=static void ublk_setup_iod_zoned(struct ublk_queue *ubq, struct request *req)\n--\ndrivers/block/ublk_drv.c-771-\ndrivers/block/ublk_drv.c:772:#define ublk_report_zones (NULL)\ndrivers/block/ublk_drv.c-773-\n--\ndrivers/block/ublk_drv.c=1382=static const struct block_device_operations ub_fops = {\n--\ndrivers/block/ublk_drv.c-1385-\t.free_disk =\tublk_free_disk,\ndrivers/block/ublk_drv.c:1386:\t.report_zones =\tublk_report_zones,\ndrivers/block/ublk_drv.c-1387-};\n"
}

13/2 2026/10/11 06:41 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 40441
							output: 38
							thoughts: 30
						

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

**Diving into the ublk_drv.c conditional**

Alright, time to get my hands dirty with this `ublk_drv.c` code. Specifically, I need to understand the `#ifdef` block guarding `ublk_report_zones`. I suspect this has implications for how zoning is handled, or potentially whether it’s even supported in a particular configuration. I want to quickly ascertain the build conditions tied to this feature, if it's dependent on a specific kernel configuration, or compile-time flags. What options are we talking about here? It could be a simple `CONFIG_` option or something more complex. This will dictate how I interpret the code flow around zone reporting and how to move forward with the task at hand. Let's see what the preprocessor directives reveal.



14/2 2026/10/11 06:41 tool read-file
0m Args:
{
  "File": "drivers/block/ublk_drv.c",
  "FirstLine": 600,
  "LineCount": 40
}

Results:
{
  "Contents": " 600:\t\treturn 0;\n 601:\t}\n 602:\t\n 603:\tstatic void ublk_dev_param_zoned_apply(struct ublk_device *ub)\n 604:\t{\n 605:\t\tub-\u003eub_disk-\u003enr_zones = ublk_get_nr_zones(ub);\n 606:\t}\n 607:\t\n 608:\t/* Based on virtblk_alloc_report_buffer */\n 609:\tstatic void *ublk_alloc_report_buffer(struct ublk_device *ublk,\n 610:\t\t\t\t\t      unsigned int nr_zones, size_t *buflen)\n 611:\t{\n 612:\t\tstruct request_queue *q = ublk-\u003eub_disk-\u003equeue;\n 613:\t\tsize_t bufsize;\n 614:\t\tvoid *buf;\n 615:\t\n 616:\t\tnr_zones = min_t(unsigned int, nr_zones,\n 617:\t\t\t\t ublk-\u003eub_disk-\u003enr_zones);\n 618:\t\n 619:\t\tbufsize = nr_zones * sizeof(struct blk_zone);\n 620:\t\tbufsize =\n 621:\t\t\tmin_t(size_t, bufsize, queue_max_hw_sectors(q) \u003c\u003c SECTOR_SHIFT);\n 622:\t\n 623:\t\twhile (bufsize \u003e= sizeof(struct blk_zone)) {\n 624:\t\t\tbuf = kvmalloc(bufsize, GFP_KERNEL | __GFP_NORETRY);\n 625:\t\t\tif (buf) {\n 626:\t\t\t\t*buflen = bufsize;\n 627:\t\t\t\treturn buf;\n 628:\t\t\t}\n 629:\t\t\tbufsize \u003e\u003e= 1;\n 630:\t\t}\n 631:\t\n 632:\t\t*buflen = 0;\n 633:\t\treturn NULL;\n 634:\t}\n 635:\t\n 636:\tstatic int ublk_report_zones(struct gendisk *disk, sector_t sector,\n 637:\t\t\t      unsigned int nr_zones, struct blk_report_zones_args *args)\n 638:\t{\n 639:\t\tstruct ublk_device *ub = disk-\u003eprivate_data;\n"
}

15/2 2026/10/11 06:41 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 41303
							output: 38
							thoughts: 25
						

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

**Diving into the ublk_drv.c Abyss**

Okay, let's get down to it. I need to understand what's happening around line 765 within `drivers/block/ublk_drv.c`. That likely points to a specific piece of the ublk driver, and given the line number, it's probably deeper than the initial setup or registration. My hunch is that this is involved with either I/O submission, completion handling, error reporting, or resource management; maybe something related to the actual data path or queue management if it's that far down. I’ll need to quickly get my bearings to understand the surrounding context. Specifically, I'll need to figure out what functions are calling that section of the code, and what functions that section might be calling. Cross-referencing with documentation for ublk, or any relevant kernel docs, will be useful. Hopefully, the surrounding code is relatively well-commented, as that will speed up the analysis process. This could be something simple, or something deceptively complex that will require a deep dive into the virtual block device code. Wish me luck!



16/2 2026/10/11 06:42 tool read-file
0m Args:
{
  "File": "drivers/block/ublk_drv.c",
  "FirstLine": 760,
  "LineCount": 20
}

Results:
{
  "Contents": " 760:\t\t\t\t      desc-\u003esector);\n 761:\t\t\treturn;\n 762:\t\tdefault:\n 763:\t\t\tWARN_ON_ONCE(1);\n 764:\t\t\treturn;\n 765:\t\t}\n 766:\t\n 767:\t\tublk_init_iod(ubq, req, ublk_op, blk_rq_sectors(req), blk_rq_pos(req));\n 768:\t}\n 769:\t\n 770:\t#else\n 771:\t\n 772:\t#define ublk_report_zones (NULL)\n 773:\t\n 774:\tstatic int ublk_dev_param_zoned_validate(const struct ublk_device *ub)\n 775:\t{\n 776:\t\treturn -EOPNOTSUPP;\n 777:\t}\n 778:\t\n 779:\tstatic void ublk_dev_param_zoned_apply(struct ublk_device *ub)\n"
}

17/2 2026/10/11 06:42 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 41898
							output: 38
							thoughts: 15
						

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

**Analyzing Conditional Compilation**

Alright, let's dive in. My immediate focus is on line 770. I need to understand the conditional compilation context there. I'm assuming there's an `#ifdef` (or perhaps an `#ifndef`, `#if`, etc.) statement governing this line, and that's the key I need to unlock. This guard is clearly significant to this section of code. I need to identify the preprocessor symbol being tested. Once I know that, I can quickly determine which features are enabled or disabled depending on this symbol. I might need to trace the definition of that symbol throughout the project. Depending on the complexity and how the feature is used, there are a few things that come to mind. I would immediately think:

*   Could this line be for a specific platform?
*   Is this guarding a deprecated feature?
*   Is this related to debugging or testing builds?
*   Is it an optimization for a certain use case?

I need to quickly assess the impact of this preprocessor directive on the overall functionality and determine if it's impacting any design decisions, performance, or behavior.



18/2 2026/10/11 06:42 tool read-file
0m Args:
{
  "File": "drivers/block/ublk_drv.c",
  "FirstLine": 580,
  "LineCount": 20
}

Results:
{
  "Contents": " 580:\t\n 581:\tstatic int ublk_dev_param_zoned_validate(const struct ublk_device *ub)\n 582:\t{\n 583:\t\tconst struct ublk_param_zoned *p = \u0026ub-\u003eparams.zoned;\n 584:\t\tint nr_zones;\n 585:\t\n 586:\t\tif (!ublk_dev_is_zoned(ub))\n 587:\t\t\treturn -EINVAL;\n 588:\t\n 589:\t\tif (!p-\u003emax_zone_append_sectors)\n 590:\t\t\treturn -EINVAL;\n 591:\t\n 592:\t\tnr_zones = ublk_get_nr_zones(ub);\n 593:\t\n 594:\t\tif (p-\u003emax_active_zones \u003e nr_zones)\n 595:\t\t\treturn -EINVAL;\n 596:\t\n 597:\t\tif (p-\u003emax_open_zones \u003e nr_zones)\n 598:\t\t\treturn -EINVAL;\n 599:\t\n"
}

19/2 2026/10/11 06:42 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 42493
							output: 38
							thoughts: 13
						

Thoughts:
Okay, I'm ready to dive into this. Let's see... looking back, specifically around line 570... what was I thinking at that point?



20/2 2026/10/11 06:42 tool read-file
0m Args:
{
  "File": "drivers/block/ublk_drv.c",
  "FirstLine": 565,
  "LineCount": 20
}

Results:
{
  "Contents": " 565:\t\treturn xa_load(\u0026ublk_zoned_report_descs, (unsigned long)req);\n 566:\t}\n 567:\t\n 568:\tstatic int ublk_get_nr_zones(const struct ublk_device *ub)\n 569:\t{\n 570:\t\tconst struct ublk_param_basic *p = \u0026ub-\u003eparams.basic;\n 571:\t\n 572:\t\t/* Zone size is a power of 2 */\n 573:\t\treturn p-\u003edev_sectors \u003e\u003e ilog2(p-\u003echunk_sectors);\n 574:\t}\n 575:\t\n 576:\tstatic int ublk_revalidate_disk_zones(struct ublk_device *ub)\n 577:\t{\n 578:\t\treturn blk_revalidate_disk_zones(ub-\u003eub_disk);\n 579:\t}\n 580:\t\n 581:\tstatic int ublk_dev_param_zoned_validate(const struct ublk_device *ub)\n 582:\t{\n 583:\t\tconst struct ublk_param_zoned *p = \u0026ub-\u003eparams.zoned;\n 584:\t\tint nr_zones;\n"
}

21/2 2026/10/11 06:42 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 42907
							output: 34
							thoughts: 16
						

Thoughts:
Okay, here's my interpretation of that thought process, tailored for an expert audience, and written in the first person:

**Navigating Preprocessor Directives**

Alright, so I'm looking at this code and I need to figure out the context around line 565. The most direct path to understanding conditional compilation is often tracing the preprocessor directives. I need to understand what's *actually* going on in that particular area of the code. My instinct is that the presence of `#ifdef` or a similar conditional compile directive before that line is relevant. So I'll start by searching for the `#ifdef` macros closest to that line to understand the state of the code. Locating the last instance of that directive, if it exists, is going to be key to deciphering the context of the code at that specific line.



22/2 2026/10/11 06:42 tool grepper
0m Args:
{
  "Expression": "^#if",
  "PathPrefixes": [
    "drivers/block/ublk_drv.c"
  ]
}

Results:
{
  "Output": "drivers/block/ublk_drv.c=515=static void ublk_init_iod(struct ublk_queue *ubq, struct request *req,\n--\ndrivers/block/ublk_drv.c-539-\ndrivers/block/ublk_drv.c:540:#ifdef CONFIG_BLK_DEV_ZONED\ndrivers/block/ublk_drv.c-541-\n--\ndrivers/block/ublk_drv.c=1430=static size_t ublk_copy_user_pages(const struct request *req,\n--\ndrivers/block/ublk_drv.c-1443-\ndrivers/block/ublk_drv.c:1444:#ifdef CONFIG_BLK_DEV_INTEGRITY\ndrivers/block/ublk_drv.c-1445-static size_t ublk_copy_user_integrity(const struct request *req,\n"
}

23/2 2026/10/11 06:42 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 43363
							output: 256
							thoughts: 1308
						

Thoughts:
**Analysis of ublk Driver Configuration and Symbol Selection for Fuzzing**

Okay, so I'm looking at this patch and immediately the `#ifdef CONFIG_BLK_DEV_ZONED` on line 540 pops out. It means that `ublk_report_zones` is compiled only when zoned block device support is enabled. The base driver itself already requires `CONFIG_BLK_DEV_UBLK`, which is a given. Since the patch touches `disk_report_zone` within `ublk_report_zones`, including `BLK_DEV_ZONED` makes perfect sense. Further, `BLK_DEV_UBLK` selects `IO_URING`, so that's another important dependency. No other obvious config dependencies are apparent in the initial analysis.

Let's dig deeper in `drivers/block/Kconfig`. Yes, `BLK_DEV_UBLK` selects `IO_URING`, as expected, and `CONFIG_BLK_DEV_ZONED` is indeed required for `ublk_report_zones`. Good. Now, the next step is to nail down the relevant symbols that are modified.

I've identified these symbols as being relevant: `ublk_ctrl_start_dev`, `ublk_stop_dev`, `ublk_ch_uring_cmd_local`, `ublk_uring_cmd_cancel_fn`, `ublk_ctrl_end_recovery`, `ublk_batch_attach`, `ublk_ch_release_work_fn`, `ublk_report_zones`, `ublk_ch_open`, and `ublk_ch_release`.

I'm thinking, are `ublk_ch_open` and `ublk_ch_release` too generic? They *are* specific to the ublk character devices. So, perhaps not as critical. However, `ublk_ctrl_start_dev`, `ublk_stop_dev`, `ublk_ch_uring_cmd_local`, `ublk_uring_cmd_cancel_fn`, `ublk_ctrl_end_recovery`, `ublk_batch_attach`, `ublk_ch_release_work_fn`, and `ublk_report_zones` are directly involved in the cancellation and state machine logic being updated by this patch.

Now, let's see about inlining. `ublk_ctrl_start_dev` is not `static`, but it's huge, over 100 lines and is called via a function pointer table or switch case in `ublk_ctrl_uring_cmd`. `ublk_stop_dev` is `static` and called from `ublk_remove` and `ublk_ctrl_stop_dev`. `ublk_ch_uring_cmd_local` is called from `ublk_ch_uring_cmd` and `ublk_ch_uring_cmd_cb`. `ublk_uring_cmd_cancel_fn` is a cancellation callback, called from `ublk_ch_uring_cmd`. `ublk_ctrl_end_recovery` is called in `ublk_ctrl_uring_cmd`. `ublk_batch_attach` is called from `ublk_handle_batch_fetch_cmd`. `ublk_report_zones` is assigned to `ub_fops.report_zones`, and `ublk_ch_release_work_fn` is a workqueue worker function.

Now, let's check on some other functions, like `ublk_queue_reset_io_flags`, `ublk_reset_ch_dev`, `ublk_start_cancel`, and `ublk_cancel_cmd`. Might they be inlined? `ublk_queue_reset_io_flags` is only 10 lines, so likely inlined. `ublk_prep_cancel` is declared `static inline`. `__ublk_fetch` is 15 lines, and might be inlined into `ublk_fetch`. So, selecting the larger functions – `ublk_ctrl_start_dev`, `ublk_stop_dev`, `ublk_ch_uring_cmd_local`, `ublk_uring_cmd_cancel_fn`, `ublk_ctrl_end_recovery`, `ublk_batch_attach`, `ublk_ch_release_work_fn`, and `ublk_report_zones` is the best choice!

The patch modifies the userspace block driver (`ublk_drv.c`), which provides virtual block devices backed by userspace processes via io_uring. This fix is dealing with race conditions between `STOP_DEV`, `START_DEV`, `END_USER_RECOVERY`, command cancellations, and io_uring command fetching/dispatching. It


24/2 2026/10/11 06:43 tool set-results
0m Args:
{
  "EnableConfigs": [
    "BLK_DEV_UBLK",
    "BLK_DEV_ZONED"
  ],
  "FocusSymbols": [
    "ublk_ctrl_start_dev",
    "ublk_stop_dev",
    "ublk_ch_uring_cmd_local",
    "ublk_uring_cmd_cancel_fn",
    "ublk_ctrl_end_recovery",
    "ublk_batch_attach",
    "ublk_ch_release_work_fn",
    "ublk_report_zones"
  ],
  "Reasoning": "The patch modifies the userspace block device driver (ublk_drv.c), addressing concurrency bugs and state synchronization between STOP_DEV, START_DEV, recovery operations, and io_uring command cancellation. It introduces the UB_STATE_STOPPING state, updates locking around cancel_mutex, adjusts cancel-related WARN_ON_ONCE checks, and fixes zone reporting indexing in ublk_report_zones. Because ublk operates via io_uring and virtual devices accessible in standard QEMU environments without special physical hardware, this reachable and concurrency-heavy code warrants fuzzing.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "BLK_DEV_UBLK",
    "BLK_DEV_ZONED"
  ],
  "FocusSymbols": [
    "ublk_ctrl_start_dev",
    "ublk_stop_dev",
    "ublk_ch_uring_cmd_local",
    "ublk_uring_cmd_cancel_fn",
    "ublk_ctrl_end_recovery",
    "ublk_batch_attach",
    "ublk_ch_release_work_fn",
    "ublk_report_zones"
  ],
  "Reasoning": "The patch modifies the userspace block device driver (ublk_drv.c), addressing concurrency bugs and state synchronization between STOP_DEV, START_DEV, recovery operations, and io_uring command cancellation. It introduces the UB_STATE_STOPPING state, updates locking around cancel_mutex, adjusts cancel-related WARN_ON_ONCE checks, and fixes zone reporting indexing in ublk_report_zones. Because ublk operates via io_uring and virtual devices accessible in standard QEMU environments without special physical hardware, this reachable and concurrency-heavy code warrants fuzzing.",
  "WorthFuzzing": true
}

25/1 2026/10/11 06:43 action If
4m Args:
{
  "WorthFuzzing": true
}

Results:
null

26/2 2026/10/11 06:43 agent kmsan-evaluator
4m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch addresses synchronization, state management, and cancellation races in the ublk driver (ublk_drv.c). Specifically:\n1. It prevents NULL pointer dereferences on io-\u003ecmd and io_uring use-after-free bugs when I/O commands are canceled while starting/stopping devices or during recovery.\n2. It introduces UB_STATE_STOPPING and manages ublk device lifecycle state transitions across START_DEV, STOP_DEV, and FETCH commands.\n3. In ublk_report_zones(), it fixes a bug where the per-batch loop index 'i' was passed to disk_report_zone() instead of the cumulative 'done_zones', ensuring multi-batch zone reporting copies to the correct index in user memory. The underlying report buffer is already explicitly zeroed with memset(), and no uninitialized kernel data is copied to user space.\n4. All added/modified variables and struct fields (e.g., ch_file, canceled, cur) are properly initialized or reside within zero-allocated structures (kzalloc_flex / kzalloc_obj).\n\nThese changes primarily address race conditions, NULL pointer dereferences, and use-after-free scenarios, which are covered by standard KASAN, LOCKDEP, and kernel oops detectors. No uninitialized memory reads or information leak hazards are introduced or exposed; thus, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false
}

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

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

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

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

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

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

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


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

Prompt:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit a4bb54a2d35bed452a582bea2ba85f6ce8ce5cdb
Author: syz-cluster <triage@syzkaller.com>
Date:   Sun Oct 11 06:40:13 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/block/ublk.rst b/Documentation/block/ublk.rst
index 28300fee22bfc..f07611b0d4895 100644
--- a/Documentation/block/ublk.rst
+++ b/Documentation/block/ublk.rst
@@ -118,7 +118,11 @@ managing and controlling ublk devices with help of several control commands:
   After the server prepares userspace resources (such as creating I/O handler
   threads & io_uring for handling ublk IO), this command is sent to the
   driver for allocating & exposing ``/dev/ublkb*``. Parameters set via
-  ``UBLK_CMD_SET_PARAMS`` are applied for creating the device.
+  ``UBLK_CMD_SET_PARAMS`` are applied for creating the device. The command
+  fails with ``-EBUSY`` if an I/O command fetched by the current server
+  was canceled, because its io_uring is gone. The server can't fetch it
+  again, and the device can be started again once the server has closed
+  ``/dev/ublkc*``.
 
 - ``UBLK_CMD_STOP_DEV``
 
@@ -126,6 +130,13 @@ managing and controlling ublk devices with help of several control commands:
   ublk server will release resources (such as destroying I/O handler threads &
   io_uring).
 
+  If a server has ``/dev/ublkc*`` open, its fetched I/O commands complete with
+  ``UBLK_IO_RES_ABORT``. Until it closes ``/dev/ublkc*``, new
+  ``UBLK_IO_FETCH_REQ`` and ``UBLK_U_IO_PREP_IO_CMDS`` commands complete with
+  ``UBLK_IO_RES_ABORT`` too, and ``UBLK_CMD_START_DEV`` fails with ``-EBUSY``,
+  even if the server hadn't fetched anything. The device can be started again
+  by a server that opens ``/dev/ublkc*`` after that.
+
 - ``UBLK_CMD_DEL_DEV``
 
   Remove ``/dev/ublkc*``. When this command returns, the allocated ublk device
@@ -195,7 +206,9 @@ managing and controlling ublk devices with help of several control commands:
   command is accepted after ublk device is quiesced and a new process has
   opened ``/dev/ublkc*`` and get all ublk queues be ready. When this command
   returns, ublk device is unquiesced and new I/O requests are passed to the
-  new process.
+  new process. It fails with ``-EBUSY`` if an I/O command of the new
+  process was canceled already. The recovery can be started over once the
+  new process has closed ``/dev/ublkc*``.
 
 - user recovery feature description
 
diff --git a/drivers/block/ublk_drv.c b/drivers/block/ublk_drv.c
index b32872421951d..1e84ccc68b9b0 100644
--- a/drivers/block/ublk_drv.c
+++ b/drivers/block/ublk_drv.c
@@ -321,6 +321,8 @@ struct ublk_device {
 #define UB_STATE_OPEN		0
 #define UB_STATE_USED		1
 #define UB_STATE_DELETED	2
+/* STOP_DEV canceled the server's commands, until its release */
+#define UB_STATE_STOPPING	3
 	unsigned long		state;
 	int			ub_number;
 
@@ -334,6 +336,13 @@ struct ublk_device {
 	u16			nr_queue_ready;
 	bool 			unprivileged_daemons;
 	struct mutex cancel_mutex;
+	/* the open /dev/ublkcN, protected by cancel_mutex */
+	struct file *ch_file;
+	/*
+	 * A cancel started in this FETCH round. Set by ublk_set_canceling(),
+	 * cleared only by ublk_reset_ch_dev() when a new round starts. While
+	 * it is set, no queue clears its ->canceling.
+	 */
 	bool canceling;
 	pid_t 	ublksrv_tgid;
 	struct delayed_work	exit_work;
@@ -687,7 +696,7 @@ static int ublk_report_zones(struct gendisk *disk, sector_t sector,
 			if (!zone->len)
 				break;
 
-			ret = disk_report_zone(disk, zone, i, args);
+			ret = disk_report_zone(disk, zone, done_zones, args);
 			if (ret)
 				goto out;
 
@@ -810,6 +819,8 @@ ublk_batch_alloc_fcmd(struct io_uring_cmd *cmd)
 	if (fcmd) {
 		fcmd->cmd = cmd;
 		fcmd->buf_group = READ_ONCE(cmd->sqe->buf_index);
+		/* a cancel may look at it before it is linked */
+		INIT_LIST_HEAD(&fcmd->node);
 	}
 	return fcmd;
 }
@@ -2399,6 +2410,9 @@ static int ublk_ch_open(struct inode *inode, struct file *filp)
 		return -EBUSY;
 	filp->private_data = ub;
 	ub->ublksrv_tgid = current->tgid;
+	mutex_lock(&ub->cancel_mutex);
+	ub->ch_file = filp;
+	mutex_unlock(&ub->cancel_mutex);
 	return 0;
 }
 
@@ -2415,11 +2429,17 @@ static void ublk_reset_ch_dev(struct ublk_device *ub)
 		spin_unlock(&ubq->cancel_lock);
 	}
 
+	/* a new FETCH round starts, the queues stay canceling until ready */
+	mutex_lock(&ub->cancel_mutex);
+	ub->canceling = false;
+	mutex_unlock(&ub->cancel_mutex);
+
 	/* set to NULL, otherwise new tasks cannot mmap io_cmd_buf */
 	ub->mm = NULL;
 	ub->nr_queue_ready = 0;
 	ub->unprivileged_daemons = false;
 	ub->ublksrv_tgid = -1;
+	clear_bit(UB_STATE_STOPPING, &ub->state);
 }
 
 static struct gendisk *ublk_get_disk(struct ublk_device *ub)
@@ -2539,12 +2559,15 @@ static void ublk_ch_release_work_fn(struct work_struct *work)
 	}
 
 	/*
-	 * disk isn't attached yet, either device isn't live, or it has
-	 * been removed already, so we needn't to do anything
+	 * No disk: the device isn't live, or it has been removed already.
+	 * There are no requests to abort, but the round still has to be
+	 * reset, so that a new server can fetch and start the device.
 	 */
 	disk = ublk_get_disk(ub);
-	if (!disk)
-		goto out;
+	if (!disk) {
+		mutex_lock(&ub->mutex);
+		goto reset;
+	}
 
 	/*
 	 * All uring_cmd are done now, so abort any request outstanding to
@@ -2576,7 +2599,7 @@ static void ublk_ch_release_work_fn(struct work_struct *work)
 
 	/* double check after grabbing lock */
 	if (!ub->ub_disk)
-		goto unlock;
+		goto reset;
 
 	/*
 	 * Transition the device to the nosrv state. What exactly this
@@ -2602,13 +2625,14 @@ static void ublk_ch_release_work_fn(struct work_struct *work)
 				WRITE_ONCE(ublk_get_queue(ub, i)->fail_io, true);
 		}
 	}
-unlock:
+reset:
+	/*
+	 * All uring_cmd has been done now, reset device & ubq. Under
+	 * ub->mutex, so START_DEV sees the round either ready or reset.
+	 */
+	ublk_reset_ch_dev(ub);
 	mutex_unlock(&ub->mutex);
 	ublk_put_disk(disk);
-
-	/* all uring_cmd has been done now, reset device & ubq */
-	ublk_reset_ch_dev(ub);
-out:
 	clear_bit(UB_STATE_OPEN, &ub->state);
 
 	/* put the reference grabbed in ublk_ch_release() */
@@ -2619,6 +2643,9 @@ static int ublk_ch_release(struct inode *inode, struct file *filp)
 {
 	struct ublk_device *ub = filp->private_data;
 
+	mutex_lock(&ub->cancel_mutex);
+	ub->ch_file = NULL;
+	mutex_unlock(&ub->cancel_mutex);
 	/*
 	 * Grab ublk device reference, so it won't be gone until we are
 	 * really released from work function.
@@ -2732,9 +2759,11 @@ static void ublk_abort_queue(struct ublk_device *ub, struct ublk_queue *ubq)
 
 static void ublk_start_cancel(struct ublk_device *ub)
 {
-	struct gendisk *disk = ublk_get_disk(ub);
+	struct gendisk *disk;
 
+	/* sync with ublk_ctrl_start_dev() publishing the disk */
 	mutex_lock(&ub->cancel_mutex);
+	disk = ublk_get_disk(ub);
 	if (ub->canceling)
 		goto out;
 
@@ -2790,7 +2819,8 @@ static void ublk_cancel_cmd(struct ublk_queue *ubq, u16 tag,
 	done = !!(io->flags & UBLK_IO_FLAG_CANCELED);
 	if (!done) {
 		io->flags |= UBLK_IO_FLAG_CANCELED;
-		cmd = io->cmd;
+		/* dependency ordered against smp_wmb() in ublk_prep_cancel() */
+		cmd = READ_ONCE(io->cmd);
 		io->cmd = NULL;
 	}
 	spin_unlock(&ubq->cancel_lock);
@@ -2879,6 +2909,7 @@ static void ublk_uring_cmd_cancel_fn(struct io_uring_cmd *cmd,
 {
 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
 	struct ublk_queue *ubq = pdu->ubq;
+	struct io_uring_cmd *cur;
 	struct task_struct *task;
 	struct ublk_io *io;
 
@@ -2895,7 +2926,9 @@ static void ublk_uring_cmd_cancel_fn(struct io_uring_cmd *cmd,
 
 	ublk_start_cancel(ubq->dev);
 
-	WARN_ON_ONCE(io->cmd != cmd);
+	/* NULL if a cancel from the control path took it meanwhile */
+	cur = READ_ONCE(io->cmd);
+	WARN_ON_ONCE(cur && cur != cmd);
 	ublk_cancel_cmd(ubq, pdu->tag, issue_flags);
 }
 
@@ -3006,13 +3039,54 @@ static void ublk_stop_dev_unlocked(struct ublk_device *ub)
 	put_disk(disk);
 }
 
+static struct file *ublk_get_ch_file(struct ublk_device *ub)
+{
+	struct file *file;
+
+	mutex_lock(&ub->cancel_mutex);
+	file = ub->ch_file;
+	if (file && !file_ref_get(&file->f_ref))
+		file = NULL;
+	mutex_unlock(&ub->cancel_mutex);
+	return file;
+}
+
 static void ublk_stop_dev(struct ublk_device *ub)
 {
+	struct file *file;
+
+	/*
+	 * FETCH, PREP and START_DEV take ub->mutex. If a server has
+	 * /dev/ublkcN open, set STOPPING, which turns it away, and hold a
+	 * reference on the file: the server's release, whose reset clears
+	 * STOPPING and lets a new server attach, can't run before we drop it.
+	 * So the cancel can run after the unlock and only meets this server's
+	 * commands; it has to: io_uring_cmd_done() may take uring_lock, under
+	 * which FETCH takes ub->mutex.
+	 */
 	mutex_lock(&ub->mutex);
 	ublk_stop_dev_unlocked(ub);
-	mutex_unlock(&ub->mutex);
 	cancel_work_sync(&ub->partition_scan_work);
+	file = ublk_get_ch_file(ub);
+	if (file) {
+		/*
+		 * The server has to close /dev/ublkcN before this device can
+		 * be started again: the reset in its release clears STOPPING.
+		 */
+		set_bit(UB_STATE_STOPPING, &ub->state);
+		/* for wake_up_var() below, see wake_up_bit() */
+		smp_mb__after_atomic();
+	}
+	mutex_unlock(&ub->mutex);
+
+	/* no server: nothing to cancel */
+	if (!file)
+		return;
+
+	/* wake a START_DEV waiting for the device to get ready */
+	wake_up_var(&ub->nr_queue_ready);
 	ublk_cancel_dev(ub);
+	__fput_sync(file);
 }
 
 static void ublk_reset_io_flags(struct ublk_queue *ubq, struct ublk_io *io)
@@ -3024,11 +3098,19 @@ static void ublk_reset_io_flags(struct ublk_queue *ubq, struct ublk_io *io)
 }
 
 /* reset per-queue io flags */
-static void ublk_queue_reset_io_flags(struct ublk_queue *ubq)
+static void ublk_queue_reset_io_flags(struct ublk_device *ub,
+				      struct ublk_queue *ubq)
 {
-	spin_lock(&ubq->cancel_lock);
-	ubq->canceling = false;
-	spin_unlock(&ubq->cancel_lock);
+	/*
+	 * A cancel in this FETCH round took a command which still counts as
+	 * ready, so the queue has to stay canceling. ub->canceling is set
+	 * under cancel_mutex before any command is taken: either we see it
+	 * here, or the cancel marks this queue again later.
+	 */
+	mutex_lock(&ub->cancel_mutex);
+	if (!ub->canceling)
+		ubq->canceling = false;
+	mutex_unlock(&ub->cancel_mutex);
 	ubq->fail_io = false;
 }
 
@@ -3050,24 +3132,17 @@ static void ublk_mark_io_ready(struct ublk_device *ub, u16 q_id,
 		ub->nr_queue_ready++;
 
 		/*
-		 * Reset queue flags as soon as this queue is ready.
-		 * This clears the canceling flag, allowing batch FETCH commands
-		 * to succeed during recovery without waiting for all queues.
+		 * Reset queue flags as soon as this queue is ready. Unless
+		 * this round saw a cancel, this clears the canceling flag,
+		 * allowing batch FETCH commands to succeed during recovery
+		 * without waiting for all queues.
 		 */
-		ublk_queue_reset_io_flags(ubq);
+		ublk_queue_reset_io_flags(ub, ubq);
 	}
 
-	/* Check if all queues are ready */
-	if (ublk_dev_ready(ub)) {
-		/*
-		 * All queues ready - clear device-level canceling flag
-		 * and wake ublk_dev_ready() waiters.
-		 */
-		mutex_lock(&ub->cancel_mutex);
-		ub->canceling = false;
-		mutex_unlock(&ub->cancel_mutex);
+	/* All queues ready - wake ublk_dev_ready() waiters */
+	if (ublk_dev_ready(ub))
 		wake_up_var(&ub->nr_queue_ready);
-	}
 }
 
 static inline int ublk_check_cmd_op(u32 cmd_op)
@@ -3151,6 +3226,12 @@ ublk_fill_io_cmd(struct ublk_io *io, struct io_uring_cmd *cmd)
 	return req;
 }
 
+/*
+ * Call before ublk_fill_io_cmd() publishes @cmd in io->cmd: a control-path
+ * cancel may complete any command found there, and io_uring_cmd_done() only
+ * takes it off the cancelable list if it is marked already. The handlers
+ * hold uring_lock, so marking takes no lock.
+ */
 static inline void ublk_prep_cancel(struct io_uring_cmd *cmd,
 				    unsigned int issue_flags,
 				    struct ublk_queue *ubq, u16 tag)
@@ -3164,6 +3245,8 @@ static inline void ublk_prep_cancel(struct io_uring_cmd *cmd,
 	pdu->ubq = ubq;
 	pdu->tag = tag;
 	io_uring_cmd_mark_cancelable(cmd, issue_flags);
+	/* pairs with the cancel loading cmd from io->cmd, then cmd->flags */
+	smp_wmb();
 }
 
 static void ublk_io_release(void *priv)
@@ -3268,6 +3351,9 @@ static int ublk_check_fetch_buf(const struct ublk_device *ub, __u64 buf_addr)
 static int __ublk_fetch(struct io_uring_cmd *cmd, struct ublk_device *ub,
 			struct ublk_io *io, u16 q_id)
 {
+	if (test_bit(UB_STATE_STOPPING, &ub->state))
+		return UBLK_IO_RES_ABORT;
+
 	/* UBLK_IO_FETCH_REQ is only allowed before dev is setup */
 	if (ublk_dev_ready(ub))
 		return -EBUSY;
@@ -3411,11 +3497,11 @@ static int ublk_ch_uring_cmd_local(struct io_uring_cmd *cmd,
 		ret = ublk_check_fetch_buf(ub, addr);
 		if (ret)
 			goto out;
+		/* before ublk_fetch() publishes io->cmd, see ublk_prep_cancel() */
+		ublk_prep_cancel(cmd, issue_flags, ubq, tag);
 		ret = ublk_fetch(cmd, ub, io, addr, q_id);
 		if (ret)
-			goto out;
-
-		ublk_prep_cancel(cmd, issue_flags, ubq, tag);
+			goto out_done;
 		return -EIOCBQUEUED;
 	}
 
@@ -3459,6 +3545,7 @@ static int ublk_ch_uring_cmd_local(struct io_uring_cmd *cmd,
 		if (ret)
 			goto out;
 		io->res = result;
+		ublk_prep_cancel(cmd, issue_flags, ubq, tag);
 		req = ublk_fill_io_cmd(io, cmd);
 		ublk_apply_io_buf(ub, io, cmd, addr, &auto_buf, &buf_idx);
 		if (buf_idx != UBLK_INVALID_BUF_IDX)
@@ -3477,19 +3564,24 @@ static int ublk_ch_uring_cmd_local(struct io_uring_cmd *cmd,
 		 * uring_cmd active first and prepare for handling new requeued
 		 * request
 		 */
+		ublk_prep_cancel(cmd, issue_flags, ubq, tag);
 		req = ublk_fill_io_cmd(io, cmd);
 		io->buf.addr = addr;
 		if (likely(ublk_get_data(ubq, io, req))) {
 			__ublk_prep_compl_io_cmd(io, req);
-			return UBLK_IO_RES_OK;
+			ret = UBLK_IO_RES_OK;
+			goto out_done;
 		}
 		break;
 	default:
 		goto out;
 	}
-	ublk_prep_cancel(cmd, issue_flags, ubq, tag);
 	return -EIOCBQUEUED;
 
+ out_done:
+	/* marked cancelable: complete through io_uring_cmd_done() */
+	io_uring_cmd_done(cmd, ret, issue_flags);
+	return -EIOCBQUEUED;
  out:
 	pr_devel("%s: complete: cmd op %d, tag %d ret %x io_flags %x\n",
 			__func__, cmd_op, tag, ret, io ? io->flags : 0);
@@ -3888,6 +3980,15 @@ static int ublk_batch_attach(struct ublk_queue *ubq,
 	bool free = false;
 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(data->cmd);
 
+	/*
+	 * Mark it cancelable before linking it into fcmd_head, where a cancel
+	 * from the control path can take and complete it: see
+	 * ublk_prep_cancel(). evts_lock orders the mark before the link.
+	 */
+	pdu->ubq = ubq;
+	pdu->fcmd = fcmd;
+	io_uring_cmd_mark_cancelable(fcmd->cmd, data->issue_flags);
+
 	spin_lock(&ubq->evts_lock);
 	if (unlikely(ubq->force_abort || ubq->canceling)) {
 		free = true;
@@ -3898,14 +3999,12 @@ static int ublk_batch_attach(struct ublk_queue *ubq,
 	spin_unlock(&ubq->evts_lock);
 
 	if (unlikely(free)) {
+		/* off the cancelable list first, then nothing can see fcmd */
+		io_uring_cmd_done(data->cmd, -ENODEV, data->issue_flags);
 		ublk_batch_free_fcmd(fcmd);
-		return -ENODEV;
+		return -EIOCBQUEUED;
 	}
 
-	pdu->ubq = ubq;
-	pdu->fcmd = fcmd;
-	io_uring_cmd_mark_cancelable(fcmd->cmd, data->issue_flags);
-
 	if (!new_fcmd)
 		goto out;
 
@@ -3913,9 +4012,12 @@ static int ublk_batch_attach(struct ublk_queue *ubq,
 	 * If the two fetch commands are originated from same io_ring_ctx,
 	 * run batch dispatch directly. Otherwise, schedule task work for
 	 * doing it.
+	 *
+	 * Use data->cmd, not fcmd->cmd: once fcmd is linked and not active,
+	 * a cancel from the control path may complete and free it.
 	 */
 	if (io_uring_cmd_ctx_handle(new_fcmd->cmd) ==
-			io_uring_cmd_ctx_handle(fcmd->cmd)) {
+			io_uring_cmd_ctx_handle(data->cmd)) {
 		data->cmd = new_fcmd->cmd;
 		ublk_batch_dispatch(ubq, data, new_fcmd);
 	} else {
@@ -4431,21 +4533,27 @@ static bool ublk_validate_user_pid(struct ublk_device *ub, pid_t ublksrv_pid)
 	return ub->ublksrv_tgid == ublksrv_pid;
 }
 
+static bool ublk_dev_ready_or_stopping(const struct ublk_device *ub)
+{
+	return ublk_dev_ready(ub) || test_bit(UB_STATE_STOPPING, &ub->state);
+}
+
 /*
- * Wait until all queues have fetched their I/O commands, and return with
- * ub->mutex held and readiness guaranteed: then every queue's ->canceling
- * is cleared. Ready may regress between wakeup and mutex_lock() (F_BATCH
- * UNPREP, daemon death), so re-check it under the mutex and wait again.
+ * Wait until all queues have fetched their I/O commands, or STOP_DEV set
+ * UB_STATE_STOPPING, and return with ub->mutex held. The queues stay
+ * canceling if this round saw a cancel, see ublk_queue_reset_io_flags().
+ * Ready may regress between wakeup and mutex_lock() (F_BATCH UNPREP,
+ * daemon death), so re-check it under the mutex and wait again.
  */
 static int ublk_wait_dev_ready_and_lock(struct ublk_device *ub)
 {
 	while (true) {
 		if (wait_var_event_interruptible(&ub->nr_queue_ready,
-						 ublk_dev_ready(ub)))
+						 ublk_dev_ready_or_stopping(ub)))
 			return -EINTR;
 
 		mutex_lock(&ub->mutex);
-		if (ublk_dev_ready(ub))
+		if (ublk_dev_ready_or_stopping(ub))
 			return 0;
 		mutex_unlock(&ub->mutex);
 	}
@@ -4469,6 +4577,7 @@ static int ublk_ctrl_start_dev(struct ublk_device *ub,
 		.dma_alignment		= 3,
 	};
 	struct gendisk *disk;
+	bool canceled;
 	int ret = -EINVAL;
 
 	if (ublksrv_pid <= 0)
@@ -4545,6 +4654,10 @@ static int ublk_ctrl_start_dev(struct ublk_device *ub,
 		ret = -EEXIST;
 		goto out_unlock;
 	}
+	if (test_bit(UB_STATE_STOPPING, &ub->state)) {
+		ret = -EBUSY;
+		goto out_unlock;
+	}
 
 	disk = blk_mq_alloc_disk(&ub->tag_set, &lim, NULL);
 	if (IS_ERR(disk)) {
@@ -4555,8 +4668,24 @@ static int ublk_ctrl_start_dev(struct ublk_device *ub,
 	disk->fops = &ub_fops;
 	disk->private_data = ub;
 
+	/*
+	 * A command of this FETCH round was canceled and can't be fetched
+	 * again, don't bring up a disk over it.  Check and publish the disk
+	 * in one cancel_mutex section: either this sees ub->canceling, or
+	 * ublk_start_cancel() sees the disk and quiesces it before marking
+	 * the queues.
+	 */
+	mutex_lock(&ub->cancel_mutex);
+	canceled = ub->canceling;
+	if (!canceled)
+		ub->ub_disk = disk;
+	mutex_unlock(&ub->cancel_mutex);
+	if (canceled) {
+		put_disk(disk);
+		ret = -EBUSY;
+		goto out_unlock;
+	}
 	ub->dev_info.ublksrv_pid = ub->ublksrv_tgid;
-	ub->ub_disk = disk;
 
 	ublk_apply_params(ub);
 
@@ -5133,6 +5262,7 @@ static int ublk_ctrl_end_recovery(struct ublk_device *ub,
 		const struct ublksrv_ctrl_cmd *header)
 {
 	int ublksrv_pid = (int)header->data[0];
+	bool canceled;
 	int ret = -EINVAL;
 
 	pr_devel("%s: Waiting for all FETCH_REQs, dev id %d...\n", __func__,
@@ -5156,6 +5286,20 @@ static int ublk_ctrl_end_recovery(struct ublk_device *ub,
 		ret = -EBUSY;
 		goto out_unlock;
 	}
+
+	/*
+	 * As in ublk_ctrl_start_dev(), a canceled command can't be fetched
+	 * again.  Best effort: the disk exists here, and a cancel after this
+	 * check is the ordinary death of the new server, which
+	 * ublk_start_cancel() handles by quiescing and marking.
+	 */
+	mutex_lock(&ub->cancel_mutex);
+	canceled = ub->canceling;
+	mutex_unlock(&ub->cancel_mutex);
+	if (canceled) {
+		ret = -EBUSY;
+		goto out_unlock;
+	}
 	ub->dev_info.ublksrv_pid = ub->ublksrv_tgid;
 	ub->dev_info.state = UBLK_S_DEV_LIVE;
 	pr_devel("%s: new ublksrv_pid %d, dev id %d\n",
diff --git a/tools/testing/selftests/ublk/.gitignore b/tools/testing/selftests/ublk/.gitignore
index e17bd28f27e04..d8e93fef7fcd3 100644
--- a/tools/testing/selftests/ublk/.gitignore
+++ b/tools/testing/selftests/ublk/.gitignore
@@ -3,3 +3,4 @@
 /tools
 kublk
 metadata_size
+ublk_cancel_ready
diff --git a/tools/testing/selftests/ublk/Makefile b/tools/testing/selftests/ublk/Makefile
index 5daf36c6c36c4..0d7c3dd9812ed 100644
--- a/tools/testing/selftests/ublk/Makefile
+++ b/tools/testing/selftests/ublk/Makefile
@@ -19,6 +19,7 @@ TEST_PROGS += test_generic_12.sh
 TEST_PROGS += test_generic_13.sh
 TEST_PROGS += test_generic_16.sh
 TEST_PROGS += test_generic_17.sh
+TEST_PROGS += test_generic_18.sh
 
 TEST_PROGS += test_batch_01.sh
 TEST_PROGS += test_batch_02.sh
@@ -74,13 +75,14 @@ TEST_PROGS += test_stress_09.sh
 
 TEST_FILES := settings
 
-TEST_GEN_PROGS_EXTENDED = kublk metadata_size
-STANDALONE_UTILS := metadata_size.c
+TEST_GEN_PROGS_EXTENDED = kublk metadata_size ublk_cancel_ready
+STANDALONE_UTILS := metadata_size.c ublk_cancel_ready.c
 
 LOCAL_HDRS += $(wildcard *.h)
 include ../lib.mk
 
 $(OUTPUT)/kublk: $(filter-out $(STANDALONE_UTILS),$(wildcard *.c))
+$(OUTPUT)/ublk_cancel_ready: ublk_cancel_ready.c ctrl.c
 
 check:
 	shellcheck -x -f gcc *.sh
diff --git a/tools/testing/selftests/ublk/batch.c b/tools/testing/selftests/ublk/batch.c
index d8d9ebed5979f..dfc81ee17d076 100644
--- a/tools/testing/selftests/ublk/batch.c
+++ b/tools/testing/selftests/ublk/batch.c
@@ -410,9 +410,16 @@ static void ublk_batch_compl_commit_cmd(struct ublk_thread *t,
 {
 	unsigned short buf_idx = user_data_to_tag(cqe->user_data);
 
-	if (op == _IOC_NR(UBLK_U_IO_PREP_IO_CMDS))
-		ublk_assert(cqe->res == 0);
-	else if (op == _IOC_NR(UBLK_U_IO_COMMIT_IO_CMDS)) {
+	if (op == _IOC_NR(UBLK_U_IO_PREP_IO_CMDS)) {
+		/* e.g. UBLK_IO_RES_ABORT after STOP_DEV: stop like a FETCH */
+		if (cqe->res < 0) {
+			ublk_dbg(UBLK_DBG_IO_CMD, "%s: prep failed %d\n",
+				 __func__, cqe->res);
+			t->state |= UBLKS_T_STOPPING;
+		} else {
+			ublk_assert(cqe->res == 0);
+		}
+	} else if (op == _IOC_NR(UBLK_U_IO_COMMIT_IO_CMDS)) {
 		int nr_elem = user_data_to_tgt_data(cqe->user_data);
 
 		ublk_assert(cqe->res == t->commit_buf_elem_size * nr_elem);
diff --git a/tools/testing/selftests/ublk/ctrl.c b/tools/testing/selftests/ublk/ctrl.c
new file mode 100644
index 0000000000000..53d54799f9097
--- /dev/null
+++ b/tools/testing/selftests/ublk/ctrl.c
@@ -0,0 +1,268 @@
+// SPDX-License-Identifier: GPL-2.0
+
+/* ublk control commands, shared by kublk and ublk_cancel_ready */
+
+#include "kublk.h"
+
+static void ublk_ctrl_init_cmd(struct ublk_dev *dev,
+		struct io_uring_sqe *sqe,
+		struct ublk_ctrl_cmd_data *data)
+{
+	struct ublksrv_ctrl_dev_info *info = &dev->dev_info;
+	struct ublksrv_ctrl_cmd *cmd = (struct ublksrv_ctrl_cmd *)ublk_get_sqe_cmd(sqe);
+
+	sqe->fd = dev->ctrl_fd;
+	sqe->opcode = IORING_OP_URING_CMD;
+	sqe->ioprio = 0;
+
+	if (data->flags & CTRL_CMD_HAS_BUF) {
+		cmd->addr = data->addr;
+		cmd->len = data->len;
+	}
+
+	if (data->flags & CTRL_CMD_HAS_DATA)
+		cmd->data[0] = data->data[0];
+
+	cmd->dev_id = info->dev_id;
+	cmd->queue_id = -1;
+
+	ublk_set_sqe_cmd_op(sqe, data->cmd_op);
+
+	io_uring_sqe_set_data(sqe, cmd);
+}
+
+int __ublk_ctrl_cmd(struct ublk_dev *dev,
+		struct ublk_ctrl_cmd_data *data)
+{
+	struct io_uring_sqe *sqe;
+	struct io_uring_cqe *cqe;
+	int ret = -EINVAL;
+
+	sqe = io_uring_get_sqe(&dev->ring);
+	if (!sqe) {
+		ublk_err("%s: can't get sqe ret %d\n", __func__, ret);
+		return ret;
+	}
+
+	ublk_ctrl_init_cmd(dev, sqe, data);
+
+	ret = io_uring_submit(&dev->ring);
+	if (ret < 0) {
+		ublk_err("uring submit ret %d\n", ret);
+		return ret;
+	}
+
+	ret = io_uring_wait_cqe(&dev->ring, &cqe);
+	if (ret < 0) {
+		ublk_err("wait cqe: %s\n", strerror(-ret));
+		return ret;
+	}
+	io_uring_cqe_seen(&dev->ring, cqe);
+
+	return cqe->res;
+}
+
+void ublk_ctrl_deinit(struct ublk_dev *dev)
+{
+	io_uring_queue_exit(&dev->ring);
+	close(dev->ctrl_fd);
+	free(dev);
+}
+
+struct ublk_dev *ublk_ctrl_init(void)
+{
+	struct ublk_dev *dev = (struct ublk_dev *)calloc(1, sizeof(*dev));
+	struct ublksrv_ctrl_dev_info *info;
+	int ret;
+
+	if (!dev)
+		return NULL;
+	info = &dev->dev_info;
+	dev->ctrl_fd = open(CTRL_DEV, O_RDWR);
+	if (dev->ctrl_fd < 0) {
+		free(dev);
+		return NULL;
+	}
+
+	info->max_io_buf_bytes = UBLK_IO_MAX_BYTES;
+
+	ret = ublk_setup_ring(&dev->ring, UBLK_CTRL_RING_DEPTH,
+			UBLK_CTRL_RING_DEPTH, IORING_SETUP_SQE128);
+	if (ret < 0) {
+		ublk_err("queue_init: %s\n", strerror(-ret));
+		close(dev->ctrl_fd);
+		free(dev);
+		return NULL;
+	}
+	dev->nr_fds = 1;
+
+	return dev;
+}
+
+int ublk_ctrl_stop_dev(struct ublk_dev *dev)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op	= UBLK_U_CMD_STOP_DEV,
+	};
+
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_try_stop_dev(struct ublk_dev *dev)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op	= UBLK_U_CMD_TRY_STOP_DEV,
+	};
+
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_start_dev(struct ublk_dev *dev,
+		int daemon_pid)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op	= UBLK_U_CMD_START_DEV,
+		.flags	= CTRL_CMD_HAS_DATA,
+	};
+
+	dev->dev_info.ublksrv_pid = data.data[0] = daemon_pid;
+
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_start_user_recovery(struct ublk_dev *dev)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op	= UBLK_U_CMD_START_USER_RECOVERY,
+	};
+
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_end_user_recovery(struct ublk_dev *dev, int daemon_pid)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op	= UBLK_U_CMD_END_USER_RECOVERY,
+		.flags	= CTRL_CMD_HAS_DATA,
+	};
+
+	dev->dev_info.ublksrv_pid = data.data[0] = daemon_pid;
+
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_add_dev(struct ublk_dev *dev)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op	= UBLK_U_CMD_ADD_DEV,
+		.flags	= CTRL_CMD_HAS_BUF,
+		.addr = (__u64) (uintptr_t) &dev->dev_info,
+		.len = sizeof(struct ublksrv_ctrl_dev_info),
+	};
+
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_del_dev(struct ublk_dev *dev)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op = UBLK_U_CMD_DEL_DEV,
+		.flags = 0,
+	};
+
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_get_info(struct ublk_dev *dev)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op	= UBLK_U_CMD_GET_DEV_INFO,
+		.flags	= CTRL_CMD_HAS_BUF,
+		.addr = (__u64) (uintptr_t) &dev->dev_info,
+		.len = sizeof(struct ublksrv_ctrl_dev_info),
+	};
+
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_set_params(struct ublk_dev *dev,
+		struct ublk_params *params)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op	= UBLK_U_CMD_SET_PARAMS,
+		.flags	= CTRL_CMD_HAS_BUF,
+		.addr = (__u64) (uintptr_t) params,
+		.len = sizeof(*params),
+	};
+	params->len = sizeof(*params);
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_get_params(struct ublk_dev *dev,
+		struct ublk_params *params)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op	= UBLK_U_CMD_GET_PARAMS,
+		.flags	= CTRL_CMD_HAS_BUF,
+		.addr = (__u64)params,
+		.len = sizeof(*params),
+	};
+
+	params->len = sizeof(*params);
+
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_get_features(struct ublk_dev *dev,
+		__u64 *features)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op	= UBLK_U_CMD_GET_FEATURES,
+		.flags	= CTRL_CMD_HAS_BUF,
+		.addr = (__u64) (uintptr_t) features,
+		.len = sizeof(*features),
+	};
+
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_update_size(struct ublk_dev *dev,
+		__u64 nr_sects)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op	= UBLK_U_CMD_UPDATE_SIZE,
+		.flags	= CTRL_CMD_HAS_DATA,
+	};
+
+	data.data[0] = nr_sects;
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_quiesce_dev(struct ublk_dev *dev, unsigned int timeout_ms)
+{
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op	= UBLK_U_CMD_QUIESCE_DEV,
+		.flags	= CTRL_CMD_HAS_DATA,
+	};
+
+	data.data[0] = timeout_ms;
+	return __ublk_ctrl_cmd(dev, &data);
+}
+
+int ublk_ctrl_reg_buf(struct ublk_dev *dev, void *addr, size_t size,
+		      __u32 flags)
+{
+	struct ublk_shmem_buf_reg buf_reg = {
+		.addr = (unsigned long)addr,
+		.len = size,
+		.flags = flags,
+	};
+	struct ublk_ctrl_cmd_data data = {
+		.cmd_op = UBLK_U_CMD_REG_BUF,
+		.flags = CTRL_CMD_HAS_BUF,
+		.addr = (unsigned long)&buf_reg,
+		.len = sizeof(buf_reg),
+	};
+
+	return __ublk_ctrl_cmd(dev, &data);
+}
diff --git a/tools/testing/selftests/ublk/kublk.c b/tools/testing/selftests/ublk/kublk.c
index 2400b46157664..15ba060ce7a3c 100644
--- a/tools/testing/selftests/ublk/kublk.c
+++ b/tools/testing/selftests/ublk/kublk.c
@@ -37,203 +37,6 @@ static const struct ublk_tgt_ops *ublk_find_tgt(const char *name)
 	return NULL;
 }
 
-static inline int ublk_setup_ring(struct io_uring *r, int depth,
-		int cq_depth, unsigned flags)
-{
-	struct io_uring_params p;
-
-	memset(&p, 0, sizeof(p));
-	p.flags = flags | IORING_SETUP_CQSIZE;
-	p.cq_entries = cq_depth;
-
-	return io_uring_queue_init_params(depth, r, &p);
-}
-
-static void ublk_ctrl_init_cmd(struct ublk_dev *dev,
-		struct io_uring_sqe *sqe,
-		struct ublk_ctrl_cmd_data *data)
-{
-	struct ublksrv_ctrl_dev_info *info = &dev->dev_info;
-	struct ublksrv_ctrl_cmd *cmd = (struct ublksrv_ctrl_cmd *)ublk_get_sqe_cmd(sqe);
-
-	sqe->fd = dev->ctrl_fd;
-	sqe->opcode = IORING_OP_URING_CMD;
-	sqe->ioprio = 0;
-
-	if (data->flags & CTRL_CMD_HAS_BUF) {
-		cmd->addr = data->addr;
-		cmd->len = data->len;
-	}
-
-	if (data->flags & CTRL_CMD_HAS_DATA)
-		cmd->data[0] = data->data[0];
-
-	cmd->dev_id = info->dev_id;
-	cmd->queue_id = -1;
-
-	ublk_set_sqe_cmd_op(sqe, data->cmd_op);
-
-	io_uring_sqe_set_data(sqe, cmd);
-}
-
-static int __ublk_ctrl_cmd(struct ublk_dev *dev,
-		struct ublk_ctrl_cmd_data *data)
-{
-	struct io_uring_sqe *sqe;
-	struct io_uring_cqe *cqe;
-	int ret = -EINVAL;
-
-	sqe = io_uring_get_sqe(&dev->ring);
-	if (!sqe) {
-		ublk_err("%s: can't get sqe ret %d\n", __func__, ret);
-		return ret;
-	}
-
-	ublk_ctrl_init_cmd(dev, sqe, data);
-
-	ret = io_uring_submit(&dev->ring);
-	if (ret < 0) {
-		ublk_err("uring submit ret %d\n", ret);
-		return ret;
-	}
-
-	ret = io_uring_wait_cqe(&dev->ring, &cqe);
-	if (ret < 0) {
-		ublk_err("wait cqe: %s\n", strerror(-ret));
-		return ret;
-	}
-	io_uring_cqe_seen(&dev->ring, cqe);
-
-	return cqe->res;
-}
-
-static int ublk_ctrl_stop_dev(struct ublk_dev *dev)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op	= UBLK_U_CMD_STOP_DEV,
-	};
-
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
-static int ublk_ctrl_try_stop_dev(struct ublk_dev *dev)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op	= UBLK_U_CMD_TRY_STOP_DEV,
-	};
-
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
-static int ublk_ctrl_start_dev(struct ublk_dev *dev,
-		int daemon_pid)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op	= UBLK_U_CMD_START_DEV,
-		.flags	= CTRL_CMD_HAS_DATA,
-	};
-
-	dev->dev_info.ublksrv_pid = data.data[0] = daemon_pid;
-
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
-static int ublk_ctrl_start_user_recovery(struct ublk_dev *dev)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op	= UBLK_U_CMD_START_USER_RECOVERY,
-	};
-
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
-static int ublk_ctrl_end_user_recovery(struct ublk_dev *dev, int daemon_pid)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op	= UBLK_U_CMD_END_USER_RECOVERY,
-		.flags	= CTRL_CMD_HAS_DATA,
-	};
-
-	dev->dev_info.ublksrv_pid = data.data[0] = daemon_pid;
-
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
-static int ublk_ctrl_add_dev(struct ublk_dev *dev)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op	= UBLK_U_CMD_ADD_DEV,
-		.flags	= CTRL_CMD_HAS_BUF,
-		.addr = (__u64) (uintptr_t) &dev->dev_info,
-		.len = sizeof(struct ublksrv_ctrl_dev_info),
-	};
-
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
-static int ublk_ctrl_del_dev(struct ublk_dev *dev)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op = UBLK_U_CMD_DEL_DEV,
-		.flags = 0,
-	};
-
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
-static int ublk_ctrl_get_info(struct ublk_dev *dev)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op	= UBLK_U_CMD_GET_DEV_INFO,
-		.flags	= CTRL_CMD_HAS_BUF,
-		.addr = (__u64) (uintptr_t) &dev->dev_info,
-		.len = sizeof(struct ublksrv_ctrl_dev_info),
-	};
-
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
-static int ublk_ctrl_set_params(struct ublk_dev *dev,
-		struct ublk_params *params)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op	= UBLK_U_CMD_SET_PARAMS,
-		.flags	= CTRL_CMD_HAS_BUF,
-		.addr = (__u64) (uintptr_t) params,
-		.len = sizeof(*params),
-	};
-	params->len = sizeof(*params);
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
-static int ublk_ctrl_get_params(struct ublk_dev *dev,
-		struct ublk_params *params)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op	= UBLK_U_CMD_GET_PARAMS,
-		.flags	= CTRL_CMD_HAS_BUF,
-		.addr = (__u64)params,
-		.len = sizeof(*params),
-	};
-
-	params->len = sizeof(*params);
-
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
-static int ublk_ctrl_get_features(struct ublk_dev *dev,
-		__u64 *features)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op	= UBLK_U_CMD_GET_FEATURES,
-		.flags	= CTRL_CMD_HAS_BUF,
-		.addr = (__u64) (uintptr_t) features,
-		.len = sizeof(*features),
-	};
-
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
 static int parse_param_types(const char *arg, __u32 *types)
 {
 	char buf[128], *save = NULL, *tok;
@@ -283,30 +86,6 @@ static void ublk_init_params_from_ctx(const struct dev_ctx *ctx,
 	};
 }
 
-static int ublk_ctrl_update_size(struct ublk_dev *dev,
-		__u64 nr_sects)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op	= UBLK_U_CMD_UPDATE_SIZE,
-		.flags	= CTRL_CMD_HAS_DATA,
-	};
-
-	data.data[0] = nr_sects;
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
-static int ublk_ctrl_quiesce_dev(struct ublk_dev *dev,
-				 unsigned int timeout_ms)
-{
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op	= UBLK_U_CMD_QUIESCE_DEV,
-		.flags	= CTRL_CMD_HAS_DATA,
-	};
-
-	data.data[0] = timeout_ms;
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
 static const char *ublk_dev_state_desc(struct ublk_dev *dev)
 {
 	switch (dev->dev_info.state) {
@@ -426,38 +205,6 @@ static void ublk_ctrl_dump(struct ublk_dev *dev)
 	fflush(stdout);
 }
 
-static void ublk_ctrl_deinit(struct ublk_dev *dev)
-{
-	close(dev->ctrl_fd);
-	free(dev);
-}
-
-static struct ublk_dev *ublk_ctrl_init(void)
-{
-	struct ublk_dev *dev = (struct ublk_dev *)calloc(1, sizeof(*dev));
-	struct ublksrv_ctrl_dev_info *info = &dev->dev_info;
-	int ret;
-
-	dev->ctrl_fd = open(CTRL_DEV, O_RDWR);
-	if (dev->ctrl_fd < 0) {
-		free(dev);
-		return NULL;
-	}
-
-	info->max_io_buf_bytes = UBLK_IO_MAX_BYTES;
-
-	ret = ublk_setup_ring(&dev->ring, UBLK_CTRL_RING_DEPTH,
-			UBLK_CTRL_RING_DEPTH, IORING_SETUP_SQE128);
-	if (ret < 0) {
-		ublk_err("queue_init: %s\n", strerror(-ret));
-		free(dev);
-		return NULL;
-	}
-	dev->nr_fds = 1;
-
-	return dev;
-}
-
 static size_t __ublk_queue_cmd_buf_sz(const struct ublk_queue *q, __u16 depth)
 {
 	size_t size = depth * (size_t)q->io_desc_size;
@@ -1283,24 +1030,6 @@ static void ublk_shmem_unregister_all(void)
 	shmem_count = 0;
 }
 
-static int ublk_ctrl_reg_buf(struct ublk_dev *dev, void *addr, size_t size,
-			     __u32 flags)
-{
-	struct ublk_shmem_buf_reg buf_reg = {
-		.addr = (unsigned long)addr,
-		.len = size,
-		.flags = flags,
-	};
-	struct ublk_ctrl_cmd_data data = {
-		.cmd_op = UBLK_U_CMD_REG_BUF,
-		.flags = CTRL_CMD_HAS_BUF,
-		.addr = (unsigned long)&buf_reg,
-		.len = sizeof(buf_reg),
-	};
-
-	return __ublk_ctrl_cmd(dev, &data);
-}
-
 /*
  * Handle one client connection: receive memfd, mmap it, register
  * the VA range with kernel, send back the assigned index.
diff --git a/tools/testing/selftests/ublk/kublk.h b/tools/testing/selftests/ublk/kublk.h
index d98f3d612d888..99b8ceff853cb 100644
--- a/tools/testing/selftests/ublk/kublk.h
+++ b/tools/testing/selftests/ublk/kublk.h
@@ -294,6 +294,38 @@ struct ublk_dev {
 
 extern int ublk_queue_io_cmd(struct ublk_thread *t, struct ublk_io *io);
 
+static inline int ublk_setup_ring(struct io_uring *r, int depth,
+		int cq_depth, unsigned int flags)
+{
+	struct io_uring_params p;
+
+	memset(&p, 0, sizeof(p));
+	p.flags = flags | IORING_SETUP_CQSIZE;
+	p.cq_entries = cq_depth;
+
+	return io_uring_queue_init_params(depth, r, &p);
+}
+
+/* ctrl.c: control commands */
+struct ublk_dev *ublk_ctrl_init(void);
+void ublk_ctrl_deinit(struct ublk_dev *dev);
+int __ublk_ctrl_cmd(struct ublk_dev *dev, struct ublk_ctrl_cmd_data *data);
+int ublk_ctrl_add_dev(struct ublk_dev *dev);
+int ublk_ctrl_del_dev(struct ublk_dev *dev);
+int ublk_ctrl_get_info(struct ublk_dev *dev);
+int ublk_ctrl_set_params(struct ublk_dev *dev, struct ublk_params *params);
+int ublk_ctrl_get_params(struct ublk_dev *dev, struct ublk_params *params);
+int ublk_ctrl_get_features(struct ublk_dev *dev, __u64 *features);
+int ublk_ctrl_start_dev(struct ublk_dev *dev, int daemon_pid);
+int ublk_ctrl_stop_dev(struct ublk_dev *dev);
+int ublk_ctrl_try_stop_dev(struct ublk_dev *dev);
+int ublk_ctrl_start_user_recovery(struct ublk_dev *dev);
+int ublk_ctrl_end_user_recovery(struct ublk_dev *dev, int daemon_pid);
+int ublk_ctrl_update_size(struct ublk_dev *dev, __u64 nr_sects);
+int ublk_ctrl_quiesce_dev(struct ublk_dev *dev, unsigned int timeout_ms);
+int ublk_ctrl_reg_buf(struct ublk_dev *dev, void *addr, size_t size,
+		      __u32 flags);
+
 static inline int __ublk_use_batch_io(__u64 flags)
 {
 	return flags & UBLK_F_BATCH_IO;
diff --git a/tools/testing/selftests/ublk/test_generic_18.sh b/tools/testing/selftests/ublk/test_generic_18.sh
new file mode 100755
index 0000000000000..2dbb59e238a41
--- /dev/null
+++ b/tools/testing/selftests/ublk/test_generic_18.sh
@@ -0,0 +1,69 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0
+
+. "$(cd "$(dirname "$0")" && pwd)"/test_common.sh
+
+ERR_CODE=0
+CANCEL_PROG="$(_ublk_test_top_dir)/ublk_cancel_ready"
+
+_prep_test "generic" "start device over canceled io commands"
+
+# STOP_DEV while kublk's UBLK_F_BATCH_IO server prepares and fetches: the
+# server has to fail cleanly when PREP or FETCH is aborted, so `kublk add`
+# must return either way.
+race_batch_stop()
+{
+	local id=9999 i res started=0
+
+	_have_feature "BATCH_IO" || return "$UBLK_SKIP_CODE"
+	for i in $(seq 1 20); do
+		timeout 20 "$UBLK_PROG" add -t null -q 2 -b -n "$id" > /dev/null 2>&1 &
+		local pid=$!
+		# vary where STOP_DEV lands relative to the batch PREP and FETCH
+		sleep "0.$((i % 10))"
+		"$UBLK_PROG" stop -n "$id" > /dev/null 2>&1
+		wait "$pid"
+		res=$?
+		"$UBLK_PROG" del -n "$id" > /dev/null 2>&1
+		if [ "$res" -eq 124 ]; then
+			echo "run $i: kublk add -b hung after STOP_DEV"
+			return 255
+		fi
+		[ "$res" -eq 0 ] && started=$((started + 1))
+	done
+	echo "20 runs: started $started, stopped before start $((20 - started))"
+}
+
+# race_batch_stop is above, the other modes are described in
+# ublk_cancel_ready.c
+for mode in stop_start partial_fetch recovery stop_restart stop_attached \
+		stop_live_restart race_start race_fetch race_async_fetch \
+		race_batch_stop; do
+	dmesg_before=$(dmesg | wc -l)
+	if [ "$mode" = race_batch_stop ]; then
+		race_batch_stop > "$UBLK_TMP" 2>&1
+	else
+		timeout 60 "$CANCEL_PROG" "$mode" > "$UBLK_TMP" 2>&1
+	fi
+	res=$?
+	msg=""
+
+	if dmesg | tail -n +"$((dmesg_before + 1))" | \
+			grep -q -e "BUG:" -e "Oops" -e "WARNING:"; then
+		msg="$mode: kernel oops/warning"
+		ERR_CODE=255
+	elif [ "$res" -eq "$UBLK_SKIP_CODE" ]; then
+		[ "$ERR_CODE" -eq 0 ] && ERR_CODE=$UBLK_SKIP_CODE
+	elif [ "$res" -ne 0 ]; then
+		msg="$mode: failed ($res)"
+		ERR_CODE=255
+	fi
+	# the output once: on failure, or always when not quiet
+	[ -n "$msg" ] && echo "$msg"
+	if [ -n "$msg" ] || [ "$UBLK_TEST_QUIET" -eq 0 ]; then
+		cat "$UBLK_TMP"
+	fi
+done
+
+_cleanup_test
+_show_result $TID $ERR_CODE
diff --git a/tools/testing/selftests/ublk/ublk_cancel_ready.c b/tools/testing/selftests/ublk/ublk_cancel_ready.c
new file mode 100644
index 0000000000000..23071babc0e4c
--- /dev/null
+++ b/tools/testing/selftests/ublk/ublk_cancel_ready.c
@@ -0,0 +1,957 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Bring a ublk device live while some of its fetched io commands are
+ * canceled.
+ *
+ * A cancel completes a fetched command and clears io->cmd, but the io
+ * still counts as ready. Only ubq->canceling keeps ublk_queue_rq() away
+ * from the NULL io->cmd. Each mode below loses ->canceling in another way:
+ *
+ * stop_start:    fetch every tag, STOP_DEV before START_DEV, START_DEV.
+ *                STOP_DEV cancels the commands of the attached server,
+ *                so START_DEV must get -EBUSY until that server is gone.
+ *                An unfixed kernel starts the device over them.
+ *
+ * partial_fetch: task A fetches tags 0..depth-2 and dies, so its
+ *                commands are canceled. Task B fetches the last tag, and
+ *                an unfixed kernel clears ->canceling when the queue gets
+ *                ready. /dev/ublkcN stays open all the time, so
+ *                ublk_ch_release() never resets the queue.
+ *
+ * recovery:      a UBLK_F_USER_RECOVERY device with two queues loses its
+ *                server. During recovery task Q0 fetches queue 0, which
+ *                clears q0->canceling, then dies. An unfixed kernel still
+ *                has ub->canceling set because queue 1 is not ready, so
+ *                ublk_start_cancel() does not mark queue 0 again. Reads
+ *                are issued on a CPU mapped to queue 0.
+ *
+ * In partial_fetch and recovery, START_DEV / END_USER_RECOVERY must refuse
+ * with -EBUSY. An unfixed kernel oopses in ublk_queue_cmd() on a NULL
+ * io->cmd.
+ *
+ * stop_restart:  control mode. STOP_DEV on a new device, before any
+ *                server opened it, takes no command. A server started
+ *                afterwards has to start the device and serve I/O.
+ *
+ * stop_attached: STOP_DEV on a device whose server opened it but fetched
+ *                nothing stops that server too: FETCH gets ABORT and
+ *                START_DEV -EBUSY, until a new server opens the device.
+ *
+ * stop_live_restart: STOP_DEV on a live device; once its server is gone,
+ *                a new server has to fetch and start it again. An unfixed
+ *                ublk_ch_release() skips the reset once the disk is gone,
+ *                so the new FETCH gets -EBUSY.
+ *
+ * race_start:    STOP_DEV and START_DEV at the same time on a device whose
+ *                server fetched every tag. START_DEV either wins, and
+ *                reads complete (they fail once STOP_DEV removes the
+ *                disk), or gets -EBUSY. An unfixed kernel cancels the
+ *                commands of the live disk.
+ *
+ * race_fetch:    STOP_DEV while a server opens the device and fetches,
+ *                then START_DEV. If STOP_DEV came before the open, it must
+ *                not take any command, so START_DEV works and every read
+ *                succeeds; otherwise START_DEV gets -EBUSY. An unfixed
+ *                kernel takes commands fetched after its unlock and goes
+ *                live over them.
+ *
+ * race_async_fetch: FETCH with IOSQE_ASYNC while STOP_DEV cancels,
+ *                then close the ring. An unfixed FETCH marks its command
+ *                cancelable only after publishing it and dropping
+ *                ub->mutex; a cancel in between completes a command which
+ *                is then put on io_uring's cancelable list. Closing the
+ *                ring walks that list: KASAN reports a use after free.
+ *                Needs a KASAN kernel to see the bug; otherwise it must
+ *                just not crash.
+ *
+ * A dying task is a child process which fetches and then calls exec().
+ * exec() cancels the task's uring_cmds before it returns, so the cancel
+ * is done once the child is reaped. A thread exit does not cancel them,
+ * and closing the ring cancels them later, from io_ring_exit_work().
+ */
+#include <sched.h>
+
+#include "kublk.h"
+#include "../kselftest.h"
+
+#define NR_QUEUES	2
+#define DEPTH		4
+#define BUF_SIZE	(64 << 10)
+#define DEV_SECTORS	(64 << 11)	/* 64MB */
+#define NR_READS	(DEPTH * 2)
+#define SERVE_DELAY_US	200000
+#define RACE_LOOPS	50
+#define ASYNC_LOOPS	300
+
+/* one control handle per thread, the race modes send commands from two */
+static __thread struct ublk_dev *ctrl_dev;
+static int cdev_fd = -1;
+static int dev_id = -1;
+static int nr_queues;
+static void *bufs[NR_QUEUES][DEPTH];
+static const struct ublksrv_io_desc *iods[NR_QUEUES];
+static size_t iods_len;
+
+static struct io_uring_sqe *get_sqe(struct io_uring *ring)
+{
+	struct io_uring_sqe *sqe = io_uring_get_sqe(ring);
+
+	if (!sqe) {
+		fprintf(stderr, "out of sqes\n");
+		exit(KSFT_FAIL);
+	}
+	return sqe;
+}
+
+static struct ublk_dev *ctrl(void)
+{
+	if (!ctrl_dev) {
+		ctrl_dev = ublk_ctrl_init();
+		if (!ctrl_dev) {
+			fprintf(stderr, "ublk_ctrl_init failed\n");
+			exit(KSFT_FAIL);
+		}
+	}
+	ctrl_dev->dev_info.dev_id = dev_id;
+	return ctrl_dev;
+}
+
+static void ctrl_put(void)
+{
+	if (ctrl_dev)
+		ublk_ctrl_deinit(ctrl_dev);
+	ctrl_dev = NULL;
+}
+
+static int dev_state(void)
+{
+	struct ublk_dev *dev = ctrl();
+	int ret = ublk_ctrl_get_info(dev);
+
+	return ret ? ret : dev->dev_info.state;
+}
+
+static int open_cdev(void)
+{
+	size_t max_len = UBLK_MAX_QUEUE_DEPTH * sizeof(struct ublksrv_io_desc);
+	int pg = getpagesize();
+	char path[64];
+
+	snprintf(path, sizeof(path), "/dev/ublkc%d", dev_id);
+	for (int i = 0; i < 100 && cdev_fd < 0; i++) {
+		cdev_fd = open(path, O_RDWR);
+		if (cdev_fd < 0)
+			usleep(50000);
+	}
+	if (cdev_fd < 0)
+		return -errno;
+
+	/* queue q's descriptors start at q * the size for the max depth */
+	max_len = (max_len + pg - 1) & ~(size_t)(pg - 1);
+	iods_len = (DEPTH * sizeof(struct ublksrv_io_desc) + pg - 1) &
+		~(size_t)(pg - 1);
+	for (int q = 0; q < nr_queues; q++) {
+		void *p = mmap(NULL, iods_len, PROT_READ,
+			       MAP_SHARED | MAP_POPULATE, cdev_fd,
+			       UBLKSRV_CMD_BUF_OFFSET + q * max_len);
+
+		if (p == MAP_FAILED)
+			return -errno;
+		iods[q] = p;
+	}
+	return 0;
+}
+
+/* the last reference to /dev/ublkcN runs ublk_ch_release() */
+static void close_cdev(void)
+{
+	for (int q = 0; q < nr_queues; q++) {
+		if (iods[q])
+			munmap((void *)iods[q], iods_len);
+		iods[q] = NULL;
+	}
+	if (cdev_fd >= 0)
+		close(cdev_fd);
+	cdev_fd = -1;
+}
+
+/* ADD_DEV and SET_PARAMS, without opening /dev/ublkcN */
+static int add_dev_noopen(int queues, __u64 flags)
+{
+	struct ublk_dev *dev = ctrl();
+	struct ublksrv_ctrl_dev_info info = {
+		.nr_hw_queues	= queues,
+		.queue_depth	= DEPTH,
+		.max_io_buf_bytes = BUF_SIZE,
+		.dev_id		= -1,
+		.flags		= UBLK_F_NO_AUTO_PART_SCAN | flags,
+	};
+	struct ublk_params p = {
+		.types	= UBLK_PARAM_TYPE_BASIC,
+		.basic	= {
+			.logical_bs_shift	= 9,
+			.physical_bs_shift	= 12,
+			.io_opt_shift		= 12,
+			.io_min_shift		= 9,
+			.max_sectors		= BUF_SIZE >> 9,
+			.dev_sectors		= DEV_SECTORS,
+		},
+	};
+	int ret;
+
+	nr_queues = queues;
+	dev->dev_info = info;
+	ret = ublk_ctrl_add_dev(dev);
+	if (ret)
+		return ret;
+	dev_id = dev->dev_info.dev_id;
+
+	ret = ublk_ctrl_set_params(ctrl(), &p);
+	if (ret)
+		return ret;
+
+	for (int q = 0; q < queues; q++)
+		for (int i = 0; i < DEPTH; i++)
+			if (!bufs[q][i] &&
+			    posix_memalign(&bufs[q][i], getpagesize(), BUF_SIZE))
+				return -ENOMEM;
+	return 0;
+}
+
+static int add_dev(int queues, __u64 flags)
+{
+	return add_dev_noopen(queues, flags) ?: open_cdev();
+}
+
+static void cleanup(void)
+{
+	if (dev_id < 0)
+		return;
+	ublk_ctrl_stop_dev(ctrl());
+	close_cdev();
+	ublk_ctrl_del_dev(ctrl());
+	dev_id = -1;
+}
+
+/* race_async_fetch sets IOSQE_ASYNC on the io commands */
+static int io_cmd_sqe_flags;
+
+static void queue_io_cmd(struct io_uring *ring, __u32 op, int q, int tag,
+			 int res)
+{
+	struct io_uring_sqe *sqe = get_sqe(ring);
+	struct ublksrv_io_cmd *cmd = (struct ublksrv_io_cmd *)sqe->cmd;
+
+	memset(sqe, 0, sizeof(*sqe));
+	sqe->fd = cdev_fd;
+	sqe->opcode = IORING_OP_URING_CMD;
+	sqe->flags = io_cmd_sqe_flags;
+	ublk_set_sqe_cmd_op(sqe, op);
+	cmd->q_id = q;
+	cmd->tag = tag;
+	cmd->result = res;
+	cmd->addr = (__u64)(uintptr_t)bufs[q][tag];
+	io_uring_sqe_set_data64(sqe, (q << 16) | tag);
+}
+
+struct async_arg {
+	pthread_barrier_t go, stopped;
+};
+
+/*
+ * FETCH every tag with IOSQE_ASYNC, racing STOP_DEV, then close the ring once
+ * STOP_DEV returned: that walks io_uring's list of cancelable commands.
+ */
+static void *race_async_fn(void *data)
+{
+	struct async_arg *a = data;
+	struct io_uring ring;
+	int ok = !io_uring_queue_init(DEPTH, &ring, 0);
+
+	if (ok)
+		for (int tag = 0; tag < DEPTH; tag++)
+			queue_io_cmd(&ring, UBLK_U_IO_FETCH_REQ, 0, tag, 0);
+	pthread_barrier_wait(&a->go);
+	if (ok)
+		io_uring_submit(&ring);
+	pthread_barrier_wait(&a->stopped);
+	if (ok)
+		io_uring_queue_exit(&ring);
+	return NULL;
+}
+
+/* reap @nr completions of canceled fetch commands, return how many */
+static int reap_aborts(struct io_uring *ring, int nr)
+{
+	struct __kernel_timespec ts = { .tv_sec = 2 };
+	struct io_uring_cqe *cqe;
+	int aborted = 0;
+
+	while (nr--) {
+		if (io_uring_wait_cqe_timeout(ring, &cqe, &ts))
+			break;
+		if (cqe->res == UBLK_IO_RES_ABORT)
+			aborted++;
+		io_uring_cqe_seen(ring, cqe);
+	}
+	return aborted;
+}
+
+/*
+ * A server thread fetches @nr_tags tags of queue @q, then completes each
+ * request after @delay_us, until its commands are aborted.
+ */
+struct server {
+	int q, first_tag, nr_tags, delay_us;
+	int failed;	/* result which ended the serve loop, 0 if none */
+	pthread_t thread;
+	pthread_barrier_t fetched;
+	/* race_fetch: wait for @go and @race_delay_us, open, fetch one by one */
+	pthread_barrier_t go;
+	int race, race_delay_us;
+};
+
+static void *server_fn(void *data)
+{
+	struct server *s = data;
+	struct io_uring ring;
+	struct io_uring_cqe *cqe;
+
+	if (io_uring_queue_init(DEPTH, &ring, 0)) {
+		pthread_barrier_wait(&s->fetched);
+		return NULL;
+	}
+	if (s->race) {
+		pthread_barrier_wait(&s->go);
+		usleep(s->race_delay_us);
+		if (open_cdev()) {
+			pthread_barrier_wait(&s->fetched);
+			io_uring_queue_exit(&ring);
+			return NULL;
+		}
+	}
+	for (int tag = s->first_tag; tag < s->first_tag + s->nr_tags; tag++) {
+		queue_io_cmd(&ring, UBLK_U_IO_FETCH_REQ, s->q, tag, 0);
+		if (s->race)
+			io_uring_submit(&ring);
+	}
+	io_uring_submit(&ring);
+	pthread_barrier_wait(&s->fetched);
+
+	while (!io_uring_wait_cqe(&ring, &cqe)) {
+		int tag = cqe->user_data & 0xffff;
+		const struct ublksrv_io_desc *iod = &iods[s->q][tag];
+		int res = cqe->res;
+
+		io_uring_cqe_seen(&ring, cqe);
+		if (res != UBLK_IO_RES_OK) {
+			__atomic_store_n(&s->failed, res, __ATOMIC_RELEASE);
+			break;
+		}
+		usleep(s->delay_us);
+		res = ublksrv_get_op(iod) <= UBLK_IO_OP_WRITE ?
+			iod->nr_sectors << 9 : 0;
+		queue_io_cmd(&ring, UBLK_U_IO_COMMIT_AND_FETCH_REQ, s->q, tag,
+			     res);
+		io_uring_submit(&ring);
+	}
+	io_uring_queue_exit(&ring);
+	return NULL;
+}
+
+/* returns once the fetch commands are issued; with @race, call race_go() */
+static void server_start(struct server *s)
+{
+	pthread_barrier_init(&s->fetched, NULL, 2);
+	pthread_barrier_init(&s->go, NULL, 2);
+	pthread_create(&s->thread, NULL, server_fn, s);
+	if (!s->race)
+		pthread_barrier_wait(&s->fetched);
+}
+
+/* wait up to 5s for the serve loop of @s to end, return its result */
+static int server_wait_failed(struct server *s)
+{
+	int res = 0;
+
+	for (int i = 0; i < 500 && !res; i++) {
+		res = __atomic_load_n(&s->failed, __ATOMIC_ACQUIRE);
+		if (!res)
+			usleep(10000);
+	}
+	return res;
+}
+
+/*
+ * A task fetches @nr_tags tags of queue @q and dies. Returns once its
+ * commands are canceled, see the top of this file.
+ */
+static int fetch_and_die(int q, int first_tag, int nr_tags)
+{
+	int status;
+	pid_t pid = fork();
+
+	if (pid < 0)
+		return -1;
+	if (!pid) {
+		struct io_uring ring;
+
+		if (io_uring_queue_init(DEPTH, &ring, 0))
+			_exit(1);
+		for (int tag = first_tag; tag < first_tag + nr_tags; tag++)
+			queue_io_cmd(&ring, UBLK_U_IO_FETCH_REQ, q, tag, 0);
+		if (io_uring_submit(&ring) != nr_tags)
+			_exit(1);
+		execlp("true", "true", NULL);
+		_exit(1);
+	}
+	if (waitpid(pid, &status, 0) != pid || !WIFEXITED(status) ||
+	    WEXITSTATUS(status))
+		return -1;
+	printf("q%d: task died with %d fetch cmds in flight\n", q, nr_tags);
+	return 0;
+}
+
+struct reads {
+	struct io_uring ring;
+	void *buf;
+	int fd, done, ok, eio, other;
+};
+
+/*
+ * Issue NR_READS reads at once, from @cpu if it is not negative: blk-mq
+ * maps the submitting CPU to the hw queue. A server holding its live
+ * tags for a while makes the other reads take the canceled tags.
+ */
+static int open_tries = 100;	/* 50ms each */
+
+static int reads_submit(struct reads *r, int cpu)
+{
+	char path[64];
+	cpu_set_t set, old;
+
+	snprintf(path, sizeof(path), "/dev/ublkb%d", dev_id);
+	r->fd = -1;
+	for (int i = 0; i < open_tries && r->fd < 0; i++) {
+		r->fd = open(path, O_RDONLY | O_DIRECT);
+		if (r->fd < 0)
+			usleep(50000);
+	}
+	if (r->fd < 0) {
+		fprintf(stderr, "open %s: %s\n", path, strerror(errno));
+		return -1;
+	}
+	if (posix_memalign(&r->buf, 4096, NR_READS * 4096) ||
+	    io_uring_queue_init(NR_READS, &r->ring, 0))
+		return -1;
+
+	for (int i = 0; i < NR_READS; i++)
+		io_uring_prep_read(get_sqe(&r->ring), r->fd,
+				   r->buf + i * 4096, 4096, i * 4096);
+
+	if (cpu >= 0) {
+		sched_getaffinity(0, sizeof(old), &old);
+		CPU_ZERO(&set);
+		CPU_SET(cpu, &set);
+		sched_setaffinity(0, sizeof(set), &set);
+	}
+	io_uring_submit(&r->ring);
+	if (cpu >= 0)
+		sched_setaffinity(0, sizeof(old), &old);
+	return 0;
+}
+
+static void reads_reap(struct reads *r, int timeout_s)
+{
+	struct __kernel_timespec ts = { .tv_sec = timeout_s };
+	struct io_uring_cqe *cqe;
+
+	while (r->done < NR_READS &&
+	       !io_uring_wait_cqe_timeout(&r->ring, &cqe, &ts)) {
+		if (cqe->res == 4096)
+			r->ok++;
+		else if (cqe->res == -EIO)
+			r->eio++;
+		else
+			r->other++;
+		r->done++;
+		io_uring_cqe_seen(&r->ring, cqe);
+	}
+}
+
+static void reads_put(struct reads *r)
+{
+	io_uring_queue_exit(&r->ring);
+	close(r->fd);
+	free(r->buf);
+}
+
+static int reads_result(struct reads *r)
+{
+	printf("reads: %d ok, %d -EIO, %d other, %d not completed\n",
+	       r->ok, r->eio, r->other, NR_READS - r->done);
+	reads_put(r);
+	return r->other || r->done < NR_READS ? KSFT_FAIL : KSFT_PASS;
+}
+
+static int start_dev(void)
+{
+	int ret = ublk_ctrl_start_dev(ctrl(), getpid());
+
+	printf("START_DEV: %d\n", ret);
+	return ret;
+}
+
+static int expect_err(const char *what, int ret, int want)
+{
+	if (ret == want)
+		return KSFT_PASS;
+	fprintf(stderr, "%s: %d, expected %d\n", what, ret, want);
+	return KSFT_FAIL;
+}
+
+/* START_DEV must fail with @want; if it went live, show what a read does */
+static int start_dev_expect(int want)
+{
+	struct reads r = {};
+	int ret = start_dev();
+
+	if (!ret && !reads_submit(&r, -1)) {
+		reads_reap(&r, 10);
+		reads_result(&r);
+	}
+	return expect_err("START_DEV", ret, want);
+}
+
+static int test_stop_start(void)
+{
+	struct io_uring ring;
+	int ret;
+
+	if (add_dev(1, 0))
+		return KSFT_FAIL;
+	if (io_uring_queue_init(DEPTH, &ring, 0))
+		return KSFT_FAIL;
+	for (int tag = 0; tag < DEPTH; tag++)
+		queue_io_cmd(&ring, UBLK_U_IO_FETCH_REQ, 0, tag, 0);
+	io_uring_submit(&ring);
+
+	/* device is ready but not started: state is UBLK_S_DEV_DEAD */
+	ret = ublk_ctrl_stop_dev(ctrl());
+	printf("STOP_DEV: %d, canceled fetch cmds: %d/%d\n", ret,
+	       reap_aborts(&ring, DEPTH), DEPTH);
+
+	/* STOP_DEV canceled the attached server: no start until it exits */
+	ret = start_dev_expect(-EBUSY);
+	io_uring_queue_exit(&ring);
+	return ret;
+}
+
+static int test_partial_fetch(void)
+{
+	struct server b = { .q = 0, .first_tag = DEPTH - 1, .nr_tags = 1,
+			    .delay_us = SERVE_DELAY_US };
+	int ret;
+
+	if (add_dev(1, 0) || fetch_and_die(0, 0, DEPTH - 1))
+		return KSFT_FAIL;
+
+	/* the last FETCH makes the queue ready and clears ->canceling */
+	server_start(&b);
+
+	ret = start_dev_expect(-EBUSY);
+
+	cleanup();
+	pthread_join(b.thread, NULL);
+	return ret;
+}
+
+static int test_stop_restart(void)
+{
+	struct server s = { .q = 0, .nr_tags = DEPTH };
+	struct reads r = {};
+	int ret;
+
+	if (add_dev_noopen(1, 0))
+		return KSFT_FAIL;
+
+	/* no server is attached, so there is nothing to cancel */
+	ret = ublk_ctrl_stop_dev(ctrl());
+	printf("STOP_DEV: %d\n", ret);
+	if (open_cdev())
+		return KSFT_FAIL;
+
+	server_start(&s);
+	if (start_dev()) {
+		ret = KSFT_FAIL;
+	} else if (reads_submit(&r, -1)) {
+		ret = KSFT_FAIL;
+	} else {
+		reads_reap(&r, 10);
+		ret = reads_result(&r);
+		if (r.ok != NR_READS)
+			ret = KSFT_FAIL;
+	}
+
+	cleanup();
+	pthread_join(s.thread, NULL);
+	return ret;
+}
+
+struct start_arg {
+	pthread_barrier_t go;
+	int ret, reads_ok;
+};
+
+static void *race_start_fn(void *data)
+{
+	struct start_arg *a = data;
+	struct reads r = {};
+
+	pthread_barrier_wait(&a->go);
+	a->ret = ublk_ctrl_start_dev(ctrl(), getpid());
+	a->reads_ok = 1;
+	/*
+	 * The disk may be gone already if STOP_DEV came right after, and
+	 * reads may fail then: they only have to complete.
+	 */
+	if (!a->ret && !reads_submit(&r, -1)) {
+		reads_reap(&r, 5);
+		a->reads_ok = r.done == NR_READS;
+		if (a->reads_ok)
+			reads_put(&r);
+		else
+			reads_result(&r);
+	}
+	ctrl_put();
+	return NULL;
+}
+
+static int test_race_start(void)
+{
+	int live = 0, ebusy = 0;
+
+	open_tries = 4;
+	for (int i = 0; i < RACE_LOOPS; i++) {
+		struct server s = { .q = 0, .nr_tags = DEPTH };
+		struct start_arg a = {};
+		pthread_t t;
+
+		if (add_dev(1, 0))
+			return KSFT_FAIL;
+		server_start(&s);
+		pthread_barrier_init(&a.go, NULL, 2);
+		pthread_create(&t, NULL, race_start_fn, &a);
+		pthread_barrier_wait(&a.go);
+		ublk_ctrl_stop_dev(ctrl());
+		pthread_join(t, NULL);
+		cleanup();
+		pthread_join(s.thread, NULL);
+
+		if (a.ret == 0)
+			live++;
+		else if (a.ret == -EBUSY)
+			ebusy++;
+		if ((a.ret && a.ret != -EBUSY) || !a.reads_ok) {
+			fprintf(stderr, "loop %d: START_DEV %d, reads %s\n",
+				i, a.ret, a.reads_ok ? "ok" : "failed");
+			return KSFT_FAIL;
+		}
+	}
+	printf("%d loops: START_DEV won %d, got -EBUSY %d\n", RACE_LOOPS,
+	       live, ebusy);
+	return KSFT_PASS;
+}
+
+static int test_race_fetch(void)
+{
+	int live = 0, ebusy = 0;
+
+	for (int i = 0; i < RACE_LOOPS; i++) {
+		/* vary who goes first: STOP_DEV, or the server's open */
+		struct server s = { .q = 0, .nr_tags = DEPTH, .race = 1,
+				    .race_delay_us = (i % 10) * 50 };
+		struct reads r = {};
+		int ret;
+
+		if (add_dev_noopen(1, 0))
+			return KSFT_FAIL;
+		server_start(&s);
+		pthread_barrier_wait(&s.go);
+		ublk_ctrl_stop_dev(ctrl());
+		pthread_barrier_wait(&s.fetched);
+
+		ret = ublk_ctrl_start_dev(ctrl(), getpid());
+		if (!ret) {
+			/* nothing was taken, so every read has to succeed */
+			live++;
+			if (reads_submit(&r, -1))
+				return KSFT_FAIL;
+			reads_reap(&r, 5);
+			if (r.ok != NR_READS) {
+				fprintf(stderr, "loop %d: live, but ", i);
+				reads_result(&r);
+				return KSFT_FAIL;
+			}
+			reads_put(&r);
+		} else if (ret == -EBUSY) {
+			ebusy++;
+		} else {
+			fprintf(stderr, "loop %d: START_DEV %d\n", i, ret);
+			return KSFT_FAIL;
+		}
+		cleanup();
+		pthread_join(s.thread, NULL);
+	}
+	printf("%d loops: START_DEV worked %d, got -EBUSY %d\n", RACE_LOOPS,
+	       live, ebusy);
+	return KSFT_PASS;
+}
+
+static int test_race_async_fetch(void)
+{
+	io_cmd_sqe_flags = IOSQE_ASYNC;
+	for (int i = 0; i < ASYNC_LOOPS; i++) {
+		struct async_arg a;
+		pthread_t t;
+
+		if (add_dev(1, 0))
+			return KSFT_FAIL;
+		pthread_barrier_init(&a.go, NULL, 2);
+		pthread_barrier_init(&a.stopped, NULL, 2);
+		pthread_create(&t, NULL, race_async_fn, &a);
+		pthread_barrier_wait(&a.go);
+		/* vary where STOP_DEV lands relative to the FETCHes */
+		usleep((i % 5) * 1000);
+		ublk_ctrl_stop_dev(ctrl());
+		pthread_barrier_wait(&a.stopped);
+		pthread_join(t, NULL);
+		cleanup();
+	}
+	printf("%d loops done\n", ASYNC_LOOPS);
+	return KSFT_PASS;
+}
+
+/*
+ * The stopped server is gone: reopen /dev/ublkcN, start a new server and
+ * the device, and read from it.
+ */
+static int restart_server(void)
+{
+	struct server s = { .q = 0, .nr_tags = DEPTH };
+	struct reads r = {};
+	int ret;
+
+	close_cdev();
+	if (open_cdev())
+		return KSFT_FAIL;
+	server_start(&s);
+	usleep(200000);
+	if (s.failed) {
+		fprintf(stderr, "new server: FETCH failed %d\n", s.failed);
+		cleanup();
+		pthread_join(s.thread, NULL);
+		return KSFT_FAIL;
+	}
+	/* -EEXIST until the old disk is freed, e.g. after a udev probe */
+	for (int i = 0; i < 100; i++) {
+		ret = start_dev();
+		if (ret != -EEXIST)
+			break;
+		usleep(50000);
+	}
+	if (ret || reads_submit(&r, -1)) {
+		fprintf(stderr, "new server: START_DEV %d\n", ret);
+		ret = KSFT_FAIL;
+	} else {
+		reads_reap(&r, 10);
+		ret = reads_result(&r);
+		if (r.ok != NR_READS)
+			ret = KSFT_FAIL;
+	}
+	cleanup();
+	pthread_join(s.thread, NULL);
+	return ret;
+}
+
+/*
+ * stop_attached: STOP_DEV while a server has the device open but has
+ * fetched nothing stops that server too: its FETCH gets ABORT and
+ * START_DEV -EBUSY. Once it is gone, a new server can start the device.
+ */
+static int test_stop_attached(void)
+{
+	struct server s = { .q = 0, .nr_tags = DEPTH };
+	int ret;
+
+	if (add_dev(1, 0))
+		return KSFT_FAIL;
+	ret = ublk_ctrl_stop_dev(ctrl());
+	printf("STOP_DEV: %d\n", ret);
+
+	server_start(&s);
+	ret = server_wait_failed(&s);
+	printf("FETCH after STOP_DEV: %d\n", ret);
+	if (ret != UBLK_IO_RES_ABORT) {
+		cleanup();
+		pthread_join(s.thread, NULL);
+		return KSFT_FAIL;
+	}
+	pthread_join(s.thread, NULL);
+	if (expect_err("START_DEV", start_dev(), -EBUSY))
+		return KSFT_FAIL;
+	return restart_server();
+}
+
+/*
+ * stop_live_restart: STOP_DEV on a live device; once its server is gone,
+ * a new server has to fetch and start it again.
+ */
+static int test_stop_live_restart(void)
+{
+	struct server s = { .q = 0, .nr_tags = DEPTH };
+	int ret;
+
+	if (add_dev(1, 0))
+		return KSFT_FAIL;
+	server_start(&s);
+	if (expect_err("START_DEV", start_dev(), 0))
+		return KSFT_FAIL;
+	ret = ublk_ctrl_stop_dev(ctrl());
+	printf("STOP_DEV: %d\n", ret);
+	pthread_join(s.thread, NULL);
+	return restart_server();
+}
+
+/* first CPU which blk-mq maps to hw queue @q */
+static int queue_cpu(int q)
+{
+	char path[96];
+	FILE *f;
+	int cpu = -1;
+
+	snprintf(path, sizeof(path), "/sys/block/ublkb%d/mq/%d/cpu_list",
+		 dev_id, q);
+	for (int i = 0; i < 100 && !(f = fopen(path, "r")); i++)
+		usleep(50000);
+	if (!f)
+		return -1;
+	if (fscanf(f, "%d", &cpu) != 1)
+		cpu = -1;
+	fclose(f);
+	return cpu;
+}
+
+static int test_recovery(void)
+{
+	struct server q1 = { .q = 1, .nr_tags = DEPTH };
+	struct io_uring ring;
+	struct reads r = {};
+	int ret, cpu;
+
+	if (add_dev(NR_QUEUES, UBLK_F_USER_RECOVERY))
+		return KSFT_FAIL;
+
+	/* the first server: fetch everything, start, then die */
+	if (io_uring_queue_init(NR_QUEUES * DEPTH, &ring, 0))
+		return KSFT_FAIL;
+	for (int q = 0; q < NR_QUEUES; q++)
+		for (int tag = 0; tag < DEPTH; tag++)
+			queue_io_cmd(&ring, UBLK_U_IO_FETCH_REQ, q, tag, 0);
+	io_uring_submit(&ring);
+	if (start_dev())
+		return KSFT_FAIL;
+	cpu = queue_cpu(0);
+	if (cpu < 0) {
+		printf("no CPU maps to queue 0, can't aim the reads\n");
+		return KSFT_SKIP;
+	}
+
+	io_uring_queue_exit(&ring);
+	close_cdev();
+	for (int i = 0; i < 100 && dev_state() != UBLK_S_DEV_QUIESCED; i++)
+		usleep(50000);
+	printf("server exited, state %d (QUIESCED is %d)\n", dev_state(),
+	       UBLK_S_DEV_QUIESCED);
+
+	for (int i = 0; i < 100; i++) {
+		ret = ublk_ctrl_start_user_recovery(ctrl());
+		if (ret != -EBUSY)
+			break;
+		usleep(50000);
+	}
+	printf("START_USER_RECOVERY: %d\n", ret);
+	if (ret || open_cdev())
+		return KSFT_FAIL;
+
+	/* queue 0 gets ready, then its task dies before queue 1 is ready */
+	if (fetch_and_die(0, 0, DEPTH))
+		return KSFT_FAIL;
+
+	printf("reads on cpu %d, which maps to queue 0\n", cpu);
+	if (reads_submit(&r, cpu))
+		return KSFT_FAIL;
+
+	server_start(&q1);
+	ret = ublk_ctrl_end_user_recovery(ctrl(), getpid());
+	printf("END_USER_RECOVERY: %d\n", ret);
+	ret = expect_err("END_USER_RECOVERY", ret, -EBUSY);
+
+	/*
+	 * Requests held back on queue 0 wait for STOP_DEV to fail them.
+	 * Close the disk before DEL_DEV, which waits for its last reference.
+	 */
+	reads_reap(&r, 1);
+	ublk_ctrl_stop_dev(ctrl());
+	reads_reap(&r, 5);
+	if (reads_result(&r))
+		ret = KSFT_FAIL;
+	cleanup();
+	pthread_join(q1.thread, NULL);
+	return ret;
+}
+
+static const struct {
+	const char *name;
+	int (*fn)(void);
+} modes[] = {
+	{ "stop_start",		test_stop_start },
+	{ "partial_fetch",	test_partial_fetch },
+	{ "recovery",		test_recovery },
+	{ "stop_restart",	test_stop_restart },
+	{ "race_start",		test_race_start },
+	{ "race_fetch",		test_race_fetch },
+	{ "race_async_fetch",	test_race_async_fetch },
+	{ "stop_attached",	test_stop_attached },
+	{ "stop_live_restart",	test_stop_live_restart },
+};
+
+int main(int argc, char **argv)
+{
+	int (*fn)(void) = NULL;
+	int ret;
+
+	for (int i = 0; argc == 2 && i < ARRAY_SIZE(modes); i++)
+		if (!strcmp(argv[1], modes[i].name))
+			fn = modes[i].fn;
+	if (!fn) {
+		fprintf(stderr, "usage: %s MODE, modes:", argv[0]);
+		for (int i = 0; i < ARRAY_SIZE(modes); i++)
+			fprintf(stderr, " %s", modes[i].name);
+		fprintf(stderr, "\n");
+		return KSFT_FAIL;
+	}
+
+	/* keep the output of a run that ends in an oops */
+	setvbuf(stdout, NULL, _IOLBF, 0);
+
+	if (access(CTRL_DEV, F_OK)) {
+		perror(CTRL_DEV);
+		return KSFT_SKIP;
+	}
+	printf("%s\n", argv[1]);
+	ret = fn();
+	cleanup();
+	ctrl_put();
+	return ret;
+}

27/3 2026/10/11 06:43 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 29484
							output: 37
							thoughts: 886
						

Thoughts:
**KMSAN Evaluation for ublk Patch**

Okay, so I need to decide if this patch for the ublk subsystem warrants a dedicated KMSAN fuzzing session. The prompt lays out the critical difference: KMSAN is for catching uninitialized memory reads, while KASAN and other standard detectors cover things like out-of-bounds accesses and use-after-free bugs. The rule is clear: *don't* waste resources on KMSAN if KASAN can already catch the potential issues. KMSAN is a heavyweight and I need to conserve resources.

I'm told to look at the patch holistically. Even if the diff itself doesn't directly introduce uninitialized fields, it could change control flow or how existing buffers are handled, potentially *exposing* uninitialized memory in existing code. My decision boils down to whether the patch touches:

1.  Kernel structures sent to userspace (via things like `copy_to_user`).
2.  Conditional logic based on potentially uninitialized variables.
3.  Allocation of complex data structures where uninitialized fields could be read.
4.  Bounds checks, lengths, or logic that let surrounding code access uninitialized bytes.

And, conversely, if the changes primarily risk problems already caught by KASAN/LOCKDEP, or if everything is properly initialized (zeroed, `memset`, `kzalloc`), I should *not* enable KMSAN.

Right, so let's get to the specifics. The patch impacts `drivers/block/ublk_drv.c`, plus the documentation and selftests. The significant change I see so far is within the `ublk_report_zones` function, specifically this line:

```c
			ret = disk_report_zone(disk, zone, i, args);
```
changed to:

```c
			ret = disk_report_zone(disk, zone, done_zones, args);
```

Let's carefully examine the context around this change in `drivers/block/ublk_drv.c` to understand exactly what is happening in this function and what `disk_report_zone` is doing now. Let's see...



28/3 2026/10/11 06:43 tool grepper
0m Args:
{
  "Expression": "ublk_report_zones",
  "PathPrefixes": [
    "drivers/block/ublk_drv.c"
  ]
}

Results:
{
  "Output": "drivers/block/ublk_drv.c=609=static void *ublk_alloc_report_buffer(struct ublk_device *ublk,\n--\ndrivers/block/ublk_drv.c-635-\ndrivers/block/ublk_drv.c:636:static int ublk_report_zones(struct gendisk *disk, sector_t sector,\ndrivers/block/ublk_drv.c-637-\t\t      unsigned int nr_zones, struct blk_report_zones_args *args)\n--\ndrivers/block/ublk_drv.c=733=static void ublk_setup_iod_zoned(struct ublk_queue *ubq, struct request *req)\n--\ndrivers/block/ublk_drv.c-771-\ndrivers/block/ublk_drv.c:772:#define ublk_report_zones (NULL)\ndrivers/block/ublk_drv.c-773-\n--\ndrivers/block/ublk_drv.c=1382=static const struct block_device_operations ub_fops = {\n--\ndrivers/block/ublk_drv.c-1385-\t.free_disk =\tublk_free_disk,\ndrivers/block/ublk_drv.c:1386:\t.report_zones =\tublk_report_zones,\ndrivers/block/ublk_drv.c-1387-};\n"
}

29/3 2026/10/11 06:43 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 31222
							output: 38
							thoughts: 28
						

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

**Analyzing the `ublk_report_zones` Function to Understand `done_zones`**

Alright, I need to get a handle on what `done_zones` actually *is*. The best way to do that in my opinion is to jump straight into `ublk_report_zones` and take a look at the code around line 636. I want to see how `done_zones` is initialized, modified, and used within that specific function context. This will give me the most immediate and relevant insight into its purpose and behavior within this subsystem. That particular line is likely going to provide the key to understanding its relationship to the broader functionality. I'm focusing on the local scope and implementation first; that should illuminate its role and provide a foundation for understanding broader implications.



30/3 2026/10/11 06:43 tool read-file
0m Args:
{
  "File": "drivers/block/ublk_drv.c",
  "FirstLine": 636,
  "LineCount": 75
}

Results:
{
  "Contents": " 636:\tstatic int ublk_report_zones(struct gendisk *disk, sector_t sector,\n 637:\t\t\t      unsigned int nr_zones, struct blk_report_zones_args *args)\n 638:\t{\n 639:\t\tstruct ublk_device *ub = disk-\u003eprivate_data;\n 640:\t\tunsigned int zone_size_sectors = disk-\u003equeue-\u003elimits.chunk_sectors;\n 641:\t\tunsigned int first_zone = sector \u003e\u003e ilog2(zone_size_sectors);\n 642:\t\tunsigned int done_zones = 0;\n 643:\t\tunsigned int max_zones_per_request;\n 644:\t\tint ret;\n 645:\t\tstruct blk_zone *buffer;\n 646:\t\tsize_t buffer_length;\n 647:\t\n 648:\t\tnr_zones = min_t(unsigned int, ub-\u003eub_disk-\u003enr_zones - first_zone,\n 649:\t\t\t\t nr_zones);\n 650:\t\n 651:\t\tbuffer = ublk_alloc_report_buffer(ub, nr_zones, \u0026buffer_length);\n 652:\t\tif (!buffer)\n 653:\t\t\treturn -ENOMEM;\n 654:\t\n 655:\t\tmax_zones_per_request = buffer_length / sizeof(struct blk_zone);\n 656:\t\n 657:\t\twhile (done_zones \u003c nr_zones) {\n 658:\t\t\tunsigned int remaining_zones = nr_zones - done_zones;\n 659:\t\t\tunsigned int zones_in_request =\n 660:\t\t\t\tmin_t(unsigned int, remaining_zones, max_zones_per_request);\n 661:\t\t\tstruct request *req;\n 662:\t\t\tstruct ublk_zoned_report_desc desc;\n 663:\t\t\tblk_status_t status;\n 664:\t\n 665:\t\t\tmemset(buffer, 0, buffer_length);\n 666:\t\n 667:\t\t\treq = blk_mq_alloc_request(disk-\u003equeue, REQ_OP_DRV_IN, 0);\n 668:\t\t\tif (IS_ERR(req)) {\n 669:\t\t\t\tret = PTR_ERR(req);\n 670:\t\t\t\tgoto out;\n 671:\t\t\t}\n 672:\t\n 673:\t\t\tdesc.sector = sector;\n 674:\t\t\tdesc.nr_zones = zones_in_request;\n 675:\t\t\tret = ublk_zoned_insert_report_desc(req, \u0026desc);\n 676:\t\t\tif (ret)\n 677:\t\t\t\tgoto free_req;\n 678:\t\n 679:\t\t\tret = blk_rq_map_kern(req, buffer, buffer_length, GFP_KERNEL);\n 680:\t\t\tif (ret)\n 681:\t\t\t\tgoto erase_desc;\n 682:\t\n 683:\t\t\tstatus = blk_execute_rq(req, 0);\n 684:\t\t\tret = blk_status_to_errno(status);\n 685:\terase_desc:\n 686:\t\t\tublk_zoned_erase_report_desc(req);\n 687:\tfree_req:\n 688:\t\t\tblk_mq_free_request(req);\n 689:\t\t\tif (ret)\n 690:\t\t\t\tgoto out;\n 691:\t\n 692:\t\t\tfor (unsigned int i = 0; i \u003c zones_in_request; i++) {\n 693:\t\t\t\tstruct blk_zone *zone = buffer + i;\n 694:\t\n 695:\t\t\t\t/* A zero length zone means no more zones in this response */\n 696:\t\t\t\tif (!zone-\u003elen)\n 697:\t\t\t\t\tbreak;\n 698:\t\n 699:\t\t\t\tret = disk_report_zone(disk, zone, done_zones, args);\n 700:\t\t\t\tif (ret)\n 701:\t\t\t\t\tgoto out;\n 702:\t\n 703:\t\t\t\tdone_zones++;\n 704:\t\t\t\tsector += zone_size_sectors;\n 705:\t\n 706:\t\t\t}\n 707:\t\t}\n 708:\t\n 709:\t\tret = done_zones;\n 710:\t\n"
}

31/3 2026/10/11 06:43 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 32593
							output: 21
							thoughts: 167
						

Thoughts:
**Analyzing the Zone Reporting Logic**

Okay, let's dive into this `ublk_report_zones` function. I see the core call here: `ret = disk_report_zone(disk, zone, i, args);`.  And I'm immediately noticing something interesting. The variable `i` is the index *within the current request*, iterating through `for (unsigned int i = 0; i < zones_in_request; i++)`. But `disk_report_zone` is expecting `unsigned int zone_idx` as an index.

Now, if we have multiple batches due to a large number of zones (`nr_zones > max_zones_per_request`), the code previously used `i` instead of `done_zones` as the index! This is where things get potentially tricky, so let me stop and think this through... What exactly *does* `disk_report_zone` do with that `done_zones` or `zone_idx` value? It's crucial to understand how that index is interpreted within the context of the underlying disk structure and how it calculates which zone to work with, to ensure we are referencing the correct one.

Okay, time to grep `disk_report_zone` and understand the implications of this index value. That's the next step to ensuring this function is correct.



32/3 2026/10/11 06:43 tool grepper
0m Args:
{
  "Expression": "int disk_report_zone\\("
}

Results:
{
  "Output": "block/blk-zoned.c=973=static unsigned int disk_zone_wplug_sync_state(struct gendisk *disk,\n--\nblock/blk-zoned.c-1012- */\nblock/blk-zoned.c:1013:int disk_report_zone(struct gendisk *disk, struct blk_zone *zone,\nblock/blk-zoned.c-1014-\t\t     unsigned int idx, struct blk_report_zones_args *args)\n--\ninclude/linux/blkdev.h=446=typedef int (*report_zones_cb)(struct blk_zone *zone, unsigned int idx,\n--\ninclude/linux/blkdev.h-448-\ninclude/linux/blkdev.h:449:int disk_report_zone(struct gendisk *disk, struct blk_zone *zone,\ninclude/linux/blkdev.h-450-\t\t     unsigned int idx, struct blk_report_zones_args *args);\n"
}

33/3 2026/10/11 06:43 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 33314
							output: 36
							thoughts: 21
						

Thoughts:
Here's my summary, as if I were thinking these thoughts:

**Examining Disk Zone Reporting in blk-zoned.c**

Alright, let's dive into this. The task at hand is to understand how the system reports on zones in a block device context. My intuition tells me that `disk_report_zone` in `block/blk-zoned.c` is the prime location to start. It's a key function name for this and that file name strongly suggests it's the right place. Hopefully, it contains the core logic for querying and interpreting zone information. I'm expecting to find details on how the kernel interacts with the hardware, what structures are used to represent the zones, and maybe even some filtering or aggregation logic. This will be the first step in getting a full view of the disk zone implementation.



34/3 2026/10/11 06:44 tool read-file
0m Args:
{
  "File": "block/blk-zoned.c",
  "FirstLine": 1010,
  "LineCount": 40
}

Results:
{
  "Contents": "1010:\t *    information for the zone. If @args specifies a user callback function,\n1011:\t *    this callback is executed.\n1012:\t */\n1013:\tint disk_report_zone(struct gendisk *disk, struct blk_zone *zone,\n1014:\t\t\t     unsigned int idx, struct blk_report_zones_args *args)\n1015:\t{\n1016:\t\tif (args \u0026\u0026 args-\u003ereport_active) {\n1017:\t\t\t/*\n1018:\t\t\t * If we come here, then this is a report zones as a fallback\n1019:\t\t\t * for a cached report. So collapse the implicit open, explicit\n1020:\t\t\t * open and closed conditions into the active zone condition.\n1021:\t\t\t */\n1022:\t\t\tswitch (zone-\u003econd) {\n1023:\t\t\tcase BLK_ZONE_COND_IMP_OPEN:\n1024:\t\t\tcase BLK_ZONE_COND_EXP_OPEN:\n1025:\t\t\tcase BLK_ZONE_COND_CLOSED:\n1026:\t\t\t\tzone-\u003econd = BLK_ZONE_COND_ACTIVE;\n1027:\t\t\t\tbreak;\n1028:\t\t\tdefault:\n1029:\t\t\t\tbreak;\n1030:\t\t\t}\n1031:\t\t}\n1032:\t\n1033:\t\tif (disk-\u003ezone_wplugs_hash)\n1034:\t\t\tdisk_zone_wplug_sync_state(disk, zone);\n1035:\t\n1036:\t\tif (args \u0026\u0026 args-\u003ecb)\n1037:\t\t\treturn args-\u003ecb(zone, idx, args-\u003edata);\n1038:\t\n1039:\t\treturn 0;\n1040:\t}\n1041:\tEXPORT_SYMBOL_GPL(disk_report_zone);\n1042:\t\n1043:\tstatic int blkdev_report_zone_cb(struct blk_zone *zone, unsigned int idx,\n1044:\t\t\t\t\t void *data)\n1045:\t{\n1046:\t\tmemcpy(data, zone, sizeof(struct blk_zone));\n1047:\t\treturn 0;\n1048:\t}\n1049:\t\n"
}

35/3 2026/10/11 06:44 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 34130
							output: 36
							thoughts: 58
						

Thoughts:
Here's my thought process, as if I were analyzing that code:

**Analyzing the Callback Function Call**

Okay, so I'm looking at a callback function being invoked with `args->cb(zone, idx, args->data)`. The core of this seems to be a callback function, and I need to figure out how it's defined and when it's called. The `args->cb` is the piece I need to track down. Given the context, this is most likely related to zoned block devices. My instincts tell me the definition and initial call will likely happen within the file `block/blk-zoned.c`, possibly within a loop or conditional block. I'll focus my search around lines 1040 to 1100. That's usually a good range for initialization or function call points, depending on the surrounding context. Let's see what's going on in that area.



36/3 2026/10/11 06:44 tool read-file
0m Args:
{
  "File": "block/blk-zoned.c",
  "FirstLine": 1042,
  "LineCount": 60
}

Results:
{
  "Contents": "1042:\t\n1043:\tstatic int blkdev_report_zone_cb(struct blk_zone *zone, unsigned int idx,\n1044:\t\t\t\t\t void *data)\n1045:\t{\n1046:\t\tmemcpy(data, zone, sizeof(struct blk_zone));\n1047:\t\treturn 0;\n1048:\t}\n1049:\t\n1050:\tstatic int blkdev_report_zone_fallback(struct block_device *bdev,\n1051:\t\t\t\t\t       sector_t sector, struct blk_zone *zone)\n1052:\t{\n1053:\t\tstruct blk_report_zones_args args = {\n1054:\t\t\t.cb = blkdev_report_zone_cb,\n1055:\t\t\t.data = zone,\n1056:\t\t\t.report_active = true,\n1057:\t\t};\n1058:\t\tint error;\n1059:\t\n1060:\t\terror = blkdev_do_report_zones(bdev, sector, 1, \u0026args);\n1061:\t\tif (error \u003c 0)\n1062:\t\t\treturn error;\n1063:\t\tif (error == 0)\n1064:\t\t\treturn -EIO;\n1065:\t\treturn 0;\n1066:\t}\n1067:\t\n1068:\t/*\n1069:\t * For devices that natively support zone append operations, we do not use zone\n1070:\t * write plugging for zone append writes, which makes the zone condition\n1071:\t * tracking invalid once zone append was used.  In that case fall back to a\n1072:\t * regular report zones to get correct information.\n1073:\t */\n1074:\tstatic inline bool blkdev_has_cached_report_zones(struct block_device *bdev)\n1075:\t{\n1076:\t\treturn disk_need_zone_resources(bdev-\u003ebd_disk) \u0026\u0026\n1077:\t\t\t(bdev_emulates_zone_append(bdev) ||\n1078:\t\t\t !test_bit(GD_ZONE_APPEND_USED, \u0026bdev-\u003ebd_disk-\u003estate));\n1079:\t}\n1080:\t\n1081:\t/**\n1082:\t * blkdev_get_zone_info - Get a single zone information from cached data\n1083:\t * @bdev:   Target block device\n1084:\t * @sector: Sector contained by the target zone\n1085:\t * @zone:   zone structure to return the zone information\n1086:\t *\n1087:\t * Description:\n1088:\t *    Get the zone information for the zone containing @sector using the zone\n1089:\t *    write plug of the target zone, if one exist, or the disk zone condition\n1090:\t *    array otherwise. The zone condition may be reported as being\n1091:\t *    the BLK_ZONE_COND_ACTIVE condition for a zone that is in the implicit\n1092:\t *    open, explicit open or closed condition.\n1093:\t *\n1094:\t *    Returns 0 on success and a negative error code on failure.\n1095:\t */\n1096:\tint blkdev_get_zone_info(struct block_device *bdev, sector_t sector,\n1097:\t\t\t\t struct blk_zone *zone)\n1098:\t{\n1099:\t\tstruct gendisk *disk = bdev-\u003ebd_disk;\n1100:\t\tsector_t zone_sectors = bdev_zone_sectors(bdev);\n1101:\t\tunsigned int zno = disk_zone_no(disk, sector);\n"
}

37/3 2026/10/11 06:44 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 35389
							output: 19
							thoughts: 16
						

Thoughts:
Okay, let's dive into this code.

**Investigating `report_zones_cb` Function Implementations**

Alright, I need to understand this `report_zones_cb` function better. Where is this function being used? What other versions of it exist? I need to look for other implementations of `report_zones_cb` to get a feel for its general purpose and the different contexts in which it might be called. Finding more examples will help me anticipate potential issues and identify interesting patterns in its usage. A little exploration will pay dividends in understanding. Let's see what we can dig up.



38/3 2026/10/11 06:44 tool grepper
0m Args:
{
  "Expression": "report_zones_cb"
}

Results:
{
  "Output": "block/blk-zoned.c=320=bool bdev_zone_mgmt_allowed(struct block_device *bdev, sector_t sector)\n--\nblock/blk-zoned.c-337- * Zone report arguments for block device drivers report_zones operation.\nblock/blk-zoned.c:338: * @cb: report_zones_cb callback for each reported zone.\nblock/blk-zoned.c:339: * @data: Private data passed to report_zones_cb.\nblock/blk-zoned.c-340- */\nblock/blk-zoned.c=341=struct blk_report_zones_args {\nblock/blk-zoned.c:342:\treport_zones_cb cb;\nblock/blk-zoned.c-343-\tvoid\t\t*data;\n--\nblock/blk-zoned.c=381=int blkdev_report_zones(struct block_device *bdev, sector_t sector,\nblock/blk-zoned.c:382:\t\t\tunsigned int nr_zones, report_zones_cb cb, void *data)\nblock/blk-zoned.c-383-{\n--\nblock/blk-zoned.c=1210=int blkdev_report_zones_cached(struct block_device *bdev, sector_t sector,\nblock/blk-zoned.c:1211:\t\t\tunsigned int nr_zones, report_zones_cb cb, void *data)\nblock/blk-zoned.c-1212-{\n--\ndrivers/md/dm-zone.c=47=int dm_blk_report_zones(struct gendisk *disk, sector_t sector,\n--\ndrivers/md/dm-zone.c-90-\ndrivers/md/dm-zone.c:91:static int dm_report_zones_cb(struct blk_zone *zone, unsigned int idx,\ndrivers/md/dm-zone.c-92-\t\t\t      void *data)\n--\ndrivers/md/dm-zone.c=136=int dm_report_zones(struct block_device *bdev, sector_t start, sector_t sector,\n--\ndrivers/md/dm-zone.c-140-\t * Set the target mapping start sector first so that\ndrivers/md/dm-zone.c:141:\t * dm_report_zones_cb() can correctly remap zone information.\ndrivers/md/dm-zone.c-142-\t */\n--\ndrivers/md/dm-zone.c-145-\treturn blkdev_report_zones(bdev, sector, nr_zones,\ndrivers/md/dm-zone.c:146:\t\t\t\t   dm_report_zones_cb, args);\ndrivers/md/dm-zone.c-147-}\n--\ninclude/linux/blkdev.h=383=struct queue_limits {\n--\ninclude/linux/blkdev.h-445-\ninclude/linux/blkdev.h:446:typedef int (*report_zones_cb)(struct blk_zone *zone, unsigned int idx,\ninclude/linux/blkdev.h-447-\t\t\t       void *data);\n--\ninclude/linux/blkdev.h=456=int blkdev_report_zones(struct block_device *bdev, sector_t sector,\ninclude/linux/blkdev.h:457:\t\tunsigned int nr_zones, report_zones_cb cb, void *data);\ninclude/linux/blkdev.h-458-int blkdev_report_zones_cached(struct block_device *bdev, sector_t sector,\ninclude/linux/blkdev.h:459:\t\tunsigned int nr_zones, report_zones_cb cb, void *data);\ninclude/linux/blkdev.h-460-int blkdev_zone_mgmt(struct block_device *bdev, enum req_op op,\n--\ninclude/linux/device-mapper.h=539=struct dm_report_zones_args {\n--\ninclude/linux/device-mapper.h-549-\t/* for internal users */\ninclude/linux/device-mapper.h:550:\treport_zones_cb cb;\ninclude/linux/device-mapper.h-551-\tvoid *data;\ninclude/linux/device-mapper.h-552-\ninclude/linux/device-mapper.h:553:\t/* must be filled by -\u003ereport_zones before calling dm_report_zones_cb */\ninclude/linux/device-mapper.h-554-\tsector_t start;\n"
}

39/3 2026/10/11 06:44 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 36664
							output: 29
							thoughts: 27
						

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

**Diving into the Zone Reporting Logic**

Okay, so I need to understand how zone reporting works at the block device level. Specifically, I need to figure out how `blkdev_report_zones` is being used. My first step is to trace all the calls to this function. I'm going to look for instances where `blkdev_report_zones` is being invoked, and a good starting point is to focus on calls associated with the `ioctl` system call, specifically the `BLKREPORTZONE` command. This will hopefully show me where the zone reporting functionality is triggered by userspace requests. This initial investigation should offer some insight into the control flow.



40/3 2026/10/11 06:44 tool grepper
0m Args:
{
  "Expression": "blkdev_report_zones",
  "PathPrefixes": [
    "block/"
  ]
}

Results:
{
  "Output": "block/blk-zoned.c=347=static int blkdev_do_report_zones(struct block_device *bdev, sector_t sector,\n--\nblock/blk-zoned.c-362-/**\nblock/blk-zoned.c:363: * blkdev_report_zones - Get zones information\nblock/blk-zoned.c-364- * @bdev:\tTarget block device\n--\nblock/blk-zoned.c-380- */\nblock/blk-zoned.c:381:int blkdev_report_zones(struct block_device *bdev, sector_t sector,\nblock/blk-zoned.c-382-\t\t\tunsigned int nr_zones, report_zones_cb cb, void *data)\n--\nblock/blk-zoned.c-390-}\nblock/blk-zoned.c:391:EXPORT_SYMBOL_GPL(blkdev_report_zones);\nblock/blk-zoned.c-392-\n--\nblock/blk-zoned.c=474=static int blkdev_copy_zone_to_user(struct blk_zone *zone, unsigned int idx,\n--\nblock/blk-zoned.c-492- */\nblock/blk-zoned.c:493:int blkdev_report_zones_ioctl(struct block_device *bdev, unsigned int cmd,\nblock/blk-zoned.c-494-\t\tunsigned long arg)\n--\nblock/blk-zoned.c-516-\tcase BLKREPORTZONE:\nblock/blk-zoned.c:517:\t\tret = blkdev_report_zones(bdev, rep.sector, rep.nr_zones,\nblock/blk-zoned.c-518-\t\t\t\t\t  blkdev_copy_zone_to_user, \u0026args);\n--\nblock/blk-zoned.c-522-\t\t\treturn -EINVAL;\nblock/blk-zoned.c:523:\t\tret = blkdev_report_zones_cached(bdev, rep.sector, rep.nr_zones,\nblock/blk-zoned.c-524-\t\t\t\t\t blkdev_copy_zone_to_user, \u0026args);\n--\nblock/blk-zoned.c=973=static unsigned int disk_zone_wplug_sync_state(struct gendisk *disk,\n--\nblock/blk-zoned.c-1007- *    Helper function for block device drivers to report one zone of a zone\nblock/blk-zoned.c:1008: *    report initiated with blkdev_report_zones(). The zone being reported is\nblock/blk-zoned.c-1009- *    specified by @zone and used to update, if necessary, the zone write plug\n--\nblock/blk-zoned.c=1193=EXPORT_SYMBOL_GPL(blkdev_get_zone_info);\n--\nblock/blk-zoned.c-1195-/**\nblock/blk-zoned.c:1196: * blkdev_report_zones_cached - Get cached zones information\nblock/blk-zoned.c-1197- * @bdev:     Target block device\n--\nblock/blk-zoned.c-1203- * Description:\nblock/blk-zoned.c:1204: *    Similar to blkdev_report_zones() but instead of calling into the low level\nblock/blk-zoned.c-1205- *    device driver to get the zone report from the device, use\n--\nblock/blk-zoned.c-1209- */\nblock/blk-zoned.c:1210:int blkdev_report_zones_cached(struct block_device *bdev, sector_t sector,\nblock/blk-zoned.c-1211-\t\t\tunsigned int nr_zones, report_zones_cb cb, void *data)\n--\nblock/blk-zoned.c-1250-}\nblock/blk-zoned.c:1251:EXPORT_SYMBOL_GPL(blkdev_report_zones_cached);\nblock/blk-zoned.c-1252-\n--\nblock/blk.h=571=static inline void blk_zone_finish_request(struct request *rq)\n--\nblock/blk.h-575-}\nblock/blk.h:576:int blkdev_report_zones_ioctl(struct block_device *bdev, unsigned int cmd,\nblock/blk.h-577-\t\tunsigned long arg);\n--\nblock/blk.h=610=static inline void blk_zone_finish_request(struct request *rq)\n--\nblock/blk.h-612-}\nblock/blk.h:613:static inline int blkdev_report_zones_ioctl(struct block_device *bdev,\nblock/blk.h-614-\t\tunsigned int cmd, unsigned long arg)\n--\nblock/ioctl.c=651=static int blkdev_common_ioctl(struct block_device *bdev, blk_mode_t mode,\n--\nblock/ioctl.c-671-\tcase BLKREPORTZONEV2:\nblock/ioctl.c:672:\t\treturn blkdev_report_zones_ioctl(bdev, cmd, arg);\nblock/ioctl.c-673-\tcase BLKRESETZONE:\n"
}

41/3 2026/10/11 06:44 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 38167
							output: 35
							thoughts: 17
						

Thoughts:
Okay, here's my interpretation of what's going on, framed as a first-person expert perspective:

**Diving into `blkdev_copy_zone_to_user`**

Alright, let's dissect `blkdev_copy_zone_to_user`. I'm immediately thinking about the implications here. We're dealing with block device data being copied to user space. This screams security considerations, performance optimization, and potential error handling right off the bat. The zone context implies we're probably working with zoned block devices, which have their own unique constraints and access patterns compared to traditional block devices.

My mind immediately starts ticking through the potential race conditions and concurrency issues involved when handling a block device. Accessing the device, getting the data and handling the results needs to be fast and correct. I'll need to figure out exactly how this function handles those potential problems. I also have to assume there are several safeguards in place to stop the userspace process from trying to read, or overwrite the data in the block device, and to stop any malicious use.

I also wonder about the underlying mechanisms. Are we using DMA? Direct access? How are we avoiding unnecessary copies? What kind of buffer management is in place to minimize overhead? How is the sector-to-offset translation handled? Are we doing any caching at this stage, or is this a straight-through path?

Furthermore, I have to consider the data integrity aspects. How are errors managed during the copy process? What happens if the device has a read error? Are we returning sensible error codes or just crashing? Is there any verification of the data after the copy to ensure it's valid?

It's clear that the design here must be carefully crafted to balance security, performance, and reliability. I need to understand the details to know if this code is doing it right. I'm going to have to dig into the actual code to check what's going on, how it's implemented, and what assumptions are being made.



42/3 2026/10/11 06:44 tool read-file
0m Args:
{
  "File": "block/blk-zoned.c",
  "FirstLine": 470,
  "LineCount": 40
}

Results:
{
  "Contents": " 470:\tstruct zone_report_args {\n 471:\t\tstruct blk_zone __user *zones;\n 472:\t};\n 473:\t\n 474:\tstatic int blkdev_copy_zone_to_user(struct blk_zone *zone, unsigned int idx,\n 475:\t\t\t\t\t    void *data)\n 476:\t{\n 477:\t\tstruct zone_report_args *args = data;\n 478:\t\n 479:\t\tif (copy_to_user(\u0026args-\u003ezones[idx], zone, sizeof(struct blk_zone)))\n 480:\t\t\treturn -EFAULT;\n 481:\t\treturn 0;\n 482:\t}\n 483:\t\n 484:\t/*\n 485:\t * Mask of valid input flags for BLKREPORTZONEV2 ioctl.\n 486:\t */\n 487:\t#define BLK_ZONE_REPV2_INPUT_FLAGS\tBLK_ZONE_REP_CACHED\n 488:\t\n 489:\t/*\n 490:\t * BLKREPORTZONE and BLKREPORTZONEV2 ioctl processing.\n 491:\t * Called from blkdev_ioctl.\n 492:\t */\n 493:\tint blkdev_report_zones_ioctl(struct block_device *bdev, unsigned int cmd,\n 494:\t\t\tunsigned long arg)\n 495:\t{\n 496:\t\tvoid __user *argp = (void __user *)arg;\n 497:\t\tstruct zone_report_args args;\n 498:\t\tstruct blk_zone_report rep;\n 499:\t\tint ret;\n 500:\t\n 501:\t\tif (!argp)\n 502:\t\t\treturn -EINVAL;\n 503:\t\n 504:\t\tif (!bdev_is_zoned(bdev))\n 505:\t\t\treturn -ENOTTY;\n 506:\t\n 507:\t\tif (copy_from_user(\u0026rep, argp, sizeof(struct blk_zone_report)))\n 508:\t\t\treturn -EFAULT;\n 509:\t\n"
}

43/3 2026/10/11 06:44 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 39213
							output: 40
							thoughts: 4156
						

Thoughts:
**Patch Analysis and KMSAN Assessment**

Okay, let's break this down. My initial observation focused on `blkdev_copy_zone_to_user` and `ublk_report_zones`. Specifically, the index correction in `ublk_report_zones` from `i` to `done_zones`.  My thinking was, "Could this change introduce uninitialized memory issues or out-of-bounds writes?".  I realized that, crucially, the `buffer` used in `ublk_report_zones` is *explicitly* zeroed out with `memset(buffer, 0, buffer_length)` before each batch processing.  The `zone` struct originates from this zeroed buffer and the fix properly computes the destination offset for zone data in user space. The `disk_report_zone` function itself is passed `done_zones` and, since each zone originates from the zeroed `buffer`, there's no risk of reading or writing uninitialized kernel memory. The fix ensures that data is written to the correct user-space buffer position, preventing overwrites. Thus, this change *itself* doesn't introduce uninitialized memory exposure.

Next, I shifted my focus to the rest of the patch, specifically the changes around the UBLK device lifecycle and its state management. The commit message points to fixes for concurrency issues related to device start/stop, cancel operations, and I/O command handling. These could potentially involve uninitialized memory in control flow.

The documentation updates highlight error conditions related to -EBUSY and I/O command cancellation, particularly when a server closes its `/dev/ublkc*` handle.  These error conditions are a key part of the patch, and they're explicitly tied to state transitions within the UBLK driver.

The code changes introduce `UB_STATE_STOPPING`, `ch_file` within `struct ublk_device` and extensive changes within `ublk_ch_open`, `ublk_reset_ch_dev`, `ublk_ch_release`, `ublk_stop_dev` and others to handle command cancellation within a ublk device context, state transitions, reference counts of the ch file. The changes appear to address race conditions between commands, STOP/START operations and cancel operations. The fix is within `ublk_batch_alloc_fcmd` where `INIT_LIST_HEAD(&fcmd->node)` is called. This initializes the linked list head so if cancel looks at it, the list is valid.

The test cases, described in `ublk_cancel_ready.c`, seem to be designed to reproduce specific race conditions and test the robustness of the new synchronization and state management.  The tests cover scenarios where commands are canceled during device start or recovery, or after a server stops. They address the bugs:
1. NULL pointer dereference in `ublk_queue_cmd()` on `io->cmd` when a device goes live with canceled io commands.
2. Use-after-free (UAF) in io_uring cancelable list when commands are canceled while being fetched asynchronously.
3. Concurrency races between STOP_DEV, START_DEV, FETCH, and cancel, state machine transitions (UB_STATE_STOPPING, canceling flag).
4. Zone reporting index off-by-one/index bug in `ublk_report_zones` where `i` was passed instead of `done_zones`.

The primary issue here is the potential for NULL `io->cmd` pointers, use-after-free conditions, and races due to incorrect state management when commands are canceled asynchronously with I/O operations and device start/stop sequences. While the patch addresses these issues, *it doesn't appear to introduce any new areas where uninitialized memory *is* directly exposed* as per my understanding of the instructions and reading through the patch. The focus of this patch is on concurrency, synchronization, and ensuring the correct state of the UBLK device, with all data initialization taken care of before user-space access.



44/3 2026/10/11 06:44 tool grepper
0m Args:
{
  "Expression": "ublk_batch_alloc_fcmd",
  "PathPrefixes": [
    "drivers/block/ublk_drv.c"
  ]
}

Results:
{
  "Output": "drivers/block/ublk_drv.c=814=static struct ublk_batch_fetch_cmd *\ndrivers/block/ublk_drv.c:815:ublk_batch_alloc_fcmd(struct io_uring_cmd *cmd)\ndrivers/block/ublk_drv.c-816-{\n--\ndrivers/block/ublk_drv.c=4031=static int ublk_handle_batch_fetch_cmd(struct ublk_batch_io_data *data)\n--\ndrivers/block/ublk_drv.c-4033-\tstruct ublk_queue *ubq = ublk_get_queue(data-\u003eub, data-\u003eheader.q_id);\ndrivers/block/ublk_drv.c:4034:\tstruct ublk_batch_fetch_cmd *fcmd = ublk_batch_alloc_fcmd(data-\u003ecmd);\ndrivers/block/ublk_drv.c-4035-\n"
}

45/3 2026/10/11 06:44 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 44499
							output: 38
							thoughts: 22
						

Thoughts:
Okay, let's dive into this code.

**Diving into `ublk_batch_alloc_fcmd`**

Alright, I see the instructions; it looks like we're looking at `ublk_batch_alloc_fcmd`, specifically around line 814. I'm going to quickly get my bearings here; based on the name, this is likely where we handle allocating Free Command descriptors in a batch. I need to understand the memory allocation strategy involved, and how it relates to the overall flow of the Ublk driver. I'm specifically interested in any potential lock contention or optimization techniques used to improve throughput. It will be useful to cross-reference this function call with the overall `ublk` data structures, and the context in which `fcmd` is allocated. Let's see what we're dealing with, and what other variables or structures it relies upon.



46/3 2026/10/11 06:45 tool read-file
0m Args:
{
  "File": "drivers/block/ublk_drv.c",
  "FirstLine": 810,
  "LineCount": 25
}

Results:
{
  "Contents": " 810:\tstatic wait_queue_head_t ublk_idr_wq;\t/* wait until one idr is freed */\n 811:\t\n 812:\tstatic DEFINE_MUTEX(ublk_ctl_mutex);\n 813:\t\n 814:\tstatic struct ublk_batch_fetch_cmd *\n 815:\tublk_batch_alloc_fcmd(struct io_uring_cmd *cmd)\n 816:\t{\n 817:\t\tstruct ublk_batch_fetch_cmd *fcmd = kzalloc_obj(*fcmd, GFP_NOIO);\n 818:\t\n 819:\t\tif (fcmd) {\n 820:\t\t\tfcmd-\u003ecmd = cmd;\n 821:\t\t\tfcmd-\u003ebuf_group = READ_ONCE(cmd-\u003esqe-\u003ebuf_index);\n 822:\t\t\t/* a cancel may look at it before it is linked */\n 823:\t\t\tINIT_LIST_HEAD(\u0026fcmd-\u003enode);\n 824:\t\t}\n 825:\t\treturn fcmd;\n 826:\t}\n 827:\t\n 828:\tstatic void ublk_batch_free_fcmd(struct ublk_batch_fetch_cmd *fcmd)\n 829:\t{\n 830:\t\tkfree(fcmd);\n 831:\t}\n 832:\t\n 833:\tstatic void __ublk_release_fcmd(struct ublk_queue *ubq)\n 834:\t{\n"
}

47/3 2026/10/11 06:45 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 45150
							output: 38
							thoughts: 298
						

Thoughts:
**Analyzing the Data Structures and Synchronization in `ublk`**

Okay, so I'm looking at this `fcmd` structure and I see it was allocated using `kzalloc_obj`, which means the memory was already zeroed out. But, `INIT_LIST_HEAD` is used, so the `next` and `prev` pointers in the list node are set to point to itself. Nothing particularly unusual there, but good to keep in mind.

Now, let's dive into `ublk_ch_open`. I need to understand how the file pointer `filp` and the underlying `ub` structure interact. Specifically, I'm noting that `ub->ch_file` is assigned `filp`. This is where things get interesting. The use of `mutex_lock` and `mutex_unlock` around the `ub->ch_file` assignment and later de-assignment in `ublk_ch_release` signals that concurrent access to this `ch_file` pointer needs to be protected. The `cancel_mutex` is clearly used for synchronization.

I'm thinking about the lifecycle here.  `ublk_ch_open` sets the `ch_file`, while `ublk_ch_release` clears it. The crucial question, as always, is: when is `ub` allocated, and how is that handled? I need to trace back and see where the `ublk_device` structure is actually being allocated and initialized to fully understand the scope and implications of that `ch_file` pointer and the associated mutex. This will probably hold the key to understanding the concurrency concerns here.



48/3 2026/10/11 06:45 tool grepper
0m Error:
no matches

Args:
{
  "Expression": "kzalloc.*ublk_device",
  "PathPrefixes": [
    "drivers/block/ublk_drv.c"
  ]
}

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

49/3 2026/10/11 06:45 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 45843
							output: 39
							thoughts: 14
						

Thoughts:
Here's my thought process, as if I were considering this myself:

**Tracing the Allocation of `ublk_device`**

Okay, so I need to track down where this `ublk_device` structure is being allocated in the kernel. This is a common debugging task, and I have a few approaches I can take. First, I'll need to remember if it is a statically defined, dynamically allocated or a memory-mapped object.

My instinct is to start with a code search. I can use `grep` or my IDE's search function to look for instances of "ublk_device" within the kernel source. But, I know that just looking for the string isn't always enough; I should also look for patterns like `kmalloc`, `kzalloc`, or `alloc_` related functions, as these are the most common allocation methods. I also have to keep in mind that the device might be embedded in some other struct, so looking for related struct field initializations may be necessary as well.

I should also check the relevant header files (`include/linux/`) for any potential declarations of `ublk_device` or anything that *contains* it. That can provide valuable clues about its structure and how it's used. Examining the context of the definition might help me deduce the initialization mechanism.

If a code search yields a potential allocation site, I'll need to carefully examine the surrounding code to understand the conditions under which the allocation happens. Is it triggered during module load, device probe, or something else? Understanding the control flow around the allocation is crucial. I will look for any accompanying `free` calls (or equivalents) and see if I can follow the lifetime of the structure. I may need to use `gdb` or a similar debugger to set breakpoints and step through the code if the allocation is conditional or complex.

Ultimately, my goal is to pinpoint the exact location and conditions under which `ublk_device` is allocated. From there, I can begin to reason about its usage and potential issues related to memory management.



50/3 2026/10/11 06:45 tool grepper
0m Error:
no matches

Args:
{
  "Expression": "sizeof\\(struct ublk_device\\)",
  "PathPrefixes": [
    "drivers/block/ublk_drv.c"
  ]
}

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

51/3 2026/10/11 06:45 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 46341
							output: 39
							thoughts: 23
						

Thoughts:
Okay, here's my attempt at summarizing that thought process, keeping in mind the user is an expert:

**Finding the `ublk_device` Allocation**

Alright, let's get down to brass tacks. I need to pinpoint where the `ublk_device` structure, let's call it `ub`, is being allocated. I'll need to locate the relevant memory allocation code, specifically looking for instances of the `struct ublk_device *ub` declaration or allocation. It's a pretty standard approach, but crucial for understanding the lifecycle and how this device is set up in the kernel. This is foundational to any deeper dive into the UBLK layer. So, searching for that allocation pattern is the starting point to identify the relevant code location.



52/3 2026/10/11 06:45 tool grepper
0m Args:
{
  "Expression": "struct ublk_device \\*ub =",
  "PathPrefixes": [
    "drivers/block/ublk_drv.c"
  ]
}

Results:
{
  "Output": "drivers/block/ublk_drv.c=636=static int ublk_report_zones(struct gendisk *disk, sector_t sector,\n--\ndrivers/block/ublk_drv.c-638-{\ndrivers/block/ublk_drv.c:639:\tstruct ublk_device *ub = disk-\u003eprivate_data;\ndrivers/block/ublk_drv.c-640-\tunsigned int zone_size_sectors = disk-\u003equeue-\u003elimits.chunk_sectors;\n--\ndrivers/block/ublk_drv.c=1330=static void ublk_free_disk(struct gendisk *disk)\ndrivers/block/ublk_drv.c-1331-{\ndrivers/block/ublk_drv.c:1332:\tstruct ublk_device *ub = disk-\u003eprivate_data;\ndrivers/block/ublk_drv.c-1333-\n--\ndrivers/block/ublk_drv.c=1350=static int ublk_open(struct gendisk *disk, blk_mode_t mode)\ndrivers/block/ublk_drv.c-1351-{\ndrivers/block/ublk_drv.c:1352:\tstruct ublk_device *ub = disk-\u003eprivate_data;\ndrivers/block/ublk_drv.c-1353-\n--\ndrivers/block/ublk_drv.c=1831=static bool __ublk_batch_prep_dispatch(struct ublk_queue *ubq,\n--\ndrivers/block/ublk_drv.c-1834-{\ndrivers/block/ublk_drv.c:1835:\tstruct ublk_device *ub = data-\u003eub;\ndrivers/block/ublk_drv.c-1836-\tstruct ublk_io *io = \u0026ubq-\u003eios[tag];\n--\ndrivers/block/ublk_drv.c=2346=static int ublk_init_hctx(struct blk_mq_hw_ctx *hctx, void *driver_data,\n--\ndrivers/block/ublk_drv.c-2348-{\ndrivers/block/ublk_drv.c:2349:\tstruct ublk_device *ub = driver_data;\ndrivers/block/ublk_drv.c-2350-\tstruct ublk_queue *ubq = ublk_get_queue(ub, hctx-\u003equeue_num);\n--\ndrivers/block/ublk_drv.c=2404=static int ublk_ch_open(struct inode *inode, struct file *filp)\ndrivers/block/ublk_drv.c-2405-{\ndrivers/block/ublk_drv.c:2406:\tstruct ublk_device *ub = container_of(inode-\u003ei_cdev,\ndrivers/block/ublk_drv.c-2407-\t\t\tstruct ublk_device, cdev);\n--\ndrivers/block/ublk_drv.c=2464=static void ublk_partition_scan_work(struct work_struct *work)\ndrivers/block/ublk_drv.c-2465-{\ndrivers/block/ublk_drv.c:2466:\tstruct ublk_device *ub =\ndrivers/block/ublk_drv.c-2467-\t\tcontainer_of(work, struct ublk_device, partition_scan_work);\n--\ndrivers/block/ublk_drv.c=2536=static void ublk_ch_release_work_fn(struct work_struct *work)\ndrivers/block/ublk_drv.c-2537-{\ndrivers/block/ublk_drv.c:2538:\tstruct ublk_device *ub =\ndrivers/block/ublk_drv.c-2539-\t\tcontainer_of(work, struct ublk_device, exit_work.work);\n--\ndrivers/block/ublk_drv.c=2642=static int ublk_ch_release(struct inode *inode, struct file *filp)\ndrivers/block/ublk_drv.c-2643-{\ndrivers/block/ublk_drv.c:2644:\tstruct ublk_device *ub = filp-\u003eprivate_data;\ndrivers/block/ublk_drv.c-2645-\n--\ndrivers/block/ublk_drv.c=2661=static int ublk_ch_mmap(struct file *filp, struct vm_area_struct *vma)\ndrivers/block/ublk_drv.c-2662-{\ndrivers/block/ublk_drv.c:2663:\tstruct ublk_device *ub = filp-\u003eprivate_data;\ndrivers/block/ublk_drv.c-2664-\tsize_t sz = vma-\u003evm_end - vma-\u003evm_start;\n--\ndrivers/block/ublk_drv.c=2792=static void ublk_cancel_cmd(struct ublk_queue *ubq, u16 tag,\n--\ndrivers/block/ublk_drv.c-2795-\tstruct ublk_io *io = \u0026ubq-\u003eios[tag];\ndrivers/block/ublk_drv.c:2796:\tstruct ublk_device *ub = ubq-\u003edev;\ndrivers/block/ublk_drv.c-2797-\tstruct io_uring_cmd *cmd = NULL;\n--\ndrivers/block/ublk_drv.c=3450=static int ublk_ch_uring_cmd_local(struct io_uring_cmd *cmd,\n--\ndrivers/block/ublk_drv.c-3456-\tu16 buf_idx = UBLK_INVALID_BUF_IDX;\ndrivers/block/ublk_drv.c:3457:\tstruct ublk_device *ub = cmd-\u003efile-\u003eprivate_data;\ndrivers/block/ublk_drv.c-3458-\tstruct ublk_queue *ubq;\n--\ndrivers/block/ublk_drv.c=4061=static int ublk_handle_non_batch_cmd(struct io_uring_cmd *cmd,\n--\ndrivers/block/ublk_drv.c-4065-\t\t\t\t\t\t\t       struct ublksrv_io_cmd);\ndrivers/block/ublk_drv.c:4066:\tstruct ublk_device *ub = cmd-\u003efile-\u003eprivate_data;\ndrivers/block/ublk_drv.c-4067-\tu16 tag = READ_ONCE(ub_cmd-\u003etag);\n--\ndrivers/block/ublk_drv.c=4091=static int ublk_ch_batch_io_uring_cmd(struct io_uring_cmd *cmd,\n--\ndrivers/block/ublk_drv.c-4095-\t\t\t\t\t\t\t  struct ublk_batch_io);\ndrivers/block/ublk_drv.c:4096:\tstruct ublk_device *ub = cmd-\u003efile-\u003eprivate_data;\ndrivers/block/ublk_drv.c-4097-\tstruct ublk_batch_io_data data = {\n--\ndrivers/block/ublk_drv.c=4161=ublk_user_copy(struct kiocb *iocb, struct iov_iter *iter, int dir)\ndrivers/block/ublk_drv.c-4162-{\ndrivers/block/ublk_drv.c:4163:\tstruct ublk_device *ub = iocb-\u003eki_filp-\u003eprivate_data;\ndrivers/block/ublk_drv.c-4164-\tstruct ublk_queue *ubq;\n--\ndrivers/block/ublk_drv.c=4430=static void ublk_cdev_rel(struct device *dev)\ndrivers/block/ublk_drv.c-4431-{\ndrivers/block/ublk_drv.c:4432:\tstruct ublk_device *ub = container_of(dev, struct ublk_device, cdev_dev);\ndrivers/block/ublk_drv.c-4433-\n--\ndrivers/block/ublk_drv.c=4511=static struct ublk_device *ublk_get_device_from_id(int idx)\ndrivers/block/ublk_drv.c-4512-{\ndrivers/block/ublk_drv.c:4513:\tstruct ublk_device *ub = NULL;\ndrivers/block/ublk_drv.c-4514-\n--\ndrivers/block/ublk_drv.c=5018=static int ublk_ctrl_del_dev(struct ublk_device **p_ub, bool wait)\ndrivers/block/ublk_drv.c-5019-{\ndrivers/block/ublk_drv.c:5020:\tstruct ublk_device *ub = *p_ub;\ndrivers/block/ublk_drv.c-5021-\tint idx = ub-\u003eub_number;\n--\ndrivers/block/ublk_drv.c=5916=static int ublk_ctrl_uring_cmd(struct io_uring_cmd *cmd,\n--\ndrivers/block/ublk_drv.c-5922-\tstruct ublksrv_ctrl_cmd header;\ndrivers/block/ublk_drv.c:5923:\tstruct ublk_device *ub = NULL;\ndrivers/block/ublk_drv.c-5924-\tu32 cmd_op = cmd-\u003ecmd_op;\n"
}

53/3 2026/10/11 06:45 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 48897
							output: 35
							thoughts: 29
						

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

**Tracing the Allocation of the `ublk_device` Structure**

Okay, so I need to figure out where the `ublk_device` structure is actually allocated in the kernel. My first instinct is to use the good old `grep` command. It's usually the quickest way to track down a specific function call or variable definition, especially when I'm dealing with kernel code. I'll search for something like `ublk_alloc_dev` – that's a pretty standard naming convention for allocation functions, right? Or, perhaps something similar, related to device allocation within the Ublk subsystem. I need to find the function, or functions, where this `ublk_device` struct is brought into existence. Once I find that, I'll have a good starting point to understand the overall device lifecycle in that subsystem.



54/3 2026/10/11 06:45 tool grepper
0m Args:
{
  "Expression": "ublk_alloc",
  "PathPrefixes": [
    "drivers/block/ublk_drv.c"
  ]
}

Results:
{
  "Output": "drivers/block/ublk_drv.c=603=static void ublk_dev_param_zoned_apply(struct ublk_device *ub)\n--\ndrivers/block/ublk_drv.c-608-/* Based on virtblk_alloc_report_buffer */\ndrivers/block/ublk_drv.c:609:static void *ublk_alloc_report_buffer(struct ublk_device *ublk,\ndrivers/block/ublk_drv.c-610-\t\t\t\t      unsigned int nr_zones, size_t *buflen)\n--\ndrivers/block/ublk_drv.c=636=static int ublk_report_zones(struct gendisk *disk, sector_t sector,\n--\ndrivers/block/ublk_drv.c-650-\ndrivers/block/ublk_drv.c:651:\tbuffer = ublk_alloc_report_buffer(ub, nr_zones, \u0026buffer_length);\ndrivers/block/ublk_drv.c-652-\tif (!buffer)\n--\ndrivers/block/ublk_drv.c=4381=static int ublk_init_queues(struct ublk_device *ub)\n--\ndrivers/block/ublk_drv.c-4398-\ndrivers/block/ublk_drv.c:4399:static int ublk_alloc_dev_number(struct ublk_device *ub, int idx)\ndrivers/block/ublk_drv.c-4400-{\n--\ndrivers/block/ublk_drv.c=4793=static int ublk_ctrl_add_dev(const struct ublksrv_ctrl_cmd *header)\n--\ndrivers/block/ublk_drv.c-4911-\ndrivers/block/ublk_drv.c:4912:\tret = ublk_alloc_dev_number(ub, header-\u003edev_id);\ndrivers/block/ublk_drv.c-4913-\tif (ret \u003c 0)\n"
}

55/3 2026/10/11 06:45 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 49649
							output: 39
							thoughts: 14
						

Thoughts:
Okay, let's dive into `ublk_ctrl_add_dev`.

**Analyzing `ublk_ctrl_add_dev`**

Alright, so I'm presented with `ublk_ctrl_add_dev`. My initial thought is to figure out what it's trying to achieve. Given the name, I'm expecting this is the function responsible for registering a new device with the ublk subsystem. Let's confirm that. I'll need to understand the data structures involved, the sequence of operations, and any error handling. I need to be thinking about potential race conditions, resource allocation, and how this integrates with the overall control flow of ublk. This feels like the critical function for expanding the functionality to multiple devices. I'm keen to get a sense for how it handles different types of ublk devices. What kind of validation is being done on the input parameters? I'm anticipating there will be sanity checks on the device name, queue depth, and any device-specific configuration details. Is this function going to allocate memory for the device structure, initialize it, and then add it to some kind of global list or hash table? Then, crucially, I need to know how it links the device to the underlying block driver. Are there any resource constraints being considered? This is going to be a key area for potential optimization, for example, avoiding excessive allocations, or preventing denial-of-service by a malicious device configuration. Let's see how they do it.



56/3 2026/10/11 06:45 tool read-file
0m Args:
{
  "File": "drivers/block/ublk_drv.c",
  "FirstLine": 4793,
  "LineCount": 40
}

Results:
{
  "Contents": "4793:\tstatic int ublk_ctrl_add_dev(const struct ublksrv_ctrl_cmd *header)\n4794:\t{\n4795:\t\tvoid __user *argp = (void __user *)(unsigned long)header-\u003eaddr;\n4796:\t\tstruct ublksrv_ctrl_dev_info info;\n4797:\t\tstruct ublk_device *ub;\n4798:\t\tint ret = -EINVAL;\n4799:\t\n4800:\t\tif (header-\u003elen \u003c sizeof(info) || !header-\u003eaddr)\n4801:\t\t\treturn -EINVAL;\n4802:\t\tif (header-\u003equeue_id != (u16)-1) {\n4803:\t\t\tpr_warn(\"%s: queue_id is wrong %x\\n\",\n4804:\t\t\t\t__func__, header-\u003equeue_id);\n4805:\t\t\treturn -EINVAL;\n4806:\t\t}\n4807:\t\n4808:\t\tif (copy_from_user(\u0026info, argp, sizeof(info)))\n4809:\t\t\treturn -EFAULT;\n4810:\t\n4811:\t\tif (info.queue_depth \u003e UBLK_MAX_QUEUE_DEPTH || !info.queue_depth ||\n4812:\t\t    info.nr_hw_queues \u003e UBLK_MAX_NR_QUEUES || !info.nr_hw_queues)\n4813:\t\t\treturn -EINVAL;\n4814:\t\n4815:\t\tif (capable(CAP_SYS_ADMIN))\n4816:\t\t\tinfo.flags \u0026= ~UBLK_F_UNPRIVILEGED_DEV;\n4817:\t\telse if (!(info.flags \u0026 UBLK_F_UNPRIVILEGED_DEV))\n4818:\t\t\treturn -EPERM;\n4819:\t\n4820:\t\t/* forbid nonsense combinations of recovery flags */\n4821:\t\tswitch (info.flags \u0026 UBLK_F_ALL_RECOVERY_FLAGS) {\n4822:\t\tcase 0:\n4823:\t\tcase UBLK_F_USER_RECOVERY:\n4824:\t\tcase (UBLK_F_USER_RECOVERY | UBLK_F_USER_RECOVERY_REISSUE):\n4825:\t\tcase (UBLK_F_USER_RECOVERY | UBLK_F_USER_RECOVERY_FAIL_IO):\n4826:\t\t\tbreak;\n4827:\t\tdefault:\n4828:\t\t\tpr_warn(\"%s: invalid recovery flags %llx\\n\", __func__,\n4829:\t\t\t\tinfo.flags \u0026 UBLK_F_ALL_RECOVERY_FLAGS);\n4830:\t\t\treturn -EINVAL;\n4831:\t\t}\n4832:\t\n"
}

57/3 2026/10/11 06:45 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 50716
							output: 39
							thoughts: 17
						

Thoughts:
Okay, here's my attempt at summarizing that segment, presented as your thought process, from the perspective of an expert:

**Analyzing Code Segment 4833-4880**

Alright, let's dive into lines 4833 to 4880. My initial scan... Hmm, it seems we're dealing with [Insert a *likely* assumption based on the user's field. e.g., a critical section for resource allocation, a data validation routine, a module interaction sequence, etc.]. My expertise tells me to quickly focus on the conditional statements and any loops here. I need to understand the logic flow within this block.

*   Are there any obvious performance bottlenecks?
*   Any potential race conditions that jump out?
*   What's the expected input range? Does this section handle edge cases gracefully, or could it lead to unexpected behavior?
*   What variables are in scope? I'm looking for any signs of global variable modification and their implications in the wider system.
*   Are there any obvious code smells?

Let me look for any unusual function calls or assignments, specifically focusing on any resource locks or unlocks, or perhaps any memory operations.

I'm particularly interested in this block's interaction with the rest of the code. Is this a stand-alone routine, or does it depend on any external services or data stores? A quick cross-reference in the surrounding code can shed light on any potential integration points and dependencies.

This will give me the information I need, to determine if this piece of code is fit for purpose.



58/3 2026/10/11 06:46 tool read-file
0m Args:
{
  "File": "drivers/block/ublk_drv.c",
  "FirstLine": 4833,
  "LineCount": 40
}

Results:
{
  "Contents": "4833:\t\tif ((info.flags \u0026 UBLK_F_QUIESCE) \u0026\u0026 !(info.flags \u0026 UBLK_F_USER_RECOVERY)) {\n4834:\t\t\tpr_warn(\"UBLK_F_QUIESCE requires UBLK_F_USER_RECOVERY\\n\");\n4835:\t\t\treturn -EINVAL;\n4836:\t\t}\n4837:\t\n4838:\t\t/*\n4839:\t\t * unprivileged device can't be trusted, but RECOVERY and\n4840:\t\t * RECOVERY_REISSUE still may hang error handling, so can't\n4841:\t\t * support recovery features for unprivileged ublk now\n4842:\t\t *\n4843:\t\t * TODO: provide forward progress for RECOVERY handler, so that\n4844:\t\t * unprivileged device can benefit from it\n4845:\t\t */\n4846:\t\tif (info.flags \u0026 UBLK_F_UNPRIVILEGED_DEV) {\n4847:\t\t\tinfo.flags \u0026= ~(UBLK_F_USER_RECOVERY_REISSUE |\n4848:\t\t\t\t\tUBLK_F_USER_RECOVERY);\n4849:\t\n4850:\t\t\t/*\n4851:\t\t\t * For USER_COPY, we depends on userspace to fill request\n4852:\t\t\t * buffer by pwrite() to ublk char device, which can't be\n4853:\t\t\t * used for unprivileged device\n4854:\t\t\t *\n4855:\t\t\t * Same with zero copy or auto buffer register.\n4856:\t\t\t */\n4857:\t\t\tif (info.flags \u0026 (UBLK_F_USER_COPY | UBLK_F_SUPPORT_ZERO_COPY |\n4858:\t\t\t\t\t\tUBLK_F_AUTO_BUF_REG))\n4859:\t\t\t\treturn -EINVAL;\n4860:\t\t}\n4861:\t\n4862:\t\t/* User copy is required to access integrity buffer */\n4863:\t\tif (info.flags \u0026 UBLK_F_INTEGRITY \u0026\u0026 !(info.flags \u0026 UBLK_F_USER_COPY))\n4864:\t\t\treturn -EINVAL;\n4865:\t\n4866:\t\tif (info.flags \u0026 UBLK_F_IO_DESC_SIZE) {\n4867:\t\t\tif (info.io_desc_size \u003c sizeof(struct ublksrv_io_desc) ||\n4868:\t\t\t    info.io_desc_size % _Alignof(struct ublksrv_io_desc) ||\n4869:\t\t\t    info.io_desc_size \u003e UBLK_MAX_IO_DESC_SIZE)\n4870:\t\t\t\treturn -EINVAL;\n4871:\t\t} else {\n4872:\t\t\tinfo.io_desc_size = sizeof(struct ublksrv_io_desc);\n"
}

59/3 2026/10/11 06:46 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 51827
							output: 39
							thoughts: 17
						

Thoughts:
Okay, here's my attempt at summarizing the thought process, tailored for an expert audience, and written in the first person:

**Analyzing Code Section 4873-4910**

Alright, let's dive into lines 4873 through 4910. My initial scan tells me this is likely the core of [mention the specific module/functionality the code likely pertains to, if inferable from context - e.g., the error handling routine, the data validation process, the core loop of the algorithm]. I need to get a clear picture of the logic here. My instinct is that this is where the main computational bottleneck probably lies.

Specifically, I'm looking for any obvious inefficiencies, potential race conditions, or memory leaks – the usual suspects. I'm focusing on the branching logic, the calls to external libraries (and the potential overhead), and how the data structures are being manipulated. Does the code allocate new memory here repeatedly, or does it reuse pre-allocated buffers? That's always a key point. Are there any recursive calls or deeply nested loops that could be optimized with a different algorithmic approach?

Let's see… line 4879, that conditional statement… aha, that's where we make the critical decision. Now, it's pretty clear that this conditional is the core of this section - and this is where it diverges based on [mention the condition based on the inference from the code, such as the value of some flag or variable]. How is that condition evaluated? Is it efficiently indexed? Does it require a full table scan or a more targeted lookup?

Okay, and then the following lines, 4885 to 4900, seems to indicate the computation happening in the “if” statement. Okay, it seems like a straightforward algorithm here. My quick glance is indicating that it is a common pattern to [summarize what the algorithm does based on the inferences from the code] and if I am right, this computation can be greatly sped up. Let me dig a little bit deeper.

Line 4899 jumps to a section of code which is the "else" condition, and it does some more computation based on some other values. Let me also investigate the "else" part too.

In sum, it feels like this section has the potential for significant optimization, particularly around [mention a specific area or potential improvement, e.g., reducing the number of nested loops, replacing a linear search with a hash table, or optimizing a particular math operation]. It’s time to formulate a proper plan for optimization.



60/3 2026/10/11 06:46 tool read-file
0m Args:
{
  "File": "drivers/block/ublk_drv.c",
  "FirstLine": 4873,
  "LineCount": 40
}

Results:
{
  "Contents": "4873:\t\t}\n4874:\t\n4875:\t\t/* the created device is always owned by current user */\n4876:\t\tublk_store_owner_uid_gid(\u0026info.owner_uid, \u0026info.owner_gid);\n4877:\t\n4878:\t\tif (header-\u003edev_id != info.dev_id) {\n4879:\t\t\tpr_warn(\"%s: dev id not match %u %u\\n\",\n4880:\t\t\t\t__func__, header-\u003edev_id, info.dev_id);\n4881:\t\t\treturn -EINVAL;\n4882:\t\t}\n4883:\t\n4884:\t\tif (header-\u003edev_id != U32_MAX \u0026\u0026 header-\u003edev_id \u003e= UBLK_MAX_UBLKS) {\n4885:\t\t\tpr_warn(\"%s: dev id is too large. Max supported is %d\\n\",\n4886:\t\t\t\t__func__, UBLK_MAX_UBLKS - 1);\n4887:\t\t\treturn -EINVAL;\n4888:\t\t}\n4889:\t\n4890:\t\tublk_dump_dev_info(\u0026info);\n4891:\t\n4892:\t\tret = mutex_lock_killable(\u0026ublk_ctl_mutex);\n4893:\t\tif (ret)\n4894:\t\t\treturn ret;\n4895:\t\n4896:\t\tret = -EACCES;\n4897:\t\tif ((info.flags \u0026 UBLK_F_UNPRIVILEGED_DEV) \u0026\u0026\n4898:\t\t    unprivileged_ublks_added \u003e= unprivileged_ublks_max)\n4899:\t\t\tgoto out_unlock;\n4900:\t\n4901:\t\tret = -ENOMEM;\n4902:\t\tub = kzalloc_flex(*ub, queues, info.nr_hw_queues);\n4903:\t\tif (!ub)\n4904:\t\t\tgoto out_unlock;\n4905:\t\tmutex_init(\u0026ub-\u003emutex);\n4906:\t\tspin_lock_init(\u0026ub-\u003elock);\n4907:\t\tmutex_init(\u0026ub-\u003ecancel_mutex);\n4908:\t\tmt_init(\u0026ub-\u003ebuf_tree);\n4909:\t\tida_init(\u0026ub-\u003ebuf_ida);\n4910:\t\tINIT_WORK(\u0026ub-\u003epartition_scan_work, ublk_partition_scan_work);\n4911:\t\n4912:\t\tret = ublk_alloc_dev_number(ub, header-\u003edev_id);\n"
}

61/3 2026/10/11 06:46 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 53087
							output: 37
							thoughts: 4902
						

Thoughts:
**Code Review and Analysis: ublk Driver Changes**

Alright, let's break down these changes in the ublk driver. My primary concern is ensuring data integrity and preventing any potential information leaks to userspace, along with maintaining proper resource management, especially when handling cancellation scenarios in io_uring.

First, the `kzalloc_flex` allocation of `ub` is safe. It's zeroed, so any new fields are initialized as expected. The new `ch_file` field, used for the character device file pointer, is initialized to NULL and handled correctly through `ublk_ch_open` and `ublk_ch_release`, protected by `cancel_mutex`.  The `canceling` and `UB_STATE_STOPPING` fields seem fine, just comments and a minor refactor.

Now, let's address the sensitive part: data exposed to user space.  I checked `disk_report_zone` and the code is now correct. The fix ensures that uninitialized data isn't being passed to userspace via `blkdev_copy_zone_to_user` and corrects the indexing logic.

The refactoring of `ublk_ch_uring_cmd_local` is interesting. The placement of `ublk_prep_cancel` has changed. This seems to be done to correctly manage the "cancelable" state of the command. If `ublk_fetch` fails (like if the device is stopping), the new code paths correctly call `io_uring_cmd_done`, thereby handling the command and preventing potentially inconsistent states. The introduction of `out_done:` to mark the command as done makes sense.  The `ublk_prep_cancel` inline function initializes `pdu->ubq` and `pdu->tag` and then marks the command as cancelable. Importantly, it uses `smp_wmb` (store memory barrier) to ensure the `pdu` fields are updated before marking the command cancelable.

The `ublk_batch_attach` changes have the same pattern of setting the pdu fields before the command is linked. The change prevents a race where commands are attached and become immediately cancelable, or where they end up being free'd.  `io_uring_cmd_done` is called in the case of a failed attach which calls `ublk_batch_free_fcmd`.

In `ublk_stop_dev`, the `ch_file` pointer is handled correctly, with proper reference counting and locking to prevent race conditions. The calls to `ublk_cancel_dev` and `__fput_sync` are consistent with what I expect.

`ublk_ctrl_start_dev` now includes a check for `UB_STATE_STOPPING` and `ub->canceling`. It uses `cancel_mutex` to ensure that either a disk is created, or a cancelling is reported as the device is busy.  The check for `canceling` in `ublk_ctrl_end_recovery` makes sense.

In `ublk_uring_cmd_cancel_fn`, the change to read `io->cmd` with `READ_ONCE` before it is marked canceled is important.

Regarding `ublk_cancel_cmd`, the use of `READ_ONCE` to read `io->cmd` is expected.

Finally, in `ublk_ch_release_work_fn`, there was a possible null pointer dereference with `ublk_put_disk(disk);`. However, by inspecting the surrounding code, the logic ensures that it's safe to call `ublk_put_disk(disk)` even if `disk` is null. The `disk` is obtained, and the `ublk_reset_ch_dev(ub)` call is always performed before `ublk_put_disk(disk)`, ensuring all necessary cleanup occurs.



62/3 2026/10/11 06:46 tool grepper
0m Args:
{
  "Expression": "ublk_put_disk",
  "PathPrefixes": [
    "drivers/block/ublk_drv.c"
  ]
}

Results:
{
  "Output": "drivers/block/ublk_drv.c=2445=static struct gendisk *ublk_get_disk(struct ublk_device *ub)\n--\ndrivers/block/ublk_drv.c-2457-\ndrivers/block/ublk_drv.c:2458:static void ublk_put_disk(struct gendisk *disk)\ndrivers/block/ublk_drv.c-2459-{\n--\ndrivers/block/ublk_drv.c=2464=static void ublk_partition_scan_work(struct work_struct *work)\n--\ndrivers/block/ublk_drv.c-2481-out:\ndrivers/block/ublk_drv.c:2482:\tublk_put_disk(disk);\ndrivers/block/ublk_drv.c-2483-}\n--\ndrivers/block/ublk_drv.c=2536=static void ublk_ch_release_work_fn(struct work_struct *work)\n--\ndrivers/block/ublk_drv.c-2634-\tmutex_unlock(\u0026ub-\u003emutex);\ndrivers/block/ublk_drv.c:2635:\tublk_put_disk(disk);\ndrivers/block/ublk_drv.c-2636-\tclear_bit(UB_STATE_OPEN, \u0026ub-\u003estate);\n--\ndrivers/block/ublk_drv.c=2760=static void ublk_start_cancel(struct ublk_device *ub)\n--\ndrivers/block/ublk_drv.c-2788-\tmutex_unlock(\u0026ub-\u003ecancel_mutex);\ndrivers/block/ublk_drv.c:2789:\tublk_put_disk(disk);\ndrivers/block/ublk_drv.c-2790-}\n--\ndrivers/block/ublk_drv.c=5075=static int ublk_ctrl_try_stop_dev(struct ublk_device *ub)\n--\ndrivers/block/ublk_drv.c-5098-out:\ndrivers/block/ublk_drv.c:5099:\tublk_put_disk(disk);\ndrivers/block/ublk_drv.c-5100-\treturn ret;\n--\ndrivers/block/ublk_drv.c=5415=static int ublk_ctrl_quiesce_dev(struct ublk_device *ub,\n--\ndrivers/block/ublk_drv.c-5449-put_disk:\ndrivers/block/ublk_drv.c:5450:\tublk_put_disk(disk);\ndrivers/block/ublk_drv.c-5451-unlock:\n"
}

63/3 2026/10/11 06:46 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 59521
							output: 39
							thoughts: 12
						

Thoughts:
Okay, here's my interpretation of "Let's read `ublk_put_disk`" as a thought process, tailored for an expert audience and presented in the first person:

**Diving into `ublk_put_disk`**

Right, let's take a look at `ublk_put_disk`. Time to dig in and see what's happening there. I know Ublk quite well, and this function name suggests it's likely involved in releasing a disk structure, potentially after an I/O operation or upon device removal, right? Or maybe even just when it's idle. I'm expecting some reference counting, probably some cleanup of resources associated with the disk, and potentially some synchronization to ensure we aren't racing with other threads. Let's see if my mental model is accurate. What's the context? What data structures does it operate on? Are there any subtle locking schemes used to ensure data integrity? I'm particularly interested in how it handles error conditions and what mechanisms are employed to prevent double frees or memory leaks. Okay, time to fire up the source code and get a clearer picture. I'm anticipating a straightforward, yet crucial, part of the Ublk data flow. Let's start with a function signature and what the function is using and calling.



64/3 2026/10/11 06:47 tool read-file
0m Args:
{
  "File": "drivers/block/ublk_drv.c",
  "FirstLine": 2455,
  "LineCount": 10
}

Results:
{
  "Contents": "2455:\t\treturn disk;\n2456:\t}\n2457:\t\n2458:\tstatic void ublk_put_disk(struct gendisk *disk)\n2459:\t{\n2460:\t\tif (disk)\n2461:\t\t\tput_device(disk_to_dev(disk));\n2462:\t}\n2463:\t\n2464:\tstatic void ublk_partition_scan_work(struct work_struct *work)\n"
}

65/3 2026/10/11 06:47 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 59985
							output: 315
							thoughts: 1938
						

Thoughts:
**KMSAN Assessment: ublk Device Patch**

Okay, let's break this down. First, the code addresses potential NULL pointer issues with `disk`, handling the `put_device` call. Then, I'm verifying the initialization of variables within `ublk_queue_reset_io_flags`. Next, the review of `ublk_mark_io_ready` confirms it wakes up the appropriate waiters.

Now, for the critical part: KMSAN. I'm carefully evaluating against the four KMSAN criteria.

1.  **Kernel Structures to Userspace:** The key area here is `ublk_report_zones`. I've confirmed that the `buffer` used for reporting is allocated and zeroed using `memset`, preventing information leaks. Moreover, the fix addresses an index issue (`done_zones` vs `i`) in user-space reporting, which eliminates the possibility of overwriting the reporting buffer. No uninitialized memory is sent to userspace.

2.  **Conditional Logic/Branching:** I'm examining any conditional logic. `ub->state`, `ub->canceling`, and `READ_ONCE(io->cmd)` are all correctly initialized and managed. No conditional branches are dependent on uninitialized data.

3.  **Complex Data Structures:** `fcmd` is zero-allocated (`kzalloc_obj`), and `INIT_LIST_HEAD(&fcmd->node)` is added to zero-allocate `fcmd->node`, which is good. The added fields to `struct ublk_device` are part of a `kzalloc_flex` allocation.

4.  **Bounds Checks/Logic:** I've scrutinized this, especially regarding `done_zones` and `nr_zones`, and confirmed the bounds checks are in place and there is no potential for access of uninitialized bytes. This patch deals with lifecycle, state transitions, synchronization/concurrency (locking `cancel_mutex`, reference counting `ch_file`, ordering with `smp_wmb`), and handling canceled `io_uring_cmd` requests (avoiding NULL dereference of `io->cmd` and use-after-free in io_uring cancel lists).

**Risks Addressed:** The patch primarily addresses use-after-free (UAF) of `io_uring` commands upon cancellation (caught by KASAN), NULL pointer dereferences of `io->cmd`, races, and synchronization issues (caught by standard kernel oops/KASAN and LOCKDEP), and a user-space zone reporting index.

**Conclusion:** Based on this thorough analysis, this patch does *not* introduce or expose uninitialized memory risks. KASAN, LOCKDEP, and standard kernel debugging tools are sufficient. KMSAN fuzzing is not needed. A `NeedsKMSAN=false` declaration is appropriate.

I've reviewed all the changes: new state bits, file handling (`ch_file`), zone reporting fix, batch allocations, cancelation preparation, and concurrency control. Every change aligns with the primary goal of improving lifecycle, concurrency, and preventing NULL dereferences or use-after-free conditions. No uninitialized memory hazards are present. Time to construct the tool call for `set-results`.



66/3 2026/10/11 06:47 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch addresses synchronization, state management, and cancellation races in the ublk driver (ublk_drv.c). Specifically:\n1. It prevents NULL pointer dereferences on io-\u003ecmd and io_uring use-after-free bugs when I/O commands are canceled while starting/stopping devices or during recovery.\n2. It introduces UB_STATE_STOPPING and manages ublk device lifecycle state transitions across START_DEV, STOP_DEV, and FETCH commands.\n3. In ublk_report_zones(), it fixes a bug where the per-batch loop index 'i' was passed to disk_report_zone() instead of the cumulative 'done_zones', ensuring multi-batch zone reporting copies to the correct index in user memory. The underlying report buffer is already explicitly zeroed with memset(), and no uninitialized kernel data is copied to user space.\n4. All added/modified variables and struct fields (e.g., ch_file, canceled, cur) are properly initialized or reside within zero-allocated structures (kzalloc_flex / kzalloc_obj).\n\nThese changes primarily address race conditions, NULL pointer dereferences, and use-after-free scenarios, which are covered by standard KASAN, LOCKDEP, and kernel oops detectors. No uninitialized memory reads or information leak hazards are introduced or exposed; thus, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch addresses synchronization, state management, and cancellation races in the ublk driver (ublk_drv.c). Specifically:\n1. It prevents NULL pointer dereferences on io-\u003ecmd and io_uring use-after-free bugs when I/O commands are canceled while starting/stopping devices or during recovery.\n2. It introduces UB_STATE_STOPPING and manages ublk device lifecycle state transitions across START_DEV, STOP_DEV, and FETCH commands.\n3. In ublk_report_zones(), it fixes a bug where the per-batch loop index 'i' was passed to disk_report_zone() instead of the cumulative 'done_zones', ensuring multi-batch zone reporting copies to the correct index in user memory. The underlying report buffer is already explicitly zeroed with memset(), and no uninitialized kernel data is copied to user space.\n4. All added/modified variables and struct fields (e.g., ch_file, canceled, cur) are properly initialized or reside within zero-allocated structures (kzalloc_flex / kzalloc_obj).\n\nThese changes primarily address race conditions, NULL pointer dereferences, and use-after-free scenarios, which are covered by standard KASAN, LOCKDEP, and kernel oops detectors. No uninitialized memory reads or information leak hazards are introduced or exposed; thus, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false
}

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