Skip to contentSkip to conversation

net/nfc: fix skb ownership and NCI status errors

PATCH New Bin Luo (University of Electronic Science and Technology of China) 2 participants 5 messages Nov 23 – Nov 24

Subsystems (4)
lore
Share & tools
lore
#0 lore raw

v3 cover net/nfc: fix skb ownership and NCI status errors

Hi,

This series addresses the review feedback on the v2 NFC callback-ownership fix.

The issue was found by source inspection during a callback-ownership audit. The NCI receive path can pass a non-NULL skb together with an error to a data_exchange_cb_t callback. The audit found consumers and wrapper callbacks that returned or freed only on success, leaving the response skb unconsumed. It also found terminal Digital DEP error paths that freed exchange state without completing the callback, and an NCI status conversion that truncated negative errno values through __u8.

Both the baseline and v3 x86_64 kernels were fully built with NFC, Digital, NCI, HCI/SHDLC, NFC-SIM, virtual NCI, PN533, PN544, Microread, ST21NFCA, KASAN, and kmemleak enabled. All three full build logs contain no warning or error lines.

The QEMU TCG test ran 32 NCI 1.0 MIFARE exchanges with status 0x01. The harness provisioned the virtual controller and polling session, then ran AF_NFC operations with effective UID 65534. The baseline returned SO_ERROR=-240 instead of 16 and kmemleak reported 47 unreferenced objects. The v3 kernel returned SO_ERROR=16, reported no unreferenced objects, and produced no KASAN report.

A test-only KUnit overlay, not included in this series, ran ten callback tests covering Digital DEP completion, ST21NFCA callbacks, LLCP error release, NCI loopback and NCI-HCI errors, four HCI wrapper branches, and PN533 response aggregation with an injected allocation failure. All ten passed. Real NFC controller hardware was not exercised.

The final QEMU run used one vCPU. A two-vCPU KASAN boot hit an early enqueue_task_fair int3 before userspace; it did not reach the NFC tests.

Patch 1 documents the callback ownership contract and updates the affected consumers and providers, including terminal Digital DEP completion and fragment cleanup. Patch 2 keeps NCI data-status errno values signed.

Best regards,
Bin Luo

Bin Luo (University of Electronic Science and Technology of China) (2):
net/nfc: fix skb ownership on data exchange errors
nfc: preserve NCI data status error codes

 drivers/nfc/microread/microread.c |  3 +--
 drivers/nfc/pn533/pn533.c         |  1 +
 drivers/nfc/pn544/pn544.c         |  3 +--
 drivers/nfc/st21nfca/core.c       |  3 +--
 drivers/nfc/st21nfca/dep.c        | 26 ++++++++++++-------------
 include/net/nfc/nfc.h             |  5 ++++-
 net/nfc/digital_dep.c             | 32 ++++++++++++++-----------------
 net/nfc/hci/core.c                |  5 +++--
 net/nfc/llcp_core.c               |  4 +++-
 net/nfc/nci/core.c                |  1 +
 net/nfc/nci/data.c                |  8 ++++----
 net/nfc/nci/hci.c                 |  4 ++++
 net/nfc/rawsock.c                 |  5 ++++-
 13 files changed, 54 insertions(+), 46 deletions(-)

base-commit: 6628e7d4c6b25c8d18f1345e3a20d21829aae7e4

#1 lore raw

PATCH v3 1/2 net/nfc: fix skb ownership on data exchange errors

NFC data exchange callbacks may receive a non-NULL response skb together with an error. Several consumers return on error without releasing that skb because the ownership contract is not documented. Some provider callbacks free the skb only on success, while forwarding paths leave it with the upper-layer callback.

Document callback ownership and make affected paths release or consume the skb. Complete terminal Digital DEP failures through the registered callback, and drop queued NCI/HCI fragments when an exchange fails. Transfer PN533 responses to its queue before subsequent error handling.

Fixes 98ff416f97c5 ("NFC: nci: Add status byte management in case of error.")

---
v3:
- Audited the data_exchange_cb_t ownership paths across NFC, HCI, and NCI.
- Added cleanup for outstanding NCI/HCI fragments on failed completion.
- Routed terminal Digital DEP errors through the completion callback.
- Made PN533 response queue ownership explicit.

