nvme: fix transport request and queue error handling
Subsystems (4)
v2 cover nvme: fix transport request and queue error handling
The six patches fix independent error paths in the NVMe transports.
Patch 1 releases the target request in nvme-loop when SG setup fails. nvmet_req_init() has already taken the queue, namespace and reservation references, and blk-mq retries the same request, so each failure leaked a set of references.
Patch 2 makes the TCP target wait for in-capsule data only when the SGL is really an offset data block descriptor. The old check looked only at the descriptor length, so a transport SGL of the same length was treated as in-capsule data; the same check is used when request initialization fails.
Patch 3 requires the R2T offset to equal the number of bytes already sent. A larger offset let the host advertise an offset past the data that its next H2CData PDU carried.
Patch 4 frees the fcloop LS request when nvmet_fc_rcv_ls_req() fails before taking ownership.
Patch 5 publishes an FC target queue only if its slot is still free. A duplicate Create Connection replaced the old pointer and leaked the queue and its controller reference.
Patch 6 rolls back the SQ binding and the controller reference taken by nvmet_install_queue() when the CQ is already bound to another controller, and destroys the CQ binding when the transport cannot install the queue.
The six patches are independent and can be applied in any order or as a subset. All carry Fixes: and Cc: stable.
Changes in v2:
- Patch 2: split the inline-SGL helper into separate conditions, as
requested by Christoph Hellwig. No functional change; a compiled
comparison of the old and new helpers found no mismatches.
- Patches 1 and 3-6: code and commit messages unchanged; add Christoph
Hellwig's Reviewed-by tags. Existing runtime evidence remains v1 data.
Previous version: https://lore.kernel.org/all/[email protected]/
Codex assisted with the review changes, descriptions and validation scripts. The updated code was function-tested and build-tested.
Shao Mingyin (6):
nvme-loop: release the target request when SG setup fails
nvmet-tcp: only wait for in-capsule data for inline SGLs
nvme-tcp: require the R2T offset to match the data sent
nvmet-fcloop: free the LS request when delivery fails
nvmet-fc: reject duplicate queue IDs on Create Connection
nvmet: roll back queue bindings on connection failure
drivers/nvme/host/tcp.c | 2 +- drivers/nvme/target/fabrics-cmd.c | 3 +++ drivers/nvme/target/fc.c | 13 ++++++++++-- drivers/nvme/target/fcloop.c | 2 ++ drivers/nvme/target/loop.c | 1 + drivers/nvme/target/tcp.c | 42 +++++++++++++++++++++++++++------------ 6 files changed, 47 insertions(+), 16 deletions(-)
---
base-commit: ddfe51b0a0f5dc9e415cc2c8ad8db17532dd426b
PATCH v2 1/6 nvme-loop: release the target request when SG setup fails
From: Shao Mingyin <[email protected]>
nvme_loop_queue_rq() calls nvmet_req_init(), which takes a reference on the submission queue percpu ref, pins the namespace and, for a reservation-enabled namespace, takes a per-controller PR reference. If sg_alloc_table_chained() then fails under memory pressure, the function returns BLK_STS_RESOURCE without calling nvmet_req_uninit(). blk-mq retries the same request and nvmet_req_init() overwrites req->ns and req->pc_ref, leaking the queue, namespace and PR references taken by the failed attempt each time this happens.
Release the request before returning BLK_STS_RESOURCE.
---
Changes in v2:
- Code and commit message unchanged; add Christoph Hellwig's Reviewed-by tag. Previous version: https://lore.kernel.org/all/[email protected]/
Tested on 7.3.0-next-20261030 (QEMU/TCG guest, 8 vCPUs) with the loop transport and a file-backed namespace on tmpfs.
The scatterlist allocation was failed with failslab, narrowed to nvme_loop_queue_rq() using the stack-trace filter. One request is not
enough: nvme-loop caps it at NVME_LOOP_MAX_SEGMENTS (256), i.e. two 128-entry chunks, and the sgpool mempool keeps two elements in reserve, so the allocation only fails when several requests are in flight. Eight concurrent 1020 KiB passthrough writes on /dev/ng0n1, with non-contiguous pages so that every 4 KiB is its own scatterlist entry, hit it; blk-mq then retries the same request.
unpatched patched delete_controller write never returns completes in about 200 ms blocked in nvmet_sq_destroy() -
The blocked task is in
nvmet_sq_destroy
nvme_loop_destroy_io_queues
nvme_loop_shutdown_ctrl
waiting for sq->confirm_done because the submission queue reference was leaked. The failed attempt also leaks its namespace and any PR reference when the retry overwrites the request fields.
drivers/nvme/target/loop.c | 1 + 1 file changed, 1 insertion(+)
drivers/nvme/target/loop.c +1 -0
@@ -159,6 +159,7 @@ static blk_status_t nvme_loop_queue_rq(struct blk_mq_hw_ctx *hctx, blk_rq_nr_phys_segments(req), iod->sg_table.sgl, NVME_INLINE_SG_CNT)) {nvme_cleanup_cmd (req); +nvmet_req_uninit (&iod->req);return BLK_STS_RESOURCE ; }
Signature · 1 line
2.27.0
PATCH v2 2/6 nvmet-tcp: only wait for in-capsule data for inline SGLs
In reply to [email protected]From: Shao Mingyin <[email protected]>
nvmet-tcp decides whether to wait for in-capsule data using only the write direction and SGL length. A write using a transport SGL can fit within inline_data_size without carrying any in-capsule data. The response path then withholds its R2T, leaving the command stuck.
If request initialization fails, the same length-only test both withholds the error response and attempts to drain inline data that will never arrive. This can also consume the following PDU as data or a digest.
Require an offset data-block SGL in both checks. Share a helper that only uses command and port fields, as the completion callback can run before nvmet_req_init() has finished.
---
Changes in v2 (Christoph Hellwig):
- Split nvmet_tcp_sgl_is_inline() into separate conditions. No functional change; keep the existing request paths unchanged.
v1: https://lore.kernel.org/all/[email protected]/
The original and revised helpers were compiled with GCC 13 and UBSAN and compared across every SGL type and opcode, with zero, boundary and large lengths and inline limits. All results matched. This function test uses command/port stubs and does not exercise TCP or request initialization. The runtime results below are from v1.
Tested on 7.3.0-next-20261030 (QEMU/TCG guest) with nvmet-tcp over loopback. The standard nvme-tcp host driver only sends in-capsule data with an inline SGL, so it can never produce the triggering combination; the test instead drives a minimal user-space NVMe/TCP host that crafts the ICReq/Connect/command PDUs itself.
It sends a valid 4 KiB write with a transport SGL (type 0x5A) on an enabled controller and I/O queue:
unpatched patched
no R2T, write hangs R2T received, H2CData sent,
write completes (status 0x0000)
drivers/nvme/target/tcp.c | 42 +++++++++++++++++++++++++++------------ 1 file changed, 29 insertions(+), 13 deletions(-)
drivers/nvme/target/tcp.c +29 -13
@@ -269,6 +269,30 @@ static inline bool nvmet_tcp_has_inline_data(struct nvmet_tcp_cmd *cmd) !cmd->rbytes_done; } +/* +* Check whether the SGL of @cmd carries in-capsule data that the host +* will send right after the command PDU. Only the offset form of the +* data block descriptor is in-capsule; a regular transport SGL is +* fetched through an R2T instead. +*/ +static inline bool nvmet_tcp_sgl_is_inline (struct nvmet_tcp_cmd *cmd) +{ +struct nvme_sgl_desc *sgl = &cmd->req.cmd->common.dptr.sgl; +u32 len =le32_to_cpu (sgl->length); + +if (sgl->type != ((NVME_SGL_FMT_DATA_DESC <<4 ) | +NVME_SGL_FMT_OFFSET )) +return false; + +if (!nvme_is_write (cmd->req.cmd)) +return false; + +if (!len) +return false; + +return len <= cmd->req.port->inline_data_size; +} +static inline struct nvmet_tcp_cmd *nvmet_tcp_get_cmd (struct nvmet_tcp_queue *queue) {
@@ -625,25 +649,19 @@ static void nvmet_tcp_queue_response(struct nvmet_req *req)struct nvmet_tcp_queue *queue = cmd->queue;enum nvmet_tcp_recv_state queue_state;struct nvmet_tcp_cmd *queue_cmd; -struct nvme_sgl_desc *sgl; -u32 len;/* Pairs with store_release in nvmet_prepare_receive_pdu() */ queue_state =smp_load_acquire (&queue->rcv_state); queue_cmd =READ_ONCE (queue->cmd);if (unlikely (cmd == queue_cmd)) { - sgl = &cmd->req.cmd->common.dptr.sgl; - len =le32_to_cpu (sgl->length); -/* -* Wait for inline data before processing the response. -* Avoid using helpers, this might happen before -* nvmet_req_init is completed. +* Wait for in-capsule data before processing the response. +* This can happen before nvmet_req_init() has completed, so +* only look at the SGL descriptor itself. */ if (queue_state ==NVMET_TCP_RECV_PDU && - len && len <= cmd->req.port->inline_data_size && -nvme_is_write (cmd->req.cmd)) +nvmet_tcp_sgl_is_inline (cmd))return ; }
@@ -981,7 +999,6 @@ static int nvmet_tcp_handle_icreq(struct nvmet_tcp_queue *queue)static int nvmet_tcp_handle_req_failure (struct nvmet_tcp_queue *queue,struct nvmet_tcp_cmd *cmd,struct nvmet_req *req) { -size_t data_len =le32_to_cpu (req->cmd->common.dptr.sgl.length);int ret;/*
@@ -991,8 +1008,7 @@ static int nvmet_tcp_handle_req_failure(struct nvmet_tcp_queue *queue,* otherwise we will need to prepare a buffer and receive the * stale data before continuing forward. */ -if (!nvme_is_write (cmd->req.cmd) || !data_len || - data_len > cmd->req.port->inline_data_size) { +if (!nvmet_tcp_sgl_is_inline (cmd)) {nvmet_prepare_receive_pdu (queue);return 0 ; }
Signature · 1 line
2.27.0
PATCH v2 3/6 nvme-tcp: require the R2T offset to match the data sent
In reply to [email protected]From: Shao Mingyin <[email protected]>
nvme_tcp_handle_r2t() rejects offsets below data_sent but accepts larger offsets. The send iterator still points at data_sent, so the next H2CData PDU carries bytes from that position while advertising the larger offset. A target that accepts the PDU can place the data at the wrong position; the Linux target rejects it and fails the connection.
Require the R2T offset to equal data_sent, rejecting the invalid request before transmitting data with a mismatched offset.
---
Changes in v2:
- Code and commit message unchanged; add Christoph Hellwig's Reviewed-by tag. Previous version: https://lore.kernel.org/all/[email protected]/
Tested on 7.3.0-next-20261030 (QEMU/TCG guest) with the nvmet-tcp target on 127.0.0.1; no extra hardware is needed.
A test-only hook in the nvmet-tcp target shifts the R2T offset by one 4 KiB block. The 4 KiB write to a loopback namespace is then answered with an R2T at offset 4096 although the host has sent 0 bytes, so the host either transmits an H2CData PDU with the wrong offset (unpatched) or rejects the R2T (patched):
unpatched patched nvmet_tcp: ttag 2 unexpected data nvme nvme0: req 99 unexpected offset 4096 (expected 0) r2t offset 4096 (expected 0)
In the unpatched case the target detects the mismatched H2CData offset and rejects it. This test demonstrates transmission of an incorrect offset, not a successful corrupted write. With the patch the host rejects the R2T before transmitting H2CData.
drivers/nvme/host/tcp.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/nvme/host/tcp.c +1 -1
@@ -846,7 +846,7 @@ static int nvme_tcp_handle_r2t(struct nvme_tcp_queue *queue,return -EPROTO ; } -if (unlikely (r2t_offset < req->data_sent)) { +if (unlikely (r2t_offset != req->data_sent)) {dev_err (queue->ctrl->ctrl.device,"req %d unexpected r2t offset %u (expected %zu)\n" , rq->tag, r2t_offset, req->data_sent);
Signature · 1 line
2.27.0
PATCH 1/1 nvme-tcp: set up R2T data transfer in the send path
nvme_tcp_handle_r2t() runs in the receive path and sets up the H2CData transfer directly in the request: it checks the R2T against req->data_sent and calls nvme_tcp_setup_h2c_data_pdu(), which resets req->pdu_sent and req->state.
The send path updates req->data_sent and req->pdu_sent only after sock_sendmsg() has returned (nvme_tcp_advance_req(), for every send except the last one of the request). When a controller splits a write into several R2Ts, it can send the next R2T as soon as it has received the last bytes of the previous one. The receive path can then handle that R2T while the sender is still between sock_sendmsg() and nvme_tcp_advance_req() for those bytes. For example, on a poll queue nvme_tcp_poll() receives while io_work sends; the sender can also be the submitting task sending directly from queue_rq() (the tag set is BLK_MQ_F_BLOCKING) while io_work receives:
send path receive path (nvme_tcp_poll)
--------- ----------------------------
sock_sendmsg(last bytes of R2T)
R2T, offset = end of previous R2T data_sent is still the old value setup_h2c_data_pdu(): pdu_sent = 0
nvme_tcp_advance_req()
data_sent += ret; pdu_sent += ret
nvme_tcp_done_send_req()
Commit e371af033c56 ("nvme-tcp: fix incorrect h2cdata pdu offset accounting") already noted that an R2T can arrive before data_sent is updated, and took the H2CData offset from the R2T. But pdu_sent is still reset by the receive path and then advanced by the send path, so the next H2CData PDU carries fewer data bytes than its header says. The controller waits for the rest until the command times out, and the host starts error recovery and reconnects.
Since commit 347d50d92e25 ("nvme-tcp: require the R2T offset to match the data sent") the receive path requires r2t_offset == data_sent, so with the old data_sent the host now rejects the valid R2T with "unexpected r2t offset" and starts error recovery instead.
Let the receive path only record the R2T, and let the send path, which owns the send state under send_mutex, check it and set up the H2CData PDU when it next takes the request off the list. The R2T is recorded before llist_add(), and nvme_tcp_process_req_list() takes the list with llist_del_all(), so the sender sees it; the send path reads the recorded fields once. The exact checks (offset equal to data_sent, length within the request) move to the send path, where data_sent is final. The receive path keeps the "<" offset check and the length check, which cannot reject a valid R2T because data_sent only grows. A bad R2T still starts error recovery, which then cancels the request.
Reproduced in QEMU with the nvmet-tcp target over loopback, a poll queue and RWF_HIPRI writes, using a debug-only patch, not part of this change, that makes nvmet send one R2T per 16 KiB (stock nvmet sends one R2T per command, so it does not hit this) and delays the host between sock_sendmsg() and nvme_tcp_advance_req() for the last bytes of an R2T. On v7.4-rc4, "unexpected r2t offset" and error recovery were seen in 6 of 15 runs; on v6.18.65, a 30 second I/O timeout and a reconnect were seen in 10 of 15 runs. With this patch (on v7.4-rc4, and backported to v6.18.65) there was no error in 15 of 15 runs on each, although a debug marker showed R2Ts handled during the delay, i.e. inside the window, in 10 and 7 of those runs. With the delay switched off (with the nvmet one-R2T-per-16KiB test helper still applied), the reject still happened in 1 of 10 runs on v7.4-rc4 (QEMU TCG, whose timing does not represent real hardware).
The problem was found with a Lean-based formal model of the code and AI-assisted analysis. The patch and this description were written with AI assistance; a human checked them against the source.
---nvme_tcp_handle_r2t() can run while the send path is still between sock_sendmsg() and nvme_tcp_advance_req() for the last bytes of the previous R2T (drivers/nvme/host/tcp.c:1261-1275 in v7.4-rc4): it then sees a stale data_sent and resets pdu_sent, which the sender advances afterwards. e371af033c56 noted that an R2T can arrive early, but fixed only the offset.
Effect by version:
- stable 5.10.y to 7.3.y ("<" check): from the code, the next H2CData PDU is short; observed as a 30 s I/O timeout and a reconnect on v6.18.65 (target data not checked).
- v7.4-rc4 and next (347d50d92e25, "!="): the valid R2T is rejected with "unexpected r2t offset" and the host reconnects.
So 347d50d92e25 changed how the race fails; it did not create it. A plain revert would bring the stall back. The patch keeps the exact check, in the send path; trees without 347d50d92e25 keep their "<" line when backporting. 347d50d92e25 is Cc: stable but not yet in a stable branch. On a bad R2T, receiving now stops only when error recovery stops the queue.
Stock nvmet sends one R2T per command; targets that send several (one outstanding, as maxr2t=0 allows) can hit this.
Reproduction: QEMU x86_64 TCG, 4 vCPUs, nvme-tcp host and nvmet-tcp over loopback, one poll queue, 5 x 64 KiB pwritev2(RWF_HIPRI) per run. Debug-only test helpers, not part of the fix: nvmet sends one R2T per 16 KiB; the host busy-waits 2 s (mdelay) in the window and logs R2Ts handled while it owns the request.
v7.4-rc4: reject + error recovery in 6 of 15 runs
v7.4-rc4 + patch (*): no error in 15 of 15; R2T handled inside
the window in 10 of them
v6.18.65: 30 s timeout + reconnect in 10 of 15
v6.18.65 + backport: no error in 15 of 15; inside the window in 7
no delay (nvmet R2T helper and marker still on):
v7.4-rc4 reject in 1 of 10; other kernels 3 of 3 clean each
(*) plus our unrelated smc/autofs/serial/ufs fixes.
An identical early-boot KASAN report, before the test, occurs on unpatched (1 of 55 boots) and patched (4 of 67) v6.18.65 images, never on v7.4-rc4 (0 of 132): unrelated to the patch.
The no-delay hit was under QEMU TCG, not representative of real hardware timing. Untested: other targets, non-poll queues, digests, TLS. The send-path error branch was never triggered. Helpers, test program and logs on request.
Found by a formal code verification tool under development (Lean-based), with AI-assisted analysis; verified by the reproduction above and human review. The patch and this text were written with AI assistance and reviewed by a human. Point of contact: Zhenwen Liang <[email protected]>.
Public list archives, git history and syzbot show no earlier report, including in the 347d50d92e25 thread.
drivers/nvme/host/tcp.c | 93 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 83 insertions(+), 10 deletions(-)
drivers/nvme/host/tcp.c +83 -10
@@ -103,6 +103,11 @@ struct nvme_tcp_request {u32 h2cdata_left;u32 h2cdata_offset;u16 ttag; +/* R2T received but not yet set up by the send path */ +bool r2t_pending; +u16 r2t_ttag; +u32 r2t_offset; +u32 r2t_length;__le16 status;struct list_head entry;struct llist_node lentry;
@@ -823,6 +828,7 @@ static int nvme_tcp_handle_r2t(struct nvme_tcp_queue *queue,struct request *rq;u32 r2t_length =le32_to_cpu (pdu->r2t_length);u32 r2t_offset =le32_to_cpu (pdu->r2t_offset); +size_t data_sent; rq =nvme_find_rq (nvme_tcp_tagset (queue), pdu->command_id);if (!rq) {
@@ -847,17 +853,25 @@ static int nvme_tcp_handle_r2t(struct nvme_tcp_queue *queue,return -EPROTO ; } -if (unlikely (req->data_sent + r2t_length > req->data_len)) { +/* +* The send path may not have accounted the last bytes of the +* previous R2T yet, so data_sent can still be too small here (it is +* written by the send path, hence READ_ONCE()). data_sent only +* grows, so these checks never reject a valid R2T; +* nvme_tcp_setup_r2t() checks the R2T exactly. +*/ + data_sent =READ_ONCE (req->data_sent); +if (unlikely (data_sent + r2t_length > req->data_len)) {dev_err (queue->ctrl->ctrl.device,"req %d r2t len %u exceeded data len %u (%zu sent)\n" , - rq->tag, r2t_length, req->data_len, req->data_sent); + rq->tag, r2t_length, req->data_len, data_sent);return -EPROTO ; } -if (unlikely (r2t_offset != req->data_sent)) { +if (unlikely (r2t_offset < data_sent)) {dev_err (queue->ctrl->ctrl.device,"req %d unexpected r2t offset %u (expected %zu)\n" , - rq->tag, r2t_offset, req->data_sent); + rq->tag, r2t_offset, data_sent);return -EPROTO ; }
@@ -869,12 +883,18 @@ static int nvme_tcp_handle_r2t(struct nvme_tcp_queue *queue,return -EPROTO ; } - req->pdu_len =0 ; - req->h2cdata_left = r2t_length; - req->h2cdata_offset = r2t_offset; - req->ttag = pdu->ttag; - -nvme_tcp_setup_h2c_data_pdu (req); +/* +* The controller can send this R2T as soon as it has the last bytes +* of the previous one, while nvme_tcp_try_send_data() has not yet +* updated data_sent and pdu_sent for them. Do not touch the send +* state here; record the R2T and let nvme_tcp_try_send() set it up +* when it takes the request off the list. llist_add() orders these +* stores before the request is visible on req_list. +*/ +WRITE_ONCE (req->r2t_ttag, pdu->ttag); +WRITE_ONCE (req->r2t_offset, r2t_offset); +WRITE_ONCE (req->r2t_length, r2t_length); + req->r2t_pending = true;llist_add (&req->lentry, &queue->req_list);queue_work_on (queue->io_cpu, nvme_tcp_wq, &queue->io_work);
@@ -1401,20 +1421,72 @@ static int nvme_tcp_try_send_ddgst(struct nvme_tcp_request *req)return -EAGAIN ; } +static int nvme_tcp_setup_r2t (struct nvme_tcp_request *req) +{ +struct nvme_tcp_queue *queue = req->queue; +struct request *rq =blk_mq_rq_from_pdu (req); +/* +* Read the recorded R2T once: a controller that violates the protocol +* could send another R2T and rewrite these fields meanwhile. +*/ +u32 r2t_length =READ_ONCE (req->r2t_length); +u32 r2t_offset =READ_ONCE (req->r2t_offset); +u16 r2t_ttag =READ_ONCE (req->r2t_ttag); + + req->r2t_pending = false; + +if (unlikely (req->data_sent + r2t_length > req->data_len)) { +dev_err (queue->ctrl->ctrl.device, +"req %d r2t len %u exceeded data len %u (%zu sent)\n" , + rq->tag, r2t_length, req->data_len, req->data_sent); +return -EPROTO ; + } + +if (unlikely (r2t_offset != req->data_sent)) { +dev_err (queue->ctrl->ctrl.device, +"req %d unexpected r2t offset %u (expected %zu)\n" , + rq->tag, r2t_offset, req->data_sent); +return -EPROTO ; + } + + req->pdu_len =0 ; + req->h2cdata_left = r2t_length; + req->h2cdata_offset = r2t_offset; + req->ttag = r2t_ttag; + +nvme_tcp_setup_h2c_data_pdu (req); +return 0 ; +} +static int nvme_tcp_try_send (struct nvme_tcp_queue *queue) {struct nvme_tcp_request *req;unsigned int noreclaim_flag; +bool fetched = false;int ret =1 ;if (!queue->request) { queue->request =nvme_tcp_fetch_request (queue);if (!queue->request)return 0 ; + fetched = true; } req = queue->request; noreclaim_flag =memalloc_noreclaim_save (); +if (fetched && req->r2t_pending) { + ret =nvme_tcp_setup_r2t (req); +if (unlikely (ret)) { +/* +* Handle a bad R2T as the receive path does: leave +* the request to the error recovery. +*/ +nvme_tcp_done_send_req (queue); +nvme_tcp_error_recovery (&queue->ctrl->ctrl); + goto out; + } + } +if (req->state ==NVME_TCP_SEND_CMD_PDU ) { ret =nvme_tcp_try_send_cmd_pdu (req);if (ret <=0 )
@@ -3120,6 +3192,7 @@ static blk_status_t nvme_tcp_setup_cmd_pdu(struct nvme_ns *ns, req->pdu_len =0 ; req->pdu_sent =0 ; req->h2cdata_left =0 ; + req->r2t_pending = false; req->data_len =blk_rq_nr_phys_segments (rq) ?blk_rq_payload_bytes (rq) :0 ; req->curr_bio = rq->bio;
Signature · 1 line
2.56.1.809.ga0b61035b5-goog
[email protected]
AI reviewRe: [PATCH] nvme-tcp: set up R2T data transfer in the send path
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] nvme-tcp: r2t_pending race in nvme_tcp_handle_r2t() and nvme_tcp_setup_r2t() - [Medium] nvme-tcp…
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] nvme-tcp: r2t_pending race in nvme_tcp_handle_r2t() and nvme_tcp_setup_r2t()
- [Medium] nvme-tcp: 32-bit overflow in r2t_length check in nvme_tcp_setup_r2t()
- [Medium] nvme-tcp: use-after-completion on send error after nvme_tcp_handle_r2t()
--
commit 7be091feb52782cced17a5c0c1c30a0e41652084
Author: Zhenwen Liang <[email protected]>
nvme-tcp: set up R2T data transfer in the send path
This commit defers H2CData PDU setup and exact R2T validation from nvme_tcp_handle_r2t() in the receive path to nvme_tcp_try_send() in the send path so that R2T handling does not race with req->data_sent and req->pdu_sent updates after sock_sendmsg().
Quoted 4 lines
drivers/nvme/host/tcp.c +0
-0
[ ... ]
Quoted 45 lines
drivers/nvme/host/tcp.c +17
-10@@ -847,17 +853,25 @@ static int nvme_tcp_handle_r2t(struct nvme_tcp_queue *queue,return -EPROTO ; } -if (unlikely (req->data_sent + r2t_length > req->data_len)) { +/* +* The send path may not have accounted the last bytes of the +* previous R2T yet, so data_sent can still be too small here (it is +* written by the send path, hence READ_ONCE()). data_sent only +* grows, so these checks never reject a valid R2T; +* nvme_tcp_setup_r2t() checks the R2T exactly. +*/ + data_sent =READ_ONCE (req->data_sent); +if (unlikely (data_sent + r2t_length > req->data_len)) {dev_err (queue->ctrl->ctrl.device,"req %d r2t len %u exceeded data len %u (%zu sent)\n" , - rq->tag, r2t_length, req->data_len, req->data_sent); + rq->tag, r2t_length, req->data_len, data_sent);return -EPROTO ; } -if (unlikely (r2t_offset != req->data_sent)) { +if (unlikely (r2t_offset < data_sent)) {dev_err (queue->ctrl->ctrl.device,"req %d unexpected r2t offset %u (expected %zu)\n" , - rq->tag, r2t_offset, req->data_sent); + rq->tag, r2t_offset, data_sent);return -EPROTO ; }@@ -869,12 +883,18 @@ static int nvme_tcp_handle_r2t(struct nvme_tcp_queue *queue,return -EPROTO ; } - req->pdu_len =0 ; - req->h2cdata_left = r2t_length; - req->h2cdata_offset = r2t_offset; - req->ttag = pdu->ttag; - -nvme_tcp_setup_h2c_data_pdu (req); +/* +* The controller can send this R2T as soon as it has the last bytes +* of the previous one, while nvme_tcp_try_send_data() has not yet +* updated data_sent and pdu_sent for them. Do not touch the send +* state here; record the R2T and let nvme_tcp_try_send() set it up
drivers/nvme/host/tcp.c static int nvme_tcp_handle_r2t(struct nvme_tcp_queue *queue, · line 900
Quoted 10 lines
drivers/nvme/host/tcp.c +7
-0+* when it takes the request off the list. llist_add() orders these +* stores before the request is visible on req_list. +*/ +WRITE_ONCE (req->r2t_ttag, pdu->ttag); +WRITE_ONCE (req->r2t_offset, r2t_offset); +WRITE_ONCE (req->r2t_length, r2t_length); + req->r2t_pending = true;llist_add (&req->lentry, &queue->req_list);queue_work_on (queue->io_cpu, nvme_tcp_wq, &queue->io_work);
[Severity: Medium]
Can an early R2T leave a completed request linked on queue->req_list when a send fails?
While req is actively being sent as queue->request, both req->lentry and req->entry are empty. Relaxing the offset check to r2t_offset < data_sent allows an R2T with r2t_offset >= data_sent to pass while req is still mid-send (for instance paused across -EAGAIN or sending its data digest) and queue req->lentry onto queue->req_list. If the active send then fails with an error other than -EAGAIN, nvme_tcp_try_send() completes the request via nvme_tcp_fail_request(queue->request) while req->lentry is still on queue->req_list:
CPU0 (send path) CPU1 (recv path)nvme_tcp_try_send()
queue->request =
nvme_tcp_fetch_request(queue)
nvme_tcp_handle_r2t()
r2t_offset >= data_sent
llist_add(&req->lentry,
&queue->req_list)
nvme_tcp_try_send_data(req)
sock_sendmsg() -> -EPIPE nvme_tcp_fail_request(req)
nvme_tcp_end_request(rq, ...)
nvme_tcp_process_req_list()
<-- processes completed req
When queue->req_list is next drained, the completed request is processed again, or if its tag was reallocated and re-queued, queue->req_list forms a cycle.
Quoted 7 lines
drivers/nvme/host/tcp.c +3
-0@@ -1401,20 +1421,72 @@ static int nvme_tcp_try_send_ddgst(struct nvme_tcp_request *req)return -EAGAIN ; } +static int nvme_tcp_setup_r2t (struct nvme_tcp_request *req) +{ +struct nvme_tcp_queue *queue = req->queue;
drivers/nvme/host/tcp.c static int nvme_tcp_try_send_ddgst(struct nvme_tcp_request *req) · line 1436
Quoted 10 lines
drivers/nvme/host/tcp.c +10
-0+struct request *rq =blk_mq_rq_from_pdu (req); +/* +* Read the recorded R2T once: a controller that violates the protocol +* could send another R2T and rewrite these fields meanwhile. +*/ +u32 r2t_length =READ_ONCE (req->r2t_length); +u32 r2t_offset =READ_ONCE (req->r2t_offset); +u16 r2t_ttag =READ_ONCE (req->r2t_ttag); + + req->r2t_pending = false;
[Severity: Medium]
Can nvme_tcp_setup_r2t() race with a concurrent nvme_tcp_handle_r2t() and clear req->r2t_pending after req has been re-added to queue->req_list?
nvme_tcp_fetch_request() clears req->entry and req->lentry before nvme_tcp_setup_r2t() runs, and nvme_tcp_handle_r2t() only checks llist_on_list(&req->lentry) || !list_empty(&req->entry) (not req->r2t_pending or req->state == NVME_TCP_SEND_CMD_PDU). If a non-conforming controller sends another R2T in that window, nvme_tcp_handle_r2t() can overwrite the r2t_* fields and re-queue req on queue->req_list right before nvme_tcp_setup_r2t() sets req->r2t_pending = false:
CPU0 (send path) CPU1 (recv path)nvme_tcp_try_send()
nvme_tcp_fetch_request()
list_del_init(&req->entry)
init_llist_node(&req->lentry)
nvme_tcp_handle_r2t()
WRITE_ONCE(req->r2t_*, ...)
req->r2t_pending = true
llist_add(&req->lentry,
&queue->req_list)
nvme_tcp_setup_r2t()
req->r2t_pending = false <-- clobbers pending flag for queued reqBesides reading a torn combination of r2t_length, r2t_offset, and r2t_ttag or clobbering NVME_TCP_SEND_CMD_PDU before the initial command PDU is sent, the second fetch from queue->req_list sees req->r2t_pending == false, skips nvme_tcp_setup_r2t(), and re-enters the send state machine in the stale state of the finished transfer.
drivers/nvme/host/tcp.c static int nvme_tcp_try_send_ddgst(struct nvme_tcp_request *req) · line 1443
Quoted 7 lines
drivers/nvme/host/tcp.c +7
-0+ +if (unlikely (req->data_sent + r2t_length > req->data_len)) { +dev_err (queue->ctrl->ctrl.device, +"req %d r2t len %u exceeded data len %u (%zu sent)\n" , + rq->tag, r2t_length, req->data_len, req->data_sent); +return -EPROTO ; + }
[Severity: Medium]
Can req->data_sent + r2t_length wrap around on 32-bit architectures?
On 32-bit kernels size_t is 32 bits, so adding u32 r2t_length to req->data_sent (and to data_sent in nvme_tcp_handle_r2t()) can wrap around when req->data_sent > 0 and bypass the req->data_len check. nvme_tcp_setup_h2c_data_pdu() then sets req->pdu_len larger than the remaining payload bytes in the request; once nvme_tcp_try_send_data() sends the last actual payload byte (req_data_sent + ret == req_data_len), it stops calling nvme_tcp_advance_req(), so req->pdu_sent stops advancing and the send loop spins indefinitely.
Checking r2t_length > req->data_len - req->data_sent (after verifying req->data_sent <= req->data_len) avoids the overflow.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
PATCH v2 4/6 nvmet-fcloop: free the LS request when delivery fails
In reply to [email protected]From: Shao Mingyin <[email protected]>
fcloop_h2t_ls_req() allocates a fcloop_lsreq from lsreq_cache and hands it to nvmet_fc_rcv_ls_req(). That function only takes ownership on success and returns an error without invoking any completion callback when the target port is shutting down, the LS payload is too large, or the target has no free LS request slot. The error is returned as-is, so the fcloop_lsreq is leaked; every failed LS during a target port teardown or an LS slot exhaustion loses one slab object.
The target-to-host direction already frees the request when nvme_fc_rcv_ls_req() fails. Do the same here.
---
Changes in v2:
- Code and commit message unchanged; add Christoph Hellwig's Reviewed-by tag. Previous version: https://lore.kernel.org/all/[email protected]/
Tested on 7.3.0-next-20261030 (QEMU/TCG guest) with the fcloop loopback transport (nvme-fc host + nvmet-fc/fcloop target); no real FC HBA is required.
The -ESHUTDOWN error path is otherwise only hit in a sub-instruction teardown race, so it is exercised with two TEST-ONLY changes (not part of this patch): a debugfs knob that makes nvmet_fc_rcv_ls_req() return -ESHUTDOWN, and SLAB_NO_MERGE on lsreq_cache so the 72-byte fcloop_lsreq does not merge into a kmalloc cache. A stock host sends 120 Create Association LS with ctrl_loss_tmo=0 (each failure deletes the controller); the cache is shrunk afterwards, which only reclaims empty slabs:
unpatched patched lsreq_cache objects 0 -> 120 lsreq_cache objects stays 0 slabs 0 -> 4 slabs stay 0
drivers/nvme/target/fcloop.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/nvme/target/fcloop.c +2 -0
@@ -379,6 +379,8 @@ fcloop_h2t_ls_req(struct nvme_fc_local_port *localport, ret =nvmet_fc_rcv_ls_req (rport->targetport, rport, &tls_req->ls_rsp, lsreq->rqstaddr, lsreq->rqstlen); +if (ret) +kmem_cache_free (lsreq_cache, tls_req);return ret; }
Signature · 1 line
2.27.0
PATCH v2 5/6 nvmet-fc: reject duplicate queue IDs on Create Connection
In reply to [email protected]From: Shao Mingyin <[email protected]>
nvmet_fc_alloc_target_queue() stores the new queue with
WARN_ON(assoc->queues[qid]); assoc->queues[qid] = queue;
The queue ID comes straight from the Create Connection LS and is only checked against NVMET_NR_QUEUES. A remote initiator can send a second Create Connection for a queue ID that already exists, or send queue ID 0 which was already created as the admin queue by Create Association. The WARN fires and the old pointer is overwritten: the old queue's base reference is never put, so its workqueue, nvmet_sq and nvmet_cq are never released. For the admin queue this also leaves the controller reference unreachable from nvmet_fc_delete_target_assoc(), so the controller and its subsystem reference leak permanently.
Publish the queue with cmpxchg() and destroy the newly created queue if the slot is already taken, returning the normal queue allocation error to the initiator. This keeps the existing error path and makes both duplicate and admin queue IDs fail cleanly.
---
Changes in v2:
- Code and commit message unchanged; add Christoph Hellwig's Reviewed-by tag. Previous version: https://lore.kernel.org/all/[email protected]/
Tested on 7.3.0-next-20261030 (QEMU/TCG guest) with nvmet-fc over the fcloop loopback transport; no FC HBA or fabric is needed.
A misbehaving FC initiator sends a duplicate Create Connection for a queue ID that already exists, or for queue ID 0 which was already created as the admin queue by Create Association. A normal host never does this, so the initiator is emulated by driving raw LS requests through fcloop. The LS response and the target debugfs controller count after controller teardown are checked:
unpatched patched duplicate conn -> ACC + WARN duplicate conn -> RJT (0x03) ctrl1 dir leaked after delete ctrl1 dir gone after delete
drivers/nvme/target/fc.c | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-)
drivers/nvme/target/fc.c +11 -2
@@ -818,8 +818,17 @@ nvmet_fc_alloc_target_queue(struct nvmet_fc_tgt_assoc *assoc,if (ret) goto out_fail_iodlist; -WARN_ON (assoc->queues[qid]); - assoc->queues[qid] = queue; +/* +* Publish the queue only if the slot is still free. A Create +* Connection may arrive twice for the same queue ID, or with the +* admin queue ID that was created by Create Association; replacing +* the old pointer would leak that queue and its controller +* reference forever. +*/ +if (cmpxchg (&assoc->queues[qid],NULL , queue)) { +nvmet_sq_destroy (&queue->nvme_sq); + goto out_fail_iodlist; + }return queue;
Signature · 1 line
2.27.0
PATCH v2 6/6 nvmet: roll back queue bindings on connection failure
In reply to [email protected]From: Shao Mingyin <[email protected]>
nvmet_install_queue() publishes the SQ controller pointer before claiming the CQ. If the CQ is already connected, it leaves the SQ pointer and the controller reference taken for it behind on failure.
An install_queue() callback failure also leaves the CQ bound after clearing the SQ pointer. The reference taken in nvmet_install_queue() is in addition to the one the caller already holds: the caller's put releases the reference acquired before the call, while this one belongs to the CQ binding. It is not released on this path, so the controller stays alive and a Connect retry on the same queue keeps finding the stale binding.
Clear the tentative SQ binding and release the extra reference on a CQ conflict. On a transport installation failure, destroy the CQ binding as well, so its controller table entry and reference are released.
---
Changes in v2:
- Code and commit message unchanged; add Christoph Hellwig's Reviewed-by tag. Previous version: https://lore.kernel.org/all/[email protected]/
drivers/nvme/target/fabrics-cmd.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/nvme/target/fabrics-cmd.c +3 -0
@@ -216,6 +216,8 @@ static u16 nvmet_install_queue(struct nvmet_ctrl *ctrl, struct nvmet_req *req)if (old) {pr_warn ("queue already connected!\n" ); req->error_loc = offsetof(struct nvmf_connect_command , opcode); + req->sq->ctrl =NULL ; +nvmet_ctrl_put (ctrl);return NVME_SC_CONNECT_CTRL_BUSY |NVME_STATUS_DNR ; }
@@ -242,6 +244,7 @@ static u16 nvmet_install_queue(struct nvmet_ctrl *ctrl, struct nvmet_req *req) err: req->sq->ctrl =NULL ; +nvmet_cq_destroy (req->cq);return ret; }
Signature · 1 line
2.27.0
Quoted 8 lines · On Sat, 14 Nov 2026 02:02:45 +0800 (CST), [email protected] wrote:
The six patches fix independent error paths in the NVMe transports.
Patch 1 releases the target request in nvme-loop when SG setup fails.
nvmet_req_init()has already taken the queue, namespace and reservation references, and blk-mq retries the same request, so each failure leaked a set of references.[...]
Thanks, applied to nvme-7.4.
[1/6] nvme-loop: release the target request when SG setup fails
commit: f2937481c28033e10e8a29b8742a767e73c696df
[2/6] nvmet-tcp: only wait for in-capsule data for inline SGLs
commit: 9dac3b1aa2a99e126a5504b7f5bc781c8b2771e0
[3/6] nvme-tcp: require the R2T offset to match the data sent
commit: 347d50d92e25d4b9c50c5f5c1d8b727b9c88d12c
[4/6] nvmet-fcloop: free the LS request when delivery fails
commit: 8c1f99419b6cc51892e259497c8e10a5d079621a
[5/6] nvmet-fc: reject duplicate queue IDs on Create Connection
commit: 153eac284ebf68be74993643e9b2fe2f9b2b1d88
[6/6] nvmet: roll back queue bindings on connection failure
commit: 3f82752e089283eb8204b9d2ebd8246077031173--
Keith Busch <[email protected]>