Validation:
- Both patches applied with git am on a clean tree at 6628e7d4c6b2.
- checkpatch --strict reported only UNKNOWN_COMMIT_ID because the local audit checkout is shallow; the Fixes commit itself was verified separately.
- Full baseline and v3 x86_64 builds passed with all modified NFC drivers enabled and no build warnings or errors.
- QEMU TCG ran 32 NCI status-error exchanges as euid 65534. Baseline SO_ERROR was -240 and kmemleak found 47 objects; v3 SO_ERROR was 16 with no unreferenced objects or KASAN report.
- Ten test-only KUnit callback tests passed, including PN533 response aggregation with an injected allocation failure. They are not part of this patch series. Real NFC hardware was not exercised. Final QEMU runs used one vCPU after a two-vCPU KASAN boot hit an early scheduler int3.

 drivers/nfc/microread/microread.c |  3 +--
 drivers/nfc/pn533/pn533.c         |  1 +
 drivers/nfc/pn544/pn544.c         |  3 +--
 drivers/nfc/st21nfca/core.c       |  3 +--
 drivers/nfc/st21nfca/dep.c        | 26 ++++++++++++-------------
 include/net/nfc/nfc.h             |  5 ++++-
 net/nfc/digital_dep.c             | 32 ++++++++++++++-----------------
 net/nfc/hci/core.c                |  5 +++--
 net/nfc/llcp_core.c               |  4 +++-
 net/nfc/nci/core.c                |  1 +
 net/nfc/nci/data.c                |  2 ++
 net/nfc/nci/hci.c                 |  4 ++++
 net/nfc/rawsock.c                 |  5 ++++-
 13 files changed, 52 insertions(+), 42 deletions(-)
drivers/nfc/microread/microread.c +1 -2
index 2bfafa94e..f221ec7b0 100644
@@ -383,8 +383,7 @@ static void microread_im_transceive_cb(void *context, struct sk_buff *skb,
 		info->async_cb(info->async_cb_context, skb, err);
 		break;
 	default:
-		if (err == 0)
-			kfree_skb(skb);
+		kfree_skb(skb);
 		break;
 	}
 }
drivers/nfc/pn533/pn533.c +1 -0
index b0133e51d..f7bdc0795 100644
@@ -2138,6 +2138,7 @@ static int pn533_data_exchange_complete(struct pn533 *dev, void *_arg,
 	}
 
 	skb_queue_tail(&dev->resp_q, resp);
+	resp = NULL;
 
 	if (mi) {
 		dev->cmd_complete_mi_arg = arg;
drivers/nfc/pn544/pn544.c +1 -2
index c4fa70e45..82f710798 100644
@@ -581,8 +581,7 @@ static void pn544_hci_data_exchange_cb(void *context, struct sk_buff *skb,
 		info->async_cb(info->async_cb_context, skb, err);
 		break;
 	default:
-		if (err == 0)
-			kfree_skb(skb);
+		kfree_skb(skb);
 		break;
 	}
 }
drivers/nfc/st21nfca/core.c +1 -2
index b5c1ca3ac..68327cafb 100644
@@ -743,8 +743,7 @@ static void st21nfca_hci_data_exchange_cb(void *context, struct sk_buff *skb,
 		info->async_cb(info->async_cb_context, skb, err);
 		break;
 	default:
-		if (err == 0)
-			kfree_skb(skb);
+		kfree_skb(skb);
 		break;
 	}
 }
drivers/nfc/st21nfca/dep.c +13 -13
index a5fab4fd5..c907b6eec 100644
@@ -449,11 +449,10 @@ static void st21nfca_im_recv_atr_res_cb(void *context, struct sk_buff *skb,
 	struct st21nfca_atr_res *atr_res;
 	int r;
 
-	if (err != 0)
-		return;
-
 	if (!skb)
 		return;
+	if (err)
+		goto out;
 
 	switch (info->async_cb_type) {
 	case ST21NFCA_CB_TYPE_READER_F:
@@ -463,7 +462,7 @@ static void st21nfca_im_recv_atr_res_cb(void *context, struct sk_buff *skb,
 				atr_res->gbi,
 				skb->len - sizeof(struct st21nfca_atr_res));
 		if (r < 0)
-			return;
+			goto out;
 
 		if (atr_res->to >= 0x0e)
 			info->dep_info.to = 0x0e;
@@ -475,7 +474,7 @@ static void st21nfca_im_recv_atr_res_cb(void *context, struct sk_buff *skb,
 		r = nfc_dep_link_is_up(info->hdev->ndev, info->dep_info.idx,
 					NFC_COMM_PASSIVE, NFC_RF_INITIATOR);
 		if (r < 0)
-			return;
+			goto out;
 
 		info->dep_info.curr_nfc_dep_pni = 0;
 		if (ST21NFCA_PP2LRI(atr_res->ppi) != info->dep_info.lri)
@@ -484,9 +483,11 @@ static void st21nfca_im_recv_atr_res_cb(void *context, struct sk_buff *skb,
 						ST21NFCA_PP2LRI(atr_res->ppi));
 		break;
 	default:
-		kfree_skb(skb);
 		break;
 	}
+
+out:
+	kfree_skb(skb);
 }
 
 int st21nfca_im_send_atr_req(struct nfc_hci_dev *hdev, u8 *gb, size_t gb_len)
@@ -561,11 +562,10 @@ static void st21nfca_im_recv_dep_res_cb(void *context, struct sk_buff *skb,
 
 	int size;
 
-	if (err != 0)
-		return;
-
 	if (!skb)
 		return;
+	if (err)
+		goto exit;
 
 	switch (info->async_cb_type) {
 	case ST21NFCA_CB_TYPE_READER_F:
@@ -596,7 +596,7 @@ static void st21nfca_im_recv_dep_res_cb(void *context, struct sk_buff *skb,
 			size++;
 			skb_pull(skb, size);
 			nfc_tm_data_received(info->hdev->ndev, skb);
-			break;
+			return;
 		case ST21NFCA_NFC_DEP_PFB_SUPERVISOR_PDU:
 			pr_err("Received a SUPERVISOR PDU\n");
 			skb_pull(skb, size);
@@ -606,10 +606,10 @@ static void st21nfca_im_recv_dep_res_cb(void *context, struct sk_buff *skb,
 			*(u8 *)skb_push(skb, 1) = info->dep_info.to | 0x10;
 
 			st21nfca_im_send_pdu(info, skb);
-			break;
+			return;
+		default:
+			goto exit;
 		}
-
-		return;
 	default:
 		break;
 	}
include/net/nfc/nfc.h +4 -1
index bcafab5c5..bdf2ac30a 100644
@@ -31,12 +31,15 @@ struct nfc_dev;
  * data_exchange_cb_t - Definition of nfc_data_exchange callback
  *
  * @context: nfc_data_exchange cb_context parameter
- * @skb: response data
+ * @skb: response data, owned by the callback if non-NULL
  * @err: If an error has occurred during data exchange, it is the
  *	error number. Zero means no error.
  *
  * When a rx or tx package is lost or corrupted or the target gets out
  * of the operating field, err is -EIO.
+ * If skb is non-NULL, the callback owns it regardless of err and must free
+ * or otherwise consume it. Providers must not access or free it after the
+ * callback returns.
  */
 typedef void (*data_exchange_cb_t)(void *context, struct sk_buff *skb,
 								int err);
net/nfc/digital_dep.c +14 -18
index 968547c30..cd6eff012 100644
@@ -703,7 +703,7 @@ static void digital_in_recv_dep_res(struct nfc_digital_dev *ddev, void *arg,
 
 			rc = digital_in_send_nack(ddev, data_exch);
 			if (rc)
-				goto error;
+				goto exit;
 
 			return;
 		} else if ((rc == -ETIMEDOUT) &&
@@ -712,7 +712,7 @@ static void digital_in_recv_dep_res(struct nfc_digital_dev *ddev, void *arg,
 
 			rc = digital_in_send_atn(ddev, data_exch);
 			if (rc)
-				goto error;
+				goto exit;
 
 			return;
 		}
@@ -734,7 +734,7 @@ static void digital_in_recv_dep_res(struct nfc_digital_dev *ddev, void *arg,
 
 			rc = digital_in_send_nack(ddev, data_exch);
 			if (rc)
-				goto error;
+				goto exit;
 
 			kfree_skb(resp);
 
@@ -742,7 +742,7 @@ static void digital_in_recv_dep_res(struct nfc_digital_dev *ddev, void *arg,
 		}
 
 		PROTOCOL_ERR("14.4.1.6");
-		goto error;
+		goto exit;
 	}
 
 	ddev->atn_count = 0;
@@ -759,7 +759,7 @@ static void digital_in_recv_dep_res(struct nfc_digital_dev *ddev, void *arg,
 	if (resp->len < size || dep_res->dir != DIGITAL_NFC_DEP_FRAME_DIR_IN ||
 	    dep_res->cmd != DIGITAL_CMD_DEP_RES) {
 		rc = -EIO;
-		goto error;
+		goto exit;
 	}
 
 	pfb = dep_res->pfb;
@@ -767,7 +767,7 @@ static void digital_in_recv_dep_res(struct nfc_digital_dev *ddev, void *arg,
 	if (DIGITAL_NFC_DEP_DID_BIT_SET(pfb)) {
 		PROTOCOL_ERR("14.8.2.1");
 		rc = -EIO;
-		goto error;
+		goto exit;
 	}
 
 	if (DIGITAL_NFC_DEP_NAD_BIT_SET(pfb)) {
@@ -777,7 +777,7 @@ static void digital_in_recv_dep_res(struct nfc_digital_dev *ddev, void *arg,
 
 	if (size > resp->len) {
 		rc = -EIO;
-		goto error;
+		goto exit;
 	}
 
 	skb_pull(resp, size);
@@ -787,7 +787,7 @@ static void digital_in_recv_dep_res(struct nfc_digital_dev *ddev, void *arg,
 		if (DIGITAL_NFC_DEP_PFB_PNI(pfb) != ddev->curr_nfc_dep_pni) {
 			PROTOCOL_ERR("14.12.3.3");
 			rc = -EIO;
-			goto error;
+			goto exit;
 		}
 
 		ddev->curr_nfc_dep_pni =
@@ -802,7 +802,7 @@ static void digital_in_recv_dep_res(struct nfc_digital_dev *ddev, void *arg,
 		if (IS_ERR(resp)) {
 			rc = PTR_ERR(resp);
 			resp = NULL;
-			goto error;
+			goto exit;
 		}
 
 		/* If resp is NULL then we're still chaining so return and
@@ -847,7 +847,7 @@ static void digital_in_recv_dep_res(struct nfc_digital_dev *ddev, void *arg,
 					     ddev->chaining_skb,
 					     ddev->data_exch);
 		if (rc)
-			goto error;
+			goto exit;
 
 		goto free_resp;
 
@@ -855,7 +855,7 @@ static void digital_in_recv_dep_res(struct nfc_digital_dev *ddev, void *arg,
 		if (!DIGITAL_NFC_DEP_PFB_IS_TIMEOUT(pfb)) { /* ATN */
 			rc = digital_in_send_saved_skb(ddev, data_exch);
 			if (rc)
-				goto error;
+				goto exit;
 
 			goto free_resp;
 		}
@@ -863,19 +863,19 @@ static void digital_in_recv_dep_res(struct nfc_digital_dev *ddev, void *arg,
 		if (ddev->atn_count || ddev->nack_count) {
 			PROTOCOL_ERR("14.12.4.4");
 			rc = -EIO;
-			goto error;
+			goto exit;
 		}
 
 		rtox = DIGITAL_NFC_DEP_RTOX_VALUE(resp->data[0]);
 		if (!rtox || rtox > DIGITAL_NFC_DEP_RTOX_MAX) {
 			PROTOCOL_ERR("14.8.4.1");
 			rc = -EIO;
-			goto error;
+			goto exit;
 		}
 
 		rc = digital_in_send_rtox(ddev, data_exch, rtox);
 		if (rc)
-			goto error;
+			goto exit;
 
 		goto free_resp;
 	}
@@ -883,7 +883,6 @@ static void digital_in_recv_dep_res(struct nfc_digital_dev *ddev, void *arg,
 exit:
 	data_exch->cb(data_exch->cb_context, resp, rc);
 
-error:
 	kfree(data_exch);
 
 	kfree_skb(ddev->chaining_skb);
@@ -892,9 +891,6 @@ static void digital_in_recv_dep_res(struct nfc_digital_dev *ddev, void *arg,
 	kfree_skb(ddev->saved_skb);
 	ddev->saved_skb = NULL;
 
-	if (rc)
-		kfree_skb(resp);
-
 	return;
 
 free_resp:
net/nfc/hci/core.c +3 -2
index ba6f0310f..0557fa3fd 100644
@@ -713,8 +713,7 @@ static void hci_transceive_cb(void *context, struct sk_buff *skb, int err)
 		hdev->async_cb(hdev->async_cb_context, skb, err);
 		break;
 	default:
-		if (err == 0)
-			kfree_skb(skb);
+		kfree_skb(skb);
 		break;
 	}
 }
@@ -833,6 +832,7 @@ static int hci_se_io(struct nfc_dev *nfc_dev, u32 se_idx,
 
 static void nfc_hci_failure(struct nfc_hci_dev *hdev, int err)
 {
+	skb_queue_purge(&hdev->rx_hcp_frags);
 	mutex_lock(&hdev->msg_tx_mutex);
 
 	if (hdev->cmd_pending_msg == NULL) {
@@ -862,6 +862,7 @@ static void nfc_hci_recv_from_llc(struct nfc_hci_dev *hdev, struct sk_buff *skb)
 	int msg_len;
 
 	if (!pskb_may_pull(skb, NFC_HCI_HCP_PACKET_HEADER_LEN)) {
+		skb_queue_purge(&hdev->rx_hcp_frags);
 		kfree_skb(skb);
 		return;
 	}
net/nfc/llcp_core.c +3 -1
index 74bf81700..0736a0ed3 100644
@@ -1636,8 +1636,10 @@ void nfc_llcp_recv(void *data, struct sk_buff *skb, int err)
 {
 	struct nfc_llcp_local *local = (struct nfc_llcp_local *) data;
 
-	if (err < 0) {
+	if (err) {
 		pr_err("LLCP PDU receive err %d\n", err);
+		if (skb)
+			kfree_skb(skb);
 		return;
 	}
 
net/nfc/nci/core.c +1 -0
index 73e3a9647..678f744a2 100644
@@ -413,6 +413,7 @@ static void nci_nfcc_loopback_cb(void *context, struct sk_buff *skb, int err)
 
 	conn_info = nci_get_conn_info_by_conn_id(ndev, ndev->cur_conn_id);
 	if (!conn_info) {
+		kfree_skb(skb);
 		nci_req_complete(ndev, NCI_STATUS_REJECTED);
 		return;
 	}
net/nfc/nci/data.c +2 -0
index 4253edea5..3bbebb950 100644
@@ -220,6 +220,8 @@ static void nci_add_rx_data_frag(struct nci_dev *ndev,
 
 	if (status) {
 		err = status;
+		kfree_skb(ndev->rx_data_reassembly);
+		ndev->rx_data_reassembly = NULL;
 		goto exit;
 	}
 
net/nfc/nci/hci.c +4 -0
index c03e8a0bd..a67bf6a72 100644
@@ -435,11 +435,14 @@ void nci_hci_data_received_cb(void *context,
 	int msg_len;
 
 	if (err) {
+		skb_queue_purge(&ndev->hci_dev->rx_hcp_frags);
+		kfree_skb(skb);
 		nci_req_complete(ndev, err);
 		return;
 	}
 
 	if (!pskb_may_pull(skb, NCI_HCI_HCP_PACKET_HEADER_LEN)) {
+		skb_queue_purge(&ndev->hci_dev->rx_hcp_frags);
 		kfree_skb(skb);
 		return;
 	}
@@ -464,6 +467,7 @@ void nci_hci_data_received_cb(void *context,
 		hcp_skb = nfc_alloc_recv_skb(NCI_HCI_HCP_PACKET_HEADER_LEN +
 					     msg_len, GFP_KERNEL);
 		if (!hcp_skb) {
+			skb_queue_purge(&ndev->hci_dev->rx_hcp_frags);
 			nci_req_complete(ndev, -ENOMEM);
 			return;
 		}
net/nfc/rawsock.c +4 -1
index f7d7a599f..3bf65b1fb 100644
@@ -156,8 +156,11 @@ static void rawsock_data_exchange_complete(void *context, struct sk_buff *skb,
 
 	pr_debug("sk=%p err=%d\n", sk, err);
 
-	if (err)
+	if (err) {
+		if (skb)
+			kfree_skb(skb);
 		goto error;
+	}
 
 	err = rawsock_add_header(skb);
 	if (err)

base-commit: 6628e7d4c6b25c8d18f1345e3a20d21829aae7e4

#2 lore raw

Re: [PATCH v3 1/2] net/nfc: fix skb ownership on data exchange errors

Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider.

Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider.

Critical: 0 · High: 1 (2) · Medium: 4 · Low: 0 (1)

If you believe none of the issues are legitimate, please reply to each issue of Medium severity or higher and explain why the AI is wrong. If any of them are legitimate and you plan to respin, please let patchwork know by including "pw-bot: cr" as a separate line at the end of your reply (one such reply per series is enough).

- [High] The patch adds skb_queue_purge(&hdev->rx_hcp_frags) at the top of nfc_hci_failure(), before any lock is taken.
- [Medium] The commit message describes the patch's most serious hunks inaccurately, and the single Fixes: 98ff416f97c5 tag covers only the…
- [Medium] The patch routes terminal Digital DEP failures through the registered callback and edits the PN533 exchange state machine, but it…
- [Medium] The commit message says queued NCI/HCI fragments are dropped "when an exchange fails", but the timeout failure paths still keep…
- [Medium] The new skb_queue_purge(&ndev->hci_dev->rx_hcp_frags) in the if (err) branch of nci_hci_data_received_cb() can run in process…

Pre-existing issues:
- [High] This problem wasn't introduced by this patch, but nci_nfcc_loopback_cb() ignores err.
- [High] This problem wasn't introduced by this patch, but nci_data_exchange_complete() only calls a connection's…
- [Low] Concern: NCI data status errnos are truncated through a __u8 parameter, so a positive value reaches data_exchange_cb_t and SO_ERROR…

--

net/nfc: fix skb ownership on data exchange errors

The patch documents that a data_exchange_cb_t callback owns a non-NULL response skb whatever the value of err. It updates HCI, NCI, LLCP, rawsock and several drivers to free or consume that skb on error. It also sends terminal Digital DEP errors through the completion callback, purges pending NCI/HCI fragments on failure, and clears the PN533 resp pointer once resp has been queued.

Quoted 6 lines

Document callback ownership and make affected paths release or consume the skb. Complete terminal Digital DEP failures through the registered callback, and drop queued NCI/HCI fragments when an exchange fails. Transfer PN533 responses to its queue before subsequent error handling.

Fixes 98ff416f97c5 ("NFC: nci: Add status byte management in case of error.")

[Severity: Medium]
The message seems to undersell what several hunks fix. Also, the single Fixes tag only matches the status hunk in nci_add_rx_data_frag().

Before this patch, pn533_data_exchange_complete() queued resp on dev->resp_q. If pn533_build_response() then failed alloc_skb(), its out:
label purged resp_q, which freed resp:

pn533_build_response()

    skb = alloc_skb(skb_len, GFP_KERNEL);
    if (skb == NULL)
        goto out;
    ...
out:
    skb_queue_purge(&dev->resp_q);

The caller then took goto error and called dev_kfree_skb(resp) on the freed skb. The new resp = NULL fixes that double free, but the message only says "Transfer PN533 responses to its queue".

In digital_in_recv_dep_res(), the old goto error paths skipped data_exch->cb(). That meant rawsock_data_exchange_complete() never called sock_put(), so the socket reference leaked and tx_work_scheduled stayed true.

In st21nfca_im_recv_atr_res_cb(), only the default case freed the skb. So the ATR_RES skb leaked on every successful READER_F exchange. The new
out: kfree_skb(skb) fixes that success-path leak, and the message doesn't mention it.

None of these appear to come from 98ff416f97c5. Could the message describe the double free, the socket reference leak and the success-path leak? Could it also carry Fixes tags for the commits that introduced them?

drivers/nfc/pn533/pn533.c static int pn533_data_exchange_complete(struct pn533 *dev, void *_arg, · line 2144

Quoted 12 lines
drivers/nfc/pn533/pn533.c +1 -0
index b0133e51dce96..f7bdc07951741 100644
@@ -2138,6 +2138,7 @@ static int pn533_data_exchange_complete(struct pn533 *dev, void *_arg,
 	}
 
 	skb_queue_tail(&dev->resp_q, resp);
+	resp = NULL;
 
 	if (mi) {
 		dev->cmd_complete_mi_arg = arg;

[Severity: Medium]
While this state machine is being changed, what happens to arg when the multi-frame workers fail?

pn533_data_exchange_complete() hands arg to mi_rx_work or mi_tx_work and returns -EINPROGRESS. If pn533_send_cmd_direct_async() fails in pn533_wq_mi_recv(), it does:

    dev_kfree_skb(skb);
    kfree(dev->cmd_complete_mi_arg);

error:

    dev->phy_ops->send_ack(dev, GFP_KERNEL);
    queue_work(dev->wq, &dev->cmd_work);

pn533_wq_mi_send() does the same with kfree(dev->cmd_complete_dep_arg). A pn533_alloc_skb() failure in mi_recv, or skb == NULL in mi_send, jumps to error: without freeing arg at all.

Neither path calls arg->cb, and neither purges dev->resp_q. Doesn't that mean rawsock_data_exchange_complete() never runs, so the sock_hold() reference from rawsock_tx_work() leaks and tx_work_scheduled stays set?

The partial responses left in resp_q would also be joined into the next exchange's response by pn533_build_response().

This patch fixes the same kind of problem for Digital DEP.

[ ... ]

Quoted 4 lines
net/nfc/hci/core.c +0 -0
index ba6f0310ffd7c..0557fa3fd42b6 100644

[ ... ]

net/nfc/hci/core.c static int hci_se_io(struct nfc_dev *nfc_dev, u32 se_idx, · line 838

Quoted 8 lines
net/nfc/hci/core.c +1 -0
@@ -833,6 +832,7 @@ static int hci_se_io(struct nfc_dev *nfc_dev, u32 se_idx,
 
 static void nfc_hci_failure(struct nfc_hci_dev *hdev, int err)
 {
+	skb_queue_purge(&hdev->rx_hcp_frags);
 	mutex_lock(&hdev->msg_tx_mutex);
 
 	if (hdev->cmd_pending_msg == NULL) {

[Severity: High]
Can this purge race with the fragment reassembly in nfc_hci_recv_from_llc()?

nfc_hci_failure() is reached through nfc_hci_driver_failure() from nfc_hci_event_received(). That function runs in hdev->msg_rx_work, because every non-response HCP message is queued to msg_rx_queue. Any event handling error ends up here, for example an unknown event (-EINVAL) or a TARGET_DISCOVERED event with a non-zero status (-EPROTO):

nfc_hci_msg_rx_work()
nfc_hci_event_received()

    nfc_hci_driver_failure()
      nfc_hci_failure()
        skb_queue_purge(&hdev->rx_hcp_frags)

At the same time, nfc_hci_recv_from_llc() runs in the LLC receive
context: shdlc sm_work, or the driver's receive thread for llc_nop. It walks rx_hcp_frags without the queue lock and does a sleeping allocation between the two walks:

    skb_queue_walk(&hdev->rx_hcp_frags, frag_skb) {
        msg_len += (frag_skb->len -
                    NFC_HCI_HCP_PACKET_HEADER_LEN);
    }

    hcp_skb = nfc_alloc_recv_skb(NFC_HCI_HCP_PACKET_HEADER_LEN +
                                 msg_len, GFP_KERNEL);
    ...
    skb_queue_walk(&hdev->rx_hcp_frags, frag_skb) {
        msg_len = frag_skb->len - NFC_HCI_HCP_PACKET_HEADER_LEN;
        skb_put_data(hcp_skb,
                     frag_skb->data + NFC_HCI_HCP_PACKET_HEADER_LEN,
                     msg_len);
    }

msg_tx_mutex is only taken after the purge, so nothing orders the two sides. Could the purge free frag_skb while the walk is still reading frag_skb->len, frag_skb->data and frag_skb->next?

Before this patch, rx_hcp_frags was only changed at runtime from the receive context.

[ ... ]

net/nfc/nci/core.c static void nci_nfcc_loopback_cb(void *context, struct sk_buff *skb, int err) · line 419

Quoted 12 lines
net/nfc/nci/core.c +1 -0
index 73e3a96470ace..678f744a20795 100644
@@ -413,6 +413,7 @@ static void nci_nfcc_loopback_cb(void *context, struct sk_buff *skb, int err)
 
 	conn_info = nci_get_conn_info_by_conn_id(ndev, ndev->cur_conn_id);
 	if (!conn_info) {
+		kfree_skb(skb);
 		nci_req_complete(ndev, NCI_STATUS_REJECTED);
 		return;
 	}

[Severity: High]
This is a pre-existing issue, but since this callback is being touched:
nci_nfcc_loopback_cb() ignores err. When conn_info is found, it still does this even if skb is NULL:

    conn_info->rx_skb = skb;

    nci_req_complete(ndev, NCI_STATUS_OK);

Three paths can call the callback with a NULL skb and an error:

- nci_core_conn_intf_error_ntf_packet(), with a conn_id supplied by the NFCC and -EIO
- the skb_cow_head() failure in nci_add_rx_data_frag(), with -ENOMEM
- the data timeout path

nci_nfcc_loopback() then does:

    if (r == NCI_STATUS_OK && resp)
        *resp = conn_info->rx_skb;

It returns 0 with *resp == NULL, and st_nci_loopback() only checks r < 0:

    r = nci_nfcc_loopback(ndev, data, data_len, &skb);
    if (r < 0)
        return r;

    msg = nfc_vendor_cmd_alloc_reply_skb(dev, ST_NCI_VENDOR_OUI,
                                         LOOPBACK, skb->len);

Can this dereference a NULL skb in the st-nci LOOPBACK vendor command? It needs a pending RF nci_transceive() so that NCI_DATA_EXCHANGE is set.

Should the callback pass on err instead of reporting NCI_STATUS_OK?

net/nfc/nci/data.c static void nci_add_rx_data_frag(struct nci_dev *ndev, · line 227

Quoted 13 lines
net/nfc/nci/data.c +2 -0
index 4253edea5c8db..3bbebb9505545 100644
@@ -220,6 +220,8 @@ static void nci_add_rx_data_frag(struct nci_dev *ndev,
 
 	if (status) {
 		err = status;
+		kfree_skb(ndev->rx_data_reassembly);
+		ndev->rx_data_reassembly = NULL;
 		goto exit;
 	}
 

[Severity: Medium]
The commit message says queued fragments are dropped "when an exchange fails". Do the timeout paths still keep them, though?

In nci_rx_work(), the data timeout completes the exchange without touching ndev->rx_data_reassembly:

    if (test_bit(NCI_DATA_EXCHANGE, &ndev->flags))
        nci_data_exchange_complete(ndev, NULL,
                                   ndev->cur_conn_id,
                                   -ETIMEDOUT);

Suppose the NFCC sent PBF_CONT segments and never sent the final one. The stale partial skb then stays in rx_data_reassembly, and later in nci_add_rx_data_frag() it is prepended to the first segment of the next exchange:

    if (ndev->rx_data_reassembly) {
        reassembly_len = ndev->rx_data_reassembly->len;

Only a later deactivate notification clears it.

In the same way, the command timeout in nfc_hci_msg_tx_work() completes with this and leaves hdev->rx_hcp_frags alone:

    hdev->cmd_pending_msg->cb(hdev->cmd_pending_msg->cb_context, NULL, -ETIME);

net/nfc/nci/hci.c void nci_hci_data_received_cb(void *context, · line 438

Quoted 9 lines
net/nfc/nci/hci.c +1 -0
index c03e8a0bd3bd6..a67bf6a72a706 100644
@@ -435,11 +435,14 @@ void nci_hci_data_received_cb(void *context,
 	int msg_len;
 
 	if (err) {
+		skb_queue_purge(&ndev->hci_dev->rx_hcp_frags);

[Severity: Medium]
Can this purge run at the same time as the reassembly further down in this function?

nci_close_device() completes a pending exchange under req_lock, but it only flushes rx_wq after unlocking:

    if (test_bit(NCI_DATA_EXCHANGE, &ndev->flags))
        nci_data_exchange_complete(ndev, NULL, ndev->cur_conn_id,
                                   -ENODEV);
    ...
    mutex_unlock(&ndev->req_lock);

    /* rx_work may take req_lock via nci_deactivate_target */
    flush_workqueue(ndev->rx_wq);

If cur_conn_id is the HCI connection, this calls nci_hci_data_received_cb(ndev, NULL, -ENODEV) from process context. The new skb_queue_purge() could then free fragments while rx_work is in the lockless skb_queue_walk() / nfc_alloc_recv_skb(GFP_KERNEL) sequence of the same function.

Getting there takes a contrived sequence. rx_work has to win the NCI_DATA_EXCHANGE bit for HCI data, another nci_transceive() has to set the bit again, and cur_conn_id has to move back to the HCI connection. Nothing seems to prevent it, though.

net/nfc/nci/hci.c void nci_hci_data_received_cb(void *context, · line 440

Quoted 2 lines
net/nfc/nci/hci.c +1 -0
+		kfree_skb(skb);
 		nci_req_complete(ndev, err);

[Severity: Low]
This isn't a bug introduced by this patch, but err is already an errno at this point. nci_req_complete() stores it in req_result, and __nci_request() then passes it through nci_to_errno() a second time.

This only changes which errno gets reported. Is that intended?

The original concern, that NCI data status errnos were truncated through a __u8 parameter, looks to be fixed by the follow-up patch in this series, "nfc: preserve NCI data status error codes", which changes the parameter to int err.

net/nfc/nci/hci.c void nci_hci_data_received_cb(void *context, · line 442

Quoted 2 lines
net/nfc/nci/hci.c +0 -0
 		return;
 	}

[Severity: High]
This is a pre-existing issue, but how often does this callback actually run? nci_data_exchange_complete() only calls the connection's data_exchange_cb when it wins the NCI_DATA_EXCHANGE bit:

    if (!test_and_clear_bit(NCI_DATA_EXCHANGE, &ndev->flags)) {
        kfree_skb(skb);
        return;
    }

Commit 8265a626cc14 added that gate. The only place the bit is set is nci_transceive(), for the RF connection:

    if (test_and_set_bit(NCI_DATA_EXCHANGE, &ndev->flags)) {

NCI HCI traffic (nci_hci_send_data()->nci_send_data()) never sets it, and neither does NFCC loopback (nci_send_data_req()->nci_send_data()). So their responses are freed, nci_hci_data_received_cb() and nci_nfcc_loopback_cb() never run, and the nci_request() callers time out.

If an RF transceive happens to be pending, an HCI or loopback completion takes the RF exchange's bit instead, and the RF exchange loses its completion.

It also means the new error-path cleanup here is only reachable in that cross-connection case.

[ ... ]

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261123063310.1267-1-luob87709%40gmail.com
#3 lore raw

PATCH v3 2/2 nfc: preserve NCI data status error codes

In reply to Bin Luo (University of Electronic Science and Technology of China)

nci_to_errno() returns negative errno values for nonzero data-status bytes. Passing that value to nci_add_rx_data_frag() through a __u8 parameter truncates the errno and changes it to an unrelated positive value before the completion callback receives it.

Keep the error parameter as int so the original errno reaches the completion path unchanged.

Fixes 98ff416f97c5 ("NFC: nci: Add status byte management in case of error.")

---
v3:
- Split the signed NCI status errno correction into a separate patch.

 net/nfc/nci/data.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)
net/nfc/nci/data.c +2 -4
index 3bbebb950..4a2326a33 100644
@@ -213,13 +213,11 @@ EXPORT_SYMBOL(nci_send_data);
 
 static void nci_add_rx_data_frag(struct nci_dev *ndev,
 				 struct sk_buff *skb,
-				 __u8 pbf, __u8 conn_id, __u8 status)
+				 __u8 pbf, __u8 conn_id, int err)
 {
 	int reassembly_len;
-	int err = 0;
 
-	if (status) {
-		err = status;
+	if (err) {
 		kfree_skb(ndev->rx_data_reassembly);
 		ndev->rx_data_reassembly = NULL;
 		goto exit;
#4 lore raw

Re: [PATCH v3 2/2] nfc: preserve NCI data status error codes

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you…

Thank you for your contribution! Sashiko AI review found more severe issue(s) in other patches of this series. This mail is only an FYI, in case you want to address the nit picks below when you respin.

Low priority / nit picks for your consideration:

- [Low] The commit message leaves out the user-visible effect of the bug, even though the patch is tagged Cc: stable.

--

nfc: preserve NCI data status error codes

This commit changes the status parameter of nci_add_rx_data_frag() from __u8 to int. The negative errno returned by nci_to_errno() then reaches the data exchange completion path without being truncated.

Quoted 4 lines

nci_to_errno() returns negative errno values for nonzero data-status bytes. Passing that value to nci_add_rx_data_frag() through a __u8 parameter truncates the errno and changes it to an unrelated positive value before the completion callback receives it.

[Severity: Low]
This isn't a bug in the code change. Since the patch is tagged for stable, though, could the commit message say what userspace actually sees?

For frame-interface targets, nci_rx_data_packet() makes this call:

    nci_add_rx_data_frag(ndev, skb, pbf, conn_id, nci_to_errno(status));

With the old __u8 parameter, -EPROTO (-71) became 185 and -ETIMEDOUT (-110) became 146.

On raw NFC sockets, that positive err takes this path:

nci_data_exchange_complete()
rawsock_data_exchange_complete()
rawsock_report_error()

rawsock_report_error() then does this:

    sk->sk_err = -err;

As a result, sk_err ends up negative (-185).

In __skb_try_recv_datagram(), sock_error() returns -sk_err, which is +185. __skb_recv_datagram() stops retrying because the value is not -EAGAIN. rawsock_recvmsg() then returns the value unchanged:

    skb = skb_recv_datagram(sk, flags, &rc);
    if (!skb)
        return rc;

So before this patch, recvmsg() returns 185 and copies nothing, instead of returning an error. With the patch applied it returns -EPROTO.

Would it help stable reviewers to add a sentence like this? "For example, for raw NFC sockets this sets a negative sk_err, so recvmsg() returns a bogus positive byte count with no data instead of an error."

Signature · 1 line
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261123063310.1267-1-luob87709%40gmail.com