Skip to contentSkip to conversation

6.18.66-rc1 review

PATCH In review Greg Kroah-Hartman 3 participants 995 messages Nov 25 Page 7 of 9

Subsystems (3)
lore
Share & tools
lore
author maintainer
#638 lore raw

PATCH 637/990 tls: keep TX and RX hardware offload on the same device

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Rishikesh Jethwani <[email protected]>

[ Upstream commit 1c8a70075235cd733095532a97f2405037c52a7b ]

After TX is offloaded on device A, a route change, or a change in the usable-slave set of an 802.3ad or balance-xor (layer3+4) bond, can make RX setup program device B. tls_device_attach() sees the existing TLS destructor and keeps ctx->netdev pointing at A. The RX driver state on B is then untracked: tls_dev_resync() and tls_dev_del() are invoked on A for a context it never created, and neither socket close nor NETDEV_DOWN on B calls tls_dev_del() for B, so the driver context leaks. The reverse setup order has the same problem.

Check the shared device binding under device_offload_lock before each tls_dev_add(). Permit the first attachment and a second direction on the same device. Reject a different device, including when the old binding was cleared by NETDEV_DOWN: the TLS destructor remains installed and tls_device_attach() cannot establish a new binding. Setup then falls back to software for the requested direction.

The RX check precedes allocation and software setup. TX uses its existing resource unwind path without calling the driver. Document the shared binding and clarify that fallback is per direction.

This issue was discovered during code review and subsequently reproduced on hardware using mlx5 and TLS 1.2 AES-GCM-128.

Changing the route between TX and RX setup installed the second direction on a different device. Driver traces showed successful adds on both devices, but both deletes at socket close targeted the first device, leaving an orphaned context on the second. Both setup orders reproduced the leak, even though all current core TLS context counters returned to zero. No crash was observed.

With the fix, the same tests correctly fall back to software for the second direction and leave no orphaned hardware context.

Fixes 4799ac81e52a ("tls: Add rx inline crypto offload")
[ sashal: Kept the branch's kzalloc(sizeof(*context), GFP_KERNEL) instead of upstream's kzalloc_obj(*context) and placed the new tls_device_can_attach() check just before it. ]
---
 Documentation/networking/tls-offload.rst | 16 ++++++++++------
 net/tls/tls_device.c                     | 24 ++++++++++++++++++++++++
 2 files changed, 34 insertions(+), 6 deletions(-)
Documentation/networking/tls-offload.rst +10 -6
index 7354d48cdf926..7ed28e40f1702 100644
@@ -76,12 +76,16 @@ During driver initialization device sets the ``NETIF_F_HW_TLS_RX`` and
 pointer in the :c:member:`tlsdev_ops` member of the
 :c:type:`struct net_device <net_device>`.
 
-When TLS cryptographic connection state is installed on a ``ktls`` socket
-(note that it is done twice, once for RX and once for TX direction,
-and the two are completely independent), the kernel checks if the underlying
-network device is offload-capable and attempts the offload. In case offload
-fails the connection is handled entirely in software using the same mechanism
-as if the offload was never tried.
+TLS cryptographic connection state is installed separately for RX and TX
+on a ``ktls`` socket. For each direction, the kernel checks if the underlying
+network device is offload-capable and attempts the offload. If offload fails,
+that direction is handled in software as if offload had never been tried.
+
+Both hardware directions share one device binding. Once one direction is
+offloaded, the other direction must use the same device. If a route change
+selects a different device, or ``NETDEV_DOWN`` has cleared the binding,
+hardware offload of the other direction is declined and it uses software
+instead.
 
 Offload request is performed via the :c:member:`tls_dev_add` callback of
 :c:type:`struct tlsdev_ops <tlsdev_ops>`:
net/tls/tls_device.c +24 -0
index 2c661e17efb8f..c49798486ea52 100644
@@ -1030,6 +1030,20 @@ int tls_device_decrypted(struct sock *sk, struct tls_context *tls_ctx)
 	return tls_device_reencrypt(sk, tls_ctx);
 }
 
+/* Both directions share ctx->netdev. A second direction must use that
+ * device; after NETDEV_DOWN clears it, no new direction can be offloaded.
+ */
+static bool tls_device_can_attach(struct tls_context *ctx, struct sock *sk,
+				  struct net_device *netdev)
+{
+	struct net_device *ctx_netdev;
+
+	ctx_netdev = rcu_dereference_protected(ctx->netdev,
+					       lockdep_is_held(&device_offload_lock));
+	return sk->sk_destruct != tls_device_sk_destruct ||
+	       ctx_netdev == netdev;
+}
+
 static void tls_device_attach(struct tls_context *ctx, struct sock *sk,
 			      struct net_device *netdev)
 {
@@ -1165,6 +1179,11 @@ int tls_set_device_offload(struct sock *sk)
 		goto release_lock;
 	}
 
+	if (!tls_device_can_attach(ctx, sk, netdev)) {
+		rc = -EOPNOTSUPP;
+		goto release_lock;
+	}
+
 	ctx->priv_ctx_tx = offload_ctx;
 	rc = netdev->tlsdev_ops->tls_dev_add(netdev, sk, TLS_OFFLOAD_CTX_DIR_TX,
 					     &ctx->crypto_send.info,
@@ -1235,6 +1254,11 @@ int tls_set_device_offload_rx(struct sock *sk, struct tls_context *ctx)
 		goto release_lock;
 	}
 
+	if (!tls_device_can_attach(ctx, sk, netdev)) {
+		rc = -EOPNOTSUPP;
+		goto release_lock;
+	}
+
 	context = kzalloc(sizeof(*context), GFP_KERNEL);
 	if (!context) {
 		rc = -ENOMEM;
Signature · 1 line
2.53.0
author maintainer
#639 lore raw

PATCH 638/990 ksmbd: return complete and aligned stream information

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Namjae Jeon <[email protected]>

[ Upstream commit 206fc30f71b005156085fd8523ccc84a2c67791b ]

FILE_STREAM_INFORMATION responses are assembled without aligning entries and truncated to the client buffer length after the fact. A short query can therefore return STATUS_BUFFER_OVERFLOW with an incomplete entry and a nonzero NextEntryOffset, which clients may reject as an invalid network response. Standalone queries can also exhaust the server response buffer and silently omit streams while reporting success.

Allocate the same large response buffer used by other variable-length QUERY_INFO classes for stream queries. Pack only complete entries within the requested output length and available response space, aligning each entry to eight bytes and sizing names after UTF-16 conversion. Return STATUS_BUFFER_OVERFLOW when more entries remain, using an SMB2 error response if no entry fits.

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
Fixes 6b8b79226bc3 ("ksmbd: fix partial file information responses")
[ sashal: Only the FILE_STREAM_INFORMATION case was added to the large-response-buffer list in smb2_allocate_rsp_buf(), because FILE_NORMALIZED_NAME_INFORMATION isn't in that list here. ]
---
 fs/smb/server/smb2pdu.c | 183 +++++++++++++++++++++++++---------------
 1 file changed, 115 insertions(+), 68 deletions(-)
fs/smb/server/smb2pdu.c +115 -68
index 88f07ec22723a..aae6e9adf2e84 100644
@@ -555,7 +555,8 @@ int smb2_allocate_rsp_buf(struct ksmbd_work *work)
 		req = smb_get_msg(work->request_buf);
 		if ((req->InfoType == SMB2_O_INFO_FILE &&
 		     (req->FileInfoClass == FILE_FULL_EA_INFORMATION ||
-		     req->FileInfoClass == FILE_ALL_INFORMATION)) ||
+		     req->FileInfoClass == FILE_ALL_INFORMATION ||
+		     req->FileInfoClass == FILE_STREAM_INFORMATION)) ||
 		    req->InfoType == SMB2_O_INFO_SECURITY)
 			sz = large_sz;
 	}
@@ -5255,41 +5256,107 @@ static void get_file_alternate_info(struct ksmbd_work *work,
 		cpu_to_le32(struct_size(file_info, FileName, conv_len));
 }
 
+struct smb2_stream_info_buffer {
+	struct smb2_query_info_rsp *rsp;
+	struct smb2_file_stream_info *last;
+	const struct nls_table *local_nls;
+	unsigned int length;
+	unsigned int capacity;
+};
+
+static int smb2_add_stream_info(struct smb2_stream_info_buffer *buf,
+				const char *name, loff_t size, u64 allocation_size)
+{
+	struct smb2_file_stream_info *file_info;
+	__le16 *utf16_name;
+	size_t name_len = strlen(name);
+	unsigned int offset = ALIGN(buf->length, 8), name_bytes;
+	int conv_len, ret = 0;
+
+	if (offset > buf->capacity ||
+	    buf->capacity - offset < sizeof(*file_info))
+		return -ENOSPC;
+
+	utf16_name = kmalloc_array(name_len + 1, sizeof(*utf16_name),
+				   KSMBD_DEFAULT_GFP);
+	if (!utf16_name)
+		return -ENOMEM;
+
+	conv_len = smbConvertToUTF16(utf16_name, name, name_len,
+				     buf->local_nls, 0);
+	if (conv_len < 0) {
+		ret = conv_len;
+		goto out;
+	}
+
+	name_bytes = conv_len * sizeof(*utf16_name);
+	if (name_bytes > buf->capacity - offset - sizeof(*file_info)) {
+		ret = -ENOSPC;
+		goto out;
+	}
+
+	file_info = (struct smb2_file_stream_info *)&buf->rsp->Buffer[offset];
+	if (buf->last) {
+		memset(&buf->rsp->Buffer[buf->length], 0, offset - buf->length);
+		buf->last->NextEntryOffset =
+			cpu_to_le32((char *)file_info - (char *)buf->last);
+	}
+	file_info->NextEntryOffset = 0;
+	file_info->StreamNameLength = cpu_to_le32(name_bytes);
+	file_info->StreamSize = cpu_to_le64(size);
+	file_info->StreamAllocationSize = cpu_to_le64(allocation_size);
+	memcpy(file_info->StreamName, utf16_name, name_bytes);
+
+	buf->last = file_info;
+	buf->length = offset + sizeof(*file_info) + name_bytes;
+out:
+	kfree(utf16_name);
+	return ret;
+}
+
 static int get_file_stream_info(struct ksmbd_work *work,
+				struct smb2_query_info_req *req,
 				struct smb2_query_info_rsp *rsp,
-				struct ksmbd_file *fp,
-				void *rsp_org)
+				struct ksmbd_file *fp)
 {
-	struct ksmbd_conn *conn = work->conn;
-	struct smb2_file_stream_info *file_info;
+	struct smb2_stream_info_buffer buf = {
+		.rsp = rsp,
+		.local_nls = work->conn->local_nls,
+	};
 	char *stream_name, *xattr_list = NULL, *stream_buf;
 	struct kstat stat;
 	const struct path *path = &fp->filp->f_path;
 	ssize_t xattr_list_len;
 	ssize_t slen;
 	loff_t ssize;
-	int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
+	unsigned int req_output_len = le32_to_cpu(req->OutputBufferLength);
+	int streamlen, idx = 0;
 	int buf_free_len;
 	int ret;
 
+	if (req_output_len < FILE_STREAM_INFORMATION_SIZE) {
+		rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
+		return -EINVAL;
+	}
+
+	buf_free_len = smb2_calc_max_out_buf_len(work,
+						 offsetof(struct smb2_query_info_rsp, Buffer),
+						 req_output_len);
+	if (buf_free_len < 0)
+		return buf_free_len;
+	buf.capacity = buf_free_len;
+
 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
 			  AT_STATX_SYNC_AS_STAT);
 	if (ret)
 		return ret;
 
-	file_info = (struct smb2_file_stream_info *)rsp->Buffer;
-
-	buf_free_len = smb2_resp_buf_len(work,
-			offsetof(struct smb2_query_info_rsp, Buffer));
-	if (buf_free_len < 0)
-		goto out;
-
 	xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
 	if (xattr_list_len < 0) {
-		goto out;
+		goto default_stream;
 	} else if (!xattr_list_len) {
 		ksmbd_debug(SMB, "empty xattr in the file\n");
-		goto out;
+		goto default_stream;
 	}
 
 	while (idx < xattr_list_len) {
@@ -5299,69 +5366,49 @@ static int get_file_stream_info(struct ksmbd_work *work,
 
 		ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
 
-		if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
-			    STREAM_PREFIX, STREAM_PREFIX_LEN))
+		if (strncmp(stream_name, XATTR_NAME_STREAM,
+			    XATTR_NAME_STREAM_LEN))
 			continue;
 
-		stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
-				STREAM_PREFIX_LEN);
-		streamlen = stream_name_len;
-
-		/* plus : size */
-		streamlen += 1;
-		stream_buf = kmalloc(streamlen + 1, KSMBD_DEFAULT_GFP);
-		if (!stream_buf)
-			break;
-
-		streamlen = snprintf(stream_buf, streamlen + 1,
-				     ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
-
-		next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
-		/* smbConvertToUTF16() also writes a terminating UTF-16 unit. */
-		if (next + sizeof(__le16) > buf_free_len) {
-			kfree(stream_buf);
-			break;
+		stream_buf = kasprintf(KSMBD_DEFAULT_GFP, ":%s",
+				       &stream_name[XATTR_NAME_STREAM_LEN]);
+		if (!stream_buf) {
+			ret = -ENOMEM;
+			goto out;
 		}
-
-		file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
-		streamlen  = smbConvertToUTF16((__le16 *)file_info->StreamName,
-					       stream_buf, streamlen,
-					       conn->local_nls, 0);
-		streamlen *= 2;
-		kfree(stream_buf);
-		file_info->StreamNameLength = cpu_to_le32(streamlen);
 		slen = ksmbd_vfs_xattr_len(file_mnt_idmap(fp->filp),
 					   path->dentry, stream_name);
 		ssize = slen < 0 ? 0 : (loff_t)slen;
-		file_info->StreamSize = cpu_to_le64(ssize);
-		file_info->StreamAllocationSize = cpu_to_le64(ssize);
+		ret = smb2_add_stream_info(&buf, stream_buf, ssize, ssize);
+		kfree(stream_buf);
+		if (ret == -ENOSPC)
+			goto overflow;
+		if (ret)
+			goto out;
+	}
 
-		nbytes += next;
-		buf_free_len -= next;
-		file_info->NextEntryOffset = cpu_to_le32(next);
+default_stream:
+	if (!S_ISDIR(stat.mode)) {
+		ret = smb2_add_stream_info(&buf, "::$DATA", stat.size,
+					   stat.blocks << 9);
+		if (ret == -ENOSPC)
+			goto overflow;
+		if (ret)
+			goto out;
 	}
 
+	ret = 0;
+	goto out;
+
+overflow:
+	rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
+	/* An empty overflow needs an SMB2 error response. */
+	ret = buf.length ? 0 : -EOVERFLOW;
 out:
-	if (!S_ISDIR(stat.mode) &&
-	    buf_free_len >= sizeof(struct smb2_file_stream_info) + (7 + 1) * 2) {
-		file_info = (struct smb2_file_stream_info *)
-			&rsp->Buffer[nbytes];
-		streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
-					      "::$DATA", 7, conn->local_nls, 0);
-		streamlen *= 2;
-		file_info->StreamNameLength = cpu_to_le32(streamlen);
-		file_info->StreamSize = cpu_to_le64(stat.size);
-		file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
-		nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
-	}
-
-	/* last entry offset should be 0 */
-	file_info->NextEntryOffset = 0;
+	if (!ret)
+		rsp->OutputBufferLength = cpu_to_le32(buf.length);
 	kvfree(xattr_list);
-
-	rsp->OutputBufferLength = cpu_to_le32(nbytes);
-
-	return 0;
+	return ret;
 }
 
 static int get_file_internal_info(struct smb2_query_info_rsp *rsp,
@@ -5646,7 +5693,7 @@ static int smb2_get_info_file(struct ksmbd_work *work,
 		break;
 
 	case FILE_STREAM_INFORMATION:
-		rc = get_file_stream_info(work, rsp, fp, work->response_buf);
+		rc = get_file_stream_info(work, req, rsp, fp);
 		break;
 
 	case FILE_INTERNAL_INFORMATION:
Signature · 1 line
2.53.0
author maintainer
#640 lore raw

PATCH 639/990 block: dont enter reclaim under rq_qos_mutex

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Josef Bacik <[email protected]>

[ Upstream commit 045cbfc369f5929ed473f7c200dc2e8146569ce5 ]

ioc_qos_write() and the wbt_lat_usec writers take rq_qos_mutex with the queue frozen, blkcg_deactivate_policy() does the same with blkcg_mutex, so nothing holding either may wait for IO. blkg_conf_prep() got GFP_NOIO for the blkg in commit 5d726c4dbeed, but the radix_tree_preload() right after it, the policy init functions and the GFP_KERNEL fallback in blkcg_activate_policy() can still enter reclaim there. lockdep reports the cycle on the first write to io.max.

Use GFP_NOIO for all of them.

Fixes 9730763f4756 ("block: correct locking order for protecting blk-wbt parameters")
Fixes 5d726c4dbeed ("blk-cgroup: fix possible deadlock while configuring policy")
Cc Tejun Heo <[email protected]>
[ sashal: Replaced upstream's kzalloc_obj(*ptr) allocator calls with kzalloc(sizeof(*ptr), GFP_NOIO) in blk-iocost.c and blk-iolatency.c, since this tree lacks kzalloc_obj. ]
---
 block/blk-cgroup.c    | 13 +++++++++----
 block/blk-iocost.c    |  5 +++--
 block/blk-iolatency.c |  3 ++-
 block/blk-throttle.c  |  3 ++-
 4 files changed, 16 insertions(+), 8 deletions(-)
block/blk-cgroup.c +9 -4
index 610ea63ad3861..36e6fdad93bd6 100644
@@ -917,7 +917,11 @@ int blkg_conf_prep(struct blkcg *blkcg, const struct blkcg_policy *pol,
 			parent = blkcg_parent(parent);
 		}
 
-		/* Drop locks to do new blkg allocation with GFP_KERNEL. */
+		/*
+		 * Drop the spinlock to allocate the new blkg. rq_qos_mutex and
+		 * blkcg_mutex stay held, and both are taken with the queue
+		 * frozen elsewhere: GFP_NOIO.
+		 */
 		spin_unlock_irq(&q->queue_lock);
 
 		new_blkg = blkg_alloc(pos, disk, GFP_NOIO);
@@ -926,7 +930,7 @@ int blkg_conf_prep(struct blkcg *blkcg, const struct blkcg_policy *pol,
 			goto fail_exit;
 		}
 
-		if (radix_tree_preload(GFP_KERNEL)) {
+		if (radix_tree_preload(GFP_NOIO)) {
 			blkg_free(new_blkg);
 			ret = -ENOMEM;
 			goto fail_exit;
@@ -1646,7 +1650,8 @@ int blkcg_activate_policy(struct gendisk *disk, const struct blkcg_policy *pol)
 		if (!pd) {
 			/*
 			 * GFP_NOWAIT failed.  Free the existing one and
-			 * prealloc for @blkg w/ GFP_KERNEL.
+			 * prealloc for @blkg w/ GFP_NOIO: blkcg_mutex is held,
+			 * and a bio based queue has not been frozen above.
 			 */
 			if (pinned_blkg)
 				blkg_put(pinned_blkg);
@@ -1658,7 +1663,7 @@ int blkcg_activate_policy(struct gendisk *disk, const struct blkcg_policy *pol)
 			if (pd_prealloc)
 				pol->pd_free_fn(pd_prealloc);
 			pd_prealloc = pol->pd_alloc_fn(disk, blkg->blkcg,
-						       GFP_KERNEL);
+						       GFP_NOIO);
 			if (pd_prealloc)
 				goto retry;
 			else
block/blk-iocost.c +3 -2
index a05e5cfd0ac0f..6c3ba62090477 100644
@@ -2982,11 +2982,12 @@ static int blk_iocost_init(struct gendisk *disk)
 	struct ioc *ioc;
 	int i, cpu, ret;
 
-	ioc = kzalloc(sizeof(*ioc), GFP_KERNEL);
+	/* The caller holds rq_qos_mutex, which is taken with the queue frozen */
+	ioc = kzalloc(sizeof(*ioc), GFP_NOIO);
 	if (!ioc)
 		return -ENOMEM;
 
-	ioc->pcpu_stat = alloc_percpu(struct ioc_pcpu_stat);
+	ioc->pcpu_stat = alloc_percpu_gfp(struct ioc_pcpu_stat, GFP_NOIO);
 	if (!ioc->pcpu_stat) {
 		kfree(ioc);
 		return -ENOMEM;
block/blk-iolatency.c +2 -1
index 741c804c217bf..3e0c9ec5df367 100644
@@ -761,7 +761,8 @@ static int blk_iolatency_init(struct gendisk *disk)
 	struct blk_iolatency *blkiolat;
 	int ret;
 
-	blkiolat = kzalloc(sizeof(*blkiolat), GFP_KERNEL);
+	/* The caller holds rq_qos_mutex, which is taken with the queue frozen */
+	blkiolat = kzalloc(sizeof(*blkiolat), GFP_NOIO);
 	if (!blkiolat)
 		return -ENOMEM;
 
block/blk-throttle.c +2 -1
index 36f8dc324d79f..faf53bf759957 100644
@@ -1327,7 +1327,8 @@ static int blk_throtl_init(struct gendisk *disk)
 	unsigned int memflags;
 	int ret;
 
-	td = kzalloc_node(sizeof(*td), GFP_KERNEL, q->node);
+	/* The caller holds rq_qos_mutex, which is taken with the queue frozen */
+	td = kzalloc_node(sizeof(*td), GFP_NOIO, q->node);
 	if (!td)
 		return -ENOMEM;
 
Signature · 1 line
2.53.0
author maintainer
#641 lore raw

PATCH 640/990 tls: Honor O_NONBLOCK in tls_sw_splice_read()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Chuck Lever <[email protected]>

[ Upstream commit 78ded647d43e335891f981f68c5992a2e763cfcc ]

tls_sw_splice_read() takes its blocking behavior from SPLICE_F_NONBLOCK alone. When splicing from a socket to a pipe, do_splice() sets that flag from the pipe's O_NONBLOCK, not the socket's. On a nonblocking socket, a splice(2) call without SPLICE_F_NONBLOCK therefore sleeps in tls_rx_rec_wait() until a record arrives. tcp_splice_read() instead reads sock->file->f_flags and returns -EAGAIN.

Polling first does not avoid the sleep once tls_sw_splice_read() consumes zero-length records, as it does after a later patch in this series. tls_sw_sock_is_readable() reports the socket readable while any record sits on rx_list, including a zero-length record that delivers no bytes to the pipe. For TLS 1.3 the strparser announces a record before decryption, when its plaintext length is still unknown, so the readiness test cannot screen such a record out. A splice that consumes the record and waits for the next stalls every connection an event loop multiplexes.

An LLM audit of the TLS read paths found this defect.

Treat the socket's O_NONBLOCK as nonblocking too. A caller that sets O_NONBLOCK on the socket and splices without SPLICE_F_NONBLOCK now gets -EAGAIN where the splice blocked before. sendfile(2) from a TLS socket changes the same way, because do_sendfile() leaves the input file's O_NONBLOCK out of the splice flags. Both now behave as they do on a plain TCP socket.

Fixes c46234ebb4d1 ("tls: RX path for ktls")
[ sashal: Passed the branch's existing NULL psock argument to tls_rx_rec_wait() since its signature has an extra parameter, substituting only the nonblock variable for the flags check. ]
---
 net/tls/tls_sw.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
net/tls/tls_sw.c +6 -3
index 4f982594f11d3..23b6e0000caf2 100644
@@ -2331,10 +2331,14 @@ ssize_t tls_sw_splice_read(struct socket *sock,  loff_t *ppos,
 	struct tls_msg *tlm;
 	struct sk_buff *skb;
 	ssize_t copied = 0;
+	bool nonblock;
 	int chunk;
 	int err;
 
-	err = tls_rx_reader_lock(sk, ctx, flags & SPLICE_F_NONBLOCK);
+	nonblock = flags & SPLICE_F_NONBLOCK ||
+		   sock->file->f_flags & O_NONBLOCK;
+
+	err = tls_rx_reader_lock(sk, ctx, nonblock);
 	if (err < 0)
 		return err;
 
@@ -2348,8 +2352,7 @@ ssize_t tls_sw_splice_read(struct socket *sock,  loff_t *ppos,
 	} else {
 		struct tls_decrypt_arg darg;
 
-		err = tls_rx_rec_wait(sk, NULL, flags & SPLICE_F_NONBLOCK,
-				      true, false);
+		err = tls_rx_rec_wait(sk, NULL, nonblock, true, false);
 		if (err <= 0)
 			goto splice_read_end;
 
Signature · 1 line
2.53.0
author maintainer
#642 lore raw

PATCH 641/990 ipv6: Protect multiple routes insertion by table lock.

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Kuniyuki Iwashima <[email protected]>

[ Upstream commit 4c6fbb1fbafa85029fa789b5b01f39ebcb459d1a ]

syzbot reported the warning below. [0]

While call_fib6_multipath_entry_notifiers() is called locklessly, fib6_siblings could be changed concurrently, leading to the warning (and later null-ptr-deref).

Let's protect multiple routes insertion with tb6_lock.

Along with that, __ip6_ins_rt() and ip6_route_del() are changed to fib6_add() and fib6_del().

Note that fib6_del() finally calls rt6_multipath_rebalance(), which requires rcu_read_lock().

[0]:
i != fen6_info->nsiblings

WARNING: drivers/net/netdevsim/fib.c:831 at nsim_fib6_event_init drivers/net/netdevsim/fib.c:831 [inline], CPU#0: syz.0.157/6279
WARNING: drivers/net/netdevsim/fib.c:831 at nsim_fib6_prepare_event drivers/net/netdevsim/fib.c:947 [inline], CPU#0: syz.0.157/6279
WARNING: drivers/net/netdevsim/fib.c:831 at nsim_fib_event_schedule_work drivers/net/netdevsim/fib.c:1003 [inline], CPU#0: syz.0.157/6279
WARNING: drivers/net/netdevsim/fib.c:831 at nsim_fib_event_nb+0x1029/0x11d0 drivers/net/netdevsim/fib.c:1043, CPU#0: syz.0.157/6279
Modules linked in:
CPU: 0 UID: 0 PID: 6279 Comm: syz.0.157 Not tainted syzkaller #0 PREEMPT(full)
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 07/24/2026
RIP: 0010:nsim_fib6_event_init drivers/net/netdevsim/fib.c:831 [inline]
RIP: 0010:nsim_fib6_prepare_event drivers/net/netdevsim/fib.c:947 [inline]
RIP: 0010:nsim_fib_event_schedule_work drivers/net/netdevsim/fib.c:1003 [inline]
RIP: 0010:nsim_fib_event_nb+0x1029/0x11d0 drivers/net/netdevsim/fib.c:1043
Code: eb 0d 4d 89 fd e8 b7 c5 6c fa be 01 00 00 00 48 89 df e8 5a 38 85 fd 4d 89 ef 4c 8b 6c 24 20 e9 4a f3 ff ff e8 98 c5 6c fa 90 <0f> 0b 90 e9 db fa ff ff 89 e9 80 e1 07 80 c1 03 38 c1 0f 8c df f0
RSP: 0018:ffffc900047bef10 EFLAGS: 00010293
RAX: ffffffff875b59a8 RBX: 0000000000000002 RCX: ffff888079770000
RDX: 0000000000000000 RSI: 0000000000000002 RDI: 0000000000000001
RBP: ffffc900047bf0a0 R08: ffff88805c0bb02f R09: 1ffff1100b817605
R10: dffffc0000000000 R11: ffffed100b817606 R12: dffffc0000000000
R13: 0000000000000000 R14: 0000000000000001 R15: ffff88802c792000
FS:  00007f334ba076c0(0000) GS:ffff888123ad0000(0000) knlGS:0000000000000000
CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 00007f334ba06ff8 CR3: 000000007a5b2000 CR4: 00000000003526f0
Call Trace:
 <TASK>
 notifier_call_chain+0x1a5/0x3d0 kernel/notifier.c:85
 atomic_notifier_call_chain+0xda/0x180 kernel/notifier.c:223
 call_fib_notifiers+0x31/0x60 net/core/fib_notifier.c:36
 call_fib6_multipath_entry_notifiers+0xf5/0x160 net/ipv6/ip6_fib.c:428
 ip6_route_multipath_add net/ipv6/route.c:5542 [inline]
 inet6_rtm_newroute+0x14f5/0x1a30 net/ipv6/route.c:5664
 rtnetlink_rcv_msg+0x802/0xc00 net/core/rtnetlink.c:7163
 netlink_rcv_skb+0x226/0x4a0 net/netlink/af_netlink.c:2572
 netlink_unicast_kernel net/netlink/af_netlink.c:1335 [inline]
 netlink_unicast+0x7bd/0x940 net/netlink/af_netlink.c:1361
 netlink_sendmsg+0x813/0xb40 net/netlink/af_netlink.c:1916
 sock_sendmsg_nosec+0x14e/0x190 net/socket.c:800
 __sock_sendmsg net/socket.c:818 [inline]
 ____sys_sendmsg+0x54e/0x850 net/socket.c:2715
 ___sys_sendmsg+0x2a5/0x360 net/socket.c:2769
 __sys_sendmmsg+0x273/0x4d0 net/socket.c:2858
 __do_sys_sendmmsg net/socket.c:2885 [inline]
 __se_sys_sendmmsg net/socket.c:2882 [inline]
 __x64_sys_sendmmsg+0xa0/0xc0 net/socket.c:2882
 do_syscall_x64 arch/x86/entry/syscall_64.c:61 [inline]
 do_syscall_64+0x166/0x520 arch/x86/entry/syscall_64.c:84
 entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7f334ab9e1d9
Code: ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 e8 ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007f334ba07028 EFLAGS: 00000246 ORIG_RAX: 0000000000000133
RAX: ffffffffffffffda RBX: 00007f334ae26090 RCX: 00007f334ab9e1d9
RDX: 04000000000001f2 RSI: 0000200000000000 RDI: 0000000000000004
RBP: 00007f334ac35888 R08: 0000000000000000 R09: 0000000000000000
R10: 00000000000000fc R11: 0000000000000246 R12: 0000000000000000
R13: 00007f334ae26128 R14: 00007f334ae26090 R15: 00007ffd96688aa8
 </TASK>
Fixes 169fd62799e8 ("ipv6: Get rid of RTNL for SIOCADDRT and RTM_NEWROUTE.")
Reported-by [email protected]
[ sashal: Dropped the third RT_DEL_REASON_UNSPEC argument from the fib6_del() call in the multipath error path, since this tree's fib6_del() takes only two arguments. ]
---
 net/ipv6/ip6_fib.c |  4 ----
 net/ipv6/route.c   | 16 ++++++++++++----
 2 files changed, 12 insertions(+), 8 deletions(-)
net/ipv6/ip6_fib.c +0 -4
index 962d01b9954e4..0ec46c65ee0b5 100644
@@ -1252,9 +1252,7 @@ static int fib6_add_rt2node(struct fib6_node *fn, struct fib6_info *rt,
 			fib6_nsiblings++;
 		}
 		BUG_ON(fib6_nsiblings != rt->fib6_nsiblings);
-		rcu_read_lock();
 		rt6_multipath_rebalance(temp_sibling);
-		rcu_read_unlock();
 	}
 
 	/*
@@ -1298,9 +1296,7 @@ static int fib6_add_rt2node(struct fib6_node *fn, struct fib6_info *rt,
 						   sibling->fib6_nsiblings - 1);
 				WRITE_ONCE(rt->fib6_nsiblings, 0);
 				list_del_rcu(&rt->fib6_siblings);
-				rcu_read_lock();
 				rt6_multipath_rebalance(next_sibling);
-				rcu_read_unlock();
 				return err;
 			}
 		}
net/ipv6/route.c +12 -4
index ac27f815d497c..4e5e01970ef73 100644
@@ -4894,8 +4894,10 @@ void rt6_multipath_rebalance(struct fib6_info *rt)
 	if (WARN_ON_ONCE(!first))
 		return;
 
+	rcu_read_lock();
 	total = rt6_multipath_total_weight(first);
 	rt6_multipath_upper_bound_set(first, total);
+	rcu_read_unlock();
 }
 
 static int fib6_ifup(struct fib6_info *rt, void *p_arg)
@@ -5432,6 +5434,7 @@ static int ip6_route_multipath_add(struct fib6_config *cfg,
 	struct fib6_info *rt_notif = NULL, *rt_last = NULL;
 	struct nl_info *info = &cfg->fc_nlinfo;
 	struct rt6_nh *nh, *nh_safe;
+	struct fib6_table *table;
 	struct fib6_config r_cfg;
 	struct rtnexthop *rtnh;
 	LIST_HEAD(rt6_nh_list);
@@ -5518,10 +5521,12 @@ static int ip6_route_multipath_add(struct fib6_config *cfg,
 	 */
 	info->skip_notify_kernel = 1;
 
+	table = rt->fib6_table;
+	spin_lock_bh(&table->tb6_lock);
+
 	err_nh = NULL;
 	list_for_each_entry(nh, &rt6_nh_list, list) {
-		err = __ip6_ins_rt(nh->fib6_info, info, extack);
-
+		err = fib6_add(&table->tb6_root, nh->fib6_info, info, extack);
 		if (err) {
 			if (replace && nhn)
 				NL_SET_ERR_MSG_MOD(extack,
@@ -5576,11 +5581,13 @@ static int ip6_route_multipath_add(struct fib6_config *cfg,
 
 	/* success ... tell user about new route */
 	ip6_route_mpath_notify(rt_notif, rt_last, info, nlflags);
+
+	spin_unlock_bh(&table->tb6_lock);
 	goto cleanup;
 
 add_errout:
 	/* send notification for routes that were added so that
-	 * the delete notifications sent by ip6_route_del are
+	 * the delete notifications sent by fib6_del() are
 	 * coherent
 	 */
 	if (rt_notif)
@@ -5590,9 +5597,10 @@ static int ip6_route_multipath_add(struct fib6_config *cfg,
 	list_for_each_entry(nh, &rt6_nh_list, list) {
 		if (err_nh == nh)
 			break;
-		ip6_route_del(&nh->r_cfg, extack);
+		fib6_del(nh->fib6_info, &nh->r_cfg.fc_nlinfo);
 	}
 
+	spin_unlock_bh(&table->tb6_lock);
 cleanup:
 	list_for_each_entry_safe(nh, nh_safe, &rt6_nh_list, list) {
 		fib6_info_release(nh->fib6_info);
Signature · 1 line
2.53.0
author maintainer
#643 lore raw

PATCH 642/990 ice: use reference counting and SRCU for PTP port access

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jacob Keller <[email protected]>

[ Upstream commit d5d859a6efff473d799d35999a35aa764dcc185b ]

The ice adapter structure maintains a list of ports associated with the adapter. This is used for supporting PTP, where the clock owner must handle many operations that require access to the PTP port structures of the associated PFs.

This is implemented using a linked list and a mutex. This sort of works, but a few places within the code do not acquire the mutex when iterating the list. This includes ice_ptp_flush_all_tx_tracker(), ice_ptp_restart_all_phy(), and ice_ptp_prepare_rebuild_sec().

Fixing this is tricky, especially since it is not clear if we can simply acquire the lock around the complete iterations.

The pattern of use for the port list is read-mostly with modifications only happening during PF initialization when elements are inserted. This typically only happens during early boot, though a PF could in principle be removed or loaded at arbitrary times via bind and unbind operations.

The use of a mutex does mean the driver can sleep while holding it, but it still creates complicates with lock ordering and prevents iterating the list in any code path that *can't* sleep.

Instead, use SRCU primitives for the port linked list, along with a reference count on the port. The kref reference counter ensures that a PF will have a valid lifetime and not be removed until the reference is released. Note that this change focuses solely on the port list and does not make an effort to resolve access to ctrl_pf, which is currently being investigated by another developer.

Use of sleepable RCU is required because we often iterate the PTP port list and perform operations that might sleep. Attempts at implementing regular RCU have thus far not proven to be acceptable.

The remove path first removes the port from the list, and we use kref_get_unless_zero to ensure that such ports are skipped when iterating the list. This ensures that once a port starts removing we will drop references and no longer be able to acquire new ones. This avoids loop iterations chaining together to indefinitely block removal.

The ice_ptp_release_port_srcu() function is used as the release function for the kref_put() call. This uses wake_up_var() to wake the removing thread. The waiting thread will block until the final reference has been removed, then it will use synchronize_srcu() to ensure any outstanding SRCU critical sections have had the necessary grace period.

This flow ensures that accesses to ports via the adapter port list will remain valid until both the SRCU critical sections have ended and all the references to the ports have been dropped. Strictly speaking, SRCU alone might be sufficient for existing code paths, but the reference count allows the option for passing a pointer to the port on to other functions if necessary in the future.

Fixes e800654e85b5 ("ice: Use ice_adapter for PTP shared data instead of auxdev")
[ sashal: Dropped the cpi_phy_lock init/destroy context, used kzalloc(sizeof(*adapter), GFP_KERNEL) instead of kzalloc_obj(), and omitted the mutex.h include context line. ]
---
 drivers/net/ethernet/intel/ice/ice_adapter.c |  17 ++-
 drivers/net/ethernet/intel/ice/ice_adapter.h |  17 ++-
 drivers/net/ethernet/intel/ice/ice_ptp.c     | 125 ++++++++++++++-----
 drivers/net/ethernet/intel/ice/ice_ptp.h     |   4 +
 4 files changed, 121 insertions(+), 42 deletions(-)
drivers/net/ethernet/intel/ice/ice_adapter.c +13 -4
index 0a8a48cd4bce6..8d0a4f6653cf0 100644
@@ -6,6 +6,7 @@
 #include <linux/pci.h>
 #include <linux/slab.h>
 #include <linux/spinlock.h>
+#include <linux/srcu.h>
 #include <linux/xarray.h>
 #include "ice_adapter.h"
 #include "ice.h"
@@ -54,26 +55,34 @@ static unsigned long ice_adapter_xa_index(struct pci_dev *pdev)
 static struct ice_adapter *ice_adapter_new(struct pci_dev *pdev)
 {
 	struct ice_adapter *adapter;
+	int err;
 
 	adapter = kzalloc(sizeof(*adapter), GFP_KERNEL);
 	if (!adapter)
 		return NULL;
 
+	err = init_srcu_struct(&adapter->ports.srcu);
+	if (err) {
+		kfree(adapter);
+		return NULL;
+	}
+
 	adapter->index = ice_adapter_index(pdev);
 	spin_lock_init(&adapter->ptp_gltsyn_time_lock);
 	spin_lock_init(&adapter->txq_ctx_lock);
 	refcount_set(&adapter->refcount, 1);
 
-	mutex_init(&adapter->ports.lock);
-	INIT_LIST_HEAD(&adapter->ports.ports);
+	spin_lock_init(&adapter->ports.lock);
+	INIT_LIST_HEAD(&adapter->ports.list);
 
 	return adapter;
 }
 
 static void ice_adapter_free(struct ice_adapter *adapter)
 {
-	WARN_ON(!list_empty(&adapter->ports.ports));
-	mutex_destroy(&adapter->ports.lock);
+	WARN_ON(!list_empty(&adapter->ports.list));
+
+	cleanup_srcu_struct(&adapter->ports.srcu);
 
 	kfree(adapter);
 }
drivers/net/ethernet/intel/ice/ice_adapter.h +11 -6
index e95266c7f20bd..636ee05f110af 100644
@@ -5,6 +5,7 @@
 #define _ICE_ADAPTER_H_
 
 #include <linux/types.h>
+#include <linux/srcu.h>
 #include <linux/spinlock_types.h>
 #include <linux/refcount_types.h>
 
@@ -14,15 +15,19 @@ struct ice_pf;
 /**
  * struct ice_port_list - data used to store the list of adapter ports
  *
- * This structure contains data used to maintain a list of adapter ports
+ * This structure contains data used to maintain a list of adapter ports.
+ * Writers modifying the list *must* acquire the lock, and use SRCU safe list
+ * operations. Readers should use srcu_read_lock() on the provided domain.
  *
- * @ports: list of ports
- * @lock: protect access to the ports list
+ * @list: list of ports
+ * @lock: protect write access to the list
+ * @srcu: Sleepable RCU domain for this adapter
  */
 struct ice_port_list {
-	struct list_head ports;
-	/* To synchronize the ports list operations */
-	struct mutex lock;
+	struct list_head list;
+	/* To synchronize write operations on the port list */
+	spinlock_t lock;
+	struct srcu_struct srcu;
 };
 
 /**
drivers/net/ethernet/intel/ice/ice_ptp.c +93 -32

209 lines not on this page · raw message

drivers/net/ethernet/intel/ice/ice_ptp.h +4 -0
index 0a5a1db66d614..1a1ea1891245b 100644
@@ -5,6 +5,8 @@
 #define _ICE_PTP_H_
 
 #include <linux/ptp_clock_kernel.h>
+#include <linux/rculist.h>
+#include <linux/kref.h>
 #include <linux/kthread.h>
 
 #include "ice_ptp_hw.h"
@@ -138,6 +140,7 @@ struct ice_ptp_tx {
  * and determine when the port's PHY offset is valid.
  *
  * @list_node: list member structure
+ * @ref: reference counter for use with adapter ports list
  * @tx: Tx timestamp tracking for this port
  * @ov_work: delayed work task for tracking when PHY offset is valid
  * @ps_lock: mutex used to protect the overall PTP PHY start procedure
@@ -147,6 +150,7 @@ struct ice_ptp_tx {
  */
 struct ice_ptp_port {
 	struct list_head list_node;
+	struct kref ref;
 	struct ice_ptp_tx tx;
 	struct kthread_delayed_work ov_work;
 	struct mutex ps_lock; /* protects overall PTP PHY start procedure */
Signature · 1 line
2.53.0
author maintainer
#644 lore raw

PATCH 643/990 blk-mq-dma: initialize the dma state for P2P, too

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Josef Bacik <[email protected]>

[ Upstream commit 035236c9e135a2ce7d0f68cb56e63d4a3da2abe1 ]

blk_rq_dma_map_iter_start() promises that the caller need not initialize the dma_iova_state, but the P2P bus address path returns before it does so. The state then holds what the last request with that tag left, and blk_rq_dma_map_coalesce() describes a transfer as one IOVA range that it isn't. Clear it on that path too.

Fixes 858299dc6160 ("block: add scatterlist-less DMA mapping helpers")
[ sashal: Kept the existing P2P request-flag code in the bus-address case and added the upstream memset of state after it, before the return. ]
---
 block/blk-mq-dma.c | 2 ++
 1 file changed, 2 insertions(+)
block/blk-mq-dma.c +2 -0
index b7c26599f6b05..fef1448453f88 100644
@@ -177,6 +177,8 @@ static bool blk_dma_map_iter_start(struct request *req, struct device *dma_dev,
 			bio_integrity(req->bio)->bip_flags |= BIP_P2P_DMA;
 		else
 			req->cmd_flags |= REQ_P2PDMA;
+		/* don't leave the state of an earlier mapping to the caller */
+		memset(state, 0, sizeof(*state));
 		return blk_dma_map_bus(iter, &vec);
 	case PCI_P2PDMA_MAP_THRU_HOST_BRIDGE:
 		/*
Signature · 1 line
2.53.0
author maintainer
#645 lore raw

PATCH 644/990 pidfs: do not report fields that do not fit into the callers struct

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Nickolai Zeldovich <[email protected]>

[ Upstream commit 1534c37167488f2b85c74de048e1d6a4ba3848de ]

The documentation of struct pidfd_info promises that "If the structure size is too small to contain a field (requested or not), to avoid confusion the mask will not contain a bit for that field", and asks userspace to trust the returned mask when deciding which fields hold valid data.

pidfd_info() does not keep that promise. It builds kinfo.mask without looking at the size encoded in the ioctl command, and copy_struct_to_user() then truncates the copy to that size. A caller that passes a 64-byte struct (PIDFD_INFO_SIZE_VER0) and requests PIDFD_INFO_COREDUMP or PIDFD_INFO_SUPPORTED_MASK gets a mask with PIDFD_INFO_COREDUMP, PIDFD_INFO_COREDUMP_SIGNAL, PIDFD_INFO_COREDUMP_CODE and PIDFD_INFO_SUPPORTED_MASK set, while the coredump_* and supported_mask fields behind the 64 bytes were never written. Trusting the mask as documented, userspace then reads whatever its own buffer held at those offsets. The same happens for a 72- or 80-byte struct and the fields added after it.

Clear the bits of the fields that lie beyond the caller's size before the copy, in the one place that knows both the final mask and the size. A request for a field that cannot be returned is thereby answered the way the header describes: the field is simply absent from the mask.

Fixes 1d8db6fd698d ("pidfs, coredump: add PIDFD_INFO_COREDUMP")
[ sashal: Dropped the COREDUMP_SIGNAL, COREDUMP_CODE and SUPPORTED_MASK clearing hunks, since those bits and struct sizes don't exist here, keeping only the PIDFD_INFO_COREDUMP check. ]
---
 fs/pidfs.c | 4 ++++
 1 file changed, 4 insertions(+)
fs/pidfs.c +4 -0
index a014db891aaa8..cfecc1098170e 100644
@@ -440,6 +440,10 @@ static long pidfd_info(struct file *file, unsigned int cmd, unsigned long arg)
 	}
 
 copy_out:
+	/* Only report fields that fit into the caller's struct. */
+	if (usize < PIDFD_INFO_SIZE_VER1)
+		kinfo.mask &= ~PIDFD_INFO_COREDUMP;
+
 	/*
 	 * If userspace and the kernel have the same struct size it can just
 	 * be copied. If userspace provides an older struct, only the bits that
Signature · 1 line
2.53.0
author maintainer
#646 lore raw

PATCH 645/990 Bluetooth: 6lowpan: avoid concurrent peer_del() in bt_6lowpan_disconnect

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Pauli Virtanen <[email protected]>

[ Upstream commit df5175dfcf4879f6bcdadee614ac089e5627b721 ]

bt_6lowpan_disconnect() looks up and accesses peer->chan, without holding locks guaranteeing peer_del() cannot free the peer concurrently.

Take devices_lock to ensure peer can be dereferenced safely.

Fixes 15f32cabf426 ("Bluetooth: 6lowpan: add missing l2cap_chan_lock()")
[ sashal: Kept this tree's existing lock/close/unlock sequence on the pinned channel instead of upstream's l2cap_chan_close_unlocked() helper, which is missing here. ]
---
 net/bluetooth/6lowpan.c | 21 ++++++++++++++++-----
 1 file changed, 16 insertions(+), 5 deletions(-)
net/bluetooth/6lowpan.c +16 -5
index 64dffdc8125b3..9515b82cda688 100644
@@ -913,18 +913,29 @@ static int bt_6lowpan_connect(bdaddr_t *addr, u8 dst_type)
 static int bt_6lowpan_disconnect(struct l2cap_conn *conn, u8 dst_type)
 {
 	struct lowpan_peer *peer;
+	struct l2cap_chan *chan;
 
 	BT_DBG("conn %p dst type %u", conn, dst_type);
 
+	spin_lock(&devices_lock);
+
 	peer = lookup_peer(conn);
-	if (!peer)
+	if (!peer) {
+		spin_unlock(&devices_lock);
 		return -ENOENT;
+	}
+
+	chan = peer->chan;
+	l2cap_chan_hold(chan);
+
+	spin_unlock(&devices_lock);
 
-	BT_DBG("peer %p chan %p", peer, peer->chan);
+	BT_DBG("peer %p chan %p", peer, chan);
 
-	l2cap_chan_lock(peer->chan);
-	l2cap_chan_close(peer->chan, ENOENT);
-	l2cap_chan_unlock(peer->chan);
+	l2cap_chan_lock(chan);
+	l2cap_chan_close(chan, ENOENT);
+	l2cap_chan_unlock(chan);
+	l2cap_chan_put(chan);
 
 	return 0;
 }
Signature · 1 line
2.53.0
author maintainer
#647 lore raw

PATCH 646/990 mm/slub: refill prefilled sheaves from the barn

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Hao Li <[email protected]>

[ Upstream commit 1b87ea06a34b213e45e3e0c4effd5043f15046ed ]

Currently, when the prefill API refills a non-full sheaf, it takes the objects from partial slabs and never from the full sheaves in the barn, so once the barn's full list becomes saturated, it stays saturated.

For objects freed via kfree_rcu(), every RCU sheaf then has to be flushed to slabs because the barn's full list has no room.

To fix this, let the sheaf refill from the barn first, and introduce a partial sheaf in the barn, which holds the leftover objects [1].

Only the prefill path needs the partial sheaf. The generic allocation path (__pcs_replace_empty_main()) exchanges an empty sheaf for a full one from the barn, so nothing is left over. The prefill path refills a sheaf that is not necessarily empty, so taking objects from the barn usually leaves leftovers, and the partial sheaf is where they are kept. refill_sheaf() only takes objects from partial slabs and never involves the partial sheaf.

The sheaf is refilled by copying objects from the partial sheaf, and then from a full sheaf taken from the barn if it is still not full. A sheaf that objects were copied from stays in the barn as the partial sheaf if it still holds objects, or goes on the empty list if it is empty. The sheaf being refilled is never replaced.

The gain comes from two sides: every full sheaf taken out makes room on the barn's full list for a future RCU sheaf, and refilling from the barn is cheaper than refilling from partial slabs under list_lock.

Note that putting the sheaf with the leftover objects on the full list instead would not work: it would occupy room on the full list, so the list would stay saturated and rcu_free_sheaf() would still keep flushing.

An earlier version of this patch swapped sheaves instead, to minimize the memcpy overhead. As Harry Yoo pointed out [2], replacing the caller's sheaf loses cache affinity, filling it directly is more straightforward, and testing showed no measurable difference between the two approaches, so the approach he suggested is used.

Tested with will-it-scale mmap1 (192 processes, one-minute runs) on the maple_node cache.

throughput: 27778727 -> 34500556 (+24.2%)

metric baseline patched change
=====================================================================
alloc_fastpath 54,124 56,696 +4.75%
alloc_slab 7,100,651 159,739 -97.75%

barn_get                          849       194,460,392    +22904539.81%
barn_get_fail                       2               217    +10750.00%
barn_put                          851       182,306,701    +21422544.07%
barn_put_fail             260,400,484       145,522,675       -44.12%
cmpxchg_double_fail         1,029,204           334,228       -67.53%
free_add_partial          326,694,687       181,935,790       -44.31%
free_fastpath                  13,297            15,611       +17.40%
free_rcu_sheaf          8,332,839,104    10,490,535,227       +25.89%
free_remove_partial         7,099,788           158,297       -97.77%
free_slab                   7,099,788           158,297       -97.77%
free_slowpath              10,969,156           782,851       -92.86%
objects                        15,295            14,849        -2.92%
objects_partial                15,295            14,849        -2.92%

partial 1,604 2,336 +45.64%
sheaf_alloc 137,757,895 141,208,076 +2.50%
sheaf_flush 8,332,823,922 4,656,725,764 -44.12%
sheaf_free 137,757,883 141,208,072 +2.50%

sheaf_prefill_fast      3,337,502,163     4,196,506,116       +25.74%
sheaf_prefill_slow                685               400       -41.61%
sheaf_refill            8,343,794,364     4,657,509,724       -44.18%
sheaf_return_fast       3,337,502,411     4,196,506,382       +25.74%
sheaf_return_slow                 437               134       -69.34%
slabs                           1,604             2,336       +45.64%
total_objects                 102,656           149,504       +45.64%

Here is what the important metric changes mean.

barn_get and barn_put: refills now take full sheaves out of the barn, and RCU sheaves are put into the barn again. Before, the barn's full list was saturated once and hardly ever consumed.

barn_put_fail: more than half of the RCU sheaves are now put into the barn instead of being flushed. The rest are still flushed because they arrive while the barn's full list is at its limit.

sheaf_refill and free_add_partial: fewer objects are taken from partial slabs to refill sheaves, and fewer slabs are added to the partial list, by the same percentage.

alloc_slab and free_slab: the partial list is almost never empty when a refill looks at it, so slabs are almost never allocated and freed again only to serve refills.

After the test, the maple_node cache holds 1604 slabs without the patch and 2336 with it. After a manual shrink
(echo 1 > /sys/kernel/slab/maple_node/shrink), it holds 485 without the patch and 563 with it. So most of the extra slabs are held only by objects sitting in sheaves and are returned by a shrink, and what remains is a small difference, because objects handed out from the barn come from many more slabs than a refill from partial slabs would use.

[ sashal: Adapted by calling refill_sheaf_from_barn() directly in the two prefill/refill functions, since the upstream pfmemalloc prefill helper doesn't exist here. ]
---
 mm/slub.c | 86 +++++++++++++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 84 insertions(+), 2 deletions(-)
mm/slub.c +84 -2
index 8fdbe531a0cba..d49b6f69136c5 100644
@@ -462,6 +462,7 @@ struct node_barn {
 	spinlock_t lock;
 	struct list_head sheaves_full;
 	struct list_head sheaves_empty;
+	struct slab_sheaf *sheaf_partial;
 	unsigned int nr_full;
 	unsigned int nr_empty;
 };
@@ -3047,6 +3048,7 @@ static void barn_init(struct node_barn *barn)
 	spin_lock_init(&barn->lock);
 	INIT_LIST_HEAD(&barn->sheaves_full);
 	INIT_LIST_HEAD(&barn->sheaves_empty);
+	barn->sheaf_partial = NULL;
 	barn->nr_full = 0;
 	barn->nr_empty = 0;
 }
@@ -3067,6 +3069,10 @@ static void barn_shrink(struct kmem_cache *s, struct node_barn *barn)
 	barn->nr_full = 0;
 	list_splice_init(&barn->sheaves_empty, &empty_list);
 	barn->nr_empty = 0;
+	if (barn->sheaf_partial) {
+		list_add(&barn->sheaf_partial->barn_list, &full_list);
+		barn->sheaf_partial = NULL;
+	}
 
 	spin_unlock_irqrestore(&barn->lock, flags);
 
@@ -5381,6 +5387,78 @@ void *kmem_cache_alloc_node_noprof(struct kmem_cache *s, gfp_t gfpflags, int nod
 }
 EXPORT_SYMBOL(kmem_cache_alloc_node_noprof);
 
+/*
+ * Refill @sheaf from the barn: from its partial sheaf first, then from its full
+ * sheaves. A sheaf that objects were copied from stays in the barn as the
+ * partial sheaf if it still holds objects, or goes on the empty list if it is
+ * empty.
+ *
+ * Returns true if the sheaf is now full, at s->sheaf_capacity.
+ * Returns false if the sheaf is still not full.
+ */
+static bool refill_sheaf_from_barn(struct kmem_cache *s,
+				   struct slab_sheaf *sheaf)
+{
+	struct node_barn *barn = get_barn(s);
+	struct slab_sheaf *src;
+	unsigned int to_move;
+	unsigned long flags;
+
+	if (!barn)
+		return false;
+
+	if (!data_race(barn->nr_full) && !data_race(barn->sheaf_partial))
+		return false;
+
+	spin_lock_irqsave(&barn->lock, flags);
+
+	/*
+	 * The partial sheaf can hold fewer objects than @sheaf needs to
+	 * reach capacity, and a sheaf on the full list is not necessarily
+	 * full (see the comment in rcu_free_sheaf()), so keep taking from
+	 * the barn until @sheaf is full or nothing is left.
+	 */
+	while (sheaf->size < s->sheaf_capacity) {
+		src = barn->sheaf_partial;
+		barn->sheaf_partial = NULL;
+		if (!src) {
+			if (!barn->nr_full)
+				break;
+			src = list_first_entry(&barn->sheaves_full,
+					       struct slab_sheaf, barn_list);
+			list_del(&src->barn_list);
+			barn->nr_full--;
+		}
+
+		to_move = min(s->sheaf_capacity - sheaf->size, src->size);
+		src->size -= to_move;
+		memcpy(&sheaf->objects[sheaf->size], &src->objects[src->size],
+		       to_move * sizeof(void *));
+		sheaf->size += to_move;
+
+		if (src->size) {
+			barn->sheaf_partial = src;
+		} else {
+			/*
+			 * No empty-limit check: the sheaf put on the empty list
+			 * was already in the barn, so the barn holds no more
+			 * sheaves than before. barn_replace_empty_sheaf() skips
+			 * the check for the same reason.
+			 */
+			list_add(&src->barn_list, &barn->sheaves_empty);
+			barn->nr_empty++;
+		}
+	}
+
+	spin_unlock_irqrestore(&barn->lock, flags);
+
+	if (sheaf->size < s->sheaf_capacity)
+		return false;
+
+	stat(s, BARN_GET);
+	return true;
+}
+
 /*
  * returns a sheaf that has at least the requested size
  * when prefilling is needed, do so with given gfp flags
@@ -5452,7 +5530,8 @@ kmem_cache_prefill_sheaf(struct kmem_cache *s, gfp_t gfp, unsigned int size)
 		sheaf = alloc_empty_sheaf(s, gfp);
 
 	if (sheaf && sheaf->size < size) {
-		if (refill_sheaf(s, sheaf, gfp)) {
+		if (!refill_sheaf_from_barn(s, sheaf) &&
+		    refill_sheaf(s, sheaf, gfp)) {
 			sheaf_flush_unused(s, sheaf);
 			free_empty_sheaf(s, sheaf);
 			sheaf = NULL;
@@ -5546,8 +5625,11 @@ int kmem_cache_refill_sheaf(struct kmem_cache *s, gfp_t gfp,
 		return 0;
 
 	if (likely(sheaf->capacity >= size)) {
-		if (likely(sheaf->capacity == s->sheaf_capacity))
+		if (likely(sheaf->capacity == s->sheaf_capacity)) {
+			if (refill_sheaf_from_barn(s, sheaf))
+				return 0;
 			return refill_sheaf(s, sheaf, gfp);
+		}
 
 		if (!__kmem_cache_alloc_bulk(s, gfp, sheaf->capacity - sheaf->size,
 					     &sheaf->objects[sheaf->size])) {
Signature · 1 line
2.53.0
author maintainer
#648 lore raw

PATCH 647/990 tracing/eprobe: Install the trigger for every instance that enables the eprobe

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: David Carlier <[email protected]>

commit be94710b1f6ba1bea33e73129c110af80e999b2d upstream.

The eprobe trigger lives in the instance of the enabling file, but it is only added when the eprobe is first enabled and only removed when the last file goes away. A second instance then records nothing, and the first instance's trigger is left behind once the eprobe is disabled there, so the eprobe can be deleted while that trigger still uses it.

Add and remove the trigger for each file. The file is never NULL here, so warn if it is and drop the dead perf paths.

Fixes 7491e2c44278 ("tracing: Add a probe that attaches to trace events")
---
 kernel/trace/trace_eprobe.c |   58 ++++++++++++++------------------------------
 1 file changed, 19 insertions(+), 39 deletions(-)
kernel/trace/trace_eprobe.c +19 -39
@@ -642,37 +642,32 @@ static int enable_trace_eprobe(struct tr
 {
 	struct trace_probe *tp;
 	struct trace_eprobe *ep;
-	bool enabled;
 	int ret = 0;
 	int cnt = 0;
 
+	if (WARN_ON_ONCE(!file))
+		return -EINVAL;
+
 	tp = trace_probe_primary_from_call(call);
 	if (WARN_ON_ONCE(!tp))
 		return -ENODEV;
-	enabled = trace_probe_is_enabled(tp);
 
 	/* This also changes "enabled" state */
-	if (file) {
-		ret = trace_probe_add_file(tp, file);
-		if (ret)
-			return ret;
-	} else
-		trace_probe_set_flag(tp, TP_FLAG_PROFILE);
-
-	if (enabled)
-		return 0;
+	ret = trace_probe_add_file(tp, file);
+	if (ret)
+		return ret;
 
+	/* The trigger lives in the instance of the file, add it for each file */
 	for_each_trace_eprobe_tp(ep, tp) {
 		ret = enable_eprobe(ep, file);
 		if (ret)
 			break;
-		enabled = true;
 		cnt++;
 	}
 
 	if (ret) {
 		/* Failed to enable one of them. Roll back all */
-		if (enabled) {
+		if (cnt) {
 			/*
 			 * It's a bug if one failed for something other than memory
 			 * not being available but another eprobe succeeded.
@@ -685,10 +680,7 @@ static int enable_trace_eprobe(struct tr
 					break;
 			}
 		}
-		if (file)
-			trace_probe_remove_file(tp, file);
-		else
-			trace_probe_clear_flag(tp, TP_FLAG_PROFILE);
+		trace_probe_remove_file(tp, file);
 	}
 
 	return ret;
@@ -700,33 +692,21 @@ static int disable_trace_eprobe(struct t
 	struct trace_probe *tp;
 	struct trace_eprobe *ep;
 
+	if (WARN_ON_ONCE(!file))
+		return -EINVAL;
+
 	tp = trace_probe_primary_from_call(call);
 	if (WARN_ON_ONCE(!tp))
 		return -ENODEV;
 
-	if (file) {
-		if (!trace_probe_get_file_link(tp, file))
-			return -ENOENT;
-		if (!trace_probe_has_single_file(tp))
-			goto out;
-		trace_probe_clear_flag(tp, TP_FLAG_TRACE);
-	} else
-		trace_probe_clear_flag(tp, TP_FLAG_PROFILE);
-
-	if (!trace_probe_is_enabled(tp)) {
-		for_each_trace_eprobe_tp(ep, tp)
-			disable_eprobe(ep, file->tr);
-	}
+	if (!trace_probe_get_file_link(tp, file))
+		return -ENOENT;
 
- out:
-	if (file)
-		/*
-		 * Synchronization is done in below function. For perf event,
-		 * file == NULL and perf_trace_event_unreg() calls
-		 * tracepoint_synchronize_unregister() to ensure synchronize
-		 * event. We don't need to care about it.
-		 */
-		trace_probe_remove_file(tp, file);
+	for_each_trace_eprobe_tp(ep, tp)
+		disable_eprobe(ep, file->tr);
+
+	/* Synchronization is done in below function. */
+	trace_probe_remove_file(tp, file);
 
 	return 0;
 }
author maintainer
#649 lore raw

PATCH 648/990 KEYS: Reject descriptions larger than KEY_MAX_DESC_SIZE

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jarkko Sakkinen <[email protected]>

commit 094c53d2994975e36d4cab7cf5d9f34c1b0f1916 upstream.

KEY_MAX_DESC_SIZE includes the trailing NULL character. Descriptions generated from payloads and in-kernel paths bypass the userspace limit.

Reject descriptions at or above KEY_MAX_DESC_SIZE with -EINVAL at the following sites:

- key_alloc(): before quota calculation
- __key_create_or_update(): before key_set_index_key()
- keyring_search(): before match_preparse
- request_key_and_link(): before match_preparse
- request_key_rcu(): before check_cached_key()

---
 include/linux/key.h         |    3 +++
 security/keys/key.c         |   10 +++++++++-
 security/keys/keyctl.c      |    2 --
 security/keys/keyring.c     |    7 ++++++-
 security/keys/request_key.c |   14 ++++++++++++--
 5 files changed, 30 insertions(+), 6 deletions(-)
include/linux/key.h +3 -0
@@ -37,6 +37,9 @@ struct net;
 
 #undef KEY_DEBUGGING
 
+/* Maximum length of a key description, including the trailing NUL */
+#define KEY_MAX_DESC_SIZE 4096
+
 #define KEY_POS_VIEW	0x01000000	/* possessor can view a key's attributes */
 #define KEY_POS_READ	0x02000000	/* possessor can read key payload / view keyring */
 #define KEY_POS_WRITE	0x04000000	/* possessor can update key payload / add link to keyring */
security/keys/key.c +9 -1
@@ -245,6 +245,8 @@ struct key *key_alloc(struct key_type *t
 	}
 
 	desclen = strlen(desc);
+	if (desclen >= KEY_MAX_DESC_SIZE)
+		goto error;
 	quotalen = desclen + 1 + type->def_datalen;
 
 	/* get hold of the key tracking for this user */
@@ -829,6 +831,7 @@ static key_ref_t __key_create_or_update(
 	key_ref_t key_ref;
 	int ret;
 	struct key_restriction *restrict_link = NULL;
+	size_t desclen;
 
 	/* look up the key type to see if it's one of the registered kernel
 	 * types */
@@ -869,7 +872,12 @@ static key_ref_t __key_create_or_update(
 		if (!index_key.description)
 			goto error_free_prep;
 	}
-	index_key.desc_len = strlen(index_key.description);
+	desclen = strlen(index_key.description);
+	if (desclen >= KEY_MAX_DESC_SIZE) {
+		key_ref = ERR_PTR(-EINVAL);
+		goto error_free_prep;
+	}
+	index_key.desc_len = desclen;
 	key_set_index_key(&index_key);
 
 	ret = __key_link_lock(keyring, &index_key);
security/keys/keyctl.c +0 -2
@@ -24,8 +24,6 @@
 #include <keys/request_key_auth-type.h>
 #include "internal.h"
 
-#define KEY_MAX_DESC_SIZE 4096
-
 static const unsigned char keyrings_capabilities[2] = {
 	[0] = (KEYCTL_CAPS0_CAPABILITIES |
 	       (IS_ENABLED(CONFIG_PERSISTENT_KEYRINGS)	? KEYCTL_CAPS0_PERSISTENT_KEYRINGS : 0) |
security/keys/keyring.c +6 -1
@@ -957,7 +957,6 @@ key_ref_t keyring_search(key_ref_t keyri
 	struct keyring_search_context ctx = {
 		.index_key.type		= type,
 		.index_key.description	= description,
-		.index_key.desc_len	= strlen(description),
 		.cred			= current_cred(),
 		.match_data.cmp		= key_default_cmp,
 		.match_data.raw_data	= description,
@@ -965,8 +964,14 @@ key_ref_t keyring_search(key_ref_t keyri
 		.flags			= KEYRING_SEARCH_DO_STATE_CHECK,
 	};
 	key_ref_t key;
+	size_t desclen;
 	int ret;
 
+	desclen = strlen(description);
+	if (desclen >= KEY_MAX_DESC_SIZE)
+		return ERR_PTR(-EINVAL);
+	ctx.index_key.desc_len = desclen;
+
 	if (recurse)
 		ctx.flags |= KEYRING_SEARCH_RECURSE;
 	if (type->match_preparse) {
security/keys/request_key.c +12 -2
@@ -584,7 +584,6 @@ struct key *request_key_and_link(struct
 		.index_key.type		= type,
 		.index_key.domain_tag	= domain_tag,
 		.index_key.description	= description,
-		.index_key.desc_len	= strlen(description),
 		.cred			= current_cred(),
 		.match_data.cmp		= key_default_cmp,
 		.match_data.raw_data	= description,
@@ -595,8 +594,14 @@ struct key *request_key_and_link(struct
 	};
 	struct key *key;
 	key_ref_t key_ref;
+	size_t desclen;
 	int ret;
 
+	desclen = strlen(description);
+	if (desclen >= KEY_MAX_DESC_SIZE)
+		return ERR_PTR(-EINVAL);
+	ctx.index_key.desc_len = desclen;
+
 	kenter("%s,%s,%p,%zu,%p,%p,%lx",
 	       ctx.index_key.type->name, ctx.index_key.description,
 	       callout_info, callout_len, aux, dest_keyring, flags);
@@ -787,7 +792,6 @@ struct key *request_key_rcu(struct key_t
 		.index_key.type		= type,
 		.index_key.domain_tag	= domain_tag,
 		.index_key.description	= description,
-		.index_key.desc_len	= strlen(description),
 		.cred			= current_cred(),
 		.match_data.cmp		= key_default_cmp,
 		.match_data.raw_data	= description,
@@ -797,6 +801,12 @@ struct key *request_key_rcu(struct key_t
 	};
 	struct key *key;
 	key_ref_t key_ref;
+	size_t desclen;
+
+	desclen = strlen(description);
+	if (desclen >= KEY_MAX_DESC_SIZE)
+		return ERR_PTR(-EINVAL);
+	ctx.index_key.desc_len = desclen;
 
 	kenter("%s,%s", type->name, description);
 
author maintainer
#650 lore raw

PATCH 649/990 KEYS: Verify the key identity in __key_unlink_begin

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jarkko Sakkinen <[email protected]>

commit 7a7f70ff7b26519c98b339a3e0cd9ee3c8d17f77 upstream.

When two keys have identical type and description, linking the second key replaces the first in a keyring. However, attempting to unlink the first key (no longer in the keyring) unlinks the second key.

This happens because __key_unlink_begin() calls assoc_array_delete() with &key->index_key, matching only on type and description rather than the key's identity.

Example:

  keyctl new_session >/dev/null
  keyctl newring ring_a @s
  keyctl newring ring_b @s
  A=$(keyctl add user A ss %:ring_a)
  B=$(keyctl add user A qq %:ring_b)
  keyctl newring R @s
  keyctl link $A %:R
  keyctl link $B %:R
  keyctl unlink $A %:R
  keyctl show

Verify the key identity before unlinking, and return -ENOENT on mismatch, instead of unlinking the key with the wrong identity.

---
 security/keys/keyring.c |    6 ++++++
 1 file changed, 6 insertions(+)
security/keys/keyring.c +6 -0
@@ -1506,9 +1506,15 @@ static int __key_unlink_begin(struct key
 			      struct assoc_array_edit **_edit)
 {
 	struct assoc_array_edit *edit;
+	const void *object;
 
 	BUG_ON(*_edit != NULL);
 
+	object = assoc_array_find(&keyring->keys, &keyring_assoc_array_ops,
+				  &key->index_key);
+	if (!object || keyring_ptr_to_key(object) != key)
+		return -ENOENT;
+
 	edit = assoc_array_delete(&keyring->keys, &keyring_assoc_array_ops,
 				  &key->index_key);
 	if (IS_ERR(edit))
author maintainer
#651 lore raw

PATCH 650/990 bootconfig: Allow keys with the maximum supported depth

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Zhiqi Zhang <[email protected]>

commit cab697164b47eecfa2f146024f5d661f99a1a1e7 upstream.

xbc_verify_tree() accepts keys with XBC_DEPTH_MAX (16) components, but xbc_node_compose_key_after() returns -ERANGE immediately after storing the sixteenth component. It rejects the key before discovering that there are no more ancestors to collect.

For example, a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p = value can be attached to an initrd successfully. However, bootconfig -l stops listing and prints "Failed to compose key -34". In the kernel, the same error propagates through copy_xbc_key_value_list() during its length probe, so proc_boot_config_init() returns before creating /proc/bootconfig.

Check the array capacity before storing the next component. This lets exactly XBC_DEPTH_MAX components be composed while retaining the check before any out-of-bounds store.

I found this issue while reviewing bootconfig's depth handling and used OpenAI Codex to verify the failure and develop the fix. I reviewed the change and wrote and ran the regression tests.

Fixes 76db5a27a827 ("bootconfig: Add Extra Boot Config support")
---
 lib/bootconfig.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
lib/bootconfig.c +1 -1
@@ -302,9 +302,9 @@ int __init xbc_node_compose_key_after(st
 		node = xbc_node_get_parent(node);
 
 	while (node && node != root) {
-		keys[depth++] = xbc_node_index(node);
 		if (depth == XBC_DEPTH_MAX)
 			return -ERANGE;
+		keys[depth++] = xbc_node_index(node);
 		node = xbc_node_get_parent(node);
 	}
 	if (!node && root)
author maintainer
#652 lore raw

PATCH 651/990 ALSA: caiaq: Kill EP1 URB before unregistering the input device

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Sergei Nizovtsev <[email protected]>

commit 5d325345185015024a86abca4cc5fa6a3f75294e upstream.

snd_disconnect() unregisters the input device via snd_usb_caiaq_input_disconnect() and only afterwards kills the EP1 command URB (cdev->ep1_in_urb). The EP1 completion handler usb_ep1_command_reply_dispatch() feeds snd_usb_caiaq_input_dispatch() for EP1_CMD_READ_{ERP,ANALOG,IO} replies, which report into cdev->input_dev. Since commit b04dcbb7f7b1 ("ALSA: caiaq: Use snd_card_free_when_closed() at disconnection") the input device is unregistered from snd_usb_caiaq_input_disconnect() but cdev->input_dev is cleared only later, in snd_usb_caiaq_input_free() from the card destructor. As the dispatch guard only tests cdev->input_dev for NULL, an EP1 reply that completes after input_unregister_device() but before cdev->ep1_in_urb is killed reports into an input device that has already been unregistered and, with no evdev client holding it open, freed.

Normally the window is closed by the USB core: usb_unbind_interface() calls usb_disable_interface() before ->disconnect(), which flushes the EP1 URB as long as endpoint 0x81 belongs to the interface being unbound. But caiaq addresses EP1 through the device-wide pipe usb_rcvbulkpipe(usb_dev, 0x1) without checking which interface owns the endpoint. If a device declares it in another interface, the URB stays live across snd_disconnect() of the interface that owns the card.

This needs a crafted device descriptor; a device that has EP1 in the interface caiaq is bound to is not affected.

Kill cdev->ep1_in_urb (and the paired midi_out_urb) before the input and audio disconnect helpers, so no EP1 completion can run once the input device has been unregistered.

Reproduced under KASAN with raw-gadget + dummy_hcd emulating an Audio Kontrol 1 (17cc:0815) with the EP1 bulk pair in interface 1: only interface 0 was bound to snd-usb-caiaq and then unbound through sysfs while the gadget flooded EP1 with EP1_CMD_READ_ERP replies. With no PCM stream running the window is very short and was only hit by stalling the unbinding CPU with a kgdb breakpoint at snd_usb_caiaq_audio_disconnect(). With the fix applied, the same test runs clean.

  BUG: KASAN: slab-use-after-free in input_event+0x3a/0xc0
  Read of size 8 at addr ffff8880151a4028 by task sh/118

  Call Trace:
   <IRQ>
   input_event+0x3a/0xc0
   snd_usb_caiaq_input_dispatch+0xab2/0xf00
   usb_ep1_command_reply_dispatch+0x1f3/0x580
   __usb_hcd_giveback_urb+0x246/0x400
   dummy_timer+0x1415/0x3380
   __hrtimer_run_queues+0x39d/0x800
   hrtimer_run_softirq+0x187/0x2d0
   handle_softirqs+0x1ff/0x930
   __irq_exit_rcu+0x15b/0x210
   irq_exit_rcu+0xe/0x20
   sysvec_apic_timer_interrupt+0x81/0xb0
   </IRQ>
   <TASK>
   asm_sysvec_apic_timer_interrupt+0x1a/0x20
  RIP: 0010:snd_usb_caiaq_audio_disconnect+0x0/0x70
   snd_disconnect+0x81/0x110
   usb_unbind_interface+0x1a0/0x860
   device_release_driver_internal+0x2c5/0x470
   unbind_store+0xde/0x100
   </TASK>

  Allocated by task 80:
   input_allocate_device+0x47/0x340
   snd_usb_caiaq_input_init+0x4c/0x1ac0
   snd_probe+0xab3/0x1160
   usb_probe_interface+0x2ea/0x810

  Freed by task 118:
   kfree+0x1ea/0x5c0
   input_dev_release+0xab/0xd0
   device_release+0xcf/0x250
   kobject_put+0x169/0x320
   snd_disconnect+0x79/0x110
   usb_unbind_interface+0x1a0/0x860
Fixes b04dcbb7f7b1 ("ALSA: caiaq: Use snd_card_free_when_closed() at disconnection")
Assisted-by Claude:claude-opus-4-8
---
 sound/usb/caiaq/device.c |   11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)
sound/usb/caiaq/device.c +8 -3
@@ -593,14 +593,19 @@ static void snd_disconnect(struct usb_in
 
 	snd_card_disconnect(card);
 
+	/*
+	 * Kill the EP1 URB before disconnecting the input device: its
+	 * completion reports into cdev->input_dev, which input_disconnect()
+	 * frees without clearing the pointer.
+	 */
+	usb_kill_urb(cdev->ep1_in_urb);
+	usb_kill_urb(cdev->midi_out_urb);
+
 #ifdef CONFIG_SND_USB_CAIAQ_INPUT
 	snd_usb_caiaq_input_disconnect(cdev);
 #endif
 	snd_usb_caiaq_audio_disconnect(cdev);
 
-	usb_kill_urb(cdev->ep1_in_urb);
-	usb_kill_urb(cdev->midi_out_urb);
-
 	snd_card_free_when_closed(card);
 }
 
author maintainer
#653 lore raw

PATCH 652/990 ALSA: hda/realtek: Fix the Dell XPS 8940 headset microphone

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Angel J <[email protected]>

commit ae28ba98f55a2f30fed57371899b8cecd7cbde64 upstream.

The Dell XPS 8940 (1028:09c5) has an ALC3861 codec (0x10ec0899). Its BIOS marks the headset microphone pin at NID 0x19 as disconnected (0x411111f0). With no external microphone input in the pin configuration, the generic parser creates a shared headphone/mic input on NID 0x1b instead. Headphone playback works, but the headset microphone is silent.

Override NID 0x19 as a front microphone without independent presence detection. This gives the generic parser the dedicated microphone input and preserves NID 0x1b for simultaneous headphone playback.

I encountered this issue on my XPS 8940. Similar symptoms were also reported by a user on Ubuntu:
https://bugs.launchpad.net/bugs/1971232

---
 sound/hda/codecs/realtek/alc882.c |   10 ++++++++++
 1 file changed, 10 insertions(+)
sound/hda/codecs/realtek/alc882.c +10 -0
@@ -50,6 +50,7 @@ enum {
 	ALC889_FIXUP_MP41_VREF,
 	ALC882_FIXUP_INV_DMIC,
 	ALC882_FIXUP_NO_PRIMARY_HP,
+	ALC898_FIXUP_DELL_XPS8940_MIC,
 	ALC887_FIXUP_ASUS_BASS,
 	ALC887_FIXUP_BASS_CHMAP,
 	ALC1220_FIXUP_GB_DUAL_CODECS,
@@ -507,6 +508,13 @@ static const struct hda_fixup alc882_fix
 		.type = HDA_FIXUP_FUNC,
 		.v.func = alc882_fixup_no_primary_hp,
 	},
+	[ALC898_FIXUP_DELL_XPS8940_MIC] = {
+		.type = HDA_FIXUP_PINS,
+		.v.pins = (const struct hda_pintbl[]) {
+			{ 0x19, 0x02a19130 }, /* headset mic, no separate jack detect */
+			{}
+		},
+	},
 	[ALC887_FIXUP_ASUS_BASS] = {
 		.type = HDA_FIXUP_PINS,
 		.v.pins = (const struct hda_pintbl[]) {
@@ -610,6 +618,8 @@ static const struct hda_quirk alc882_fix
 	SND_PCI_QUIRK(0x1025, 0x0259, "Acer Aspire 5935", ALC889_FIXUP_DAC_ROUTE),
 	SND_PCI_QUIRK(0x1025, 0x026b, "Acer Aspire 8940G", ALC882_FIXUP_ACER_ASPIRE_8930G),
 	SND_PCI_QUIRK(0x1025, 0x0296, "Acer Aspire 7736z", ALC882_FIXUP_ACER_ASPIRE_7736),
+	SND_PCI_QUIRK(0x1028, 0x09c5, "Dell XPS 8940",
+		      ALC898_FIXUP_DELL_XPS8940_MIC),
 	SND_PCI_QUIRK(0x1043, 0x13c2, "Asus A7M", ALC882_FIXUP_EAPD),
 	SND_PCI_QUIRK(0x1043, 0x1873, "ASUS W90V", ALC882_FIXUP_ASUS_W90V),
 	SND_PCI_QUIRK(0x1043, 0x1971, "Asus W2JC", ALC882_FIXUP_ASUS_W2JC),
author maintainer
#654 lore raw

PATCH 653/990 ALSA: usb-audio: Drop capture packets with bogus actual_length

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Gichoon Han <[email protected]>

commit eed0e9583a290e6adbe3a8480bdae911f31e1ed9 upstream.

retire_capture_urb() copies urb->iso_frame_desc[i].actual_length bytes out of urb->transfer_buffer at the packet's offset, but never checks that value against the requested packet length. A host controller reporting more data than requested makes memcpy() read past the end of the URB transfer buffer.

Commit 06be918062ad ("ALSA: usb-audio: Bound packet copies by the PCM buffer size") clamps the count to the PCM ring buffer size, which protects the destination. The source slot is only ep->curpacksize bytes per packet, though, so the over-read remains.

This was hit on an ARM32 system (vendor 5.4 kernel; the code path is unchanged in mainline) with a full-speed UAC1 microphone behind a high-speed hub, i.e. the EHCI siTD path. sitd_complete() computes actual_length as desc->length - SITD_LENGTH(t); the controller reported a remaining length larger than the programmed one, the value wrapped to ~4G, and the capture copy faulted on the first unmapped page after the URB buffer:

  Unable to handle kernel paging request at virtual address e8756000
  Internal error: Oops: 7 [#1] PREEMPT SMP ARM
  r3 : 00000000  r2 : 0001e700  r1 : e8756000  r0 : e878fc80
  Code: ba000002 f5d1f03c f5d1f05c f5d1f07c (e8b151f8)

A packet can never legitimately carry more than its requested length, so warn and skip it instead of copying.

---
 sound/usb/pcm.c |    6 ++++++
 1 file changed, 6 insertions(+)
sound/usb/pcm.c +6 -0
@@ -1337,6 +1337,12 @@ static void retire_capture_urb(struct sn
 					    "frame %d active: %d\n", i,
 					    urb->iso_frame_desc[i].status);
 		bytes = urb->iso_frame_desc[i].actual_length;
+		if (unlikely(bytes > urb->iso_frame_desc[i].length)) {
+			dev_warn_ratelimited(&subs->dev->dev,
+					     "packet %d: actual_length %u exceeds length %u, dropping\n",
+					     i, bytes, urb->iso_frame_desc[i].length);
+			continue;
+		}
 		if (subs->stream_offset_adj > 0) {
 			unsigned int adj = min(subs->stream_offset_adj, bytes);
 			cp += adj;
author maintainer
#655 lore raw

PATCH 654/990 ALSA: hda: Fix [codec] ID matching in patch files for IDs with bit 31 set

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Andrew Davison <[email protected]>

commit fda103c1432f344e1cd548f346d157b1e67ee7c5 upstream.

parse_codec_mode() reads the vendor and subsystem IDs of a patch file's [codec] line into an int, and skips the check when the value is zero or negative, as documented. An ID with bit 31 set, such as SigmaTel's 0x8384xxxx or Intel's 0x8086xxxx, comes out negative, so it is taken as a wildcard and the section is applied to every codec instead of the one it names.

This was seen on an OpenPeak OpenFrame 2 with an IDT 92HD75B2X5 (0x111d7608). A patch file written for the STAC9202 (0x83847632) in the related OpenFrame 1 was applied to it, swapping the headphone and speaker pin configurations, so auto-mute never muted the speaker.

Read the IDs as long long, so real IDs are compared exactly. Values written as negative numbers (e.g. -1) still act as wildcards, as documented; a hex value such as 0xffffffff is now compared as written.

Tested on 6.18.60 on an OpenFrame 2, with a rebuilt snd-hda-codec and the STAC9202 patch file: user_pin_configs stays empty for the IDT codec, and the headphone and line-out pins are assigned as the BIOS sets them. Not tested on a STAC9202 itself.

The bug was tracked down and this fix written with an AI coding assistant (Claude Code, Claude Opus 5.5), which also ran the tests above. I have reviewed the change and the tests.

Fixes ef940b0403d4 ("ALSA: hda - Allow patching with any vendor/subsystem ids")
---
 sound/hda/common/sysfs.c |    5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
sound/hda/common/sysfs.c +3 -2
@@ -511,11 +511,12 @@ static inline int strmatch(const char *a
 static void parse_codec_mode(char *buf, struct hda_bus *bus,
 			     struct hda_codec **codecp)
 {
-	int vendorid, subid, caddr;
+	long long vendorid, subid;
+	int caddr;
 	struct hda_codec *codec;
 
 	*codecp = NULL;
-	if (sscanf(buf, "%i %i %i", &vendorid, &subid, &caddr) == 3) {
+	if (sscanf(buf, "%lli %lli %i", &vendorid, &subid, &caddr) == 3) {
 		list_for_each_codec(codec, bus) {
 			if ((vendorid <= 0 || codec->core.vendor_id == vendorid) &&
 			    (subid <= 0 || codec->core.subsystem_id == subid) &&
author maintainer
#656 lore raw

PATCH 655/990 selftests/ftrace: Add missing spaces after ! in probe syntax tests

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jaewon Jung <[email protected]>

commit 36990c8fda77d918b1e52d5d6df3a144b552d86e upstream.

Add the missing space between ! and grep. Otherwise, the shell tries to run !grep and reports "!grep: not found". This always skips the conditional checks without checking for kernel return probe argument support.

Fixes 25f00e40ce79 ("tracing/probes: Support $argN in return probe (kprobe and fprobe)")
---
 tools/testing/selftests/ftrace/test.d/dynevent/fprobe_syntax_errors.tc |    4 ++--
 tools/testing/selftests/ftrace/test.d/kprobe/kprobe_syntax_errors.tc   |    2 +-
 2 files changed, 3 insertions(+), 3 deletions(-)
tools/testing/selftests/ftrace/test.d/dynevent/fprobe_syntax_errors.tc +2 -2
@@ -33,7 +33,7 @@ check_error 'f vfs_read ^$stack10000'	#
 
 check_error 'f vfs_read ^$arg10000'	# BAD_ARG_NUM
 
-if !grep -q 'kernel return probes support:' README; then
+if ! grep -q 'kernel return probes support:' README; then
 check_error 'f vfs_read $retval ^$arg1' # BAD_VAR
 fi
 check_error 'f vfs_read ^$none_var'	# BAD_VAR
@@ -100,7 +100,7 @@ if grep -q "<argname>" README; then
 check_error 'f vfs_read args=^$arg*'		# BAD_VAR_ARGS
 check_error 'f vfs_read +0(^$arg*)'		# BAD_VAR_ARGS
 check_error 'f vfs_read $arg* ^$arg*'		# DOUBLE_ARGS
-if !grep -q 'kernel return probes support:' README; then
+if ! grep -q 'kernel return probes support:' README; then
 check_error 'f vfs_read%return ^$arg*'		# NOFENTRY_ARGS
 fi
 check_error 'f vfs_read ^hoge'			# NO_BTFARG
tools/testing/selftests/ftrace/test.d/kprobe/kprobe_syntax_errors.tc +1 -1
@@ -108,7 +108,7 @@ if grep -q "<argname>" README; then
 check_error 'p vfs_read args=^$arg*'		# BAD_VAR_ARGS
 check_error 'p vfs_read +0(^$arg*)'		# BAD_VAR_ARGS
 check_error 'p vfs_read $arg* ^$arg*'		# DOUBLE_ARGS
-if !grep -q 'kernel return probes support:' README; then
+if ! grep -q 'kernel return probes support:' README; then
 check_error 'r vfs_read ^$arg*'			# NOFENTRY_ARGS
 fi
 check_error 'p vfs_read+20 ^$arg*'		# NOFENTRY_ARGS
author maintainer
#657 lore raw

PATCH 656/990 tracing/selftests: Fix false bashism in kprobe_non_uniq_symbol.tc

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Steven Rostedt <[email protected]>

commit 88d5f8cb8a6276194ac8c1de44f3ed77d7e938ce upstream.

The checkbashism is giving a false positive to the kprobe test of:

($"foo" should be eval_gettext "foo"):
if [ "$(grep -c -E "[[:alnum:]]+ t ${SYMBOL}$" /proc/kallsyms)" -le '1' ]; then

This is because it sees the $" at the end of the grep as a bash symbol. Instead, escape the '$' with a backslash as it is within quotes and that '$' is for grep to process an end of line character and not a bash variable.

---
 tools/testing/selftests/ftrace/test.d/kprobe/kprobe_non_uniq_symbol.tc |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/testing/selftests/ftrace/test.d/kprobe/kprobe_non_uniq_symbol.tc +1 -1
@@ -6,7 +6,7 @@
 SYMBOL='name_show'
 
 # We skip this test on kernel where SYMBOL is unique or does not exist.
-if [ "$(grep -c -E "[[:alnum:]]+ t ${SYMBOL}$" /proc/kallsyms)" -le '1' ]; then
+if [ "$(grep -c -E "[[:alnum:]]+ t ${SYMBOL}\$" /proc/kallsyms)" -le '1' ]; then
 	exit_unsupported
 fi
 
author maintainer
#658 lore raw

PATCH 657/990 kprobes: Fix error return and slot leak in __register_kprobe()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Masami Hiramatsu (Google) <[email protected]>

commit 6a658cc2d605e5acf35e638c62f480460d5939cd upstream.

When arm_kprobe() fails in __register_kprobe(), the probe is removed from kprobe_table and synchronize_rcu() is executed, but the error code ret was ignored and try_to_optimize_kprobe(p) was executed, returning 0. Additionally, the instruction slot allocated by prepare_kprobe() was leaked.

Fix this by releasing the instruction slot via arch_remove_kprobe(p) and returning ret when arm_kprobe() fails.

Fixes 587e8e6d640b ("kprobes: Adopt guard() and scoped_guard()")
---
 kernel/kprobes.c |    2 ++
 1 file changed, 2 insertions(+)
kernel/kprobes.c +2 -0
@@ -1631,6 +1631,8 @@ static int __register_kprobe(struct kpro
 		if (ret) {
 			hlist_del_rcu(&p->hlist);
 			synchronize_rcu();
+			arch_remove_kprobe(p);
+			return ret;
 		}
 	}
 
author maintainer
#659 lore raw

PATCH 658/990 kprobes: Fix double free and NULL deref in unregister_kretprobes()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Masami Hiramatsu (Google) <[email protected]>

commit 2053bac1d6e47b33fa2e570c87518395e64f7da0 upstream.

In unregister_kretprobes(), if __unregister_kprobe_top() returns an error (e.g., if the kretprobe was not registered or was already unregistered), rethook_free(rps[i]->rh) or rcu_assign_pointer(rps[i]->rph->rp, NULL) is still executed. For rethook-based kretprobes, calling rethook_free() on an already-freed rethook causes a double-free / list corruption in RCU. For legacy kretprobes, rps[i]->rph is NULL after previous cleanup, resulting in a NULL pointer dereference.

Skip rethook_free() and rph cleanup if __unregister_kprobe_top() fails, and clear rps[i]->rh after synchronize_rcu() has waited for in-flight pre_handler_kretprobe() invocations to complete.

Fixes 73f9b911faa7 ("kprobes: Use rethook for kretprobe if possible")
---
 kernel/kprobes.c |    8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
kernel/kprobes.c +6 -2
@@ -2290,8 +2290,10 @@ void unregister_kretprobes(struct kretpr
 	for (i = 0; i < num; i++) {
 		guard(mutex)(&kprobe_mutex);
 
-		if (__unregister_kprobe_top(&rps[i]->kp) < 0)
+		if (__unregister_kprobe_top(&rps[i]->kp) < 0) {
 			rps[i]->kp.addr = NULL;
+			continue;
+		}
 #ifdef CONFIG_KRETPROBE_ON_RETHOOK
 		rethook_free(rps[i]->rh);
 #else
@@ -2303,7 +2305,9 @@ void unregister_kretprobes(struct kretpr
 	for (i = 0; i < num; i++) {
 		if (rps[i]->kp.addr) {
 			__unregister_kprobe_bottom(&rps[i]->kp);
-#ifndef CONFIG_KRETPROBE_ON_RETHOOK
+#ifdef CONFIG_KRETPROBE_ON_RETHOOK
+			rps[i]->rh = NULL;
+#else
 			free_rp_inst(rps[i]);
 #endif
 		}
author maintainer
#660 lore raw

PATCH 659/990 kprobes: Validate re-registration earlier in register_kretprobe()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Masami Hiramatsu (Google) <[email protected]>

commit a553b499f22bf054964d4fd16d136f3d4f836c23 upstream.

register_kretprobe() only checked for re-registration if rp->kp.addr was specified, skipping the check when rp was registered with symbol_name and rp->kp.addr was NULL. In that scenario, register_kretprobe() proceeded to allocate a new rethook (or kretprobe holder), and when register_kprobe(&rp->kp) subsequently failed due to re-registration, the error path freed and NULL-ed rp->rh (or rp->rph) on the still-active kretprobe, leading to NULL pointer dereferences when the active probe was hit.

Resolve the target address via _kprobe_addr() up-front and check whether the probe is already registered at that address via check_kprobe_rereg_at() before allocating any resources, and drop the WARN_ON_ONCE() in the re-registration check now that re-registration is gracefully detected and rejected.

Fixes 0188b87899ff ("kretprobe: Avoid re-registration of the same kretprobe earlier")
---
 kernel/kprobes.c |   72 ++++++++++++++++++++++++++++++-------------------------
 1 file changed, 40 insertions(+), 32 deletions(-)
kernel/kprobes.c +40 -32
@@ -1478,52 +1478,61 @@ _kprobe_addr(kprobe_opcode_t *addr, cons
 	return addr;
 }
 
-static kprobe_opcode_t *kprobe_addr(struct kprobe *p)
-{
-	bool on_func_entry;
-
-	return _kprobe_addr(p->addr, p->symbol_name, p->offset, &on_func_entry);
-}
-
 /*
  * Check the 'p' is valid and return the aggregator kprobe
  * at the same address.
  */
-static struct kprobe *__get_valid_kprobe(struct kprobe *p)
+static struct kprobe *__get_valid_kprobe_at(struct kprobe *p, kprobe_opcode_t *addr)
 {
+	struct hlist_head *head;
 	struct kprobe *ap, *list_p;
 
 	lockdep_assert_held(&kprobe_mutex);
 
-	ap = get_kprobe(p->addr);
-	if (unlikely(!ap))
+	if (unlikely(!addr))
 		return NULL;
 
-	if (p == ap)
-		return ap;
-
-	list_for_each_entry(list_p, &ap->list, list)
-		if (list_p == p)
-		/* kprobe p is a valid probe */
+	head = &kprobe_table[hash_ptr(addr, KPROBE_HASH_BITS)];
+	hlist_for_each_entry_rcu(ap, head, hlist,
+				 lockdep_is_held(&kprobe_mutex)) {
+		if (ap == p) {
+			p->addr = addr;
 			return ap;
+		}
+		if (ap->addr == addr && kprobe_aggrprobe(ap)) {
+			list_for_each_entry(list_p, &ap->list, list) {
+				if (list_p == p) {
+					p->addr = addr;
+					return ap;
+				}
+			}
+		}
+	}
 
 	return NULL;
 }
 
-/*
- * Warn and return error if the kprobe is being re-registered since
- * there must be a software bug.
- */
-static inline int warn_kprobe_rereg(struct kprobe *p)
+static inline struct kprobe *__get_valid_kprobe(struct kprobe *p)
+{
+	return __get_valid_kprobe_at(p, p->addr);
+}
+
+/* Return error if the kprobe is being re-registered */
+static inline int check_kprobe_rereg_at(struct kprobe *p, kprobe_opcode_t *addr)
 {
 	guard(mutex)(&kprobe_mutex);
 
-	if (WARN_ON_ONCE(__get_valid_kprobe(p)))
+	if (__get_valid_kprobe_at(p, addr))
 		return -EINVAL;
 
 	return 0;
 }
 
+static inline int check_kprobe_rereg(struct kprobe *p)
+{
+	return check_kprobe_rereg_at(p, p->addr);
+}
+
 static int check_ftrace_location(struct kprobe *p)
 {
 	unsigned long addr = (unsigned long)p->addr;
@@ -1654,7 +1663,7 @@ int register_kprobe(struct kprobe *p)
 		return PTR_ERR(addr);
 	p->addr = addr;
 
-	ret = warn_kprobe_rereg(p);
+	ret = check_kprobe_rereg(p);
 	if (ret)
 		return ret;
 
@@ -2190,20 +2199,19 @@ int register_kretprobe(struct kretprobe
 	int ret;
 	int i;
 	void *addr;
+	bool on_func_entry;
 
-	ret = kprobe_on_func_entry(rp->kp.addr, rp->kp.symbol_name, rp->kp.offset);
-	if (ret)
-		return ret;
+	addr = _kprobe_addr(rp->kp.addr, rp->kp.symbol_name, rp->kp.offset, &on_func_entry);
+	if (IS_ERR(addr))
+		return PTR_ERR(addr);
+
+	if (!on_func_entry)
+		return -EINVAL;
 
-	/* If only 'rp->kp.addr' is specified, check reregistering kprobes */
-	if (rp->kp.addr && warn_kprobe_rereg(&rp->kp))
+	if (check_kprobe_rereg_at(&rp->kp, addr))
 		return -EINVAL;
 
 	if (kretprobe_blacklist_size) {
-		addr = kprobe_addr(&rp->kp);
-		if (IS_ERR(addr))
-			return PTR_ERR(addr);
-
 		for (i = 0; kretprobe_blacklist[i].name != NULL; i++) {
 			if (kretprobe_blacklist[i].addr == addr)
 				return -EINVAL;
author maintainer
#661 lore raw

PATCH 660/990 mmc: jz4740: Remove the host before resetting the controller

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Olivier Louvignes <[email protected]>

commit 6b8b1e8827837bf4cf1f87219038fddae9e81b0b upstream.

jz4740_mmc_remove() masks every interrupt and resets the controller before mmc_remove_host(), which removes the card and lets the card's driver send its last commands. Those commands then run on a controller that was just reset, and can wait out the driver's 5 s request timeout.

With an SDIO card that cost 5 s on every unbind: on a HiBy R1 (Ingenic X1600, a BCM43430A1 driven by brcmfmac), the CMD52 that sdio_release_irq() sends from brcmfmac's remove waited 5.1 s. The command had finished (END_CMD_RES set in MSC_STAT), but MSC_IMASK read 0xffffffff although the request had unmasked END_CMD_RES. MSC_STAT can still show IS_RESETTING after jz4740_mmc_reset() returns, so the reset most likely completed after that write and undid it.

Remove the host first, then quiesce the controller, as other host drivers do. On the R1, unbinding the Wi-Fi's MSC now takes 0.65 s.

Fixes 61bfbdb85687 ("MMC: Add support for the controller on JZ4740 SoCs.")
---
 drivers/mmc/host/jz4740_mmc.c |    5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/mmc/host/jz4740_mmc.c +3 -2
@@ -1151,12 +1151,13 @@ static void jz4740_mmc_remove(struct pla
 {
 	struct jz4740_mmc_host *host = platform_get_drvdata(pdev);
 
+	/* The card's driver may still send commands as it goes */
+	mmc_remove_host(host->mmc);
+
 	timer_delete_sync(&host->timeout_timer);
 	jz4740_mmc_set_irq_enabled(host, 0xff, false);
 	jz4740_mmc_reset(host);
 
-	mmc_remove_host(host->mmc);
-
 	free_irq(host->irq, host);
 
 	if (host->use_dma)
author maintainer
#662 lore raw

PATCH 661/990 mmc: sunxi: fix clock and runtime PM leaks on probe failure

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Anfernee Cao <[email protected]>

commit e35e360bd66898a977c296ab71fe4bae17ddceb7 upstream.

sunxi_mmc_resource_request() enables the bus, card, output and sample clocks before returning. Several failure paths later in sunxi_mmc_probe() leave them running:

- If devm_request_threaded_irq() fails, the clocks enabled by sunxi_mmc_enable() are never disabled.
- If dma_alloc_coherent(), mmc_of_parse() or sunxi_mmc_init_host() fails, probe only frees the DMA buffer and the mmc_host.
- If mmc_add_host() fails, runtime PM has already been enabled, but pm_runtime_disable() is never called.

Besides leaking the clocks, this leaves the clock enable counts unbalanced, so a reprobe (for example after -EPROBE_DEFER) calls clk_prepare_enable() on the same clocks again.

Disable the IRQ and the clocks in the probe error path, and disable runtime PM on the mmc_add_host() failure path. Also handle a failure of devm_request_threaded_irq() in sunxi_mmc_resource_request().

Tested with QEMU's orangepi-pc machine: with forced sunxi_mmc_init_host() and mmc_add_host() failures the MMC clocks stay disabled in clk_summary, and a normal probe with an emulated SD card still works.

This issue was found by manual code inspection.

Fixes 3cbcb16095f9 ("mmc: sunxi: Add driver for SD/MMC hosts found on Allwinner sunxi SoCs")
Fixes 9a8e1e8cc2c0 ("mmc: sunxi: Add runtime_pm support")
Cc [email protected] # v4.18+
---
 drivers/mmc/host/sunxi-mmc.c |   24 ++++++++++++++++++------
 1 file changed, 18 insertions(+), 6 deletions(-)
drivers/mmc/host/sunxi-mmc.c +18 -6
@@ -1355,8 +1355,13 @@ static int sunxi_mmc_resource_request(st
 		goto error_disable_mmc;
 	}
 
-	return devm_request_threaded_irq(&pdev->dev, host->irq, sunxi_mmc_irq,
-			sunxi_mmc_handle_manual_stop, 0, "sunxi-mmc", host);
+	ret = devm_request_threaded_irq(&pdev->dev, host->irq, sunxi_mmc_irq,
+					sunxi_mmc_handle_manual_stop, 0,
+					"sunxi-mmc", host);
+	if (ret)
+		goto error_disable_mmc;
+
+	return 0;
 
 error_disable_mmc:
 	sunxi_mmc_disable(host);
@@ -1386,9 +1391,11 @@ static int sunxi_mmc_probe(struct platfo
 
 	host->sg_cpu = dma_alloc_coherent(&pdev->dev, PAGE_SIZE,
 					  &host->sg_dma, GFP_KERNEL);
-	if (!host->sg_cpu)
-		return dev_err_probe(&pdev->dev, -ENOMEM,
-				     "Failed to allocate DMA descriptor mem\n");
+	if (!host->sg_cpu) {
+		ret = dev_err_probe(&pdev->dev, -ENOMEM,
+				    "Failed to allocate DMA descriptor mem\n");
+		goto error_disable_mmc;
+	}
 
 	if (host->cfg->ccu_has_timings_switch) {
 		/*
@@ -1468,7 +1475,7 @@ static int sunxi_mmc_probe(struct platfo
 
 	ret = mmc_add_host(mmc);
 	if (ret)
-		goto error_free_dma;
+		goto error_disable_rpm;
 
 	dev_info(&pdev->dev, "initialized, max. request size: %u KB%s\n",
 		 mmc->max_req_size >> 10,
@@ -1476,8 +1483,13 @@ static int sunxi_mmc_probe(struct platfo
 
 	return 0;
 
+error_disable_rpm:
+	pm_runtime_disable(&pdev->dev);
 error_free_dma:
 	dma_free_coherent(&pdev->dev, PAGE_SIZE, host->sg_cpu, host->sg_dma);
+error_disable_mmc:
+	disable_irq(host->irq);
+	sunxi_mmc_disable(host);
 	return ret;
 }
 
author maintainer
#663 lore raw

PATCH 662/990 mmc: mmci: fix DMA channel leak when mmc_add_host() fails

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Anfernee Cao <[email protected]>

commit 2d8927fadbf95e2d2dfa95bcc73882d6e19c2ce4 upstream.

mmci_probe() calls mmci_dma_setup(), which acquires the RX and TX DMA channels via dma_request_chan(). These channels are not managed by devres, and are released only by mmci_dma_release().

If the following mmc_add_host() fails, probe jumps to the clk_disable label, which only disables the clock. As probe then fails, mmci_remove() is never called, so both DMA channels are leaked.

Release them by adding a dedicated unwind label, reached only after mmci_dma_setup().

This issue was found by manual code inspection.

Fixes b38a20f29a49 ("mmc: mmci: fix return value check of mmc_add_host()")
---
 drivers/mmc/host/mmci.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/mmc/host/mmci.c +3 -1
@@ -2477,11 +2477,13 @@ static int mmci_probe(struct amba_device
 
 	ret = mmc_add_host(mmc);
 	if (ret)
-		goto clk_disable;
+		goto dma_release;
 
 	pm_runtime_put(&dev->dev);
 	return 0;
 
+dma_release:
+	mmci_dma_release(host);
  clk_disable:
 	clk_disable_unprepare(host->clk);
 	return ret;
author maintainer
#664 lore raw

PATCH 663/990 mmc: omap: synchronize clock timer before disabling fclk

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Runyu Xiao <[email protected]>

commit c931c51681e33b24bc8d65c6df35b70e1827daa2 upstream.

mmc_omap_select_slot() removes clk_timer with timer_delete() before switching slots and changing the functional clock state. timer_delete() only removes a pending timer and does not wait for a callback that is already running.

If mmc_omap_clk_timer() is already running, it can therefore call mmc_omap_fclk_enable() while the request or slot-switch path changes the same clock state. During host removal, the same window can overlap the final clock shutdown.

Use timer_delete_sync() so the callback has completed before slot switching or changing the functional clock state. Keep the timer restartable for normal request handling.

Fixes 0807a9b5739a ("MMC: OMAP: Lazy clock shutdown")
---
 drivers/mmc/host/omap.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/mmc/host/omap.c +2 -2
@@ -214,7 +214,7 @@ static void mmc_omap_select_slot(struct
 	host->mmc = slot->mmc;
 	spin_unlock_irqrestore(&host->slot_lock, flags);
 no_claim:
-	timer_delete(&host->clk_timer);
+	timer_delete_sync(&host->clk_timer);
 	if (host->current_slot != slot || !claimed)
 		mmc_omap_fclk_offdelay(host->current_slot);
 
@@ -273,7 +273,7 @@ static void mmc_omap_release_slot(struct
 		/* Keeps clock running for at least 8 cycles on valid freq */
 		mod_timer(&host->clk_timer, jiffies  + HZ/10);
 	else {
-		timer_delete(&host->clk_timer);
+		timer_delete_sync(&host->clk_timer);
 		mmc_omap_fclk_offdelay(slot);
 		mmc_omap_fclk_enable(host, 0);
 	}
author maintainer
#665 lore raw

PATCH 664/990 mmc: sdhci-esdhc-imx: map unsupported driver type to Type B

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Ian Ray <[email protected]>

commit d35d93c2902592a84347a15deac4d67a323694c9 upstream.

Since commit 5a52c5701a67 ("mmc: core: Fix host controller programming for fixed driver type"), the eMMC driver strength is passed directly to mmc_set_driver_type(), which propagates the value through ios.drv_type all the way to sdhci_set_ios(). For value 4, SDHCI correctly warns:

mmc2: invalid driver type, default to driver type B

The host driver type has no effect on this controller: esdhc_writew_le() never programs the driver-type field of SDHCI_HOST_CONTROL2. Hook set_ios() and force drv_type to the always-valid Type B, so that SDHCI never sees an unsupported value.

Tested on i.MX8MP (usdhc3, eMMC in HS400) with fixed-emmc-driver-type = <4>: the warning is gone and the HS_TIMING register contains 0x43 as expected.

---
 drivers/mmc/host/sdhci-esdhc-imx.c |   17 +++++++++++++++++
 1 file changed, 17 insertions(+)
drivers/mmc/host/sdhci-esdhc-imx.c +17 -0
@@ -1131,6 +1131,20 @@ static void esdhc_reset_tuning(struct sd
 	}
 }
 
+static void sdhci_esdhc_imx_set_ios(struct mmc_host *mmc, struct mmc_ios *ios)
+{
+	/*
+	 * This controller has no driver-type control: esdhc_writew_le()
+	 * discards the driver-type field when writing SDHCI_HOST_CONTROL2.
+	 * The programmed value is therefore irrelevant, but SDHCI rejects
+	 * non-SD values such as 4 (eMMC 40 ohm, from fixed-emmc-driver-type).
+	 * Force an always-valid Type B.
+	 */
+	ios->drv_type = MMC_SET_DRIVER_TYPE_B;
+
+	sdhci_set_ios(mmc, ios);
+}
+
 static void usdhc_init_card(struct mmc_host *mmc, struct mmc_card *card)
 {
 	struct sdhci_host *host = mmc_priv(mmc);
@@ -1929,6 +1943,9 @@ static int sdhci_esdhc_imx_probe(struct
 		host->max_timeout_count = 0xF;
 	}
 
+	/* No SDHCI driver type control */
+	host->mmc_host_ops.set_ios = sdhci_esdhc_imx_set_ios;
+
 	if (imx_data->socdata->flags & ESDHC_FLAG_MAN_TUNING)
 		sdhci_esdhc_ops.platform_execute_tuning =
 					esdhc_executing_tuning;
author maintainer
#666 lore raw

PATCH 665/990 mmc: meson-gx: report busy from DAT0 alone

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Igor Velkov <[email protected]>

commit 318fdb75f4dc9d18ae621b9fb25eb11160c95649 upstream.

meson_mmc_card_busy() reports busy only while DAT0..3 are all low. A busy card drives DAT0 low and leaves DAT1..3 to the pull-ups, and the callback is defined as "Check if the card is pulling dat[0] low". So a busy card is reported free, and the core, which prefers card_busy over CMD13 in mmc_busy_cb(), stops polling after CMD6 and erase at once. The controller hides this on R1b commands, where it waits for busy itself. Once max_busy_timeout is reported, the core sends the longer waits, the 120 s BKOPS and 240 s sanitize switches among them, as R1 and has only the polling left.

Look at DAT0 only, as sdhci_card_busy() does. The checks around the voltage switch in mmc_set_uhs_voltage() still hold: the card drives DAT0..3 low together after CMD11 and keeps them low together on failure.

Fixes 186cd8b7f586 ("mmc: meson-gx: implement card_busy callback")
---
 drivers/mmc/host/meson-gx-mmc.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/mmc/host/meson-gx-mmc.c +2 -2
@@ -1079,8 +1079,8 @@ static int meson_mmc_card_busy(struct mm
 
 	regval = readl(host->regs + SD_EMMC_STATUS);
 
-	/* We are only interrested in lines 0 to 3, so mask the other ones */
-	return !(FIELD_GET(STATUS_DATI, regval) & 0xf);
+	/* The card signals busy on DAT0 alone. */
+	return !(FIELD_GET(STATUS_DATI, regval) & BIT(0));
 }
 
 static int meson_mmc_voltage_switch(struct mmc_host *mmc, struct mmc_ios *ios)
author maintainer
#667 lore raw

PATCH 666/990 mmc: meson-gx: honour the busy timeout for R1b commands

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Igor Velkov <[email protected]>

commit 7e3cc541aa5855bc36e6cbffa82efc2795955a10 upstream.

For a command without data the driver programs a fixed 1024 ms into the CMD_CFG timeout field, and for R1b the controller waits for the card to release busy within that time. The core sends erase and cache flush as R1b with busy timeouts of up to 60 s and 30 s, and the controller gives up after one second:

mmc_erase: erase error -110, status 0x0
mmc1: cache flush error -110

Program the timeout from cmd->busy_timeout, kept between 1024 ms, the fixed value until now, and 32768 ms, the most the field holds, and rounded up to a power of two. The clamp comes first: MMC_IOC_CMD passes cmd_timeout_ms from user space straight into busy_timeout, and roundup_pow_of_two() of a value above 2^31 does not fit in unsigned int. sdhci takes its command timeout from cmd->busy_timeout in the same way.

Fixes 51c5d8447bd7 ("MMC: meson: initial support for GX platforms")
---
 drivers/mmc/host/meson-gx-mmc.c |   16 +++++++++++++++-
 1 file changed, 15 insertions(+), 1 deletion(-)
drivers/mmc/host/meson-gx-mmc.c +15 -1
@@ -214,6 +214,20 @@ static unsigned int meson_mmc_get_timeou
 	return min(timeout, 32768U); /* max. 2^15 ms */
 }
 
+/* For R1b the controller waits for busy to be released within this timeout. */
+static unsigned int meson_mmc_get_cmd_timeout_msecs(struct mmc_command *cmd)
+{
+	unsigned int timeout = cmd->busy_timeout;
+
+	if (!timeout)
+		return SD_EMMC_CMD_TIMEOUT;
+
+	timeout = clamp_t(unsigned int, timeout, SD_EMMC_CMD_TIMEOUT,
+			  SD_EMMC_CMD_TIMEOUT_MAX);
+
+	return roundup_pow_of_two(timeout);
+}
+
 static struct mmc_command *meson_mmc_get_next_command(struct mmc_command *cmd)
 {
 	if (cmd->opcode == MMC_SET_BLOCK_COUNT && !cmd->error)
@@ -840,7 +854,7 @@ static void meson_mmc_start_cmd(struct m
 		cmd_data = host->bounce_dma_addr & CMD_DATA_MASK;
 	} else {
 		cmd_cfg |= FIELD_PREP(CMD_CFG_TIMEOUT_MASK,
-				      ilog2(SD_EMMC_CMD_TIMEOUT));
+				      ilog2(meson_mmc_get_cmd_timeout_msecs(cmd)));
 	}
 
 	/* Last descriptor */
author maintainer
#668 lore raw

PATCH 667/990 mmc: meson-gx: report the longest busy wait the controller can do

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Igor Velkov <[email protected]>

commit 18e9f7fb05ada68d491ff49165b9644f790e0e0c upstream.

The driver does not set max_busy_timeout, so the core takes the host for one that can wait for busy indefinitely and sends erase and cache flush as R1b with busy timeouts of up to 60 s and 30 s. The CMD_CFG timeout field holds at most 32768 ms, so the controller times out first.

Report 32768 ms as max_busy_timeout. The core then sizes discards to fit and, for a longer wait, sends R1 and polls for busy itself.

Fixes 51c5d8447bd7 ("MMC: meson: initial support for GX platforms")
---
 drivers/mmc/host/meson-gx-mmc.c |    3 +++
 1 file changed, 3 insertions(+)
drivers/mmc/host/meson-gx-mmc.c +3 -0
@@ -1180,6 +1180,9 @@ static int meson_mmc_probe(struct platfo
 
 	mmc->caps |= MMC_CAP_CMD23;
 
+	/* The longest busy wait the CMD_CFG timeout field can hold. */
+	mmc->max_busy_timeout = SD_EMMC_CMD_TIMEOUT_MAX;
+
 	if (mmc->caps & MMC_CAP_SDIO_IRQ)
 		mmc->caps2 |= MMC_CAP2_SDIO_IRQ_NOTHREAD;
 
author maintainer
#669 lore raw

PATCH 668/990 mmc: meson-gx: name the limit of the CMD_CFG timeout field

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Igor Velkov <[email protected]>

commit e1644210d15f7f8adbe6315199b4b73bead63a2c upstream.

The data timeout is capped at a literal 32768 ms with a comment next to it. Give the limit a name beside the other timeout constants.

Fixes 51c5d8447bd7 ("MMC: meson: initial support for GX platforms")
---
 drivers/mmc/host/meson-gx-mmc.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/mmc/host/meson-gx-mmc.c +2 -1
@@ -125,6 +125,7 @@
 #define SD_EMMC_CFG_RESP_TIMEOUT 256 /* in clock cycles */
 #define SD_EMMC_CMD_TIMEOUT 1024 /* in ms */
 #define SD_EMMC_CMD_TIMEOUT_DATA 4096 /* in ms */
+#define SD_EMMC_CMD_TIMEOUT_MAX 32768 /* in ms, 2^15: limit of CMD_CFG_TIMEOUT_MASK */
 #define SD_EMMC_CFG_CMD_GAP 16 /* in clock cycles */
 #define SD_EMMC_DESC_BUF_LEN PAGE_SIZE
 
@@ -211,7 +212,7 @@ static unsigned int meson_mmc_get_timeou
 
 	timeout = roundup_pow_of_two(timeout);
 
-	return min(timeout, 32768U); /* max. 2^15 ms */
+	return min_t(unsigned int, timeout, SD_EMMC_CMD_TIMEOUT_MAX);
 }
 
 /* For R1b the controller waits for busy to be released within this timeout. */
author maintainer
#670 lore raw

PATCH 669/990 errseq: dont let errseq_check_and_advance() hide later errors

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Shashank Mohan Jain <[email protected]>

commit 94defd41d80f10bbe883c0c8d1b28d1665b6b153 upstream.

errseq_check_and_advance() reads the errseq_t, sets ERRSEQ_SEEN with a cmpxchg() and then advances *since to the value it computed, ignoring whether the cmpxchg() succeeded. When it fails because errseq_set() recorded a different error in the meantime, *since ends up holding a value that was never stored in the errseq_t.

errseq_set() only bumps the counter when ERRSEQ_SEEN is set. So as long as nobody has seen the new error, recording the original errno again recreates exactly the old value, and once another subscriber marks it seen, it is equal to the stale *since. The next check through that cursor then reports nothing, although -ENOSPC was recorded after the value that check reported, and -EIO was recorded again after it returned:

  cursor f                writeback              cursor g
  --------                ---------              --------
                          set(-EIO)
  check_and_advance(&f)
    old = [c, EIO]
                          set(-ENOSPC)
                          -> [c, ENOSPC]
    cmpxchg() fails
    f = [c, EIO, SEEN]
    returns -EIO
                          set(-EIO)
                          -> [c, EIO]
                          (no bump: unseen)
                                                 check_and_advance(&g)
                                                 -> [c, EIO, SEEN]
                                                 returns -EIO

check_and_advance(&f)
[c, EIO, SEEN] == f
returns 0 <- -ENOSPC and the second -EIO are lost

For file->f_wb_err this means that fsync() on one descriptor can return 0 although writeback failed after the previous fsync() on that descriptor returned, when writeback errors race with fsync() on another descriptor of the same file. The same applies to syncfs() through sb->s_wb_err, which every file on the filesystem shares, and to the ext4 and jbd2 cursors on the block device mapping. The kernel-doc promises "Negative errno if one has been stored, or 0 if no new error has occurred".

Retry with the value found when the cmpxchg() fails, so that *since is only ever advanced to a value that was actually stored with ERRSEQ_SEEN set. Every later errseq_set() then has to bump the counter, and the error is reported. The retry loop terminates because each iteration needs a concurrent update, like the loop in errseq_set().

A TLA+ model of errseq_set() and errseq_check_and_advance(), checked with the TLC model checker, finds the lost error with the current code; with this change TLC checks that an error recorded after a check returned is always reported by the next check (exhaustively for two subscribers with three checks each, and one writer recording four errors or two writers recording two each). The KUnit race test added in the next patch misses the error in 1-6% of 2 million rounds on 4-CPU UML before this change (depending on host load), and in none after it.

---
 lib/errseq.c |   29 ++++++++++++++++++-----------
 1 file changed, 18 insertions(+), 11 deletions(-)
lib/errseq.c +18 -11
@@ -162,7 +162,8 @@ EXPORT_SYMBOL(errseq_check);
  * points to. If it does, then just return 0.
  *
  * If it doesn't, then the value has changed. Set the "seen" flag, and try to
- * swap it into place as the new eseq value. Then, set that value as the new
+ * swap it into place as the new eseq value. If the swap fails because the
+ * value changed, retry with the new value. Then, set that value as the new
  * "since" value, and return whatever the error portion is set to.
  *
  * Note that no locking is provided here for concurrent updates to the "since"
@@ -184,24 +185,30 @@ int errseq_check_and_advance(errseq_t *e
 	 * to take the lock that protects the "since" value.
 	 */
 	old = READ_ONCE(*eseq);
-	if (old != *since) {
+	while (old != *since) {
 		/*
 		 * Set the flag and try to swap it into place if it has
 		 * changed.
 		 *
-		 * We don't care about the outcome of the swap here. If the
-		 * swap doesn't occur, then it has either been updated by a
-		 * writer who is altering the value in some way (updating
-		 * counter or resetting the error), or another reader who is
-		 * just setting the "seen" flag. Either outcome is OK, and we
-		 * can advance "since" and return an error based on what we
-		 * have.
+		 * If the swap fails, a writer or another reader changed the
+		 * value under us, so retry with the new value.  "since" must
+		 * only ever be set to a value that was stored with the SEEN
+		 * flag: errseq_set() does not bump the counter while the
+		 * flag is clear, so an unstored value could come back later
+		 * and hide the errors that were recorded in the meantime.
 		 */
 		new = old | ERRSEQ_SEEN;
-		if (new != old)
-			cmpxchg(eseq, old, new);
+		if (new != old) {
+			errseq_t cur = cmpxchg(eseq, old, new);
+
+			if (cur != old) {
+				old = cur;
+				continue;
+			}
+		}
 		*since = new;
 		err = -(new & ERRNO_MASK);
+		break;
 	}
 	return err;
 }
author maintainer
#671 lore raw

PATCH 670/990 backing-file: pass RWF_NOAPPEND to synchronous writes

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Chris Mason <[email protected]>

commit afa735786a89bde4959db52f20e3579de54ec740 upstream.

pwritev2() with RWF_NOAPPEND ignores the offset and appends the data on an overlayfs or FUSE passthrough file that was opened with O_APPEND, and the call still returns success. The flag must make the write go to the given offset even though the file is in append mode. Any user who can write to the file is affected, with the default mount options.

overlayfs and FUSE passthrough forward the reads and writes on their files to a backing file on an underlying filesystem, through the helpers in fs/backing-file.c.

The flag works for the file that the user opened: kiocb_set_rw_flags() clears IOCB_APPEND in the write's kiocb. It also copies RWF_NOAPPEND into ki_flags, as it does with every RWF_ flag.

overlayfs and FUSE passthrough then pass the write on to the backing file. They opened it with the open flags of the user's file, so it is in append mode too.

For a synchronous write, do_backing_file_write_iter() calls vfs_iter_write(), which sets up a new kiocb for the backing file. That kiocb starts out with IOCB_APPEND set. vfs_iter_write() is only given the flags of the user's kiocb that are in BACKING_IOCB_MASK, and RWF_NOAPPEND is not one of them. So nothing clears IOCB_APPEND again, and the data goes to the end of the file while the call returns success.

An asynchronous write reuses the flags of the user's kiocb and is not affected.

Reproduced by calling pwritev2() with RWF_NOAPPEND at offset 0, on an overlayfs file and on a FUSE passthrough file opened with O_APPEND: the data was at the end of the file afterwards.

Fix this by adding RWF_NOAPPEND to BACKING_IOCB_MASK.

---
 fs/backing-file.c |    7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
fs/backing-file.c +6 -1
@@ -114,8 +114,13 @@ struct backing_aio {
 
 static struct kmem_cache *backing_aio_cachep;
 
+/*
+ * RWF_NOAPPEND stays set in ki_flags.  Pass it on, because the backing file is
+ * in append mode as well and a new kiocb for it starts with IOCB_APPEND.
+ */
 #define BACKING_IOCB_MASK \
-	(IOCB_NOWAIT | IOCB_HIPRI | IOCB_DSYNC | IOCB_SYNC | IOCB_APPEND)
+	(IOCB_NOWAIT | IOCB_HIPRI | IOCB_DSYNC | IOCB_SYNC | IOCB_APPEND | \
+	 (__force int) RWF_NOAPPEND)
 
 static rwf_t iocb_to_rw_flags(int flags)
 {
author maintainer
#672 lore raw

PATCH 671/990 pidfd: restrict task access ioctls to the callers pid namespace

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Chen Linxuan <[email protected]>

commit ee8323fdc827c580425644db605a4be776cace57 upstream.

pidfds can cross pid namespace boundaries: a task may obtain one for a process outside of its own pid namespace hierarchy through SO_PASSPIDFD or SO_PEERPIDFD, via SCM_RIGHTS, or through file descriptor inheritance.

The namespace ioctls gate access with a ptrace check against the target's credentials only. That check does not account for the pid namespace relationship between the caller and the target, so a task inside a pid namespace can use a pidfd obtained across that boundary to acquire namespace file descriptors of a task outside of its hierarchy.

procfs exposes the equivalent information only for tasks visible in the reader's pid namespace, and PIDFD_GET_INFO already answers with -EREMOTE for targets outside the caller's hierarchy. Extend that policy to the namespace ioctls: fail with -EREMOTE unless the target is visible in the caller's active pid namespace. Callers in ancestor pid namespaces are unaffected.

Unlike PIDFD_GET_INFO, the visibility check is performed after the task lookup here, so reaped targets outside of the caller's pid namespace hierarchy answer -ESRCH instead of -EREMOTE.

---
 fs/pidfs.c |    8 ++++++++
 1 file changed, 8 insertions(+)
fs/pidfs.c +8 -0
@@ -514,6 +514,14 @@ static long pidfd_ioctl(struct file *fil
 		return -EINVAL;
 
 	/*
+	 * Require the target to be visible in the caller's pid namespace
+	 * for operations that grant access to its resources, mirroring
+	 * procfs and PIDFD_GET_INFO.
+	 */
+	if (!pid_in_current_pidns(pidfd_pid(file)))
+		return -EREMOTE;
+
+	/*
 	 * We're trying to open a file descriptor to the namespace so perform a
 	 * filesystem cred ptrace check. Hold @task's exec_update_lock for the
 	 * duration of the ptrace check and the namespace lookup so that the
author maintainer
#673 lore raw

PATCH 672/990 eventpoll: wake the next waiter when a woken waiter is killed

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Mani Tofigh <[email protected]>

commit 9f4413e522faed76f4cf610098b2369eb3ba1f1c upstream.

Processes sharing an epoll instance can sleep forever while an event is ready. An event wakes only one waiter, which then wakes the next one in ep_done_scan() if events are still ready. Since commit c257a340ede0 ("fs, epoll: short circuit fetching events if thread has been killed"), ep_send_events() returns before the scan when the waiter has a fatal signal. If the woken waiter is killed before it runs, nobody wakes the next one:

Task A Task B Task C
epoll_wait(ep, -1) epoll_wait(ep, -1)

                                                    write(efd)
                                                      /* wakes A only */
                                                    kill(A, SIGKILL)
  ep_send_events()
    return -EINTR
      /* skips ep_done_scan() */
                             /* still asleep */

B then sleeps until another file on the instance becomes ready, if ever. This can hit eg a pre-fork server whose worker gets OOM killed. Commit 7fab29e35630 ("fs/epoll: restore waking from ep_done_scan()") fixed the same kind of hang when the wakeup in ep_done_scan() was removed.

Keep the early return so that a dying task still doesn't take events nobody will see, but wake the next waiter there if events are ready, as ep_done_scan() would have. With the fix, B gets the event.

This bug was identified and confirmed with the help of a deterministic hypervisor currently under development. The C reproducer below however hits it within about 2s.

Fixes c257a340ede0 ("fs, epoll: short circuit fetching events if thread has been killed")
---
 fs/eventpoll.c |   11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)
fs/eventpoll.c +9 -2
@@ -2088,10 +2088,17 @@ static int ep_send_events(struct eventpo
 	/*
 	 * Always short-circuit for fatal signals to allow threads to make a
 	 * timely exit without the chance of finding more events available and
-	 * fetching repeatedly.
+	 * fetching repeatedly. The wakeup that got us here may have been the
+	 * only one for the events on ->rdllist, so pass it on to the next
+	 * waiter, as ep_done_scan() would have.
 	 */
-	if (fatal_signal_pending(current))
+	if (fatal_signal_pending(current)) {
+		spin_lock_irq(&ep->lock);
+		if (!list_empty(&ep->rdllist))
+			wake_up(&ep->wq);
+		spin_unlock_irq(&ep->lock);
 		return -EINTR;
+	}
 
 	init_poll_funcptr(&pt, NULL);
 
author maintainer
#674 lore raw

PATCH 673/990 aio: dont let exit_aio() return before complete() is done

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Christian Brauner <[email protected]>

commit ac4b449b39e605123c12ea10042cafc9b6f39603 upstream.

exit_aio() kills all contexts in one go and waits for them with a single on-stack struct ctx_rq_wait. The count starts at table->nr, each killed context drops one count in free_ioctx_reqs() and exit_aio() subtracts the empty slots afterwards. Whoever drops the last count either calls complete() or, if it is exit_aio(), skips the wait.

With a full table skipped is zero and atomic_sub_and_test(0, ...) only tells us whether the count already hit zero. free_ioctx_reqs() runs from the percpu_ref RCU callback, so if exit_aio() is off the CPU long enough the last callback can have done its atomic_dec_and_test() but not yet called complete():

    free_ioctx_reqs()                    exit_aio()
    atomic_dec_and_test() // 1 -> 0
                                         atomic_sub_and_test(0) // true
                                         kfree(table)
                                         return
    complete(&wait.comp)

complete() then locks and writes a completion on a stack frame that is gone. So hold an extra count for exit_aio() itself. Then the last count is always dropped by exit_aio() after it waited, or by a callback while exit_aio() waits for it. An unprivileged user gets there with four io_setup() calls and an exit without io_destroy().

---
 fs/aio.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/aio.c +2 -2
@@ -910,7 +910,7 @@ void exit_aio(struct mm_struct *mm)
 	if (!table)
 		return;
 
-	atomic_set(&wait.count, table->nr);
+	atomic_set(&wait.count, table->nr + 1);
 	init_completion(&wait.comp);
 
 	skipped = 0;
@@ -934,7 +934,7 @@ void exit_aio(struct mm_struct *mm)
 		kill_ioctx(mm, ctx, &wait);
 	}
 
-	if (!atomic_sub_and_test(skipped, &wait.count)) {
+	if (!atomic_sub_and_test(skipped + 1, &wait.count)) {
 		/* Wait until all IO for the context are done. */
 		wait_for_completion(&wait.comp);
 	}
author maintainer
#675 lore raw

PATCH 674/990 fs: fix the SEEK_CUR f_lock condition

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Christian Brauner <[email protected]>

commit 1448959fe3d013ffdb8302d17e4a8fdad2d2da95 upstream.

Commit da06e3c51794 ("fs: don't needlessly acquire f_lock") wanted to skip f_lock for SEEK_CUR on files that already serialize f_pos through f_pos_lock, i.e. FMODE_ATOMIC_POS files and directories, and keep it for everything else. The condition it added does the opposite:
file_seek_cur_needs_f_lock() returns false exactly for the files that never take f_pos_lock and true for the ones that do.

So since v6.15 a SEEK_CUR on a shared block device or on a character device that uses fixed_size_llseek() updates f_pos without any lock and two concurrent calls can lose an update, while regular files and directories pay for a spinlock they don't need.

Invert the condition.

---
 fs/file.c |   10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)
fs/file.c +7 -3
@@ -1210,14 +1210,18 @@ static inline bool file_needs_f_pos_lock
 
 bool file_seek_cur_needs_f_lock(struct file *file)
 {
-	if (!(file->f_mode & FMODE_ATOMIC_POS) && !file->f_op->iterate_shared)
-		return false;
-
 	/*
+	 * Files that go through f_pos_lock when they are shared, i.e.
+	 * FMODE_ATOMIC_POS files and directories, don't need f_lock for a
+	 * SEEK_CUR. Everything else does, since nothing else serializes
+	 * the f_pos update.
+	 *
 	 * Note that we are not guaranteed to be called after fdget_pos() on
 	 * this file obj, in which case the caller is expected to provide the
 	 * appropriate locking.
 	 */
+	if ((file->f_mode & FMODE_ATOMIC_POS) || file->f_op->iterate_shared)
+		return false;
 
 	return true;
 }
author maintainer
#676 lore raw

PATCH 675/990 splice, net: avoid MSG_MORE when the bvec array fills

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Avi Weiss <[email protected]>

commit 8eaa35c6c29ae669949f4b5b0814c3d34c8ed658 upstream.

splice_to_socket() leaves tail at the last included pipe buffer when its 16-entry bvec array fills. If the requested length exceeds the available pipe data, pipe_occupancy() counts that buffer again and sets MSG_MORE even though the pipe is empty. Small TCP transfers can then be delayed until the cork timeout expires.

Advance tail before checking the array limit so the occupancy test counts only pipe buffers that have not been included in the send.

Fixes ca2d49f77ce4 ("splice, net: Fix splice_to_socket() to handle pipe bufs larger than a page")
---
 fs/splice.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/splice.c +1 -1
@@ -865,9 +865,9 @@ ssize_t splice_to_socket(struct pipe_ino
 
 			bvec_set_page(&bvec[bc++], buf->page, seg, buf->offset);
 			remain -= seg;
+			tail++;
 			if (remain == 0 || bc >= ARRAY_SIZE(bvec))
 				break;
-			tail++;
 		}
 
 		if (!bc)
author maintainer
#677 lore raw

PATCH 676/990 libfs: make i_rwsem the lock of the offset tree

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Christian Brauner <[email protected]>

commit e7d73cef9726bea49de97ae1fd76405df4050a75 upstream.

The offset tree of a directory is only changed with the directory's i_rwsem held exclusive and offset_readdir() walks it with i_rwsem held shared. But the maple tree doesn't know that. It is set up with its internal spinlock, which every mtree_*() helper takes, and readdir takes rcu_read_lock() around each lookup.

The next patch makes readdir keep one ma_state across dir_emit(), which can sleep. That is safe because no writer can run while readdir holds i_rwsem. But the maple tree only allows keeping a ma_state across a sleep if it is protected by the tree's lock. A reader that relies on rcu_read_lock() has to mas_pause() before it drops it, and that means a walk from the root for every entry again.

So tell the tree what protects it. Initialize it with MT_FLAGS_LOCK_EXTERN and the directory's i_rwsem as its lock and switch the writers from the mtree_*() helpers to the mas_*() api. They all run with i_rwsem held exclusive already. With lockdep enabled the maple tree now also checks that every writer holds i_rwsem exclusive.

Nothing can reach the offset tree anymore when the directory inode is destroyed. So clear the external lock with mt_on_stack() and destroy the tree with __mt_destroy() instead of taking i_rwsem in ->destroy_inode().

---
 fs/libfs.c         |   46 +++++++++++++++++++++++++++++-----------------
 include/linux/fs.h |    2 +-
 mm/shmem.c         |    2 +-
 3 files changed, 31 insertions(+), 19 deletions(-)
fs/libfs.c +29 -17
@@ -264,17 +264,18 @@ static long dentry2offset(struct dentry
 	return (long)dentry->d_fsdata;
 }
 
-static struct lock_class_key simple_offset_lock_class;
-
 /**
  * simple_offset_init - initialize an offset_ctx
  * @octx: directory offset map to be initialized
+ * @dir: the directory @octx belongs to
  *
+ * The directory's i_rwsem is the lock of the offset map. Writers hold it
+ * exclusive, offset_readdir() holds it shared.
  */
-void simple_offset_init(struct offset_ctx *octx)
+void simple_offset_init(struct offset_ctx *octx, struct inode *dir)
 {
-	mt_init_flags(&octx->mt, MT_FLAGS_ALLOC_RANGE);
-	lockdep_set_class(&octx->mt.ma_lock, &simple_offset_lock_class);
+	mt_init_flags(&octx->mt, MT_FLAGS_ALLOC_RANGE | MT_FLAGS_LOCK_EXTERN);
+	mt_set_external_lock(&octx->mt, &dir->i_rwsem);
 	octx->next_offset = DIR_OFFSET_MIN;
 }
 
@@ -297,12 +298,13 @@ int simple_offset_add(struct offset_ctx
 	unsigned long offset;
 	int ret;
 
+	MA_STATE(mas, &octx->mt, 0, 0);
+
 	if (dentry2offset(dentry) != 0)
 		return -EBUSY;
 
-	ret = mtree_alloc_cyclic(&octx->mt, &offset, dentry, DIR_OFFSET_MIN,
-				 DIR_OFFSET_MAX, &octx->next_offset,
-				 GFP_KERNEL);
+	ret = mas_alloc_cyclic(&mas, &offset, dentry, DIR_OFFSET_MIN,
+			       DIR_OFFSET_MAX, &octx->next_offset, GFP_KERNEL);
 	if (unlikely(ret < 0))
 		return ret == -EBUSY ? -ENOSPC : ret;
 
@@ -315,7 +317,9 @@ static int simple_offset_replace(struct
 {
 	int ret;
 
-	ret = mtree_store(&octx->mt, offset, dentry, GFP_KERNEL);
+	MA_STATE(mas, &octx->mt, offset, offset);
+
+	ret = mas_store_gfp(&mas, dentry, GFP_KERNEL);
 	if (ret)
 		return ret;
 	offset_set(dentry, offset);
@@ -330,13 +334,14 @@ static int simple_offset_replace(struct
  */
 void simple_offset_remove(struct offset_ctx *octx, struct dentry *dentry)
 {
-	long offset;
+	long offset = dentry2offset(dentry);
+
+	MA_STATE(mas, &octx->mt, offset, offset);
 
-	offset = dentry2offset(dentry);
 	if (offset == 0)
 		return;
 
-	mtree_erase(&octx->mt, offset);
+	mas_erase(&mas);
 	offset_set(dentry, 0);
 }
 
@@ -394,16 +399,20 @@ int simple_offset_rename_exchange(struct
 	long new_index = dentry2offset(new_dentry);
 	int ret;
 
+	MA_STATE(old_mas, &old_ctx->mt, old_index, old_index);
+	MA_STATE(new_mas, &new_ctx->mt, new_index, new_index);
+
 	if (WARN_ON(!old_index || !new_index))
 		return -EINVAL;
 
-	ret = mtree_store(&new_ctx->mt, new_index, old_dentry, GFP_KERNEL);
+	ret = mas_store_gfp(&new_mas, old_dentry, GFP_KERNEL);
 	if (WARN_ON(ret))
 		return ret;
 
-	ret = mtree_store(&old_ctx->mt, old_index, new_dentry, GFP_KERNEL);
+	ret = mas_store_gfp(&old_mas, new_dentry, GFP_KERNEL);
 	if (WARN_ON(ret)) {
-		mtree_store(&new_ctx->mt, new_index, new_dentry, GFP_KERNEL);
+		mas_set(&new_mas, new_index);
+		mas_store_gfp(&new_mas, new_dentry, GFP_KERNEL);
 		return ret;
 	}
 
@@ -418,11 +427,14 @@ int simple_offset_rename_exchange(struct
  * @octx: directory offset ctx that is about to be destroyed
  *
  * During fs teardown (eg. umount), a directory's offset map might still
- * contain entries. xa_destroy() cleans out anything that remains.
+ * contain entries. __mt_destroy() cleans out anything that remains.
+ * Nothing can reach the map of a directory that is being destroyed, so
+ * this runs without the directory's i_rwsem.
  */
 void simple_offset_destroy(struct offset_ctx *octx)
 {
-	mtree_destroy(&octx->mt);
+	mt_on_stack(octx->mt);
+	__mt_destroy(&octx->mt);
 }
 
 /**
include/linux/fs.h +1 -1
@@ -3781,7 +3781,7 @@ struct offset_ctx {
 	unsigned long		next_offset;
 };
 
-void simple_offset_init(struct offset_ctx *octx);
+void simple_offset_init(struct offset_ctx *octx, struct inode *dir);
 int simple_offset_add(struct offset_ctx *octx, struct dentry *dentry);
 void simple_offset_remove(struct offset_ctx *octx, struct dentry *dentry);
 void simple_offset_rename(struct inode *old_dir, struct dentry *old_dentry,
mm/shmem.c +1 -1
@@ -3183,7 +3183,7 @@ static struct inode *__shmem_get_inode(s
 		inode->i_size = 2 * BOGO_DIRENT_SIZE;
 		inode->i_op = &shmem_dir_inode_operations;
 		inode->i_fop = &simple_offset_dir_operations;
-		simple_offset_init(shmem_get_offset_ctx(inode));
+		simple_offset_init(shmem_get_offset_ctx(inode), inode);
 		break;
 	case S_IFLNK:
 		/*
author maintainer
#678 lore raw

PATCH 677/990 mm/mmzone: read the zoneref slot once in zonelist_zone()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Gregory Price (Meta) <[email protected]>

commit 9c52ebe9c89d41c56fcb5d94efe9e539414175a9 upstream.

Memory hotplug rebuilds zonelists in place while allocations walk them, so a zoneref slot can change between two loads of it.

zonelist_zone() loads the slot with a plain access. The compiler may load it again later instead of keeping the zone it already read, so a caller can check one zone and then use another, or the NULL terminator.

Use READ_ONCE(). Callers that take a zone from a slot and keep using it, such as get_page_from_freelist() with ac->preferred_zoneref, need that single load.

---
 include/linux/mmzone.h |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
include/linux/mmzone.h +2 -1
@@ -1710,7 +1710,8 @@ extern struct zone *next_zone(struct zon
 
 static inline struct zone *zonelist_zone(struct zoneref *zoneref)
 {
-	return zoneref->zone;
+	/* Memory hotplug rewrites zonelists in place. */
+	return READ_ONCE(zoneref->zone);
 }
 
 static inline int zonelist_zone_idx(const struct zoneref *zoneref)
author maintainer
#679 lore raw

PATCH 678/990 mm, page_alloc: pass zone pointer to trace_reclaim_retry_zone

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Josef Bacik <[email protected]>

commit 6c48b3ab4ee435c41c3395d31e8ec3dbccc3478c upstream.

should_reclaim_retry() walks a zonelist and passes the zoneref pointer to the reclaim_retry_zone tracepoint, which loads the zone from the entry again to find the node.

Memory hotplug rebuilds the zonelists in place while allocations are under way. When a zone in front of the zoneref entry has become empty, the entries move up, and this one can be the end marker by the time the tracepoint looks at it. zonelist_node_idx() then dereferences a NULL zone. Short of that, the event can name another zone than the one its numbers belong to.

Pass the zone pointer instead of the zoneref pointer.

---
 include/trace/events/oom.h |    8 ++++----
 mm/page_alloc.c            |    2 +-
 2 files changed, 5 insertions(+), 5 deletions(-)
include/trace/events/oom.h +4 -4
@@ -33,7 +33,7 @@ TRACE_EVENT(oom_score_adj_update,
 
 TRACE_EVENT(reclaim_retry_zone,
 
-	TP_PROTO(struct zoneref *zoneref,
+	TP_PROTO(struct zone *zone,
 		int order,
 		unsigned long reclaimable,
 		unsigned long available,
@@ -41,7 +41,7 @@ TRACE_EVENT(reclaim_retry_zone,
 		int no_progress_loops,
 		bool wmark_check),
 
-	TP_ARGS(zoneref, order, reclaimable, available, min_wmark, no_progress_loops, wmark_check),
+	TP_ARGS(zone, order, reclaimable, available, min_wmark, no_progress_loops, wmark_check),
 
 	TP_STRUCT__entry(
 		__field(	int, node)
@@ -55,8 +55,8 @@ TRACE_EVENT(reclaim_retry_zone,
 	),
 
 	TP_fast_assign(
-		__entry->node = zonelist_node_idx(zoneref);
-		__entry->zone_idx = zonelist_zone_idx(zoneref);
+		__entry->node = zone_to_nid(zone);
+		__entry->zone_idx = zone_idx(zone);
 		__entry->order = order;
 		__entry->reclaimable = reclaimable;
 		__entry->available = available;
mm/page_alloc.c +1 -1
@@ -4674,7 +4674,7 @@ should_reclaim_retry(gfp_t gfp_mask, uns
 		 */
 		wmark = __zone_watermark_ok(zone, order, min_wmark,
 				ac->highest_zoneidx, alloc_flags, available);
-		trace_reclaim_retry_zone(z, order, reclaimable,
+		trace_reclaim_retry_zone(zone, order, reclaimable,
 				available, min_wmark, *no_progress_loops, wmark);
 		if (wmark) {
 			ret = true;
author maintainer
#680 lore raw

PATCH 679/990 mm: page_frag: refill the cache for large fragments

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Josef Bacik <[email protected]>

commit c028ecdf15131a2ab70d78a76657b81c00fa240d upstream.

A fragment which is larger than PAGE_SIZE can only be served from the 32K page of a page_frag_cache. If memory is low and the cache had to fall back to a single page, __page_frag_alloc_align() returns NULL and keeps that page.

Since the offset counts up, this check comes first and is made whenever the fragment does not fit behind nc->offset, no matter how big the page of the cache is. So the cache is never refilled on behalf of a large
fragment: with fragsz = 10000 the first three allocations succeed, the fourth one and all the following ones fail although memory is plentiful. nc->offset does not move either, so this lasts until smaller fragments have used up the rest of the page, which never happens if the cache has no other user.

The nfp driver allocates its receive buffers with napi_alloc_frag() and netdev_alloc_frag(). They are larger than a page with a jumbo MTU.

Only give up if the fragment does not fit into the page at all, which is what the comment describes. The fourth allocation in the scenario above with a 32k page will thus now proceed to refill the cache.

Fixes 8218f62c9c9b ("mm: page_frag: use initial zero offset for page_frag_alloc_align()")
Assisted-by LLM
[[email protected]: make the comment more obvious]
---
 mm/page_frag_cache.c |   21 +++++++++++++--------
 1 file changed, 13 insertions(+), 8 deletions(-)
mm/page_frag_cache.c +13 -8
@@ -119,15 +119,20 @@ refill:
 	size = PAGE_SIZE << encoded_page_decode_order(encoded_page);
 	offset = __ALIGN_KERNEL_MASK(nc->offset, ~align_mask);
 	if (unlikely(offset + fragsz > size)) {
-		if (unlikely(fragsz > PAGE_SIZE)) {
+		if (unlikely(fragsz > size)) {
 			/*
-			 * The caller is trying to allocate a fragment
-			 * with fragsz > PAGE_SIZE but the cache isn't big
-			 * enough to satisfy the request, this may
-			 * happen in low memory conditions.
-			 * We don't release the cache page because
-			 * it could make memory pressure worse
-			 * so we simply return NULL here.
+			 * The caller is trying to allocate a fragment that's
+			 * larger than the whole cache page.
+			 *
+			 * Either fragsz is larger than PAGE_FRAG_CACHE_MAX_SIZE
+			 * so this cannot ever succeed.
+			 *
+			 * Or the refill has fallen back to order-0 due to a low
+			 * memory condition. Then we don't want to release the
+			 * cache page to attempt a new large-size refill because
+			 * it could make memory pressure worse.
+			 *
+			 * So in both cases we simply return NULL here.
 			 */
 			return NULL;
 		}
author maintainer
#681 lore raw

PATCH 680/990 mm/mempolicy: read the zoneref slot once in mempolicy_slab_node()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Gregory Price (Meta) <[email protected]>

commit 4cc1bcdf2e4ebcd319005ce2ea132489f6155139 upstream.

For a bind or preferred-many policy, mempolicy_slab_node() tests the first matching slot's zone for NULL, then reads the slot again to look up the zone's node. Offlining a zone's last block rebuilds the zonelists in place, so the second read can return the terminator:

CPU 0 CPU 1
mempolicy_slab_node()
zonelist_zone(slot 4)
= node 2 NORMAL
offline_pages()
build_all_zonelists()
slot 4 = NULL
zonelist_node_idx(slot 4)
zone_to_nid(NULL)

Current GCC merges the two reads, but nothing requires it. With mm/mempolicy.o built with -fno-inline -fno-ipa-sra, holding a bound task's slab_strict_numa allocation between the reads while a movable block earlier in the zonelist goes offline oopses every time:

  BUG: kernel NULL pointer dereference, address: 0000000000000060
  RIP: 0010:zone_to_nid+0x0/0x10
  Call Trace:
   kmem_cache_alloc_noprof+0x294/0x610
   do_getname+0x34/0x230

mempolicy_slab_node() and zonelist_node_idx() are tail calls here, so neither appears in the trace.

Read the slot once and use that zone.

---
 mm/mempolicy.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
mm/mempolicy.c +3 -1
@@ -2088,6 +2088,7 @@ unsigned int mempolicy_slab_node(void)
 	case MPOL_PREFERRED_MANY:
 	{
 		struct zoneref *z;
+		struct zone *zone;
 
 		/*
 		 * Follow bind policy behavior and start allocation at the
@@ -2098,7 +2099,8 @@ unsigned int mempolicy_slab_node(void)
 		zonelist = &NODE_DATA(node)->node_zonelists[ZONELIST_FALLBACK];
 		z = first_zones_zonelist(zonelist, highest_zoneidx,
 							&policy->nodes);
-		return zonelist_zone(z) ? zonelist_node_idx(z) : node;
+		zone = zonelist_zone(z);
+		return zone ? zone_to_nid(zone) : node;
 	}
 	case MPOL_LOCAL:
 		return node;
author maintainer
#682 lore raw

PATCH 681/990 mm/memory_hotplug: resize zones under their seqlock

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Josef Bacik <[email protected]>

commit 58e81bb7de5aac8ec5e4aa21d401e7dafbd4058b upstream.

With CONFIG_DEBUG_VM the page allocator checks that a page which is freed, split or allocated lies within its zone. The check reads zone->zone_start_pfn and zone->spanned_pages under zone->span_seqlock, as memory hotplug can change the two at any time.

Commit 27cacaad16c5 ("mm,memory_hotplug: drop unneeded locking") removed the write side, since all resizing is serialized by the hotplug lock. That leaves the reader without protection. When memory below the start of a zone goes online, the start is lowered first and the size is raised afterwards. When the lowest memory of a zone goes offline, the size is reduced first. In between, the zone seems to end before its last pages. If one of them goes through the allocator at that moment, it is reported as being outside of the zone triggers VM_BUG_ON_PAGE().

Write the two fields in a write section of the seqlock. Interrupts are disabled as pages are freed from interrupts, too, and the reader would wait for the writer which it has interrupted.

---
 mm/memory_hotplug.c |   44 ++++++++++++++++++++++++++++----------------
 1 file changed, 28 insertions(+), 16 deletions(-)
mm/memory_hotplug.c +28 -16
@@ -479,6 +479,22 @@ static unsigned long find_biggest_sectio
 	return 0;
 }
 
+/*
+ * The page allocator checks pages against the span of their zone while the
+ * zone is resized, see page_outside_zone_boundaries(). It must not see the
+ * new value of one field together with the old value of the other one.
+ */
+static void zone_set_span(struct zone *zone, unsigned long start_pfn,
+			  unsigned long spanned_pages)
+{
+	unsigned long flags;
+
+	write_seqlock_irqsave(&zone->span_seqlock, flags);
+	zone->zone_start_pfn = start_pfn;
+	zone->spanned_pages = spanned_pages;
+	write_sequnlock_irqrestore(&zone->span_seqlock, flags);
+}
+
 static void shrink_zone_span(struct zone *zone, unsigned long start_pfn,
 			     unsigned long end_pfn)
 {
@@ -494,13 +510,10 @@ static void shrink_zone_span(struct zone
 		 */
 		pfn = find_smallest_section_pfn(nid, zone, end_pfn,
 						zone_end_pfn(zone));
-		if (pfn) {
-			zone->spanned_pages = zone_end_pfn(zone) - pfn;
-			zone->zone_start_pfn = pfn;
-		} else {
-			zone->zone_start_pfn = 0;
-			zone->spanned_pages = 0;
-		}
+		if (pfn)
+			zone_set_span(zone, pfn, zone_end_pfn(zone) - pfn);
+		else
+			zone_set_span(zone, 0, 0);
 	} else if (zone_end_pfn(zone) == end_pfn) {
 		/*
 		 * If the section is biggest section in the zone, it need
@@ -511,11 +524,10 @@ static void shrink_zone_span(struct zone
 		pfn = find_biggest_section_pfn(nid, zone, zone->zone_start_pfn,
 					       start_pfn);
 		if (pfn)
-			zone->spanned_pages = pfn - zone->zone_start_pfn + 1;
-		else {
-			zone->zone_start_pfn = 0;
-			zone->spanned_pages = 0;
-		}
+			zone_set_span(zone, zone->zone_start_pfn,
+				      pfn - zone->zone_start_pfn + 1);
+		else
+			zone_set_span(zone, 0, 0);
 	}
 }
 
@@ -706,12 +718,12 @@ static void online_pages_range(unsigned
 static void __meminit resize_zone_range(struct zone *zone, unsigned long start_pfn,
 		unsigned long nr_pages)
 {
-	unsigned long old_end_pfn = zone_end_pfn(zone);
+	unsigned long end_pfn = max(start_pfn + nr_pages, zone_end_pfn(zone));
 
-	if (zone_is_empty(zone) || start_pfn < zone->zone_start_pfn)
-		zone->zone_start_pfn = start_pfn;
+	if (!zone_is_empty(zone) && start_pfn > zone->zone_start_pfn)
+		start_pfn = zone->zone_start_pfn;
 
-	zone->spanned_pages = max(start_pfn + nr_pages, old_end_pfn) - zone->zone_start_pfn;
+	zone_set_span(zone, start_pfn, end_pfn - start_pfn);
 }
 
 static void __meminit resize_pgdat_range(struct pglist_data *pgdat, unsigned long start_pfn,
author maintainer
#683 lore raw

PATCH 682/990 mm/page_alloc: dont undo another isolation in alloc_contig_range

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Gregory Price (Meta) <[email protected]>

commit 7d9c29ed8feec8bfbe5e5f673ba2b5926da11375 upstream.

An alloc_contig_range() that overlaps a block going offline can leave the offline spinning until it gets a signal, holding the device hotplug lock. When isolation fails, alloc_contig_frozen_range() undoes it over the whole range, clearing the offline's MIGRATE_ISOLATE too:

CPU 1 (offline_pages) CPU 2 (alloc_contig_range)
start_isolate_page_range()
blocks are MIGRATE_ISOLATE
start_isolate_page_range()
-EBUSY on CPU 1's blocks
undo_isolate_page_range()
blocks are MIGRATE_MOVABLE
test_pages_isolated()
never succeeds again

start_isolate_page_range() fails only on a block someone else isolated, after undoing its own, so this undo only ever clears another caller's. Return directly, as before alloc_contig_range() went pageblock granular.

With offline_pages() parked after isolating a DIMM block and a 1G hugetlb allocation made over it, the offline on base still loops 30s later in 4 of 4 runs:

  offline_pages+0x5b2/0x1570
  memory_subsys_offline+0x17e/0x470
  device_offline+0x250/0x340
  state_store+0x88/0x110

With this patch the allocation still fails, and the offline completes in 3 of 3 runs.

---
 mm/page_alloc.c |    6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
mm/page_alloc.c +5 -1
@@ -7104,9 +7104,13 @@ int alloc_contig_range_noprof(unsigned l
 	 * put back to page allocator so that buddy can use them.
 	 */
 
+	/*
+	 * On failure this has undone its own isolation, and any other
+	 * isolated blocks in the range belong to someone else, e.g. offline.
+	 */
 	ret = start_isolate_page_range(start, end, mode);
 	if (ret)
-		goto done;
+		return ret;
 
 	drain_all_pages(cc.zone);
 
author maintainer
#684 lore raw

PATCH 683/990 mm/page_alloc: keep the pagesets of an empty zone

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Josef Bacik <[email protected]>

commit 7bfcf81b1cb469bc016fa8e07939c0924b9ff8db upstream.

When the last memory of a zone goes offline, zone_pcp_reset() frees zone->per_cpu_pageset and zone->per_cpu_zonestats. Nothing waits for those who found the zone populated and still use the two pointers. They take neither the memory hotplug lock nor any other lock which offline_pages() holds, and some of them can sleep:

CPU0 vmstat_update() CPU1 offline_pages()
refresh_cpu_vm_stats()

    for_each_populated_zone(zone)
      pcp = zone->per_cpu_pageset
      cond_resched()
                                      adjust_present_page_count()
                                      zone_pcp_reset(zone)
                                        free_percpu(zone->per_cpu_pageset)
      decay_pcp_high(zone, pcp)
      __this_cpu_write(pcp->expire, 0)

The same goes for drain_all_pages(NULL), which takes pcp->lock, for zone_pcp_update(), show_free_areas() and the readers and writers of the zonestats. If the per-cpu memory has got a new owner in the meantime, it is corrupted.

The pagesets are only freed because setup_zone_pageset() would otherwise leak them when the zone gets memory again. Keep them instead and let setup_zone_pageset() and zone_pcp_init() use them again, like it is done with pgdat->per_cpu_nodestats. Their lists are empty, and their limits have been calculated for a zone without memory by the init_per_zone_wmark_min() of offline_pages(), which is what setup_zone_pageset() would come up with as well.

---
 mm/page_alloc.c |   20 ++++++++++++++------
 1 file changed, 14 insertions(+), 6 deletions(-)
mm/page_alloc.c +14 -6
@@ -6210,6 +6210,10 @@ void __meminit setup_zone_pageset(struct
 {
 	int cpu;
 
+	/* The zone has been populated before, see zone_pcp_reset(). */
+	if (zone->per_cpu_pageset != &boot_pageset)
+		return;
+
 	/* Size may be 0 on !SMP && !NUMA */
 	if (sizeof(struct per_cpu_zonestat) > 0)
 		zone->per_cpu_zonestats = alloc_percpu(struct per_cpu_zonestat);
@@ -6303,6 +6307,10 @@ void __init setup_per_cpu_pageset(void)
 
 __meminit void zone_pcp_init(struct zone *zone)
 {
+	/* This initialization only needs to be done once */
+	if (zone->per_cpu_pageset)
+		return;
+
 	/*
 	 * per cpu subsystem is not up at this point. The following code
 	 * relies on the ability of the linker to provide the
@@ -7344,6 +7352,12 @@ void zone_pcp_enable(struct zone *zone)
 	mutex_unlock(&pcp_batch_high_lock);
 }
 
+/*
+ * The zone has become empty. Its pagesets and zonestats are not freed: nothing
+ * keeps somebody who found the zone populated, such as refresh_cpu_vm_stats()
+ * or drain_all_pages(), from still using them. They are used again when the
+ * zone gets memory again.
+ */
 void zone_pcp_reset(struct zone *zone)
 {
 	int cpu;
@@ -7354,12 +7368,6 @@ void zone_pcp_reset(struct zone *zone)
 			pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu);
 			drain_zonestat(zone, pzstats);
 		}
-		free_percpu(zone->per_cpu_pageset);
-		zone->per_cpu_pageset = &boot_pageset;
-		if (zone->per_cpu_zonestats != &boot_zonestats) {
-			free_percpu(zone->per_cpu_zonestats);
-			zone->per_cpu_zonestats = &boot_zonestats;
-		}
 	}
 }
 
author maintainer
#685 lore raw

PATCH 684/990 mm/page_alloc: detect zonelist rebuilds from memory hot-add

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Gregory Price (Meta) <[email protected]>

commit e5db040c3d09c5d85dda70f736d4d1a6714b741e upstream.

The zonelist_update_seq retry was limited to CONFIG_MEMORY_HOTREMOVE, presumably because only hot-remove takes zones out of a zonelist.

However, build_zonerefs_node() rewrites the zonelists in place, so onlining the first block of a zone shifts the entries that follow it in every zonelist containing that zone. This can cause a spurious allocation failure for a __GFP_THISNODE caller.

For a node with only ZONE_NORMAL, onlining its first ZONE_MOVABLE block rewrites the node's ZONELIST_NOFALLBACK list as:

[NORMAL, NULL] -> [MOVABLE, NULL] -> [MOVABLE, NORMAL, NULL]

A concurrent GFP_KERNEL | __GFP_THISNODE allocation can observe the intermediate list, skip ZONE_MOVABLE, and find no eligible zone. With CONFIG_MEMORY_HOTREMOVE=n, check_retry_zonelist() returns 0 and the allocation fails even though the node has free ZONE_NORMAL memory.

Gate the sequence checks on CONFIG_MEMORY_HOTPLUG, which covers every configuration that rebuilds zonelists after boot.

Fixes 3d36424b3b58 ("mm/page_alloc: fix race condition between build_all_zonelists and page allocation")
---
 mm/page_alloc.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
mm/page_alloc.c +2 -2
@@ -4416,7 +4416,7 @@ static DEFINE_SEQLOCK(zonelist_update_se
 
 static unsigned int zonelist_iter_begin(void)
 {
-	if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE))
+	if (IS_ENABLED(CONFIG_MEMORY_HOTPLUG))
 		return read_seqbegin(&zonelist_update_seq);
 
 	return 0;
@@ -4424,7 +4424,7 @@ static unsigned int zonelist_iter_begin(
 
 static unsigned int check_retry_zonelist(unsigned int seq)
 {
-	if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE))
+	if (IS_ENABLED(CONFIG_MEMORY_HOTPLUG))
 		return read_seqretry(&zonelist_update_seq, seq);
 
 	return seq;
author maintainer
#686 lore raw

PATCH 685/990 mm/page_alloc: snapshot the preferred zone against shrink rebuilds

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Gregory Price (Meta) <[email protected]>

commit b3e3a760eb68449e2794ef68ab212173d9c3e8c7 upstream.

get_page_from_freelist() and alloc_pages_bulk_noprof() reread ac->preferred_zoneref->zone at every use. Offlining a zone's last block rebuilds the zonelists in place, and the shrunk list's NULL terminator can land on the preferred slot mid-walk:

CPU 0 CPU 1
get_page_from_freelist(GFP_KERNEL | __GFP_THISNODE)
zone = NORMAL (slot 1)
offline_pages()
build_all_zonelists()
[MOVABLE, NORMAL, NULL] -> [NORMAL, NULL]
rmqueue(zonelist_zone(slot 1), zone)
zone_statistics(NULL, zone)

  BUG: kernel NULL pointer dereference, address: 0000000000000060
  RIP: 0010:get_page_from_freelist+0x6a5/0x15f0
  Call Trace:
   __alloc_frozen_pages_noprof+0x125/0x330

Read the slot once. Zones are never freed, so a stale zone is safe, and a NULL slot fails the same way as walking off the end.

---
 mm/page_alloc.c |   31 +++++++++++++++++++++++--------
 1 file changed, 23 insertions(+), 8 deletions(-)
mm/page_alloc.c +23 -8
@@ -3793,12 +3793,21 @@ get_page_from_freelist(gfp_t gfp_mask, u
 {
 	struct zoneref *z;
 	struct zone *zone;
+	struct zone *preferred_zone;
 	struct pglist_data *last_pgdat = NULL;
 	bool last_pgdat_dirty_ok = false;
 	bool no_fallback;
 	bool skip_kswapd_nodes = nr_online_nodes > 1;
 	bool skipped_kswapd_nodes = false;
 
+	/*
+	 * A concurrent zonelist rebuild can NULL or replace this slot. Zones
+	 * are never freed, so reading it once keeps a usable zone.
+	 */
+	preferred_zone = zonelist_zone(ac->preferred_zoneref);
+	if (!preferred_zone)
+		return NULL;
+
 retry:
 	/*
 	 * Scan zonelist, looking for a zone with enough free.
@@ -3845,7 +3854,7 @@ retry:
 		}
 
 		if (no_fallback && !defrag_mode && nr_online_nodes > 1 &&
-		    zone != zonelist_zone(ac->preferred_zoneref)) {
+		    zone != preferred_zone) {
 			int local_nid;
 
 			/*
@@ -3853,7 +3862,7 @@ retry:
 			 * fragmenting fallbacks. Locality is more important
 			 * than fragmentation avoidance.
 			 */
-			local_nid = zonelist_node_idx(ac->preferred_zoneref);
+			local_nid = zone_to_nid(preferred_zone);
 			if (zone_to_nid(zone) != local_nid) {
 				alloc_flags &= ~ALLOC_NOFRAGMENT;
 				goto retry;
@@ -3917,7 +3926,7 @@ check_alloc_wmark:
 				goto try_this_zone;
 
 			if (!node_reclaim_enabled() ||
-			    !zone_allows_reclaim(zonelist_zone(ac->preferred_zoneref), zone))
+			    !zone_allows_reclaim(preferred_zone, zone))
 				continue;
 
 			ret = node_reclaim(zone->zone_pgdat, gfp_mask, order);
@@ -3939,7 +3948,7 @@ check_alloc_wmark:
 		}
 
 try_this_zone:
-		page = rmqueue(zonelist_zone(ac->preferred_zoneref), zone, order,
+		page = rmqueue(preferred_zone, zone, order,
 				gfp_mask, alloc_flags, ac->migratetype);
 		if (page) {
 			prep_new_page(page, order, gfp_mask, alloc_flags);
@@ -5156,6 +5165,7 @@ unsigned long alloc_pages_bulk_noprof(gf
 	struct page *page;
 	unsigned long __maybe_unused UP_flags;
 	struct zone *zone;
+	struct zone *preferred_zone;
 	struct zoneref *z;
 	struct per_cpu_pages *pcp;
 	struct list_head *pcp_list;
@@ -5206,6 +5216,11 @@ unsigned long alloc_pages_bulk_noprof(gf
 		goto out;
 	gfp = alloc_gfp;
 
+	/* Read once; see get_page_from_freelist(). */
+	preferred_zone = zonelist_zone(ac.preferred_zoneref);
+	if (!preferred_zone)
+		goto failed;
+
 	/* Find an allowed local zone that meets the low watermark. */
 	z = ac.preferred_zoneref;
 	for_next_zone_zonelist_nodemask(zone, z, ac.highest_zoneidx, ac.nodemask) {
@@ -5216,8 +5231,8 @@ unsigned long alloc_pages_bulk_noprof(gf
 			continue;
 		}
 
-		if (nr_online_nodes > 1 && zone != zonelist_zone(ac.preferred_zoneref) &&
-		    zone_to_nid(zone) != zonelist_node_idx(ac.preferred_zoneref)) {
+		if (nr_online_nodes > 1 && zone != preferred_zone &&
+		    zone_to_nid(zone) != zone_to_nid(preferred_zone)) {
 			goto failed;
 		}
 
@@ -5225,7 +5240,7 @@ unsigned long alloc_pages_bulk_noprof(gf
 retry_this_zone:
 		mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK) + nr_pages;
 		if (zone_watermark_fast(zone, 0,  mark,
-				zonelist_zone_idx(ac.preferred_zoneref),
+				zone_idx(preferred_zone),
 				alloc_flags, gfp)) {
 			break;
 		}
@@ -5284,7 +5299,7 @@ retry_this_zone:
 	pcp_trylock_finish(UP_flags);
 
 	__count_zid_vm_events(PGALLOC, zone_idx(zone), nr_account);
-	zone_statistics(zonelist_zone(ac.preferred_zoneref), zone, nr_account);
+	zone_statistics(preferred_zone, zone, nr_account);
 
 out:
 	return nr_populated;
author maintainer
#687 lore raw

PATCH 686/990 mm/page_alloc: clear ->private of deferred free pages

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Josef Bacik <[email protected]>

commit aae6b83fe47ed8bff9195efbe1d191ec52e5436e upstream.

free_pages_nolock() and free_frozen_pages_nolock() put the page on zone->trylock_free_pages if they get neither the pcp lock nor zone->lock. add_page_to_zone_llist() keeps the order of the page in page->private. The next free_one_page() which does get zone->lock passes these pages to split_large_buddy() with ->private still set.

__free_one_page() writes ->private of the head of the resulting free page only. If the deferred page is merged with its lower buddy, it becomes a tail of that free page and keeps the order in ->private.

All other free pages which are not the head of a buddy have a ->private of zero, and since commit 819bfbd47e49 ("mm/page_alloc: remove set_page_private() in prep_compound_tail()") the allocator relies on it. When the stale page is allocated again as a tail of a larger page:

- prep_compound_tail() hits VM_WARN_ON_ONCE(tail->private);
- with the page checks enabled, __free_pages_prepare() reports "BUG: Bad page state", "nonzero private", and leaks the whole page;
- without them the value is seen by whoever uses that page next, e.g. as folio->private of a folio which is split off a large folio.

Only pages of an order above zero are affected. Those can be freed through _nolock() by the stack depot (order 2) and by SLUB (a new slab which cannot be added to the partial list by kmalloc_nolock()).

Clear ->private when the page is taken off the list.

---
 mm/page_alloc.c |    2 ++
 1 file changed, 2 insertions(+)
mm/page_alloc.c +2 -0
@@ -1608,6 +1608,8 @@ static void free_one_page(struct zone *z
 		llist_for_each_entry_safe(p, tmp, llnode, pcp_llist) {
 			unsigned int p_order = p->private;
 
+			/* It may end up as a tail of the merged free page. */
+			p->private = 0;
 			split_large_buddy(zone, p, page_to_pfn(p), p_order, fpi_flags);
 			__count_vm_events(PGFREE, 1 << p_order);
 		}
author maintainer
#688 lore raw

PATCH 687/990 btrfs: fix bio counter and bioc leak when async checksumming fails

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Mani Tofigh <[email protected]>

commit d27d0039bc1334be8a72c769e14c0b0c3efc317d upstream.

A single failed checksum allocation can make a later device replace hang forever. btrfs_submit_chunk() takes a dev-replace bio counter reference and a bioc before it hands a write to the checksum worker. If the checksum fails there (e.g., its allocation fails), run_one_async_done() ends the bio but drops neither. The counter then never gets back to zero and the next replace waits for it:

  [ 8.369] BTRFS info (device ram0): dev_replace from /dev/ram0 (devid 1) to /dev/ram1 finished
  [41.534] INFO: task btrfscsum:80 blocked for more than 20 seconds.
  [41.534]  btrfs_rm_dev_replace_blocked+0x135/0x180
  [41.534]  btrfs_dev_replace_finishing+0xefe/0x13b0

The worker is only used when CONFIG_BTRFS_EXPERIMENTAL is off and the checksum isn't a fast one, e.g., sha256. We hit it on a sha256 filesystem.

We put the bioc and drop the counter in that error branch. We also put the bioc on the synchronous error path and on the btrfs_split_bio() error path, which both only drop the counter. With the fix, the replace doesn't hang anymore.

This bug was identified and confirmed with the help of fault-injection testing on a deterministic hypervisor currently under development. Our C reproducer however hits it within about 35s.

Fixes f8a53bb58ec7 ("btrfs: handle checksum generation in the storage layer")
Fixes c7c97ceff98c ("btrfs: handle bio_split() errors")
---
 fs/btrfs/bio.c |    4 ++++
 1 file changed, 4 insertions(+)
fs/btrfs/bio.c +4 -0
@@ -624,6 +624,8 @@ static void run_one_async_done(struct bt
 
 	/* If an error occurred we just want to clean up the bio and move on. */
 	if (bio->bi_status) {
+		btrfs_put_bioc(async->bioc);
+		btrfs_bio_counter_dec(async->bbio->inode->root->fs_info);
 		btrfs_bio_end_io(async->bbio, bio->bi_status);
 		return;
 	}
@@ -759,6 +761,7 @@ static bool btrfs_submit_chunk(struct bt
 		split = btrfs_split_bio(fs_info, bbio, map_length);
 		if (IS_ERR(split)) {
 			status = errno_to_blk_status(PTR_ERR(split));
+			btrfs_put_bioc(bioc);
 			btrfs_bio_counter_dec(fs_info);
 			goto end_bbio;
 		}
@@ -820,6 +823,7 @@ done:
 	return map_length == length;
 
 fail:
+	btrfs_put_bioc(bioc);
 	btrfs_bio_counter_dec(fs_info);
 	/*
 	 * We have split the original bbio, now we have to end both the current
author maintainer
#689 lore raw

PATCH 688/990 coda: honor the append state of each write

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Hungyu Lin <[email protected]>

commit 87ea037a9166a5842356ce68e3585fc6e756603b upstream.

coda_open() adds O_APPEND to the container file's f_flags after it has been opened, without updating its cached f_iocb_flags. An O_APPEND write can therefore overwrite existing data instead of appending. For example, writing "Z" to a file containing "abc" produces "Zbc" rather than "abcZ".

Pass RWF_APPEND or RWF_NOAPPEND to vfs_iter_write() according to the incoming IOCB_APPEND state. This also honors changes made with F_SETFL and per-write append overrides instead of relying on the container's open-time flags.

Fixes 164f4064ca81 ("keep iocb_flags() result cached in struct file")
---
 fs/coda/file.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
fs/coda/file.c +2 -1
@@ -71,6 +71,7 @@ coda_file_write_iter(struct kiocb *iocb,
 	struct file *host_file = cfi->cfi_container;
 	loff_t ki_pos = iocb->ki_pos;
 	size_t count = iov_iter_count(to);
+	rwf_t flags = (iocb->ki_flags & IOCB_APPEND) ? RWF_APPEND : RWF_NOAPPEND;
 	ssize_t ret;
 
 	ret = venus_access_intent(coda_inode->i_sb, coda_i2f(coda_inode),
@@ -80,7 +81,7 @@ coda_file_write_iter(struct kiocb *iocb,
 		goto finish_write;
 
 	inode_lock(coda_inode);
-	ret = vfs_iter_write(cfi->cfi_container, to, &iocb->ki_pos, 0);
+	ret = vfs_iter_write(cfi->cfi_container, to, &iocb->ki_pos, flags);
 	coda_inode->i_size = file_inode(host_file)->i_size;
 	coda_inode->i_blocks = (coda_inode->i_size + 511) >> 9;
 	inode_set_mtime_to_ts(coda_inode, inode_set_ctime_current(coda_inode));
author maintainer
#690 lore raw

PATCH 689/990 net: dst_metadata: fix memcmp overread in skb_metadata_dst_cmp

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jean-Paul Sergent <[email protected]>

commit 74a7db839308dd7d1c3f72dd1e3299784df3affb upstream.

Commit 3fcece12bc1b6 ("net: store port/representator id in metadata_dst") dropped the options_len equality check when converting skb_metadata_dst_cmp() to a type switch, so the memcmp length is taken from skb a alone. When skb b carries fewer options than a, the comparison reads past b's allocation.

Hit in practice with Cilium geneve GRO aggregation, comparing an skb carrying 12 bytes of tunnel options against one carrying none:

memcmp: detected buffer overflow: 108 byte read of buffer size 96

  WARNING: CPU: 0 PID: 15 at lib/string_helpers.c:1036 __fortify_report
   __fortify_panic+0x9/0x10
   skb_metadata_dst_cmp+0x11b/0x120
   dev_gro_receive+0x303/0x620
   gro_cell_poll+0x67/0xa0

Restore the check: unequal options_len means different metadata and no aggregation; the memcmp only runs when both sides carry the same options length.

Fixes 3fcece12bc1b6 ("net: store port/representator id in metadata_dst")
Cc Ilya Maximets <[email protected]>
Cc Sasha Levin <[email protected]>
Cc Jakub Kicinski <[email protected]>
Cc "David S. Miller" <[email protected]>
Cc Eric Dumazet <[email protected]>
Cc Paolo Abeni <[email protected]>
Cc Simon Horman <[email protected]>
Cc Sridhar Samudrala <[email protected]>
Cc Kees Cook <[email protected]>
---
 include/net/dst_metadata.h |    2 ++
 1 file changed, 2 insertions(+)
include/net/dst_metadata.h +2 -0
@@ -116,6 +116,8 @@ static inline int skb_metadata_dst_cmp(c
 		return memcmp(&a->u.port_info, &b->u.port_info,
 			      sizeof(a->u.port_info));
 	case METADATA_IP_TUNNEL:
+		if (a->u.tun_info.options_len != b->u.tun_info.options_len)
+			return 1;
 		return memcmp(&a->u.tun_info, &b->u.tun_info,
 			      sizeof(a->u.tun_info) +
 					 a->u.tun_info.options_len);
author maintainer
#691 lore raw

PATCH 690/990 macsec: reject frames that decapsulate into runt Ethernet frames

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Kyle Zeng <[email protected]>

commit 1d5e2c57e9ffc134e14b3f837c8d7c53b508bd22 upstream.

When an SCI is unknown and the C bit is clear, macsec_handle_frame() removes the SecTAG and the default ICV without checking how much of the frame remains. A short frame can therefore become an skb shorter than ETH_HLEN. eth_type_trans() cannot pull its Ethernet header, and a second stacked MACsec device can copy stale skb headroom into a packet delivered to a packet socket.

The matched-SCI path has a related hole: macsec_validate_skb() accepts a short_length of one, so a frame that passes the existing length check can still become a 13-byte Ethernet frame.

Require enough bytes for the MACsec overhead and a complete Ethernet header before decapsulating an unknown-SCI frame. Apply the same bound in macsec_validate_skb(), using the selected SecY's ICV length, to cover the no-SA, synchronous-decrypt and asynchronous-decrypt delivery paths. Leave other unknown-SCI handling unchanged.

Fixes c09440f7dcb3 ("macsec: introduce IEEE 802.1AE driver")
---
 drivers/net/macsec.c |   15 ++++++++++-----
 1 file changed, 10 insertions(+), 5 deletions(-)
drivers/net/macsec.c +10 -5
@@ -403,8 +403,10 @@ static bool macsec_validate_skb(struct s
 	int len = skb->len - 2 * ETH_ALEN;
 	int extra_len = macsec_extra_len(!!(h->tci_an & MACSEC_TCI_SC)) + icv_len;
 
-	/* a) It comprises at least 17 octets */
-	if (skb->len <= 16)
+	/* a) It comprises at least 17 octets. The SecTAG and ICV must
+	 * also leave a complete Ethernet header.
+	 */
+	if (skb->len < ETH_HLEN + extra_len)
 		return false;
 
 	/* b) MACsec EtherType: already checked */
@@ -1326,9 +1328,12 @@ drop_direct:
 nosci:
 	/* 10.6.1 if the SC is not found */
 	cbit = !!(hdr->tci_an & MACSEC_TCI_C);
-	if (!cbit)
-		macsec_finalize_skb(skb, MACSEC_DEFAULT_ICV_LEN,
-				    macsec_extra_len(macsec_skb_cb(skb)->has_sci));
+	if (!cbit) {
+		len = macsec_extra_len(macsec_skb_cb(skb)->has_sci);
+		if (skb->len < ETH_HLEN + len + MACSEC_DEFAULT_ICV_LEN)
+			goto drop_nosc;
+		macsec_finalize_skb(skb, MACSEC_DEFAULT_ICV_LEN, len);
+	}
 
 	list_for_each_entry_rcu(macsec, &rxd->secys, secys) {
 		struct sk_buff *nskb;
author maintainer
#692 lore raw

PATCH 691/990 mctp: accept MSG_CMSG_COMPAT in recvmsg

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Davidlohr Bueso <[email protected]>

commit 350e1d0d3b386fcc0cff2d37aa920fab4800bf72 upstream.

32-bit userspace running on a 64-bit kernel is unable to receive MCTP messages on an AF_MCTP socket, even though sending succeeds. There is nothing for MCTP to do with it beyond not rejecting it, as af_packet, af_key and can/isotp already do, for example.

---
 net/mctp/af_mctp.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/mctp/af_mctp.c +1 -1
@@ -291,7 +291,7 @@ static int mctp_recvmsg(struct socket *s
 	u8 type;
 	int rc;
 
-	if (flags & ~(MSG_DONTWAIT | MSG_TRUNC | MSG_PEEK))
+	if (flags & ~(MSG_DONTWAIT | MSG_TRUNC | MSG_PEEK | MSG_CMSG_COMPAT))
 		return -EOPNOTSUPP;
 
 	skb = skb_recv_datagram(sk, flags, &rc);
author maintainer
#693 lore raw

PATCH 692/990 net/mlx5e: Fix queue stats access to queues without stats

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Breno Leitao <[email protected]>

commit 9a24799e219b1699bb1c144248c8c500b9504db5 upstream.

I am seeing the following mlx5e crash in the Meta fleet:

  pc : mlx5e_get_queue_stats_rx+0x4c/0xc8
  Call trace:
   mlx5e_get_queue_stats_rx+0x4c/0xc8 (P)
   netdev_stat_queue_sum+0x78/0x480
   netdev_nl_qstats_get_dump_one+0xf0/0x268
   netdev_nl_qstats_get_dumpit+0x7c/0x1f8

When dumping device-wide qstats, the core calls the per-queue callbacks for every queue below real_num_{rx,tx}_queues, regardless of whether the netdev is up. Some of those queues have no stats behind them:

- RX stats live in priv->channel_stats[], which only has entries for channels that have been opened (stats_nch). real_num_rx_queues can be larger, for example after the channel count is raised while the netdev is down, or after opening the channels failed part way.

- TX stats are looked up in priv->txq2sq_stats[], which is NULL for SQs that were never activated and for HTB queues while the channels are closed.

In both cases the callback dereferences a NULL pointer. The dump needs no privileges, so any user can trigger it.

Return early for RX queues at or above stats_nch and for TX queues without SQ stats.

---
 drivers/net/ethernet/mellanox/mlx5/core/en_main.c |    5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/net/ethernet/mellanox/mlx5/core/en_main.c +4 -1
@@ -5413,7 +5413,7 @@ static void mlx5e_get_queue_stats_rx(str
 	struct mlx5e_rq_stats *xskrq_stats;
 	struct mlx5e_rq_stats *rq_stats;
 
-	if (mlx5e_is_uplink_rep(priv) || !mlx5e_stats_nch_read(priv))
+	if (mlx5e_is_uplink_rep(priv) || i >= mlx5e_stats_nch_read(priv))
 		return;
 
 	channel_stats = priv->channel_stats[i];
@@ -5440,6 +5440,9 @@ static void mlx5e_get_queue_stats_tx(str
 	 * inactive sqs.
 	 */
 	sq_stats = priv->txq2sq_stats[i];
+	if (!sq_stats)
+		return;
+
 	stats->packets = sq_stats->packets;
 	stats->bytes = sq_stats->bytes;
 }
author maintainer
#694 lore raw

PATCH 693/990 net/mlx5e: SHAMPO, Disable end padding when relaxed ordering is supported

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jiabin Deng <[email protected]>

commit 68c183619f24982a635930697bf8e148f2d78f71 upstream.

When SHAMPO and relaxed ordering writes are enabled, aligned RQ end padding can corrupt received TCP data. Due to reordering, alignment padding written at the end of one packet can overwrite data from the next packet.

The current RQ end padding selection avoids alignment padding for LRO, but not for SHAMPO. Extend the condition to SHAMPO to prevent this corruption.

The issue was observed in a two-host test using a BlueField-3 NIC and an NVIDIA H20 GPU. In the original test with MTU 1500, 354 of 400 transfers contained corrupted data before the fix. After applying this change, all 400 transfers across eight message sizes from 32 KiB to 4 MiB, with 50 transfers per size, completed successfully, with no incorrect bytes or corrupted intervals.

---
 drivers/net/ethernet/mellanox/mlx5/core/en/params.c |    5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/net/ethernet/mellanox/mlx5/core/en/params.c +3 -2
@@ -873,10 +873,11 @@ static void mlx5e_build_rx_cq_param(stru
 
 static u8 rq_end_pad_mode(struct mlx5_core_dev *mdev, struct mlx5e_params *params)
 {
-	bool lro_en = params->packet_merge.type == MLX5E_PACKET_MERGE_LRO;
+	bool no_pad = params->packet_merge.type == MLX5E_PACKET_MERGE_LRO ||
+		      params->packet_merge.type == MLX5E_PACKET_MERGE_SHAMPO;
 	bool ro = MLX5_CAP_GEN(mdev, relaxed_ordering_write);
 
-	return ro && lro_en ?
+	return ro && no_pad ?
 		MLX5_WQ_END_PAD_MODE_NONE : MLX5_WQ_END_PAD_MODE_ALIGN;
 }
 
author maintainer
#695 lore raw

PATCH 694/990 net/rds: Do not unpin a page after a failed atomic pin

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Kyle Zeng <[email protected]>

commit 8d5ce4751fad9499ea408163af7f410f18a85782 upstream.

rds_cmsg_atomic() assumes that a non-NULL output from rds_pin_pages() represents a pin that it owns. However, pin_user_pages_fast() can roll back a fast-GUP pin after racing fork() and then fail in the slow path, for example after a concurrent mprotect(PROT_NONE). The output slot can still contain the already-unpinned page.

The common error path calls unpin_user_page() on that stale pointer. This can consume another subsystem's pin and allow the page to be freed while it is still in use. A local unprivileged reproducer triggers a KASAN use-after-free write through an io_uring registered buffer.

Clear page when rds_pin_pages() does not return one. The error path continues to release the page on errors after a successful pin, and successful requests retain their existing ownership and behavior. All four RDS atomic ancillary operations share this path.

The issue was found by an LLM.

Fixes 15133f6e67d8 ("RDS: Implement atomic operations")
---
 net/rds/rdma.c |    5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
net/rds/rdma.c +4 -1
@@ -960,8 +960,11 @@ int rds_cmsg_atomic(struct rds_sock *rs,
 	}
 
 	ret = rds_pin_pages(args->local_addr, 1, &page, 1);
-	if (ret != 1)
+	if (ret != 1) {
+		/* A failed pin can leave a stale page pointer. */
+		page = NULL;
 		goto err;
+	}
 	ret = 0;
 
 	sg_set_page(rm->atomic.op_sg, page, 8, offset_in_page(args->local_addr));
author maintainer
#696 lore raw

PATCH 695/990 net/smc: fix lgr/lnk lifetime vs diag reader race

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Mahanta Jambigi <[email protected]>

commit d7900fa51642fbc2a5a03354238e71050a7d391d upstream.

The diag dump walks the socket hash table under a read_lock and dereferences conn->lgr and conn->lnk. Several paths expose a window where a hashed socket has freed or partially freed conn/lgr/lnk state.

First, smc_conn_abort() calls smc_conn_free() during early handshake aborts while the socket is still hashed in SMC_INIT, synchronously freeing the lgr on the smc_lgr_cleanup_early() path without holding the hash write_lock. A concurrent diag reader can load a non-NULL conn->lgr and dereference it after the kfree. Skip the connection, link group and DMB attributes in __smc_diag_dump() for sockets in SMC_INIT or SMC_CLOSED or fallen back to TCP, and take diag_mode from an is_smcd flag cached at connection creation.

The state filter alone does not close the race. A connection aborted by a failed handshake can keep its alert token, because smc_conn_free() skips the unregister when smc_lgr_terminate_sched() has emptied lgr->list; close_work may also have been queued before the abort, as the CDC receive path is not excluded by the handshake's socket lock. smc_close_passive_work() would then move the hashed socket from SMC_INIT to SMC_APPCLOSEWAIT1 or SMC_PROCESSABORT, states the filter does not cover, and later run a passive-closing sock_put() that smc_connect_decline_fallback() dropped already. Return early from smc_close_passive_work() when the connection was freed; the check holds the socket lock that every smc_conn_free() caller holds as well, so a hashed socket with a freed connection stays in SMC_INIT or SMC_CLOSED until release.

This changes the sock_diag output for such sockets: the connection, link group and DMB attributes are omitted, which smcss does not read for sockets in these states, while SMC_DIAG_FALLBACK is still reported and an SMC-D socket in SMC_INIT or SMC_CLOSED still reports SMC_DIAG_MODE_SMCD from the cached flag. A fallback socket is a plain TCP socket with no SMC connection state to report; the stale conn fields left behind by smc_conn_abort() must not be read.

Second, in smc_conn_kill() on SMC-D with dmb_nocopy, smcd_buf_detach() NULLs and frees conn->sndbuf_desc while the socket is still hashed. A concurrent diag reader entering the CONNINFO block can dereference the freed descriptor. Unhash the socket right before smcd_buf_detach(). As a result, killed ACTIVE and APPCLOSEWAIT sockets that are still open are no longer visible to smcss on loopback-ism devices.

Third, in the terminal teardown branches of smc_close_active_abort() (PEERCLOSEWAIT and PROCESSABORT groups) and in smc_close_passive_work(), smc_conn_free() drops lgr and lnk references while the socket is still hashed. Unhash immediately before each smc_conn_free() call at those sites. Sockets killed in those close states are therefore unhashed, and their inuse accounting dropped, before close(), even if the fd is still open.

Fourth, use smp_load_acquire() / smp_store_release() on sk_state to order these checks on weakly ordered CPUs. A reader that observes SMC_ACTIVE is guaranteed to see the connection setup that preceded the store; a reader that observes SMC_CLOSED from smc_listen_out_err() skips the connection fields in any case, so that particular store is hardening kept for uniformity, not a required ordering.

Additionally, in __smc_diag_dump(), use the cached link->ibname instead of link->smcibdev->ibdev->name, avoiding a NULL pointer dereference or use-after-free of the IB device when __smcr_link_clear() zeroes the link during concurrent SMC-R link failover. The link data is still read without conns_lock or send_lock, so a dump racing a failover may transiently report zeroed or mixed link fields; this does not affect memory safety and the next dump reports the new link. Like the SMC netlink link dump and the tracepoints, the name is the one cached at link creation time.

Fixes f16a7dd5cf27 ("smc: netlink interface for SMC sockets")
Fixes 2a0674fffb6b ("net/smc: improve abnormal termination of link groups")
Fixes 46c28dbd4c23 ("net/smc: no socket state changes in tasklet context")
Fixes 9dbe086c69b8 ("net/smc: fix invalid link access in dumping SMC-R connections")
Fixes ae2be35cbed2 ("net/smc: {at|de}tach sndbuf to peer DMB if supported")
---
 net/smc/af_smc.c    |   10 +++++-----
 net/smc/smc.h       |    1 +
 net/smc/smc_close.c |   14 ++++++++++++++
 net/smc/smc_core.c  |    8 +++++++-
 net/smc/smc_diag.c  |   12 ++++++++----
 5 files changed, 35 insertions(+), 10 deletions(-)
net/smc/af_smc.c +5 -5
@@ -976,7 +976,7 @@ static int smc_connect_fallback(struct s
 	smc_copy_sock_settings_to_clc(smc);
 	smc->connect_nonblock = 0;
 	if (smc->sk.sk_state == SMC_INIT)
-		smc->sk.sk_state = SMC_ACTIVE;
+		smp_store_release(&smc->sk.sk_state, SMC_ACTIVE);
 	return 0;
 }
 
@@ -1381,7 +1381,7 @@ static int smc_connect_rdma(struct smc_s
 	smc_copy_sock_settings_to_clc(smc);
 	smc->connect_nonblock = 0;
 	if (smc->sk.sk_state == SMC_INIT)
-		smc->sk.sk_state = SMC_ACTIVE;
+		smp_store_release(&smc->sk.sk_state, SMC_ACTIVE);
 
 	return 0;
 connect_abort:
@@ -1484,7 +1484,7 @@ static int smc_connect_ism(struct smc_so
 	smc_copy_sock_settings_to_clc(smc);
 	smc->connect_nonblock = 0;
 	if (smc->sk.sk_state == SMC_INIT)
-		smc->sk.sk_state = SMC_ACTIVE;
+		smp_store_release(&smc->sk.sk_state, SMC_ACTIVE);
 
 	return 0;
 connect_abort:
@@ -1955,7 +1955,7 @@ static void smc_listen_out_connected(str
 	struct sock *newsmcsk = &new_smc->sk;
 
 	if (newsmcsk->sk_state == SMC_INIT)
-		newsmcsk->sk_state = SMC_ACTIVE;
+		smp_store_release(&newsmcsk->sk_state, SMC_ACTIVE);
 
 	smc_listen_out(new_smc);
 }
@@ -1969,7 +1969,7 @@ static void smc_listen_out_err(struct sm
 	this_cpu_inc(net->smc.smc_stats->srv_hshake_err_cnt);
 	if (newsmcsk->sk_state == SMC_INIT)
 		sock_put(&new_smc->sk); /* passive closing */
-	newsmcsk->sk_state = SMC_CLOSED;
+	smp_store_release(&newsmcsk->sk_state, SMC_CLOSED);
 
 	smc_listen_out(new_smc);
 }
net/smc/smc.h +1 -0
@@ -196,6 +196,7 @@ struct smc_connection {
 	struct rb_node		alert_node;
 	struct smc_link_group	*lgr;		/* link group of connection */
 	struct smc_link		*lnk;		/* assigned SMC-R link */
+	bool			is_smcd;	/* SMC-R or SMC-D connection */
 	u32			alert_token_local; /* unique conn. id */
 	u8			peer_rmbe_idx;	/* from tcp handshake */
 	int			peer_rmbe_size;	/* size of peer rx buffer */
net/smc/smc_close.c +14 -0
@@ -154,6 +154,7 @@ void smc_close_active_abort(struct smc_s
 		if (sk->sk_state != SMC_PEERABORTWAIT)
 			break;
 		sk->sk_state = SMC_CLOSED;
+		sk->sk_prot->unhash(sk);
 		smc_conn_free(&smc->conn);
 		release_clcsock = true;
 		sock_put(sk); /* passive closing */
@@ -165,6 +166,7 @@ void smc_close_active_abort(struct smc_s
 		if (sk->sk_state != SMC_PEERABORTWAIT)
 			break;
 		sk->sk_state = SMC_CLOSED;
+		sk->sk_prot->unhash(sk);
 		smc_conn_free(&smc->conn);
 		release_clcsock = true;
 		break;
@@ -367,6 +369,17 @@ static void smc_close_passive_work(struc
 	lock_sock(sk);
 	old_state = sk->sk_state;
 
+	if (conn->freed) {
+		/* conn->freed is set under the socket lock, which is
+		 * held here as well, so this cannot race with the free; the
+		 * state machine and its postponed sock_put() are not owed
+		 * anymore
+		 */
+		release_sock(sk);
+		sock_put(sk); /* sock_hold done by schedulers of close_work */
+		return;
+	}
+
 	rxflags = &conn->local_rx_ctrl.conn_state_flags;
 	if (rxflags->peer_conn_abort) {
 		/* peer has not received all data */
@@ -433,6 +446,7 @@ wakeup:
 		sk->sk_state_change(sk);
 		if ((sk->sk_state == SMC_CLOSED) &&
 		    (sock_flag(sk, SOCK_DEAD) || !sk->sk_socket)) {
+			sk->sk_prot->unhash(sk);
 			smc_conn_free(conn);
 			if (smc->clcsock)
 				release_clcsock = true;
net/smc/smc_core.c +7 -1
@@ -1516,8 +1516,10 @@ static void smc_conn_kill(struct smc_con
 			tasklet_kill(&conn->rx_tsklet);
 		else
 			tasklet_unlock_wait(&conn->rx_tsklet);
-		if (smc_ism_support_dmb_nocopy(conn->lgr->smcd))
+		if (smc_ism_support_dmb_nocopy(conn->lgr->smcd)) {
+			smc->sk.sk_prot->unhash(&smc->sk);
 			smcd_buf_detach(conn);
+		}
 	} else {
 		smc_cdc_wait_pend_tx_wr(conn);
 	}
@@ -2037,6 +2039,10 @@ create:
 			goto out;
 		}
 	}
+	/* cache the connection type: smc_diag reads it after
+	 * smc_conn_free() dropped the link group reference
+	 */
+	conn->is_smcd = conn->lgr->is_smcd;
 	smc_lgr_hold(conn->lgr); /* lgr_put in smc_conn_free() */
 	if (!conn->lgr->is_smcd)
 		smcr_link_hold(conn->lnk); /* link_put in smc_conn_free() */
net/smc/smc_diag.c +8 -4
@@ -87,10 +87,10 @@ static int __smc_diag_dump(struct sock *
 
 	r = nlmsg_data(nlh);
 	smc_diag_msg_common_fill(r, sk);
-	r->diag_state = sk->sk_state;
+	r->diag_state = smp_load_acquire(&sk->sk_state);
 	if (smc->use_fallback)
 		r->diag_mode = SMC_DIAG_MODE_FALLBACK_TCP;
-	else if (smc_conn_lgr_valid(&smc->conn) && smc->conn.lgr->is_smcd)
+	else if (smc->conn.is_smcd)
 		r->diag_mode = SMC_DIAG_MODE_SMCD;
 	else
 		r->diag_mode = SMC_DIAG_MODE_SMCR;
@@ -103,6 +103,10 @@ static int __smc_diag_dump(struct sock *
 	if (nla_put(skb, SMC_DIAG_FALLBACK, sizeof(fallback), &fallback) < 0)
 		goto errout;
 
+	if (r->diag_state == SMC_INIT || r->diag_state == SMC_CLOSED ||
+	    smc->use_fallback)
+		goto out;
+
 	if ((req->diag_ext & (1 << (SMC_DIAG_CONNINFO - 1))) &&
 	    smc->conn.alert_token_local) {
 		struct smc_connection *conn = &smc->conn;
@@ -154,8 +158,7 @@ static int __smc_diag_dump(struct sock *
 			.lnk[0].link_id = link->link_id,
 		};
 
-		memcpy(linfo.lnk[0].ibname, link->smcibdev->ibdev->name,
-		       sizeof(link->smcibdev->ibdev->name));
+		memcpy(linfo.lnk[0].ibname, link->ibname, sizeof(link->ibname));
 		smc_gid_be16_convert(linfo.lnk[0].gid, link->gid);
 		smc_gid_be16_convert(linfo.lnk[0].peer_gid, link->peer_gid);
 
@@ -185,6 +188,7 @@ static int __smc_diag_dump(struct sock *
 			goto errout;
 	}
 
+out:
 	nlmsg_end(skb, nlh);
 	return 0;
 
author maintainer
#697 lore raw

PATCH 696/990 net/smc: fix link group ownership in handshake abort

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Mahanta Jambigi <[email protected]>

commit e227b511582828c5a6513f70fc6a71211e5efbf0 upstream.

An aborted first-contact handshake can hang the handshake worker on the socket lock it already holds, reset the clcsock of a socket that has fallen back to TCP, or corrupt the alert-node lookup when the handshake retries with the same connection.

The abort leaves a connection registered in a link group that another context has already unlinked for termination: smc_conn_free() skips the unregister when lgr->list is empty, so the alert token and alert node stay in lgr->conns_all. If the handshake retries another device or SMC version, smc_conn_create() creates a second link group and smc_lgr_register_conn() inserts the same alert node into it: the token loop is skipped, rb_link_node() links a node that is still in the old tree into the new one, and a second sock_hold() is taken where only one sock_put() will follow. The old group's terminator then keeps returning that node from rb_first() and can kill a connection that now belongs to the new group.

smc_lgr_cleanup_early() also starts a second termination of the link group that is already being terminated, which takes lock_sock() on the socket the handshake worker holds; if the termination work wins the race instead, it later kills the freed connection and aborts the clcsock of a socket that has fallen back to TCP. Making the unregister unconditional also lets smc_conn_free() reach the delayed free work on a claimed link group, where the lockless freeing check can arm it after the owner has cancelled it.

Always unregister the connection, claim a link group for termination once under lgr_lock, keep the link group alive across the abort, and arm the delayed free work only under the same lock and cancel it synchronously before the teardown. Drop an already freed connection in smc_conn_kill() without running the connection and socket teardown.

Fixes 2a0674fffb6b ("net/smc: improve abnormal termination of link groups")
Fixes f9aab6f2ce57 ("net/smc: immediate freeing in smc_lgr_cleanup_early()")
---
 net/smc/af_smc.c   |   11 ++++---
 net/smc/smc_core.c |   78 ++++++++++++++++++++++++++++++++++++++---------------
 net/smc/smc_core.h |    6 ++--
 3 files changed, 65 insertions(+), 30 deletions(-)
net/smc/af_smc.c +6 -5
@@ -1009,14 +1009,15 @@ static void smc_conn_abort(struct smc_so
 {
 	struct smc_connection *conn = &smc->conn;
 	struct smc_link_group *lgr = conn->lgr;
-	bool lgr_valid = false;
-
-	if (smc_conn_lgr_valid(conn))
-		lgr_valid = true;
+	bool lgr_valid = local_first && smc_conn_lgr_valid(conn);
 
+	if (lgr_valid)
+		smc_lgr_hold(lgr);	/* lgr_put below */
 	smc_conn_free(conn);
-	if (local_first && lgr_valid)
+	if (lgr_valid) {
 		smc_lgr_cleanup_early(lgr);
+		smc_lgr_put(lgr);
+	}
 }
 
 /* check if there is a rdma device available for this connection. */
net/smc/smc_core.c +56 -22

143 lines not on this page · raw message

net/smc/smc_core.h +3 -3
@@ -297,9 +297,9 @@ struct smc_link_group {
 	struct delayed_work	free_work;	/* delayed freeing of an lgr */
 	struct work_struct	terminate_work;	/* abnormal lgr termination */
 	struct workqueue_struct	*tx_wq;		/* wq for conn. tx workers */
-	u8			sync_err : 1;	/* lgr no longer fits to peer */
-	u8			terminating : 1;/* lgr is terminating */
-	u8			freeing : 1;	/* lgr is being freed */
+	u8			sync_err;	/* lgr no longer fits to peer */
+	u8			terminating;	/* lgr is terminating */
+	u8			freeing;	/* lgr is being freed */
 
 	refcount_t		refcnt;		/* lgr reference count */
 	bool			is_smcd;	/* SMC-R or SMC-D */
author maintainer
#698 lore raw

PATCH 697/990 net: bridge: use one headroom snapshot for ND replies

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jun Yang <[email protected]>

commit e573df093ef849bb7c763aed591cb6556b110671 upstream.

br_nd_send() calls LL_RESERVED_SPACE(dev) once to size the reply skb and again to reserve its headroom. When a port requiring more headroom is added to the bridge, br_add_if() can increase dev->needed_headroom between the two calls. The reserved headroom can then exceed the space accounted for by alloc_skb().

Take one headroom snapshot and use it for both the allocation size and skb_reserve().

---
 net/bridge/br_arp_nd_proxy.c |    6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
net/bridge/br_arp_nd_proxy.c +4 -2
@@ -262,6 +262,7 @@ static void br_nd_send(struct net_bridge
 	struct sk_buff *reply;
 	struct ipv6hdr *pip6;
 	int na_olen = 8; /* opt hdr + ETH_ALEN for target */
+	int headroom;
 	int ns_olen;
 	int i, len;
 	u8 *daddr;
@@ -271,7 +272,8 @@ static void br_nd_send(struct net_bridge
 	if (!dev || skb_linearize(request))
 		return;
 
-	len = LL_RESERVED_SPACE(dev) + sizeof(struct ipv6hdr) +
+	headroom = LL_RESERVED_SPACE(dev);
+	len = headroom + sizeof(struct ipv6hdr) +
 		sizeof(*na) + na_olen + dev->needed_tailroom;
 
 	reply = alloc_skb(len, GFP_ATOMIC);
@@ -280,7 +282,7 @@ static void br_nd_send(struct net_bridge
 
 	reply->protocol = htons(ETH_P_IPV6);
 	reply->dev = dev;
-	skb_reserve(reply, LL_RESERVED_SPACE(dev));
+	skb_reserve(reply, headroom);
 	skb_push(reply, sizeof(struct ethhdr));
 	skb_set_mac_header(reply, 0);
 
author maintainer
#699 lore raw

PATCH 698/990 net: dsa: microchip: initialize the IRQ access mutex

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Tapio Reijonen <[email protected]>

commit ba1dc196502f3435f4ae53ed6745caacf066f83e upstream.

ksz_switch_register() initializes dev_mutex, regmap_mutex, alu_mutex and vlan_mutex but not lock_irq, which the IRQ chip takes in its bus lock callbacks on every mask and unmask of a switch interrupt, and the PTP code takes the same way. The zeroed mutex happens to work on the uncontended fast path, but with CONFIG_DEBUG_MUTEXES the first lock, from the IRQ domain mapping during probe, warns:

DEBUG_LOCKS_WARN_ON(lock->magic != lock)

  WARNING: kernel/locking/mutex.c:625 at __mutex_lock
  ...
  ksz_irq_domain_map
  irq_domain_associate_locked
  irq_create_mapping_affinity
  ksz_irq_common_setup
  ksz9477_setup
  dsa_register_switch
  ksz_spi_probe

and turns lock debugging off for the rest of the boot.

Initialize it with the other mutexes.

Triggered at every boot of a KSZ9897S over SPI on an i.MX6 SoloX board with CONFIG_DEBUG_MUTEXES, on v7.4-rc1 and earlier. With this patch the same board boots with lock debugging enabled and it stays enabled (debug_locks 1) through two hours of unrelated stress tests.

Fixes c9cd961c0d43 ("net: dsa: microchip: lan937x: add interrupt support for port phy link")
---
 drivers/net/dsa/microchip/ksz_common.c |    1 +
 1 file changed, 1 insertion(+)
drivers/net/dsa/microchip/ksz_common.c +1 -0
@@ -5418,6 +5418,7 @@ int ksz_switch_register(struct ksz_devic
 	mutex_init(&dev->regmap_mutex);
 	mutex_init(&dev->alu_mutex);
 	mutex_init(&dev->vlan_mutex);
+	mutex_init(&dev->lock_irq);
 
 	ret = ksz_switch_detect(dev);
 	if (ret)
author maintainer
#700 lore raw

PATCH 699/990 net: leave O_NONBLOCK to the sendmsg and recvmsg syscalls

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jens Axboe <[email protected]>

commit bdc350ddbcbe4788158019d4d8e8e9345cb16235 upstream.

____sys_sendmsg() and ____sys_recvmsg() turn O_NONBLOCK on the socket into MSG_DONTWAIT. That is right for the system calls, but io_uring uses __sys_sendmsg_sock() and __sys_recvmsg_sock() for a blocking attempt from io-wq as well, after the non-blocking attempts with MSG_DONTWAIT have failed. On an O_NONBLOCK socket that attempt can't block either and the request completes with -EAGAIN, unlike IORING_OP_SEND and RECV, which call sock_sendmsg() and sock_recvmsg() directly and don't look at O_NONBLOCK at all.

Move the O_NONBLOCK handling to ___sys_sendmsg() and ___sys_recvmsg(), which the sendmsg, sendmmsg, recvmsg and recvmmsg system calls go through. The io_uring helpers then pass the flags the caller asked for.

Fixes 0fa03c624d8f ("io_uring: add support for sendmsg()")
Fixes aa1fa28fc73e ("io_uring: add support for recvmsg()")
---
 net/socket.c |   11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)
net/socket.c +6 -5
@@ -2613,8 +2613,6 @@ static int ____sys_sendmsg(struct socket
 	flags &= ~MSG_INTERNAL_SENDMSG_FLAGS;
 	msg_sys->msg_flags = flags;
 
-	if (sock->file->f_flags & O_NONBLOCK)
-		msg_sys->msg_flags |= MSG_DONTWAIT;
 	/*
 	 * If this is sendmmsg() and current destination address is same as
 	 * previously succeeded address, omit asking LSM's decision.
@@ -2678,6 +2676,9 @@ static int ___sys_sendmsg(struct socket
 
 	msg_sys->msg_name = &address;
 
+	if (sock->file->f_flags & O_NONBLOCK)
+		flags |= MSG_DONTWAIT;
+
 	err = sendmsg_copy_msghdr(msg_sys, msg, flags, &iov);
 	if (err < 0)
 		return err;
@@ -2842,9 +2843,6 @@ static int ____sys_recvmsg(struct socket
 	/* We assume all kernel code knows the size of sockaddr_storage */
 	msg_sys->msg_namelen = 0;
 
-	if (sock->file->f_flags & O_NONBLOCK)
-		flags |= MSG_DONTWAIT;
-
 	if (unlikely(nosec))
 		err = sock_recvmsg_nosec(sock, msg_sys, flags);
 	else
@@ -2886,6 +2884,9 @@ static int ___sys_recvmsg(struct socket
 	struct sockaddr __user *uaddr;
 	ssize_t err;
 
+	if (sock->file->f_flags & O_NONBLOCK)
+		flags |= MSG_DONTWAIT;
+
 	err = recvmsg_copy_msghdr(msg_sys, msg, flags, &uaddr, &iov);
 	if (err < 0)
 		return err;
author maintainer
#701 lore raw

PATCH 700/990 net: mana: report RX checksum offload for IPv6

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Hamza Mahfooz <[email protected]>

commit bbcd02741c4cfbf9e1c59b1906f21ef772bd15eb upstream.

The hardware validates TCP and UDP checksums for both IPv4 and IPv6 and reports the result in rx_tcp_csum_succeed and rx_udp_csum_succeed. However, mana_rx_skb() also requires rx_iphdr_csum_succeed before it sets CHECKSUM_UNNECESSARY. That bit is only set for IPv4 (since IPv6 has no header checksum), so IPv6 TCP and UDP traffic is always checksummed again in software.

So, only look at the L4 result. For IPv4 this makes no material difference since CHECKSUM_UNNECESSARY only covers the L4 checksum, and ip_rcv_core() always verifies the IPv4 header checksum in software.

Between two Azure Standard_E16s_v6 VMs (VF enabled), IPv6 TCP and UDP packets (including VXLAN over IPv6), now arrive with CHECKSUM_UNNECESSARY instead of CHECKSUM_NONE, so GRO no longer checksums them in software. Calls to __skb_gro_checksum_complete() on the receiver during an 8 second iperf3 run:

before after

  TCP/IPv4, 12.2 Gbps              23       28
  TCP/IPv6, 12.1 Gbps         8728419       25
  UDP/IPv6, 1.5 Gbps          1071380       20
  TCP/VXLAN/IPv6, 10.9 Gbps   7934373       18
Fixes ca9c54d2d6a5 ("net: mana: Add a driver for Microsoft Azure Network Adapter (MANA)")
---
 drivers/net/ethernet/microsoft/mana/mana_en.c |    7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)
drivers/net/ethernet/microsoft/mana/mana_en.c +3 -4
@@ -1978,10 +1978,9 @@ static void mana_rx_skb(void *buf_va, bo
 	skb_checksum_none_assert(skb);
 	skb_record_rx_queue(skb, rxq_idx);
 
-	if ((ndev->features & NETIF_F_RXCSUM) && cqe->rx_iphdr_csum_succeed) {
-		if (cqe->rx_tcp_csum_succeed || cqe->rx_udp_csum_succeed)
-			skb->ip_summed = CHECKSUM_UNNECESSARY;
-	}
+	if ((ndev->features & NETIF_F_RXCSUM) &&
+	    (cqe->rx_tcp_csum_succeed || cqe->rx_udp_csum_succeed))
+		skb->ip_summed = CHECKSUM_UNNECESSARY;
 
 	if (cqe->rx_hashtype != 0 && (ndev->features & NETIF_F_RXHASH)) {
 		hash_value = cqe->ppi[0].pkt_hash;
author maintainer
#702 lore raw

PATCH 701/990 net: stmmac: ptp: fix support for PTP_EXTTS_REQUEST2 ioctl

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: James Clark <[email protected]>

commit b66fca408bf85bb40f48a689daac75421f5283f8 upstream.

Commit 7c571ac57d9d ("net: ptp: introduce .supported_extts_flags to ptp_clock_info") modified the PTP core to validate the supported flags of external timestamp requests, rather than relying on each driver to check them.

stmmac_enable() and dwmac1000_ptp_enable() ignore the flags, and neither stmmac_ptp_clock_ops nor dwmac1000_ptp_clock_ops was given any .supported_extts_flags. Since PTP_EXTTS_REQUEST2 always implies PTP_STRICT_FLAGS, the core now rejects every PTP_EXTTS_REQUEST2 for this driver with -EOPNOTSUPP, where before that commit the same requests succeeded. Only the PTP_EXTTS_REQUEST ioctl still works.

Tests on an NXP i.MX 8M Plus (FRDM-IMX8MPLUS, GMAC 5.10a) show that the auxiliary snapshot inputs timestamp just the rising edge. The reference manuals for the STM32MP13 (GMAC 4.20a) and the Cyclone V HPS (GMAC 3.70a, which uses dwmac1000_ptp_clock_ops) say the same.

Encode this in .supported_extts_flags. A PTP_EXTTS_REQUEST2 for the rising edge then succeeds, and one for the falling edge or for both edges fails with -EOPNOTSUPP.

---
 drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c |    2 ++
 1 file changed, 2 insertions(+)
drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c +2 -0
@@ -302,6 +302,7 @@ const struct ptp_clock_info stmmac_ptp_c
 	.n_per_out = 0, /* will be overwritten in stmmac_ptp_register */
 	.n_pins = 0,
 	.pps = 0,
+	.supported_extts_flags = PTP_RISING_EDGE | PTP_STRICT_FLAGS,
 	.adjfine = stmmac_adjust_freq,
 	.adjtime = stmmac_adjust_time,
 	.gettime64 = stmmac_get_time,
@@ -319,6 +320,7 @@ const struct ptp_clock_info dwmac1000_pt
 	.n_per_out = 0,
 	.n_pins = 0,
 	.pps = 0,
+	.supported_extts_flags = PTP_RISING_EDGE | PTP_STRICT_FLAGS,
 	.adjfine = stmmac_adjust_freq,
 	.adjtime = stmmac_adjust_time,
 	.gettime64 = stmmac_get_time,
author maintainer
#703 lore raw

PATCH 702/990 net: usb: lan78xx: let unregister_netdev() stop phylink

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: YuanZhe Liu <[email protected]>

commit 9280128245612b30ca4a238daa6a777b0f4e583e upstream.

lan78xx_disconnect() stops phylink before unregistering the net device. phylink_start() is only called from lan78xx_open(), so when the device is unplugged before the interface has been brought up, the attached PHY is still in PHY_READY and phy_stop() reports:

called from state READY

  WARNING: drivers/net/phy/phy.c:1670 at phy_stop+0xad/0x380

The same warning is emitted after an ifup/ifdown cycle, where the PHY is already in PHY_HALTED.

unregister_netdev() already closes a running device, which calls lan78xx_stop() and phylink_stop() with dev->dev_mutex held and after the URBs have been terminated. Unregister first and disconnect the PHY afterwards, so the interface is stopped exactly once and only while it is running, and the net device can no longer be opened while its phylink instance has no PHY attached.

Fixes e110bc825897 ("net: usb: lan78xx: Convert to PHYLINK for improved PHY and MAC management")
---
 drivers/net/usb/lan78xx.c |    5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
drivers/net/usb/lan78xx.c +2 -3
@@ -4594,13 +4594,12 @@ static void lan78xx_disconnect(struct us
 	udev = interface_to_usbdev(intf);
 	net = dev->net;
 
+	unregister_netdev(net);
+
 	rtnl_lock();
-	phylink_stop(dev->phylink);
 	phylink_disconnect_phy(dev->phylink);
 	rtnl_unlock();
 
-	unregister_netdev(net);
-
 	timer_shutdown_sync(&dev->stat_monitor);
 	set_bit(EVENT_DEV_DISCONNECT, &dev->flags);
 	cancel_delayed_work_sync(&dev->wq);
author maintainer
#704 lore raw

PATCH 703/990 xsk: defer software checksum until the skb is complete

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Rongzheng Wang <[email protected]>

commit f2eddafbfcc004098425fee7c5664adbe29152d7 upstream.

When XDP_UMEM_TX_SW_CSUM is used with multi-buffer TX, xsk_skb_metadata() calls skb_checksum_help() while only the first descriptor has been added to the skb. The checksum therefore covers just the first fragment, and skb_checksum_help() sets ip_summed to CHECKSUM_NONE, so the remaining fragments are never included in the checksum.

Move the software checksum calculation to the point where the last descriptor has been added to the skb.

On a checksum failure the packet is now dropped instead of being returned to the application for a retry. This path is not reachable with the existing metadata validation, but the behavior change is intentional.

---
 net/xdp/xsk.c |   23 +++++++++++++++--------
 1 file changed, 15 insertions(+), 8 deletions(-)
net/xdp/xsk.c +15 -8
@@ -902,14 +902,6 @@ static int xsk_skb_metadata(struct sk_bu
 		skb->csum_start = hr + csum_start;
 		skb->csum_offset = csum_offset;
 		skb->ip_summed = CHECKSUM_PARTIAL;
-
-		if (unlikely(pool->tx_sw_csum)) {
-			int err;
-
-			err = skb_checksum_help(skb);
-			if (err)
-				return err;
-		}
 	}
 
 	if (flags & XDP_TXMD_FLAGS_LAUNCH_TIME)
@@ -921,6 +913,15 @@ static int xsk_skb_metadata(struct sk_bu
 	return 0;
 }
 
+static int xsk_skb_sw_csum(struct sk_buff *skb, struct xsk_buff_pool *pool)
+{
+	if (unlikely(pool->tx_sw_csum &&
+		     skb->ip_summed == CHECKSUM_PARTIAL))
+		return skb_checksum_help(skb);
+
+	return 0;
+}
+
 static struct sk_buff *xsk_build_skb_zerocopy(struct xdp_sock *xs,
 					      struct xdp_desc *desc)
 {
@@ -1174,6 +1175,12 @@ static int __xsk_generic_xmit(struct soc
 			continue;
 		}
 
+		err = xsk_skb_sw_csum(skb, xs->pool);
+		if (unlikely(err)) {
+			xsk_drop_skb(skb);
+			goto out;
+		}
+
 		err = __dev_direct_xmit(skb, xs->queue_id);
 		if  (err == NETDEV_TX_BUSY) {
 			/* Tell user-space to retry the send */
author maintainer
#705 lore raw

PATCH 704/990 vsock/virtio: clear vqs[] to avoid a UAF on a failed PM restore

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jerome Mohm <[email protected]>

commit 2a24ba1694f14299fbde3fa107e5d56629f2f8b6 upstream.

virtio_vsock_vqs_del() frees the virtqueues but leaves vsock->vqs[] pointing at them. If virtio_vsock_restore() then fails, the driver stays bound with a dangling vqs[], and the next freeze or unbind passes a freed virtqueue to virtqueue_detach_unused_buf():

  BUG: KASAN: slab-use-after-free in virtqueue_detach_unused_buf
   virtio_vsock_vqs_del (net/vmw_vsock/virtio_transport.c:785)
   virtio_vsock_remove
  Freed by task ...:
   vp_del_vqs
   virtio_vsock_freeze

Clear vqs[] after del_vqs() and when virtio_find_vqs() fails. Return early from virtio_vsock_vqs_del() when vqs[] is empty: the detach loops would pass NULL to virtqueue_detach_unused_buf(), and a second del_vqs() would free virtio-mmio's IRQ again, which only WARNs in free_irq() ("Trying to free already-free IRQ").

Found with the help of Anthropic's Claude and reproduced on virtio-pci and virtio-mmio by failing the restore with failslab, without other kernel changes; the virtio-mmio WARN was found by the netdev Sashiko review and reproduced with v1 of this patch. With this patch neither report appears on virtio-pci or virtio-mmio guests, and the vsock vmtest.sh single-VM tests pass. A find_vqs() failure after some virtqueues were set up was not exercised.

---
 net/vmw_vsock/virtio_transport.c |   16 +++++++++++++---
 1 file changed, 13 insertions(+), 3 deletions(-)
net/vmw_vsock/virtio_transport.c +13 -3
@@ -690,8 +690,10 @@ static int virtio_vsock_vqs_init(struct
 	atomic_set(&vsock->queued_replies, 0);
 
 	ret = virtio_find_vqs(vdev, VSOCK_VQ_MAX, vsock->vqs, vqs_info, NULL);
-	if (ret < 0)
+	if (ret < 0) {
+		memset(vsock->vqs, 0, sizeof(vsock->vqs));
 		return ret;
+	}
 
 	virtio_vsock_update_guest_cid(vsock);
 
@@ -752,11 +754,19 @@ static void virtio_vsock_vqs_del(struct
 	vsock->event_run = false;
 	mutex_unlock(&vsock->event_lock);
 
+	virtio_vsock_skb_queue_purge(&vsock->send_pkt_queue);
+
 	/* Flush all device writes and interrupts, device will not use any
 	 * more buffers.
 	 */
 	virtio_reset_device(vdev);
 
+	/* After a failed restore no virtqueues are live, and a second
+	 * del_vqs() would free virtio-mmio's IRQ again (a WARN in free_irq()).
+	 */
+	if (!vsock->vqs[VSOCK_VQ_RX])
+		return;
+
 	mutex_lock(&vsock->rx_lock);
 	while ((skb = virtqueue_detach_unused_buf(vsock->vqs[VSOCK_VQ_RX])))
 		kfree_skb(skb);
@@ -767,10 +777,10 @@ static void virtio_vsock_vqs_del(struct
 		kfree_skb(skb);
 	mutex_unlock(&vsock->tx_lock);
 
-	virtio_vsock_skb_queue_purge(&vsock->send_pkt_queue);
-
 	/* Delete virtqueues and flush outstanding callbacks if any */
 	vdev->config->del_vqs(vdev);
+
+	memset(vsock->vqs, 0, sizeof(vsock->vqs));
 }
 
 static int virtio_vsock_probe(struct virtio_device *vdev)
author maintainer
#706 lore raw

PATCH 705/990 tsacct: Keep task begin times stable across suspend

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Hungyu Lin <[email protected]>

commit c49b3c20a2d0b22700e2100a527e68e829ece7f0 upstream.

bacct_add_tsk() derives ac_btime and ac_btime64 by subtracting a CLOCK_MONOTONIC elapsed duration from CLOCK_REALTIME. MONOTONIC stops during suspend while REALTIME continues, so querying an existing task after resume moves its reported begin time forward by the time spent suspended.

Calculate the begin time from the wall-clock boot timestamp and the task's CLOCK_BOOTTIME start timestamp instead. This accounts for suspend and adds the nanoseconds before truncating to seconds. Keep ac_etime and ac_tgetime on CLOCK_MONOTONIC and retain the existing rebasing when the wall clock is adjusted.

The new begin time can be negative: setting CLOCK_REALTIME is bounded by CLOCK_MONOTONIC, which excludes suspend, rather than CLOCK_BOOTTIME. A permitted backward clock adjustment after suspend can therefore put the task's begin time before the epoch. Clamp ac_btime64 at zero too, instead of wrapping in the unsigned field, and retain its positive range.

---
 kernel/tsacct.c |   10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)
kernel/tsacct.c +6 -4
@@ -24,7 +24,7 @@ void bacct_add_tsk(struct user_namespace
 	const struct cred *tcred;
 	u64 utime, stime, utimescaled, stimescaled;
 	u64 now_ns, delta;
-	time64_t btime;
+	struct timespec64 btime;
 
 	BUILD_BUG_ON(TS_COMM_LEN < TASK_COMM_LEN);
 
@@ -39,9 +39,11 @@ void bacct_add_tsk(struct user_namespace
 	do_div(delta, NSEC_PER_USEC);
 	stats->ac_etime = delta;
 	/* Convert to seconds for btime (note y2106 limit) */
-	btime = ktime_get_real_seconds() - div_u64(delta, USEC_PER_SEC);
-	stats->ac_btime = clamp_t(time64_t, btime, 0, U32_MAX);
-	stats->ac_btime64 = btime;
+	getboottime64(&btime);
+	btime = timespec64_add(btime, ns_to_timespec64(tsk->start_boottime));
+	stats->ac_btime = clamp_t(time64_t, btime.tv_sec, 0, U32_MAX);
+	/* Setting the clock back after suspend can make btime negative. */
+	stats->ac_btime64 = max_t(time64_t, btime.tv_sec, 0);
 
 	if (tsk->flags & PF_EXITING)
 		stats->ac_exitcode = tsk->exit_code;
author maintainer
#707 lore raw

PATCH 706/990 tls: only install push_pending_record for a TX context

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Rishikesh Jethwani <[email protected]>

commit c47e766c5307c06a78304582b2b5b5ab01ee1358 upstream.

tls_set_sw_offload() assigns ctx->push_pending_record for both directions, but the hook is a TX-side dispatcher. On a socket whose TX side is HW offloaded, tls_set_device_offload() installs tls_device_push_pending_record(); any later TLS_RX setsockopt overwrites it with tls_sw_push_pending_record(), because tls_set_device_offload_rx() itself calls tls_set_sw_offload(sk, 0, NULL) for the software half of a successful HW RX offload, and so does the fallback when the RX offload is declined (NIC with TX-only offload, tls_dev_add() failure).

Quoted 1 line

From then on tls_handle_open_record() (a TLS_SET_RECORD_TYPE cmsg after

a MSG_MORE send, or the close path with a pending writer) runs tls_sw_push_pending_record() against priv_ctx_tx, which is a struct tls_offload_context_tx, not a struct tls_sw_context_tx, and reads open_rec from inside the offload context. On x86_64 without lock debugging that field overlays sg_tx_data[2].dma_address, which is never set, so the push is silently skipped and the data buffered by the MSG_MORE send is later sent under the cmsg's record type, e.g. application data in a handshake or alert record. Enabling CONFIG_DEBUG_SPINLOCK, CONFIG_DEBUG_LOCK_ALLOC and CONFIG_LOCKDEP, but not CONFIG_LOCK_STAT, in the tested x86_64 configuration moves open_rec over sg_tx_data[5].page_link. Once populated, its page pointer and scatterlist flags are interpreted as a tls_rec pointer and dereferenced while reading msg_plaintext.sg.size.

Only set the hook when initialising the TX side.

Found by code review while developing TLS 1.3 HW offload rekey support.

Tested with HW TLS TX and RX offload on Mellanox ConnectX-6 Dx (Crypto Enabled): after setting TLS_RX, send() "AAAA" with MSG_MORE, then sendmsg() "BBBB" with a TLS_SET_RECORD_TYPE cmsg for a handshake record. Without this patch the peer receives a single handshake record "AAAABBBB"; with it, an application data record "AAAA" followed by a handshake record "BBBB".

---
 net/tls/tls_sw.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
net/tls/tls_sw.c +2 -1
@@ -2933,7 +2933,8 @@ int tls_set_sw_offload(struct sock *sk,
 		}
 	}
 
-	ctx->push_pending_record = tls_sw_push_pending_record;
+	if (tx)
+		ctx->push_pending_record = tls_sw_push_pending_record;
 
 	/* setkey is the last operation that could fail during a
 	 * rekey. if it succeeds, we can start modifying the
author maintainer
#708 lore raw

PATCH 707/990 tcp: do not coalesce segments after FIN

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Hyunwoo Kim <[email protected]>

commit 1c46780dec48893b8c25fd5e33a3127e8dc39dd4 upstream.

A FIN consumes a sequence number. If another FIN segment is coalesced into an skb that already carries FIN, end_seq advances to account for the additional FIN, but tcp_flags still contains only one FIN bit.

When the preceding gap is filled and tcp_ofo_queue() processes the coalesced skb, rcv_nxt advances to the skb's end_seq. When the receive path consumes all data in the skb, copied_seq advances by the data length and one sequence number for FIN. If three or more FIN segments have been coalesced into one skb, tcp_inq() can still return a positive value after the receive queue becomes empty and the SOCK_DONE adjustment is applied.

TCP_ZEROCOPY_RECEIVE is another consumer affected by this state. tcp_zerocopy_receive() takes its length from tcp_inq() and follows skb->next without checking for the end of the receive queue.

Software kTLS receive is one consumer affected by this state. When strp->copy_mode is false, tls_strp_msg_consume() calls the TCP helper tcp_read_done() to consume the current TLS record. In the reproducer, tcp_read_done() consumed the record data and one FIN before freeing the receive skb.

When kTLS looked for the next record, tcp_inq() reported at least TLS_HEADER_SIZE bytes even though the receive queue was empty. tcp_recv_skb() returned NULL, so tls_strp_load_anchor_with_queue() hit WARN_ON_ONCE() and returned without updating the anchor.

Since tcp_inq() had reported at least TLS_HEADER_SIZE, tls_strp_read_sock() proceeded to tls_strp_check_queue_ok(). skb_shinfo(strp->anchor)->frag_list still pointed to the freed receive skb. tls_strp_check_queue_ok() then read TCP_SKB_CB(first)->seq through the stale pointer, causing a use-after-free.

The reproducer followed this call path:

tls_rx_rec_done()
tls_strp_msg_consume()
tcp_read_done() // frees the receive skb
tls_strp_check_rcv()
tls_strp_read_sock()
tls_strp_load_anchor_with_queue() // returns after WARN_ON_ONCE()
tcp_recv_skb() == NULL
tls_strp_check_queue_ok()
TCP_SKB_CB(first)->seq // reads the freed receive skb

KASAN reported:

  BUG: KASAN: slab-use-after-free in tls_strp_check_queue_ok.isra.0+0x5f/0x100
  Read of size 4 at addr ffff888103169ca8 by task ktls-server/71
  ...
  Call Trace:
   <TASK>
   ...
   tls_strp_check_queue_ok.isra.0+0x5f/0x100
   tls_strp_check_rcv+0x2a9/0x400
   ...
   tls_sw_recvmsg+0x3ce/0xa10
   ...
   sock_recvmsg+0xea/0x100
   __sys_recvfrom+0x142/0x1f0
   ...
   __x64_sys_recvfrom+0x76/0x90
   do_syscall_64+0xdd/0x4a0
   entry_SYSCALL_64_after_hwframe+0x77/0x7f
   ...
   </TASK>
  ...
  Freed by task 71:
   ...
   napi_skb_cache_put+0x24/0xf0
   skb_attempt_defer_free+0x183/0x3b0
   tcp_read_done+0x2d4/0x340
   tls_strp_msg_consume+0x45/0x80
   tls_sw_recvmsg+0x3c4/0xa10
   ...

In tcp_try_coalesce(), skip coalescing when the destination skb already carries FIN. tcp_add_backlog() calls skb_try_coalesce() directly instead of using this helper, so add the same check there. Since both paths check only the destination skb, a final segment carrying data and FIN can still be coalesced into an skb without FIN when the other coalescing checks pass.

Fixes e93a0435f809 ("tcp: allow segment with FIN in tcp_try_coalesce()")
Fixes 4f693b55c3d2 ("tcp: implement coalescing on backlog queue")
---
 net/ipv4/tcp_input.c |    4 ++++
 net/ipv4/tcp_ipv4.c  |    2 ++
 2 files changed, 6 insertions(+)
net/ipv4/tcp_input.c +4 -0
@@ -5063,6 +5063,10 @@ static bool tcp_try_coalesce(struct sock
 	if (!tcp_skb_can_collapse_rx(to, from))
 		return false;
 
+	/* Nothing follows a FIN. */
+	if (unlikely(TCP_SKB_CB(to)->tcp_flags & TCPHDR_FIN))
+		return false;
+
 	if (!skb_try_coalesce(to, from, fragstolen, &delta))
 		return false;
 
net/ipv4/tcp_ipv4.c +2 -0
@@ -2084,6 +2084,8 @@ bool tcp_add_backlog(struct sock *sk, st
 	    ((TCP_SKB_CB(tail)->tcp_flags ^
 	      TCP_SKB_CB(skb)->tcp_flags) &
 	     (TCPHDR_ECE | TCPHDR_CWR | TCPHDR_AE)) ||
+	    /* Nothing follows a FIN, see tcp_try_coalesce() */
+	    (TCP_SKB_CB(tail)->tcp_flags & TCPHDR_FIN) ||
 	    !tcp_skb_can_collapse_rx(tail, skb) ||
 	    thtail->doff != th->doff ||
 	    memcmp(thtail + 1, th + 1, hdrlen - sizeof(*th)) ||
author maintainer
#709 lore raw

PATCH 708/990 tcp: fix authentication bypass via unsupported TCP auth options

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jérémy Jean <[email protected]>

commit 7cc235fb1251fec1183e3158c60d2e504c2a8e8b upstream.

tcp_inbound_hash() parses both TCP-MD5 and TCP-AO options when at least one of the two features is enabled. With TCP_MD5SIG=y and TCP_AO=n, a packet carrying an AO option reaches the disabled tcp_inbound_ao_hash() stub. That stub returns success, so sockets configured to require MD5 authentication end up accepting unauthenticated data. A forged AO option skips the unsigned fast path, which is the only place where tcp_inbound_hash() can return SKB_DROP_REASON_TCP_MD5NOTFOUND.

The inverse configuration with TCP_MD5SIG=n and TCP_AO=y has the same problem for an MD5 option on AO sockets.

Note that TCP-AO depends on 64BIT: therefore, every 32-bit kernel with TCP_MD5SIG=y is in the vulnerable configuration.

Make the disabled stubs reject options for the unsupported authentication scheme. This matches the real helpers' behavior for sockets without keys. It also means that kernels with TCP_MD5SIG=n and TCP_AO=y now drop segments carrying an MD5 option on unkeyed sockets, as kernels configured with TCP_MD5SIG=y already do.

---
 include/net/tcp_ao.h |    3 ++-
 net/ipv4/tcp.c       |    3 ++-
 2 files changed, 4 insertions(+), 2 deletions(-)
include/net/tcp_ao.h +2 -1
@@ -287,7 +287,8 @@ static inline enum skb_drop_reason tcp_i
 		const struct request_sock *req, int l3index,
 		const struct tcp_ao_hdr *aoh)
 {
-	return SKB_NOT_DROPPED_YET;
+	NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPAOKEYNOTFOUND);
+	return SKB_DROP_REASON_TCP_AOUNEXPECTED;
 }
 
 static inline struct tcp_ao_key *tcp_ao_do_lookup(const struct sock *sk,
net/ipv4/tcp.c +2 -1
@@ -4965,7 +4965,8 @@ tcp_inbound_md5_hash(const struct sock *
 		     const void *saddr, const void *daddr,
 		     int family, int l3index, const __u8 *hash_location)
 {
-	return SKB_NOT_DROPPED_YET;
+	NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMD5UNEXPECTED);
+	return SKB_DROP_REASON_TCP_MD5UNEXPECTED;
 }
 
 #endif
author maintainer
#710 lore raw

PATCH 709/990 tcp: fix request_sock use-after-free during Fast Open accept()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Hyunwoo Kim <[email protected]>

commit 62754aad50d0b30938bd8ce30b43474ce502a2af upstream.

Commit e3d95ad7da4f ("inet: avoid fastopen lock for regular accept()") made inet_csk_accept() check tfo_listener before taking fastopenq.lock to avoid taking the lock for connections that did not use Fast Open.

reqsk_fastopen_remove() clears tfo_listener while holding fastopenq.lock, then reads req->sk. If inet_csk_accept() concurrently observes tfo_listener after it has been cleared, it skips fastopenq.lock and drops the last reference to the request_sock. This can free the request_sock while reqsk_fastopen_remove() is still using it.

If the freed memory is reused for a new request_sock with req->sk == NULL, the reset path in reqsk_fastopen_remove() can append the new request_sock to the original listener's list of requests that caused an RST. After the new request_sock is freed, the next append writes through the stale rskq_rst_tail into freed memory.

KASAN reported the following use-after-free when writing fastopenq->rskq_rst_tail->dl_next = req:

  BUG: KASAN: slab-use-after-free in reqsk_fastopen_remove+0x142/0x210
  Write of size 8 at addr ffff888108230688 by task swapper/5/0
  ...
  Call Trace:
   <IRQ>
   ...
   reqsk_fastopen_remove+0x142/0x210
   tcp_check_req+0x96f/0xdd0
   ...
   tcp_rcv_state_process+0x19c/0x26b0
   ...
   tcp_v4_do_rcv+0x16e/0x490
   tcp_v4_rcv+0x14a0/0x1af0
   ...
   ip_protocol_deliver_rcu+0x39/0x1e0
   ip_local_deliver_finish+0x124/0x1e0
   ip_local_deliver+0xfb/0x1e0
   ...
   </IRQ>

To widen the race windows, mdelay(5) was added after newsk = req->sk, mdelay(20) after the if (req) reqsk_put(req) block, and mdelay(100) after tcp_rsk(req)->tfo_listener = false. The KASAN report above was reproduced with this kernel.

For the lockless check, use tcp_sk(newsk)->syn_fastopen_child instead of tfo_listener, which reqsk_fastopen_remove() clears.

syn_fastopen_child is a field of the Fast Open child TCP socket referenced by newsk, not of the request_sock. It is set before the child socket is added to the accept queue. The paths that call reqsk_fastopen_remove() in response to a remote ACK or RST do not clear this field.

inet_csk_accept() uses this field to take fastopenq.lock only for Fast Open child sockets and rechecks tfo_listener while holding the lock. Connections that did not use Fast Open continue to avoid the lock.

---
 net/ipv4/inet_connection_sock.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/ipv4/inet_connection_sock.c +1 -1
@@ -684,7 +684,7 @@ struct sock *inet_csk_accept(struct sock
 	newsk = req->sk;
 
 	if (sk->sk_protocol == IPPROTO_TCP &&
-	    tcp_rsk(req)->tfo_listener) {
+	    tcp_sk(newsk)->syn_fastopen_child) {
 		spin_lock_bh(&queue->fastopenq.lock);
 		if (tcp_rsk(req)->tfo_listener) {
 			/* We are still waiting for the final ACK from 3WHS
author maintainer
#711 lore raw

PATCH 710/990 seg6: validate state in netfilter continuations

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Zixuan Chai <[email protected]>

commit 549484dd3e80a721d51bd695f22a800d2e05bea1 upstream.

When nf_hooks_lwtunnel is enabled, End.DX4 sends decapsulated packets through NF_INET_PRE_ROUTING. If DNAT changes the inner destination, nf_nat_ipv4_pre_routing() drops skb_dst(), and the continuation then dereferences the missing dst's lwtstate. This causes a KASAN NULL pointer dereference and fatal exception panic.

End.DX6 has the same issue with IPv6 DNAT. In seg6_iptunnel, POST_ROUTING SNAT with an outbound XFRM policy can replace the dst before the continuation resumes.

Validate the current dst and expected lwtstate type in each NF_HOOK() continuation before calling the existing handler. Drop packets with missing or incompatible state while preserving direct no-hook paths. The helpers return bool because callers only need a validity check.

Testing shows that the End.DX4 DNAT reproducer triggers a KASAN NULL pointer dereference without this change and no longer does so with the fix. The SNAT+ESP/XFRM reproducer also completes without the reported fault. The in-tree End.DX4 netfilter forwarding selftest passes all four bidirectional checks with nf_hooks_lwtunnel disabled and enabled.

---
 net/ipv6/seg6_iptunnel.c |   46 +++++++++++++++++++++++++++++++++++----
 net/ipv6/seg6_local.c    |   55 ++++++++++++++++++++++++++++++++++++++++++++---
 2 files changed, 94 insertions(+), 7 deletions(-)
net/ipv6/seg6_iptunnel.c +42 -4
@@ -18,6 +18,7 @@
 #include <net/ip6_fib.h>
 #include <net/route.h>
 #include <net/seg6.h>
+#include <net/dst_metadata.h>
 #include <linux/seg6.h>
 #include <linux/seg6_iptunnel.h>
 #include <net/addrconf.h>
@@ -58,6 +59,21 @@ static inline struct seg6_lwt *seg6_lwt_
 	return (struct seg6_lwt *)lwt->data;
 }
 
+static bool seg6_skb_has_lwtstate(struct sk_buff *skb)
+{
+	struct dst_entry *dst;
+
+	if (unlikely(!skb_valid_dst(skb)))
+		return false;
+
+	dst = skb_dst(skb);
+	if (unlikely(!dst->lwtstate ||
+		     dst->lwtstate->type != LWTUNNEL_ENCAP_SEG6))
+		return false;
+
+	return true;
+}
+
 static inline struct seg6_iptunnel_encap *
 seg6_encap_lwtunnel(struct lwtunnel_state *lwt)
 {
@@ -538,6 +554,17 @@ drop:
 	return err;
 }
 
+static int seg6_input_core_nf(struct net *net, struct sock *sk,
+			      struct sk_buff *skb)
+{
+	if (unlikely(!seg6_skb_has_lwtstate(skb))) {
+		kfree_skb(skb);
+		return -EINVAL;
+	}
+
+	return seg6_input_core(net, sk, skb);
+}
+
 static int seg6_input_nf(struct sk_buff *skb)
 {
 	struct net_device *dev = skb_dst_dev(skb);
@@ -546,10 +573,10 @@ static int seg6_input_nf(struct sk_buff
 	switch (skb->protocol) {
 	case htons(ETH_P_IP):
 		return NF_HOOK(NFPROTO_IPV4, NF_INET_POST_ROUTING, net, NULL,
-			       skb, NULL, dev, seg6_input_core);
+			       skb, NULL, dev, seg6_input_core_nf);
 	case htons(ETH_P_IPV6):
 		return NF_HOOK(NFPROTO_IPV6, NF_INET_POST_ROUTING, net, NULL,
-			       skb, NULL, dev, seg6_input_core);
+			       skb, NULL, dev, seg6_input_core_nf);
 	}
 
 	return -EINVAL;
@@ -624,6 +651,17 @@ drop:
 	return err;
 }
 
+static int seg6_output_core_nf(struct net *net, struct sock *sk,
+			       struct sk_buff *skb)
+{
+	if (unlikely(!seg6_skb_has_lwtstate(skb))) {
+		kfree_skb(skb);
+		return -EINVAL;
+	}
+
+	return seg6_output_core(net, sk, skb);
+}
+
 static int seg6_output_nf(struct net *net, struct sock *sk, struct sk_buff *skb)
 {
 	struct net_device *dev = skb_dst_dev(skb);
@@ -631,10 +669,10 @@ static int seg6_output_nf(struct net *ne
 	switch (skb->protocol) {
 	case htons(ETH_P_IP):
 		return NF_HOOK(NFPROTO_IPV4, NF_INET_POST_ROUTING, net, sk, skb,
-			       NULL, dev, seg6_output_core);
+			       NULL, dev, seg6_output_core_nf);
 	case htons(ETH_P_IPV6):
 		return NF_HOOK(NFPROTO_IPV6, NF_INET_POST_ROUTING, net, sk, skb,
-			       NULL, dev, seg6_output_core);
+			       NULL, dev, seg6_output_core_nf);
 	}
 
 	return -EINVAL;
net/ipv6/seg6_local.c +52 -3

103 lines not on this page · raw message

author maintainer
#712 lore raw

PATCH 711/990 mptcp: reject DATA_ACKs against a reversed send interval

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Kyle Zeng <[email protected]>

commit d75e5cd72995ec2fa77ec77a593cea28e2490ff1 upstream.

ack_update_msk() samples snd_nxt before taking the data lock, but reads snd_una after taking it. Concurrent transmission and ACK processing can therefore leave the sampled upper bound behind snd_una. Active-open completion also exposes a reversed interval when it initializes snd_una to IDSN + 1 while the socket-owned state synchronization is deferred.

A peer-supplied 64-bit Data ACK half a sequence space away can pass both wraparound comparisons against such an interval. The resulting snd_una can make __mptcp_retrans() inflate a fragment's already_sent field. Later ACKs can then underflow data_len and cause out-of-bounds page fragments to be passed to TCP.

Read snd_nxt after acquiring the data lock and reject reversed intervals before checking the received Data ACK. This keeps the interval shorter than half the sequence space, so the existing upper-bound check cannot accept an advance beyond snd_nxt. Preserve the existing handling of old ACKs and keep the transmit fields under their existing socket locking.

Fixes 7439d687b79c ("mptcp: avoid a few atomic ops in the rx path")
Fixes 3f83d8a77eee ("mptcp: fix more tx path fields initialization")
---
 net/mptcp/options.c |   12 ++++++++----
 1 file changed, 8 insertions(+), 4 deletions(-)
net/mptcp/options.c +8 -4
@@ -1137,9 +1137,9 @@ static void ack_update_msk(struct mptcp_
 			   struct sock *ssk,
 			   struct mptcp_options_received *mp_opt)
 {
-	u64 new_wnd_end, new_snd_una, snd_nxt = READ_ONCE(msk->snd_nxt);
+	u64 new_wnd_end, new_snd_una, old_snd_una;
 	struct sock *sk = (struct sock *)msk;
-	u64 old_snd_una;
+	u64 snd_nxt;
 
 	mptcp_data_lock(sk);
 
@@ -1148,10 +1148,14 @@ static void ack_update_msk(struct mptcp_
 	 * more dangerous than missing an ack
 	 */
 	old_snd_una = msk->snd_una;
+	snd_nxt = READ_ONCE(msk->snd_nxt);
 	new_snd_una = mptcp_expand_seq(old_snd_una, mp_opt->data_ack, mp_opt->ack64);
 
-	/* ACK for data not even sent yet? Ignore.*/
-	if (unlikely(after64(new_snd_una, snd_nxt)))
+	/* The active-open state sync can defer the snd_nxt update. Do not
+	 * accept an ACK against a reversed interval, or beyond snd_nxt.
+	 */
+	if (unlikely(before64(snd_nxt, old_snd_una) ||
+		     after64(new_snd_una, snd_nxt)))
 		new_snd_una = old_snd_una;
 
 	new_wnd_end = new_snd_una + tcp_sk(ssk)->snd_wnd;
author maintainer
#713 lore raw

PATCH 712/990 ipv4: keep XFRM headers out of corked skb lengths

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Kyle Zeng <[email protected]>

commit 0f47fce51a98d3d9f439c16861d519a7b833a176 upstream.

__ip_append_data() allocates space for dst.header_len in the first skb, but includes that space in skb->len until __ip_make_skb() pulls it. Fragment accounting uses an MTU that already excludes the XFRM headers. As a result, the next skb can have a fraggap larger than its capped datalen, and skb_copy_and_csum_bits() can overwrite its shared info.

For example, five AH tunnel states can reserve 500 bytes while leaving an effective MTU of 348. With 40 bytes of IPv4 options, the second skb has room for 288 bytes of fragment data but receives a 500-byte gap copy. The overwritten shared info is subsequently consumed by the skb release paths.

Reserve the XFRM headers together with the link-layer headroom instead. This keeps skb->len, the gap-copy offsets and the trim lengths relative to the IPv4 packet throughout corking. The network and transport header addresses and the headroom available to XFRM at output are unchanged. Both paged and linear allocations, including subsequent corked appends, use the corrected accounting.

Fixes 353e5c9abd90 ("ipv4: Fix IPsec slowpath fragmentation problem")
---
 net/ipv4/ip_output.c |    8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
net/ipv4/ip_output.c +4 -4
@@ -1151,16 +1151,16 @@ alloc_new_skb:
 			 */
 			skb->ip_summed = csummode;
 			skb->csum = 0;
-			skb_reserve(skb, hh_len);
+			skb_reserve(skb, hh_len + exthdrlen);
 
 			/*
 			 *	Find where to start putting bytes.
 			 */
-			data = skb_put(skb, fraglen + exthdrlen - pagedlen);
-			skb_set_network_header(skb, exthdrlen);
+			data = skb_put(skb, fraglen - pagedlen);
+			skb_reset_network_header(skb);
 			skb->transport_header = (skb->network_header +
 						 fragheaderlen);
-			data += fragheaderlen + exthdrlen;
+			data += fragheaderlen;
 
 			if (fraggap) {
 				skb->csum = skb_copy_and_csum_bits(
author maintainer
#714 lore raw

PATCH 713/990 ipv4: fib_trie: prevent speculative out-of-bounds child access

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Daniël Trujillo <[email protected]>

commit fd3d73286662950656f54616d0b3fea29e2dc99a upstream.

fib_table_lookup() checks the child index against the bounds before passing it to get_child_rcu().

The index is derived from the lookup key, which in turn is derived from flp->daddr. A userspace process can therefore influence the index by triggering lookups for chosen destination IPv4 addresses.

If this bounds check is mispredicted as in-bounds, an out-of-bounds index can be transiently passed to get_child_rcu(). The value loaded beyond the child array is then treated as a node pointer. A later transient dereference of that pointer can cause a data-dependent cache footprint.

This was found during Spectre-v1 research. Leakage was demonstrated with instrumentation that delays branch resolution with a CLFLUSH before the mispredicted branch and makes the leaked location deterministic for reproducible measurement. In that setup, a userspace-controlled IPv4 lookup key was able to trigger a transient out-of-bounds child access. The transient use of the loaded value as a pointer caused a data-dependent cache footprint that was recoverable from userspace using Prime+Probe. A real-world attacker would likely need to delay branch resolution, which was not demonstrated end-to-end without the added CLFLUSH.

Sanitize the index with array_index_nospec() before accessing the child array. This removed the observed leakage in the described setup.

Apply the hardening before setting cindex in fib_table_lookup(), because cindex can later be used by the backtrace path to load another child pointer. fib_find_node() has the same pattern, with the checked index derived from a user-provided key in fib_table_insert() and fib_table_delete(). leaf_walk_rcu() has a similar checked cindex before get_child_rcu(), and the traversed state can be influenced by userspace actions. fib_find_node() runs under RTNL and leaf_walk_rcu() is not on the packet lookup hot path, so harden those analogous accesses in the same way. Also harden fib_trie_get_next(), where a mispredicted loop condition could transiently read one child past the array.

I see a slowdown of roughly 10% in a microbenchmark where we call fib_table_lookup() with 64 routes directly from inside the kernel. I observed no slowdown in a loopback UDP sendto() microbenchmark.

Fixes 9f9e636d4f89 ("fib_trie: Optimize fib_table_lookup to avoid wasting time on loops/variables")
---
 net/ipv4/fib_trie.c |   14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)
net/ipv4/fib_trie.c +13 -1
@@ -61,6 +61,7 @@
 #include <linux/export.h>
 #include <linux/vmalloc.h>
 #include <linux/notifier.h>
+#include <linux/nospec.h>
 #include <net/net_namespace.h>
 #include <net/inet_dscp.h>
 #include <net/ip.h>
@@ -961,6 +962,8 @@ static struct key_vector *fib_find_node(
 			break;
 		}
 
+		index = array_index_nospec(index, 1ul << n->bits);
+
 		/* keep searching until we find a perfect match leaf or NULL */
 	} while (IS_TNODE(n));
 
@@ -1466,6 +1469,8 @@ int fib_table_lookup(struct fib_table *t
 		if (IS_LEAF(n))
 			goto found;
 
+		index = array_index_nospec(index, 1ul << n->bits);
+
 		/* only record pn and cindex if we are going to be chopping
 		 * bits later.  Otherwise we are just wasting cycles.
 		 */
@@ -1766,6 +1771,8 @@ static struct key_vector *leaf_walk_rcu(
 		if (cindex >> pn->bits)
 			break;
 
+		cindex = array_index_nospec(cindex, 1ul << pn->bits);
+
 		/* descend into the next child */
 		n = get_child_rcu(pn, cindex++);
 		if (!n)
@@ -1787,6 +1794,8 @@ static struct key_vector *leaf_walk_rcu(
 			continue;
 		}
 
+		cindex = array_index_nospec(cindex, 1ul << pn->bits);
+
 		/* grab the next available node */
 		n = get_child_rcu(pn, cindex++);
 		if (!n)
@@ -2438,7 +2447,10 @@ static struct key_vector *fib_trie_get_n
 
 	while (!IS_TRIE(pn)) {
 		while (cindex < child_length(pn)) {
-			struct key_vector *n = get_child_rcu(pn, cindex++);
+			struct key_vector *n;
+
+			cindex = array_index_nospec(cindex, child_length(pn));
+			n = get_child_rcu(pn, cindex++);
 
 			if (!n)
 				continue;
author maintainer
#715 lore raw

PATCH 714/990 ipv6: fix cached route reuse for control messages

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Xia Yan <[email protected]>

commit f778e80b3daf5033fb996f45c2b5d0ce1e82c0a7 upstream.

A connected IPv6 UDP or ping socket can reuse its cached route when an SO_MARK cmsg requests another mark. A packet can then bypass a prohibit rule instead of failing with EACCES.

ip6_sk_dst_lookup_flow() reads the cache even when connected is false. UDP clears connected after parsing IP or socket control messages. Ping always passes false.

Only read the cache when connected is true. Ordinary connected UDP sends keep using the cache. Ping sends do a fresh lookup.

Found during code review of IPv6 UDP route caching. On UML, the same connected-socket selftest fails four IPv6 cases before the fix and passes all 54 with it.

---
 net/ipv6/ip6_output.c |   13 ++++++++-----
 1 file changed, 8 insertions(+), 5 deletions(-)
net/ipv6/ip6_output.c +8 -5
@@ -1287,7 +1287,7 @@ EXPORT_SYMBOL_GPL(ip6_dst_lookup_flow);
  *	@sk: socket which provides the dst cache and route info
  *	@fl6: flow to lookup
  *	@final_dst: final destination address for ipsec lookup
- *	@connected: whether @sk is connected or not
+ *	@connected: whether the flow can use and update the socket dst cache
  *
  *	This function performs a route lookup on the given flow with the
  *	possibility of using the cached route in the socket if it is valid.
@@ -1304,11 +1304,14 @@ struct dst_entry *ip6_sk_dst_lookup_flow
 					 const struct in6_addr *final_dst,
 					 bool connected)
 {
-	struct dst_entry *dst = sk_dst_check(sk, inet6_sk(sk)->dst_cookie);
+	struct dst_entry *dst;
 
-	dst = ip6_sk_dst_check(sk, dst, fl6);
-	if (dst)
-		return dst;
+	if (connected) {
+		dst = sk_dst_check(sk, inet6_sk(sk)->dst_cookie);
+		dst = ip6_sk_dst_check(sk, dst, fl6);
+		if (dst)
+			return dst;
+	}
 
 	dst = ip6_dst_lookup_flow(sock_net(sk), sk, fl6, final_dst);
 	if (connected && !IS_ERR(dst))
author maintainer
#716 lore raw

PATCH 715/990 ipv6: reject routes without an inet6_dev

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Yingjie Wang <[email protected]>

commit 08a1eb7a634f665718ebe74e0960e242f597135e upstream.

ip6_route_output() and ip6_route_lookup() can return an error-free route whose rt6i_idev is NULL. Lowering an external nexthop device's MTU below IPV6_MIN_MTU tears down its inet6_dev, while fib6_ifdown() leaves routes using nexthop objects in the FIB.

An unprivileged user with CAP_NET_ADMIN in a private user and network namespace can construct this state. Consumers which treat a route without an error as usable can then dereference the NULL rt6i_idev. This was reproduced as a KASAN NULL pointer dereference in ip6_tnl_xmit().

An audit of IPv6 route and tunnel users found this unchecked ip6_dst_idev() dereference.

A similar missing inet6_dev check was fixed in commit 1b9b5323725e ("netfilter: ip6t_rpfilter: reject routes without inet6_dev"). However, the route construction path still marks routes without an inet6_dev as successful, leaving every consumer responsible for the same check.

Acquire the inet6_dev reference before initializing the destination. If a non-reject route has no inet6_dev, initialize it as RTN_UNREACHABLE instead of a successful route. Explicit reject routes keep their original type and error. This establishes that ordinary error-free IPv6 routes have an inet6_dev while retaining the existing defensive checks at callers.

The modified route object builds cleanly with W=1. A full x86_64 KASAN bzImage build completes; it reports two pre-existing kernel-doc warnings outside this change.

Tests:
- make W=1 net/ipv6/route.o
- full x86_64 KASAN bzImage build with W=1
- KASAN QEMU with an unprivileged user and network namespace: after lowering the MTU, the stale route returned No route to host, a normal route still resolved, and the collect_md trigger completed without KASAN, oops, or panic
- tools/testing/selftests/net/ip6_tunnel.sh in the same KASAN QEMU

---
 net/ipv6/route.c |    8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
net/ipv6/route.c +7 -1
@@ -1143,6 +1143,12 @@ static void ip6_rt_init_dst(struct rt6_i
 		return;
 	}
 
+	/* addrconf_ifdown() removed inet6_dev. The device can't do IPv6. */
+	if (!rt->rt6i_idev) {
+		ip6_rt_init_dst_reject(rt, RTN_UNREACHABLE);
+		return;
+	}
+
 	rt->dst.error = 0;
 	rt->dst.output = ip6_output;
 
@@ -1178,10 +1184,10 @@ static void ip6_rt_copy_init(struct rt6_
 	const struct net_device *dev = nh->fib_nh_dev;
 	struct fib6_info *f6i = res->f6i;
 
+	rt->rt6i_idev = dev ? in6_dev_get(dev) : NULL;
 	ip6_rt_init_dst(rt, res);
 
 	rt->rt6i_dst = f6i->fib6_dst;
-	rt->rt6i_idev = dev ? in6_dev_get(dev) : NULL;
 	rt->rt6i_flags = res->fib6_flags;
 	if (nh->fib_nh_gw_family) {
 		rt->rt6i_gateway = nh->fib_nh_gw6;
author maintainer
#717 lore raw

PATCH 716/990 ipvs: Defer application parent freeing until after RCU readers

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Chengfeng Ye <[email protected]>

commit 1e0808008e44d736e57a897a51d14fa995099010 upstream.

unregister_ip_vs_app() removes each incarnation from its protocol list and uses call_rcu() to defer freeing it, but frees the parent application immediately. An RCU reader that already found an incarnation can still access the parent through inc->app in ip_vs_app_inc_get().

During FTP helper module unload, the following interleaving is possible:

CPU 0 (RCU reader) CPU 1 (module unload)
tcp_app_conn_bind()

    find inc in protocol list
                                     unregister_ip_vs_app()
                                       ip_vs_app_inc_release(inc)
                                         list_del_rcu(&inc->p_list)
                                         call_rcu(&inc->rcu_head, ...)
                                       kfree(a)
    ip_vs_app_inc_get(inc)
      try_module_get(inc->app->module)

The helper module is already going away, so try_module_get() would fail, but evaluating its argument first reads the freed parent. The subsequent rcu_barrier() in pernet unregistration cannot protect this earlier free. KASAN reported:

  BUG: KASAN: slab-use-after-free in ip_vs_app_inc_get+0x7c/0x90
  Call Trace:
   ip_vs_app_inc_get+0x7c/0x90
   tcp_app_conn_bind+0x1bc/0x290
   ip_vs_conn_new+0x1915/0x20d0
   ip_vs_schedule+0x697/0xea0
   tcp_conn_schedule+0x489/0x820
   ip_vs_in_hook+0x7bf/0x1f40
  Allocated by task 88:
   kmemdup_noprof+0x20/0x50
   register_ip_vs_app+0x12d/0x2c0
   __ip_vs_ftp_init+0x56/0x160 [ip_vs_ftp]
  Freed by task 104:
   kfree+0x131/0x3c0
   unregister_ip_vs_app+0x2f4/0x5b0
   unregister_pernet_operations+0x232/0x490
   unregister_pernet_subsys+0x1c/0x30
   __do_sys_delete_module+0x346/0x510

Use kfree_rcu() with the existing rcu_head to keep the parent alive until these readers finish. Successful helper references already prevent normal module unload, and incarnation RCU callbacks do not access the parent.

---
 net/netfilter/ipvs/ip_vs_app.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/netfilter/ipvs/ip_vs_app.c +1 -1
@@ -243,7 +243,7 @@ void unregister_ip_vs_app(struct netns_i
 		}
 
 		list_del(&a->a_list);
-		kfree(a);
+		kfree_rcu(a, rcu_head);
 
 		/* decrease the module use count */
 		ip_vs_use_count_dec();
author maintainer
#718 lore raw

PATCH 717/990 ipvs: fix protocol data lifetime during namespace teardown

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Chengfeng Ye <[email protected]>

commit 832aa3e89e806bb2667fe4e656b705f4088b3c9d upstream.

IPVS frees its per-net protocol data before control cleanup cancels defense work and unregisters the sysctl table. A defense worker can load a protocol data pointer, then namespace cleanup can unlink and free that object before the worker dereferences pd->pp or pd->next. The worker's securetcp_lock does not serialize with protocol cleanup. A concurrent defense-mode sysctl write can reach the same timeout update path.

KASAN reported:

  BUG: KASAN: slab-use-after-free in ip_vs_protocol_timeout_change
  Workqueue: events_long defense_work_handler
  Call Trace:
   ip_vs_protocol_timeout_change+0x1b4/0x1e0
   update_defense_level+0x63e/0xd80
   defense_work_handler+0x1e/0xc0
  Allocated by task 125:
   ip_vs_protocol_net_init+0xda/0x2f0
   __ip_vs_init+0x16b/0x240
   setup_net+0xfc/0x310
  Freed by task 12:
   ip_vs_protocol_net_cleanup+0x1d6/0x2e0
   __ip_vs_cleanup_batch+0x7d/0x100
   cleanup_net+0x38c/0x770

Run control cleanup before protocol cleanup so that defense work and active sysctl handlers have finished before their protocol data is freed. Initialize protocols before exposing the control interface, and unwind in reverse order, to enforce the same lifetime on initialization failure. Protocol initialization and exit do not depend on control state.

Fixes 9330419d9aa4 ("IPVS: netns, use ip_vs_proto_data as param.")
---
 net/netfilter/ipvs/ip_vs_core.c |   12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
net/netfilter/ipvs/ip_vs_core.c +6 -6
@@ -2319,12 +2319,12 @@ static int __net_init __ip_vs_init(struc
 	if (ip_vs_estimator_net_init(ipvs) < 0)
 		goto estimator_fail;
 
-	if (ip_vs_control_net_init(ipvs) < 0)
-		goto control_fail;
-
 	if (ip_vs_protocol_net_init(ipvs) < 0)
 		goto protocol_fail;
 
+	if (ip_vs_control_net_init(ipvs) < 0)
+		goto control_fail;
+
 	if (ip_vs_app_net_init(ipvs) < 0)
 		goto app_fail;
 
@@ -2344,10 +2344,10 @@ sync_fail:
 conn_fail:
 	ip_vs_app_net_cleanup(ipvs);
 app_fail:
-	ip_vs_protocol_net_cleanup(ipvs);
-protocol_fail:
 	ip_vs_control_net_cleanup(ipvs);
 control_fail:
+	ip_vs_protocol_net_cleanup(ipvs);
+protocol_fail:
 	ip_vs_estimator_net_cleanup(ipvs);
 estimator_fail:
 	net->ipvs = NULL;
@@ -2364,8 +2364,8 @@ static void __net_exit __ip_vs_cleanup_b
 		ipvs = net_ipvs(net);
 		ip_vs_conn_net_cleanup(ipvs);
 		ip_vs_app_net_cleanup(ipvs);
-		ip_vs_protocol_net_cleanup(ipvs);
 		ip_vs_control_net_cleanup(ipvs);
+		ip_vs_protocol_net_cleanup(ipvs);
 		ip_vs_estimator_net_cleanup(ipvs);
 		IP_VS_DBG(2, "ipvs netns %d released\n", ipvs->gen);
 		net->ipvs = NULL;
author maintainer
#719 lore raw

PATCH 718/990 gtp: free the skb after handling an echo response

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Joas Antonio dos Santos <[email protected]>

commit f17b293d155f377e4cff582b8113991d2ad346d6 upstream.

gtp0_handle_echo_resp() and gtp1u_handle_echo_resp() return the result of genlmsg_multicast_netns() to gtp_encap_recv(). When the netlink notification is delivered that result is 0, and gtp_encap_recv() treats 0 as "the skb has been consumed":

	switch (ret) {
	case 1:
		netdev_dbg(gtp->dev, "pass up to the process\n");
		break;
	case 0:
		break;
	case -1:
		netdev_dbg(gtp->dev, "GTP packet has been dropped\n");
		kfree_skb(skb);
		ret = 0;
		break;
	}

The echo response handlers only read from the skb and never free it or pass it on, so every echo response that is reported to a listener on the gtp multicast group leaks the skb. Echo responses are handled for any peer when the UDP sockets were created by the kernel, so a remote host can leak memory on the receiver by sending GTP echo responses while a process with CAP_NET_ADMIN is subscribed to the gtp multicast group, for example a daemon that monitors echo responses.

The error paths do not leak but have a related problem. -ENOMEM and the error from genlmsg_multicast_netns() (-ESRCH when nobody listens) are not -1, so they are returned unchanged to the UDP stack, which takes a negative value from encap_rcv() as a request to resubmit the packet to the protocol with that number.

Return -1 when the notification cannot be built, so that gtp_encap_recv() drops the skb, and consume the skb once the notification has been handed to netlink, whether or not anybody is listening.

Found by LLM-assisted source review, untested.

---
 drivers/net/gtp.c |   22 ++++++++++++++--------
 1 file changed, 14 insertions(+), 8 deletions(-)
drivers/net/gtp.c +14 -8
@@ -560,16 +560,19 @@ static int gtp0_handle_echo_resp(struct
 
 	msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
 	if (!msg)
-		return -ENOMEM;
+		return -1;
 
 	ret = gtp_genl_fill_echo(msg, 0, 0, 0, GTP_CMD_ECHOREQ, echo);
 	if (ret < 0) {
 		nlmsg_free(msg);
-		return ret;
+		return -1;
 	}
 
-	return genlmsg_multicast_netns(&gtp_genl_family, dev_net(gtp->dev),
-				       msg, 0, GTP_GENL_MCGRP, GFP_ATOMIC);
+	genlmsg_multicast_netns(&gtp_genl_family, dev_net(gtp->dev),
+				msg, 0, GTP_GENL_MCGRP, GFP_ATOMIC);
+	consume_skb(skb);
+
+	return 0;
 }
 
 static int gtp_proto_to_family(__u16 proto)
@@ -747,16 +750,19 @@ static int gtp1u_handle_echo_resp(struct
 
 	msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
 	if (!msg)
-		return -ENOMEM;
+		return -1;
 
 	ret = gtp_genl_fill_echo(msg, 0, 0, 0, GTP_CMD_ECHOREQ, echo);
 	if (ret < 0) {
 		nlmsg_free(msg);
-		return ret;
+		return -1;
 	}
 
-	return genlmsg_multicast_netns(&gtp_genl_family, dev_net(gtp->dev),
-				       msg, 0, GTP_GENL_MCGRP, GFP_ATOMIC);
+	genlmsg_multicast_netns(&gtp_genl_family, dev_net(gtp->dev),
+				msg, 0, GTP_GENL_MCGRP, GFP_ATOMIC);
+	consume_skb(skb);
+
+	return 0;
 }
 
 static int gtp_parse_exthdrs(struct sk_buff *skb, unsigned int *hdrlen)
author maintainer
#720 lore raw

PATCH 719/990 hv_netvsc: Stop PPI parsing on invalid metadata

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Erni Sri Satya Vennela <[email protected]>

commit 19a227903e65c7a9c179156485660a4e017575fe upstream.

rndis_get_ppi() uses continue when a per-packet information entry has an invalid size or offset, or cannot hold the requested metadata. However, the remaining length and entry pointer are only updated at the bottom of the loop. Each error path therefore retries the same invalid entry indefinitely, repeatedly logging the error and preventing receive processing from completing.

Return NULL on these validation failures instead of continuing. This terminates the lookup when malformed metadata is encountered while preserving the existing behavior for valid entries.

The issue was reported through an internal bug-tracking system and confirmed by manual code inspection. The pre-fix hang has not been reproduced locally.

Fixes 44144185951a ("hv_netvsc: Add validation for untrusted Hyper-V values")
---
 drivers/net/hyperv/rndis_filter.c |    6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
drivers/net/hyperv/rndis_filter.c +3 -3
@@ -401,12 +401,12 @@ static inline void *rndis_get_ppi(struct
 		/* Validate ppi_offset and ppi_size */
 		if (ppi->size > len) {
 			netdev_err(ndev, "Invalid ppi size: %u\n", ppi->size);
-			continue;
+			return NULL;
 		}
 
 		if (ppi->ppi_offset >= ppi->size) {
 			netdev_err(ndev, "Invalid ppi_offset: %u\n", ppi->ppi_offset);
-			continue;
+			return NULL;
 		}
 
 		if (ppi->type == type && ppi->internal == internal) {
@@ -414,7 +414,7 @@ static inline void *rndis_get_ppi(struct
 			if (ppi->size - ppi->ppi_offset < ppi_size) {
 				netdev_err(ndev, "Invalid ppi: size %u ppi_offset %u\n",
 					   ppi->size, ppi->ppi_offset);
-				continue;
+				return NULL;
 			}
 			return (void *)((ulong)ppi + ppi->ppi_offset);
 		}
author maintainer
#721 lore raw

PATCH 720/990 hv_sock: Report no unread data before a channel is available

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Andrea Parri <[email protected]>

commit 71b06766b7c49ed5f489b8bd104f82ff164d67a3 upstream.

The Hyper-V transport is assigned before the asynchronous VMBus channel offer completes. Its zero-initialized hvsock therefore has a NULL chan until hvs_open_connection() associates the channel with the socket.

SIOCINQ can query the assigned transport while the socket is connecting, or after connect() fails once the transport has been assigned. Unlike poll(), that path does not check stream_is_active() before calling the transport's stream_has_data callback. hvs_stream_has_data() then passes the NULL channel to hvs_channel_readable_payload(), and any user in the guest can trigger an oops:

  BUG: kernel NULL pointer dereference, address: 0000000000000178
  RIP: 0010:hvs_stream_has_data+0x23/0x120
  Call Trace:
   <TASK>
   ? vsock_ioctl+0x74/0xf0
   sock_do_ioctl+0x42/0xf0
   sock_ioctl+0x27d/0x310
   do_vfs_ioctl+0x700/0x810
   __x64_sys_ioctl+0x7d/0xf0

Return zero unread bytes when no channel is available, before accessing the receive state or ring. Leave the existing channel-backed receive handling unchanged.

The oops was reproduced on an unmodified v7.4-rc1 kernel in a WSL2 guest with a small user-space program, available on request. With this patch, the program reports zero unread bytes and the kernel logs nothing. Other vsock_test cases were not run, as most of them need a host-side peer.

AI assistance was used to identify the issue and develop the fix.

---
 net/vmw_vsock/hyperv_transport.c |    3 +++
 1 file changed, 3 insertions(+)
net/vmw_vsock/hyperv_transport.c +3 -0
@@ -698,6 +698,9 @@ static s64 hvs_stream_has_data(struct vs
 	struct hvsock *hvs = vsk->trans;
 	s64 ret;
 
+	if (!hvs->chan)
+		return 0;
+
 	if (hvs->recv_data_len > 0)
 		return hvs->recv_data_len;
 
author maintainer
#722 lore raw

PATCH 721/990 net: gro: avoid parsing headers from shared fragments

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Kyle Zeng <[email protected]>

commit 44818c9a826d766dc0e21179dc76f229334f1dda upstream.

When an skb has an empty linear head, skb_gro_reset_offset() can expose the first page fragment directly to GRO header parsers. For an SKBFL_SHARED_FRAG skb, those bytes may still be writable through a file mapping. Headers validated during receive can therefore differ from the headers later copied into the linear head and used during completion.

For example, changing an IPv6 destination-options length between the short and full header fetches in ipv6_gro_pull_exthdrs() can make ipv6_gro_complete() pass an out-of-bounds offset to udp6_gro_complete(). A userspace reproducer triggered a KASAN slab-out-of-bounds read there on an unmodified kernel as UID 1000. The same completion path can write the UDP checksum and length through the invalid offset. The packet has trusted TCP GSO metadata and spliced file data, so it reaches completion without an skb zerocopy destructor or a second GRO packet.

Disable the direct-fragment fast path for skbs with externally writable fragments. With an empty linear head, frag0_len remains zero, so skb_gro_header_slow() pulls each required header into the linear head before it is inspected. Subsequent pulls preserve the validated prefix. This covers both gro_receive_skb() and napi_gro_frags(), including other protocols using the same helpers. Linear headers and private fragments retain their existing fast paths.

Codex assisted with review of the supplied report, reproducer and draft fix, related-path analysis, and this changelog. The patched net/core/gro.o builds with W=1 using the supplied x86-64 configuration, allyesconfig and allmodconfig. The fix was checked by code-path analysis; the reproducer and kernel selftests have not been run on a booted patched kernel.

The issue was found by an LLM.

Fixes dff0b0161ad5 ("net: gro: parse ipv6 ext headers without frag0 invalidation")
---
 net/core/gro.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
net/core/gro.c +2 -1
@@ -419,7 +419,8 @@ static inline void skb_gro_reset_offset(
 	headlen = skb_headlen(skb);
 	NAPI_GRO_CB(skb)->frag0 = skb->data;
 	NAPI_GRO_CB(skb)->frag0_len = headlen;
-	if (headlen)
+	/* Shared fragments must be pulled into the linear head before parsing. */
+	if (headlen || skb_has_shared_frag(skb))
 		return;
 
 	pinfo = skb_shinfo(skb);
author maintainer
#723 lore raw

PATCH 722/990 net: gro: do not undo remote checksum offload on merged packets

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Eric Dumazet <[email protected]>

commit c817ec1b06875b98460fbd19591be541bc3fa924 upstream.

skb_gro_flush_final_remcsum() calls skb_gro_remcsum_cleanup() to undo the checksum adjustment done by skb_gro_remcsum_process() when the packet was not consumed by GRO.

When the inner handler merged the packet (NAPI_GRO_CB(skb)->same_flow is set), grc->offset can no longer be trusted:

- skb_gro_receive() either gives the frags or the head of the skb to the held packet, or uses __skb_pull(skb, offset) before adding the skb to the frag_list of the held packet.

- skb_gro_receive_list() uses skb_pull(skb, skb_gro_offset(skb)).

grc->offset is relative to the original skb->data, so the 2-byte read-modify-write done by skb_gro_remcsum_cleanup() can land in the payload of a packet which now belongs to the GRO packet. pskb_may_pull() can also be called on this frag_list member.

With fraglist GRO, this can also be a use-after-free:
pskb_may_pull(skb, skb_gro_offset(skb)) in skb_gro_receive_list() or udp_gro_receive_segment() releases the first page fragment if it only contains headers. NAPI_GRO_CB(skb)->frag0 and frag0_len are not updated, so skb_gro_remcsum_cleanup() takes the fast path and writes through frag0 into a page the skb no longer holds a reference on. The non merged case, where frag0 is used after this pull, is handled in the following patch.

For skbs merged by skb_gro_receive(), the cleanup can be skipped:
the skb is freed, or its headers are rebuilt from the head skb in skb_segment().

Fraglist members keep their own inner headers, as skb_segment_list() only copies the link-layer and tunnel headers from the head skb. Their checksum can not be right in all cases: a packet forwarded with its tunnel header needs the original value, while a VXLAN packet decapsulated locally needs the adjusted one, as vxlan_remcsum() only adjusts the head skb. Make skb_gro_receive_list() refuse packets with skb->remcsum_offload set, so that fraglist members never carry an adjusted checksum.

This affects VXLAN (VXLAN_F_REMCSUM_NOPARTIAL) and GUE (FOU_F_REMCSUM_NOPARTIAL).

This was found while fixing a report from Taesoo Kim and Cen Zhang, who used LLM assisted code analysis and provided reproducers.

Fixes 26c4f7da3e41 ("net: Fix remcsum in GRO path to not change packet")
---
 include/net/gro.h |    8 +++++++-
 net/core/gro.c    |    7 +++++++
 2 files changed, 14 insertions(+), 1 deletion(-)
include/net/gro.h +7 -1
@@ -351,7 +351,13 @@ static inline void skb_gro_remcsum_clean
 	void *ptr;
 	size_t plen = grc->offset + sizeof(u16);
 
-	if (!grc->delta)
+	/* Once merged, grc->offset can not be trusted: the frags or head
+	 * of this skb now belong to the GRO packet, or skb->data was pulled
+	 * past the headers before adding it to a frag_list.
+	 * skb_gro_receive_list() does not merge packets with an adjusted
+	 * checksum, other merged packets do not use their headers anymore.
+	 */
+	if (!grc->delta || NAPI_GRO_CB(skb)->same_flow)
 		return;
 
 	ptr = skb_gro_header(skb, plen, grc->offset);
net/core/gro.c +7 -0
@@ -243,6 +243,13 @@ int skb_gro_receive_list(struct sk_buff
 		     NAPI_GRO_CB(skb)->flush))
 		return -E2BIG;
 
+	/* Fraglist members keep their own headers. Their checksum can not
+	 * be right both for a forwarded packet and for a decapsulated one,
+	 * if remote checksum offload adjusted it.
+	 */
+	if (unlikely(skb->remcsum_offload))
+		return -EINVAL;
+
 	if (!pskb_may_pull(skb, skb_gro_offset(skb))) {
 		NAPI_GRO_CB(skb)->flush = 1;
 		return -ENOMEM;
author maintainer
#724 lore raw

PATCH 723/990 net: gro: invalidate frag0 after a pull

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Eric Dumazet <[email protected]>

commit 98d949a15ff9d3fffaa6983223178374aab92db6 upstream.

Since commit bd56a29c7a4e ("net: gro: change skb_gro_network_header()"), skb_gro_header_slow() no longer invalidates NAPI_GRO_CB(skb)->frag0 after pskb_may_pull(). skb_gro_may_pull() keeps comparing against the frag0_len value set in skb_gro_reset_offset(), assuming that after a slow pull, all later accesses are beyond frag0_len.

This is not true:

- udp4_gro_receive() and udp6_gro_receive() read the network header with skb_gro_network_header() after udp_gro_udphdr() pulled the UDP header.

- vxlan_gro_receive() calls skb_gro_remcsum_cleanup() at a lower offset after the inner handlers pulled their headers.

- skb_gro_remcsum_process() can pull beyond the inner Ethernet header before eth_gro_receive() reads it.

- napi_frags_skb() calls __skb_pull(skb, ETH_HLEN) after a slow pull, so frag0 still points to the Ethernet header.

If the pull consumed the first page fragment, __skb_pull_tail() released it. If the head had to grow, pskb_expand_head() freed the old one. These reads, and the 2-byte write in skb_gro_remcsum_cleanup(), then access memory the skb no longer holds a reference on.

esp4_gro_receive(), esp6_gro_receive(), skb_gro_receive_list() and udp_gro_receive_segment() also pull directly and never invalidated frag0.

Add skb_gro_frag0_invalidate(), which only clears frag0_len, and call it before each of these pulls. This is a single store in the slow path, and frag0 stays non NULL, so skb_gro_network_header() does not need a NULL test.

frag0 must be invalidated even if the pull fails: __pskb_pull_tail() can return NULL after pskb_expand_head() freed the old head, for instance if a frag_list member has to be cloned or pulled.

As frag0 is now invalidated before a pull that can fail, gro_try_pull_from_frag0() can see an skb whose linear part does not cover skb_gro_offset() while frag0 still points to the start of the packet, for instance after skb_gro_remcsum_cleanup() pulled a shorter length. Copying from frag0 would then corrupt the headers: only use frag0 while frag0_len is not zero, and use pskb_may_pull() otherwise. If this pull fails, for instance after a failed pskb_pull() in esp4_gro_receive(), do not hold the packet: later GRO lookups and gro_complete() handlers expect its headers in the linear part.

This was found by Taesoo Kim and Cen Zhang, using LLM assisted code analysis, and confirmed with reproducers.

Fixes bd56a29c7a4e ("net: gro: change skb_gro_network_header()")
Fixes 9fd1ff5d2ac7 ("udp: Support UDP fraglist GRO/GSO.")
---
 include/net/gro.h       |   10 ++++++++++
 net/core/gro.c          |   20 ++++++++++++++++----
 net/ipv4/esp4_offload.c |    1 +
 net/ipv4/udp_offload.c  |    1 +
 net/ipv6/esp6_offload.c |    1 +
 5 files changed, 29 insertions(+), 4 deletions(-)
include/net/gro.h +10 -0
@@ -160,9 +160,19 @@ static inline bool skb_gro_may_pull(cons
 	return likely(hlen <= NAPI_GRO_CB(skb)->frag0_len);
 }
 
+/* A pull can release the page fragment frag0 points to, or reallocate
+ * skb->head, even if it fails. Call this before the pull, to make sure later
+ * skb_gro_header() and skb_gro_network_header() calls no longer use frag0.
+ */
+static inline void skb_gro_frag0_invalidate(struct sk_buff *skb)
+{
+	NAPI_GRO_CB(skb)->frag0_len = 0;
+}
+
 static inline void *skb_gro_header_slow(struct sk_buff *skb, unsigned int hlen,
 					unsigned int offset)
 {
+	skb_gro_frag0_invalidate(skb);
 	if (!pskb_may_pull(skb, hlen))
 		return NULL;
 
net/core/gro.c +16 -4
@@ -250,6 +250,7 @@ int skb_gro_receive_list(struct sk_buff
 	if (unlikely(skb->remcsum_offload))
 		return -EINVAL;
 
+	skb_gro_frag0_invalidate(skb);
 	if (!pskb_may_pull(skb, skb_gro_offset(skb))) {
 		NAPI_GRO_CB(skb)->flush = 1;
 		return -ENOMEM;
@@ -464,12 +465,19 @@ static void gro_pull_from_frag0(struct s
 	}
 }
 
-static void gro_try_pull_from_frag0(struct sk_buff *skb)
+static bool gro_try_pull_from_frag0(struct sk_buff *skb)
 {
 	int grow = skb_gro_offset(skb) - skb_headlen(skb);
 
-	if (grow > 0)
+	if (grow <= 0)
+		return true;
+
+	/* frag0 can only be used if no pull happened. */
+	if (likely(NAPI_GRO_CB(skb)->frag0_len)) {
 		gro_pull_from_frag0(skb, grow);
+		return true;
+	}
+	return pskb_may_pull(skb, skb_gro_offset(skb));
 }
 
 static void gro_flush_oldest(struct gro_node *gro, struct list_head *head)
@@ -571,13 +579,17 @@ found_ptype:
 	if (NAPI_GRO_CB(skb)->flush)
 		goto normal;
 
+	/* Must be called before setting NAPI_GRO_CB(skb)->{age|last}.
+	 * A held packet must have its headers in the linear part.
+	 */
+	if (unlikely(!gro_try_pull_from_frag0(skb)))
+		goto normal;
+
 	if (unlikely(gro_list->count >= MAX_GRO_SKBS))
 		gro_flush_oldest(gro, &gro_list->list);
 	else
 		gro_list->count++;
 
-	/* Must be called before setting NAPI_GRO_CB(skb)->{age|last} */
-	gro_try_pull_from_frag0(skb);
 	NAPI_GRO_CB(skb)->age = jiffies;
 	NAPI_GRO_CB(skb)->last = skb;
 	if (!skb_is_gso(skb))
net/ipv4/esp4_offload.c +1 -0
@@ -37,6 +37,7 @@ static struct sk_buff *esp4_gro_receive(
 	__be32 seq;
 	__be32 spi;
 
+	skb_gro_frag0_invalidate(skb);
 	if (!pskb_pull(skb, offset))
 		return NULL;
 
net/ipv4/udp_offload.c +1 -0
@@ -759,6 +759,7 @@ static struct sk_buff *udp_gro_receive_s
 			pp = p;
 		} else {
 			if (NAPI_GRO_CB(skb)->is_flist) {
+				skb_gro_frag0_invalidate(skb);
 				if (!pskb_may_pull(skb, skb_gro_offset(skb))) {
 					NAPI_GRO_CB(skb)->flush = 1;
 					return NULL;
net/ipv6/esp6_offload.c +1 -0
@@ -64,6 +64,7 @@ static struct sk_buff *esp6_gro_receive(
 	if (NAPI_GRO_CB(skb)->proto == IPPROTO_UDP)
 		encap_type = UDP_ENCAP_ESPINUDP;
 
+	skb_gro_frag0_invalidate(skb);
 	if (!pskb_pull(skb, offset))
 		return NULL;
 
author maintainer
#725 lore raw

PATCH 724/990 netfilter: nf_dup: preserve guard across NFQUEUE reinjection

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Zihan Xi <[email protected]>

commit 82052e5b5ec36504fe1b9c3c28a711a78fcacf37 upstream.

NFQUEUE can suspend traversal of a duplicated packet while the task-local duplication guard is set. The output call then returns and clears the guard before a later verdict resumes hook traversal.

Save the guard in the queue entry and restore it while reinjection continues hook traversal. Preserve and restore the verdict task's prior state, including nested synchronous reinjection.

Fixes cd58bcd9787e ("netfilter: xt_TEE: have cloned packet travel through Xtables too")
Assisted-by LLM
---
 include/net/netfilter/nf_queue.h |    1 +
 net/netfilter/nf_queue.c         |    1 +
 net/netfilter/nfnetlink_queue.c  |   17 ++++++++++++++---
 3 files changed, 16 insertions(+), 3 deletions(-)
include/net/netfilter/nf_queue.h +1 -0
@@ -23,6 +23,7 @@ struct nf_queue_entry {
 	struct net_device	*physout;
 #endif
 	struct nf_hook_state	state;
+	bool			in_nf_duplicate;
 	bool			nf_ct_is_unconfirmed;
 	u16			size; /* sizeof(entry) + saved route keys */
 
net/netfilter/nf_queue.c +1 -0
@@ -218,6 +218,7 @@ static int __nf_queue(struct sk_buff *sk
 	*entry = (struct nf_queue_entry) {
 		.skb	= skb,
 		.skb_dev = skb->dev,
+		.in_nf_duplicate = current->in_nf_duplicate,
 		.state	= *state,
 		.hook_index = index,
 		.size	= sizeof(*entry) + route_key_size,
net/netfilter/nfnetlink_queue.c +14 -3
@@ -44,6 +44,7 @@
 #include <net/sock.h>
 #include <net/tcp_states.h>
 #include <net/netfilter/nf_queue.h>
+#include <net/net_debug.h>
 #include <net/netns/generic.h>
 
 #include <linux/atomic.h>
@@ -351,21 +352,30 @@ static void nf_reinject(struct nf_queue_
 	const struct nf_hook_entry *hook_entry;
 	const struct nf_hook_entries *hooks;
 	struct sk_buff *skb = entry->skb;
+	bool old_in_nf_duplicate;
 	const struct net *net;
 	unsigned int i;
 	int err;
 	u8 pf;
 
+	DEBUG_NET_WARN_ONCE(current->in_nf_duplicate &&
+			    !entry->in_nf_duplicate,
+			    "%s called with unexpected duplication guard",
+			    __func__);
+	local_bh_disable();
+	old_in_nf_duplicate = current->in_nf_duplicate;
+
 	net = entry->state.net;
 	pf = entry->state.pf;
 
+	current->in_nf_duplicate = entry->in_nf_duplicate;
 	hooks = nf_hook_entries_head(net, pf, entry->state.hook);
 
 	i = entry->hook_index;
 	if (!hooks || i >= hooks->num_hook_entries) {
 		kfree_skb_reason(skb, SKB_DROP_REASON_NETFILTER_DROP);
 		nf_queue_entry_free(entry);
-		return;
+		goto out;
 	}
 
 	hook_entry = &hooks->hooks[i];
@@ -388,9 +398,7 @@ next_hook:
 	switch (verdict & NF_VERDICT_MASK) {
 	case NF_ACCEPT:
 	case NF_STOP:
-		local_bh_disable();
 		entry->state.okfn(entry->state.net, entry->state.sk, skb);
-		local_bh_enable();
 		break;
 	case NF_QUEUE:
 		err = nf_queue(skb, &entry->state, i, verdict);
@@ -404,6 +412,9 @@ next_hook:
 	}
 
 	nf_queue_entry_free(entry);
+out:
+	current->in_nf_duplicate = old_in_nf_duplicate;
+	local_bh_enable();
 }
 
 /* return true if the entry has an unconfirmed conntrack attached that isn't owned by us
author maintainer
#726 lore raw

PATCH 725/990 netfilter: xt_recent: do not call remove_proc_entry() under recent_lock

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Cen Zhang (Microsoft) <[email protected]>

commit 17c2e41736b62cfe444c64d67860b1fbc1e886ac upstream.

recent_proc_net_exit() removes the /proc/net/xt_recent/<name> entries of a dying network namespace while holding spin_lock_bh(&recent_lock). remove_proc_entry() may sleep: proc_entry_rundown() waits until every task that is still inside the entry's file operations has left. A reader of such an entry is counted in by proc_reg_read() before recent_seq_start() takes recent_lock. So if a read is in flight when the namespace is torn down, cleanup_net() sleeps in atomic context holding the spinlock that the reader is spinning on, and neither side can ever make progress.

An unprivileged user can trigger this from a user namespace by adding a rule with the "recent" match and reading its proc file while the namespace is being destroyed. As recent_lock is global, every later attempt to take it spins forever too: the spinning can spread to all CPUs, and network namespace teardown stops system-wide.

  BUG: sleeping function called from invalid context at
    kernel/sched/completion.c:116
   #3: (recent_lock){+...}-{3:3}, at: recent_net_exit+0x2b/0x140
  Workqueue: netns cleanup_net
  Call Trace:
   proc_entry_rundown+0x185/0x1b0
   remove_proc_entry+0x21a/0x520
   recent_net_exit+0x7f/0x140
   cleanup_net+0x414/0x8f0
  ...
  rcu: INFO: rcu_preempt self-detected stall on CPU
  Call Trace:
   queued_spin_lock_slowpath+0x313/0xc20
   recent_seq_start+0x87/0x1b0
   seq_read_iter+0x265/0x11e0
   proc_reg_read+0x1ab/0x270

Fix by taking recent_mutex instead of recent_lock. According to commit a0e889bb1bdc ("[NETFILTER]: recent match: fix "sleeping function called from invalid context""), recent_mutex is the lock to use here: it protects recent_net->tables and was introduced so that proc entries are created and removed without recent_lock held, because those calls may sleep. hashlimit_proc_net_exit() does the same for xt_hashlimit.

Fixes 665e205c16c1 ("netfilter: xt_recent: fix namespace destroy path")
---
 net/netfilter/xt_recent.c |    7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
net/netfilter/xt_recent.c +4 -3
@@ -649,14 +649,15 @@ static void __net_exit recent_proc_net_e
 
 	/* recent_net_exit() is called before recent_mt_destroy(). Make sure
 	 * that the parent xt_recent proc entry is empty before trying to
-	 * remove it.
+	 * remove it. Use recent_mutex instead of recent_lock since
+	 * remove_proc_entry() may sleep.
 	 */
-	spin_lock_bh(&recent_lock);
+	mutex_lock(&recent_mutex);
 	list_for_each_entry(t, &recent_net->tables, list)
 	        remove_proc_entry(t->name, recent_net->xt_recent);
 
 	recent_net->xt_recent = NULL;
-	spin_unlock_bh(&recent_lock);
+	mutex_unlock(&recent_mutex);
 
 	remove_proc_entry("xt_recent", net->proc_net);
 }
author maintainer
#727 lore raw

PATCH 726/990 netfilter: flowtable: extend ct timeout of offloaded GRE flows

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Michail Andreas Michalopoulos <[email protected]>

commit 46ecda278f6eedffb2898d41e3e56757c996a41f upstream.

Since commit 03428ca5cee9 ("netfilter: conntrack: rework offload nf_conn timeout extension logic"), the flowtable gc worker extends the timeout of an offloaded conntrack entry from nf_flow_table_extend_ct_timeout() once it falls below 5 minutes. That function only knows about TCP and UDP and hits WARN_ON_ONCE() for any other layer 4 protocol. However, GRE flows can be offloaded too, both via nft_flow_offload and act_ct, since commit 4e8d9584d154 ("netfilter: flowtable: Support GRE").

The timeout of an offloaded GRE entry drops below that threshold as soon as a packet of the flow still goes through conntrack. With ip6gre tunnels using the default encapsulation limit this is ordinary traffic:
the flowtable does not parse the Destination Options header in front of GRE, so every packet of the flow takes the classic forwarding path. It also happens for a packet with ttl <= 1, which the flowtable fast path passes up to the classic forwarding path. nf_conntrack_gre_packet() then refreshes ct->timeout to the GRE stream timeout (180 seconds by default), and the next gc run triggers, as reported by syzbot:

  WARNING: net/netfilter/nf_flow_table_core.c:553 at nf_flow_table_extend_ct_timeout+0x1ee/0x2f0
  Workqueue: events_power_efficient nf_flow_offload_work_gc
  Call Trace:
   nf_flow_offload_gc_step+0x545/0x7b0
   nf_flow_table_iterate+0x13c/0x1f0
   nf_flow_offload_work_gc+0x22/0x70
   process_scheduled_works+0xc3d/0x1630
   worker_thread+0xa47/0xfb0
   kthread+0x38b/0x480

Besides the splat, which panics the machine with panic_on_warn, the default branch sets the new timeout to 1 jiffy, so the conntrack entry expires right away and the offloaded flow is torn down.

Handle GRE like UDP and extend the timeout to NF_CT_DAY. GRE conntrack has no protocol state to take into account, and NF_CT_DAY is also what flow_offload_add() already sets for every offloaded entry, GRE included. This also restores the behaviour from before commit 03428ca5cee9, when the conntrack gc worker extended offloaded entries of any protocol to NF_CT_DAY.

Fixes 03428ca5cee9 ("netfilter: conntrack: rework offload nf_conn timeout extension logic")
Reported-by [email protected]
Assisted-by LLM
---
 net/netfilter/nf_flow_table_core.c |    1 +
 1 file changed, 1 insertion(+)
net/netfilter/nf_flow_table_core.c +1 -0
@@ -537,6 +537,7 @@ static void nf_flow_table_extend_ct_time
 
 		switch (l4proto) {
 		case IPPROTO_UDP:
+		case IPPROTO_GRE:
 			new_timeout = NF_CT_DAY;
 			break;
 		case IPPROTO_TCP:
author maintainer
#728 lore raw

PATCH 727/990 netfs: preserve prepare_write errno on reissue

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Iván Ezequiel Rodriguez <[email protected]>

commit 62869ecb3aeca670b86058387e7533a33524b95b upstream.

prepare_write() may call netfs_prepare_write_failed() (FAILED + errno) before write_retry calls netfs_reissue_write(). Clearing subreq->error to 0 for a clean I/O reissue (82e8885bd763) then makes netfs_do_issue_write() terminate with 0. The collector copies front->error into stream->error and mapping_set_error(), which ignores 0, so writeback failure is silent.

Skip clearing error when NETFS_SREQ_FAILED is already set; do_issue_write() already terminates FAILED subrequests.

Fixes 82e8885bd763 ("netfs: when subreq is marked for retry, do not check if it faced an error")
---
 fs/netfs/write_issue.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
fs/netfs/write_issue.c +3 -1
@@ -252,7 +252,9 @@ void netfs_reissue_write(struct netfs_io
 	iov_iter_truncate(&subreq->io_iter, size);
 
 	subreq->retry_count++;
-	subreq->error = 0;
+	/* Keep prepare_write() errno; do_issue_write() terminates FAILED. */
+	if (!test_bit(NETFS_SREQ_FAILED, &subreq->flags))
+		subreq->error = 0;
 	__clear_bit(NETFS_SREQ_MADE_PROGRESS, &subreq->flags);
 	__set_bit(NETFS_SREQ_IN_PROGRESS, &subreq->flags);
 	netfs_stat(&netfs_n_wh_retry_write_subreq);
author maintainer
#729 lore raw

PATCH 728/990 netfs: keep the prepare_read errno when abandoning read retries

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Paulo Alcantara <[email protected]>

commit d88a0c3a96fd6d7228d04532cecb23f23676aa2d upstream.

When ->prepare_read() fails while retrying a read, netfs_retry_read_subrequests() marks the subrequest failed and abandons the rest, which overwrites the error of every failed subrequest with -ENOMEM. The reader then gets -ENOMEM for e.g. a handle that couldn't be reopened (-EHOSTDOWN, -ENOENT), a credit wait interrupted by a signal (-ERESTARTSYS) or umount -f (-EIO). The first pass doesn't have this problem, as netfs_cancel_read() keeps the errno.

Record the errno of ->prepare_read() in the subrequest and keep the error of subrequests that already failed, using -ENOMEM only for those abandoned while still waiting for a retry.

Fixes ee4cdf7ba857 ("netfs: Speed up buffered reading")
---
 fs/netfs/read_retry.c |   16 ++++++++++++----
 1 file changed, 12 insertions(+), 4 deletions(-)
fs/netfs/read_retry.c +12 -4
@@ -28,6 +28,7 @@ static void netfs_retry_read_subrequests
 	struct netfs_io_subrequest *subreq;
 	struct netfs_io_stream *stream = &rreq->io_streams[0];
 	struct list_head *next;
+	int ret;
 
 	_enter("R=%x", rreq->debug_id);
 
@@ -140,8 +141,11 @@ static void netfs_retry_read_subrequests
 
 			/* Renegotiate max_len (rsize) */
 			stream->sreq_max_len = subreq->len;
-			if (rreq->netfs_ops->prepare_read &&
-			    rreq->netfs_ops->prepare_read(subreq) < 0) {
+			ret = 0;
+			if (rreq->netfs_ops->prepare_read)
+				ret = rreq->netfs_ops->prepare_read(subreq);
+			if (ret < 0) {
+				subreq->error = ret;
 				trace_netfs_sreq(subreq, netfs_sreq_trace_reprep_failed);
 				__set_bit(NETFS_SREQ_FAILED, &subreq->flags);
 				goto abandon;
@@ -222,7 +226,9 @@ static void netfs_retry_read_subrequests
 				part = netfs_limit_iter(&source, 0, part, stream->sreq_max_segs);
 
 			netfs_stat(&netfs_n_rh_download);
-			if (rreq->netfs_ops->prepare_read(subreq) < 0) {
+			ret = rreq->netfs_ops->prepare_read(subreq);
+			if (ret < 0) {
+				subreq->error = ret;
 				trace_netfs_sreq(subreq, netfs_sreq_trace_reprep_failed);
 				__set_bit(NETFS_SREQ_FAILED, &subreq->flags);
 				goto abandon;
@@ -258,7 +264,9 @@ abandon:
 		if (!test_bit(NETFS_SREQ_FAILED, &subreq->flags) &&
 		    !test_bit(NETFS_SREQ_NEED_RETRY, &subreq->flags))
 			continue;
-		subreq->error = -ENOMEM;
+		if (!subreq->error ||
+		    !test_bit(NETFS_SREQ_FAILED, &subreq->flags))
+			subreq->error = -ENOMEM;
 		__set_bit(NETFS_SREQ_FAILED, &subreq->flags);
 		__clear_bit(NETFS_SREQ_NEED_RETRY, &subreq->flags);
 	}
author maintainer
#730 lore raw

PATCH 729/990 netfs: dont hang a read whose retry is abandoned

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Paulo Alcantara <[email protected]>

commit d1bb754ab9e775b0fbb2743d3df425c25a561114 upstream.

When ->prepare_read() fails while retrying a read, or a subrequest can't be allocated, netfs_retry_read_subrequests() marks the remaining subrequests failed without reissuing them. If none was reissued in that pass, nothing is in progress any more to wake the collector, which returned after the retry, so an offloaded read (readahead, async direct I/O) never completes and its folios stay locked.

Wake the collector after abandoning, so it collects the failed subrequests and completes the request.

Fixes e2d46f2ec332 ("netfs: Change the read result collector to only use one work item")
---
 fs/netfs/read_retry.c |    1 +
 1 file changed, 1 insertion(+)
fs/netfs/read_retry.c +1 -0
@@ -270,6 +270,7 @@ abandon:
 		__set_bit(NETFS_SREQ_FAILED, &subreq->flags);
 		__clear_bit(NETFS_SREQ_NEED_RETRY, &subreq->flags);
 	}
+	netfs_wake_collector(rreq);
 }
 
 /*
author maintainer
#731 lore raw

PATCH 730/990 net/sched: sch_teql: reject qdiscs from another network namespace

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jamal Hadi Salim <[email protected]>

commit 1ae84bdd736f8fab30180159996e1d193f8029ff upstream.

Reported by shaos <[email protected]> with a reproducer, which was reproduced and verified in our test environment.

The issue:
The teql master devices are created once in the initial network namespace and their Qdisc_ops are global. teql_qdisc_init() takes the teql_master embedded in the registered sch->ops and uses it without checking whether the new qdisc's device lives in the same network namespace as the master. A qdisc created in another netns can therefore attach to the init-net master and change its MTU and flags.

The Fix:
Reject a teql qdisc whose device is not in the master's network namespace with -EOPNOTSUPP and an extack message; same-netns teql still works.

Initialize the private skb queue before any validation so every constructor failure path, including qdisc_create_dflt(), which resets the qdisc before destroying it, sees an initialized empty queue.

Conditions to recreate the bug:
CONFIG_NET_SCH_TEQL=y, CONFIG_DUMMY=y, CONFIG_USER_NS=y, CONFIG_NET_NS=y. As an unprivileged UID, unshare a user and network namespace, create a dummy device, set its MTU to 60000, and add a root teql0 qdisc:

unshare -Urn
ip link add dummy0 type dummy
ip link set dummy0 mtu 60000
tc qdisc add dev dummy0 root teql0

The init-net teql0 device changes from MTU 1500 to 60000. A pfifo control on the same device leaves the MTU unchanged, and a direct MTU change on init-net teql0 is denied. The namespace needs CAP_NET_ADMIN; no init-net privilege is required. With the fix the attach fails with "Operation not supported" and the init-net MTU stays 1500.

---
 net/sched/sch_teql.c |    9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
net/sched/sch_teql.c +7 -2
@@ -198,6 +198,8 @@ static int teql_qdisc_init(struct Qdisc
 	struct Qdisc *first;
 	unsigned long flags;
 
+	skb_queue_head_init(&q->q);
+
 	if (dev->hard_header_len > m->dev->hard_header_len)
 		return -EINVAL;
 
@@ -209,9 +211,12 @@ static int teql_qdisc_init(struct Qdisc
 		return -EOPNOTSUPP;
 	}
 
-	q->m = m;
+	if (dev_net(dev) != dev_net(m->dev)) {
+		NL_SET_ERR_MSG_MOD(extack, "teql master is in a different network namespace");
+		return -EOPNOTSUPP;
+	}
 
-	skb_queue_head_init(&q->q);
+	q->m = m;
 
 	raw_spin_lock_irqsave(&m->slaves_lock, flags);
 	first = rcu_dereference_protected(m->slaves, lockdep_is_held(&m->slaves_lock));
author maintainer
#732 lore raw

PATCH 731/990 net/sched: act_ife: encode configured zero metadata values

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jamal Hadi Salim <[email protected]>

commit 7d02c07c738bf5c4b9a7d7ef498fbf465c446853 upstream.

Reported by shaos <[email protected]> with a reproducer for the 32-bit case, which was reproduced and verified in our test environment.

The issue:
ife_check_meta_u32() and ife_check_meta_u16() both reserve eight bytes of metadata for a configured value even when that value is zero, but the matching encoder returns without calling ife_tlv_meta_encode(). The encoder therefore writes neither the TLV header nor its value, while the enclosing IFE length still includes the reserved bytes, exposing stale skb headroom contents to the peer.

The 32-bit helper has been present since the IFE action was introduced (v4.6); the 16-bit helper was added with the 16-bit metadata helpers used by the skbtcindex callback (v4.9). Both defects predate the oldest supported stable kernel (5.10), so they are fixed together in this patch. Each hunk keeps its own Fixes: tag for provenance.

The fix:
Encode any configured value, including zero; skip the TLV only when there is neither a configured nor a runtime value. The runtime fallback is unchanged.

A raw TCA_IFE_METALST netlink request is needed to express the configured zero: the IFE_META_SKBMARK attribute carries four zero payload bytes for the u32 helper, and IFE_META_TCINDEX two zero payload bytes for the 16-bit helper (not an absent or zero-length attribute). Stock tc cannot build these requests; "use mark 0x0" emits no mark attribute and "allow mark" emits a zero-length one.

Conditions to recreate the bug:
CONFIG_NET_ACT_IFE=y, CONFIG_NET_IFE_SKBMARK=y, CONFIG_NET_IFE_SKBTCINDEX=y, CONFIG_NET_CLS_MATCHALL=y, CONFIG_NET_SCH_INGRESS=y, CONFIG_USER_NS=y, CONFIG_NET_NS=y, CONFIG_VETH=y. In a fresh user and network namespace create a veth pair and attach clsact to the egress side. Install a matchall filter whose ife encode action carries a zero skb mark (or a zero tcindex) in TCA_IFE_METALST. Send a frame through the veth and inspect the IFE metadata in the received frame. The metadata region is eight bytes but holds neither a valid TLV header nor a value; it exposes prior headroom contents. Setting the value to a nonzero one does not trigger the leak. The namespace needs CAP_NET_ADMIN; no additional privilege is required. With the fix the zero TLVs are 0001000800000000 (u32) and 0005000600000000 (u16).

---
 net/sched/act_ife.c |    6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)
net/sched/act_ife.c +2 -4
@@ -50,8 +50,7 @@ int ife_encode_meta_u16(u16 metaval, voi
 		edata = *(u16 *)mi->metaval;
 	else if (metaval)
 		edata = metaval;
-
-	if (!edata) /* will not encode */
+	else
 		return 0;
 
 	edata = htons(edata);
@@ -94,8 +93,7 @@ int ife_encode_meta_u32(u32 metaval, voi
 		edata = *(u32 *)mi->metaval;
 	else if (metaval)
 		edata = metaval;
-
-	if (!edata) /* will not encode */
+	else
 		return 0;
 
 	edata = htonl(edata);
author maintainer
#733 lore raw

PATCH 732/990 net/sched: act_ife: require a full Ethernet header on egress

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jamal Hadi Salim <[email protected]>

commit 11dbce09083473249c3843ff31bf8d8fa01bdeef upstream.

This is a followup of commit 5b483f7791b0 ("net/sched: act_ife: Only operate on Ethernet frames") as reported by Sashiko.

The finding was raised by both Sashiko providers (nipa and gemini) while reviewing the parent patchset. shaos <[email protected]> independently reported the same undersized-egress path with a reproducer, which was reproduced and verified in our test environment.

The issue:
On egress tcf_ife_is_eth_skb() only checks the device type; it does not check that the skb carries a full Ethernet header. For an Ethernet or loopback device it returns true even when the skb has no Ethernet header. tcf_ife_encode() then calls ife_encode(), which copies ETH_HLEN bytes from skb->data. A short skb therefore reads past its linear data and the copied bytes, including stale kernel memory, are emitted in the outer Ethernet header.

The parent commit fixed the reported ingress mac_len case but left the egress path without a length check.

A total-length test is not sufficient: a non-GSO TUN skb can have a large total length while only a single byte sits in the linear area, so ife_encode() still reads past the linear header. Require instead that the Ethernet header the encoder copies is present in the linear part of the skb.

The Fix:
On egress require pskb_may_pull(skb, ETH_HLEN) before encoding, which ensures the Ethernet header is present in the linear data ife_encode() copies from; the ingress mac_len check is unchanged. A short egress skb is now dropped instead of being encoded.

Conditions to recreate the bug:
CONFIG_NET_ACT_IFE=y, CONFIG_NET_CLS_MATCHALL=y, CONFIG_NET_SCH_INGRESS=y, CONFIG_TUN=y, CONFIG_NET_ACT_MIRRED=y. In two user and network namespaces (a victim and an attacker), open a TUN device in IFF_TUN mode and attach clsact to it and to lo. Redirect ingress traffic from the TUN device to lo egress with mirred, and install an ife encode action on lo egress:

tc qdisc add dev <tun> clsact
tc qdisc add dev lo clsact
tc filter add dev <tun> ingress matchall action mirred egress \
redirect dev lo
tc filter add dev lo egress matchall action ife encode use mark 1 \
action ok

Send a TUN packet shorter than ETH_HLEN (a one-byte payload is enough) and receive the emitted frame on the other side. Without the fix the outer Ethernet header contains bytes copied past the short packet; with the fix the short skb is dropped. The attacker needs CAP_NET_ADMIN in its user namespace; no init-net privilege is required.

The same path is reachable when the total length is large but the Ethernet header is not linear: write a non-GSO virtio header with hdr_len=1 followed by an 8192-byte packet so that only one byte stays linear. Without the fix the copied header reads past the linear data; with the fix the header is pulled into the linear area before the copy.

---
 net/sched/act_ife.c |    7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
net/sched/act_ife.c +5 -2
@@ -871,13 +871,16 @@ drop:
  * is an Ethernet header because the skb could've been redirected with mirred
  * from a non-Ethernet device.
  */
-static bool tcf_ife_is_eth_skb(const struct sk_buff *skb)
+static bool tcf_ife_is_eth_skb(struct sk_buff *skb)
 {
 	if (skb->dev->type != ARPHRD_ETHER &&
 	    skb->dev->type != ARPHRD_LOOPBACK)
 		return false;
 
-	return !skb_at_tc_ingress(skb) || skb->mac_len == ETH_HLEN;
+	if (skb_at_tc_ingress(skb))
+		return skb->mac_len == ETH_HLEN;
+
+	return pskb_may_pull(skb, ETH_HLEN);
 }
 
 TC_INDIRECT_SCOPE int tcf_ife_act(struct sk_buff *skb,
author maintainer
#734 lore raw

PATCH 733/990 NFSv4: Prevent indefinite waits for out-of-order OPEN stateids

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Tim Menninger <[email protected]>

commit 151d95a1e696979a7d54b23c96338754be2fcc1f upstream.

When processing an out-of-order OPEN stateid on an NFSv4.1 or later mount, nfs_set_open_stateid_locked() waits for stateid updates to be processed in order. A five-second timeout is intended to prevent indefinite waits when preceding updates never arrive.

However, each iteration calls schedule_timeout() with a fresh five-second timeout. An update to the shared open state can wake the caller without satisfying its ordering check. The remaining timeout is then discarded, and the next iteration starts another full wait.

Under sustained concurrent OPEN/CLOSE activity on the same open state, repeated wakeups can prevent the timeout from ever expiring. Some tasks can remain stuck in update_open_stateid() while others continue making progress.

Compute a single deadline on entry and pass only the remaining time to schedule_timeout(). Once the deadline expires, take the existing timeout path rather than starting another wait. This prevents wakeups from extending the wait indefinitely.

Observed on Linux 6.8.0 and reproduced on 7.3.0 with 96 concurrent O_RDWR|O_TRUNC open/close loops on one NFSv4.1/TCP file (nconnect=16). Ten workers made no progress for over 300 seconds while others ran. With the fix, all workers resumed after transient stalls.

Fixes c9399f21c215 ("NFSv4: Fix OPEN / CLOSE race")
---
 fs/nfs/nfs4proc.c |    5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
fs/nfs/nfs4proc.c +4 -1
@@ -1775,6 +1775,8 @@ static void nfs_set_open_stateid_locked(
 {
 	DEFINE_WAIT(wait);
 	int status = 0;
+	unsigned long deadline = jiffies + 5 * HZ;
+	signed long remaining;
 	for (;;) {
 
 		if (nfs_stateid_is_sequential(state, stateid))
@@ -1809,7 +1811,8 @@ static void nfs_set_open_stateid_locked(
 
 		if (!fatal_signal_pending(current) &&
 		    !nfs_current_task_exiting()) {
-			if (schedule_timeout(5*HZ) == 0)
+			remaining = (long)(deadline - jiffies);
+			if (remaining <= 0 || schedule_timeout(remaining) == 0)
 				status = -EAGAIN;
 			else
 				status = 0;
author maintainer
#735 lore raw

PATCH 734/990 openvswitch: advance by the real header length in get_ipv6_ext_hdrs()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Joas Antonio dos Santos <[email protected]>

commit dbce972650ed6348e3d3856e49308aa5603e02a7 upstream.

get_ipv6_ext_hdrs() walks the IPv6 extension header chain to fill key->ipv6.exthdrs, but advances to the next header with ipv6_optlen() whatever the current header is. That is only right for Hop-by-Hop, Destination Options and Routing headers:

- an Authentication Header is ((hdrlen + 2) << 2) bytes long (ipv6_authlen()), so with hdrlen = 4 the walk skips 40 bytes instead of 24 and reads the next "header" from the ICV and payload;

- a Fragment header is always 8 bytes, and the byte read as hdrlen is its Reserved field, which the sender controls and receivers ignore, so a non-zero value makes the walk skip up to 2048 bytes and miss the headers that follow;

- in a non-first fragment nothing after the Fragment header is a header at all, it is the middle of the fragmentable part, yet the walk keeps parsing it as an extension header chain.

In all cases the OFPIEH12_* bits stored in key->ipv6.exthdrs depend on bytes chosen by the sender rather than on the headers that are actually
present: payload bytes that look like another AH or a Hop-by-Hop header add OFPIEH12_UNREP/OFPIEH12_UNSEQ, and real headers after a Fragment header can go unreported. Flows that match on OVS_KEY_ATTR_IPV6_EXTHDRS then classify such packets wrongly. There is no memory safety issue, skb_header_pointer() bounds every read.

Advance by sizeof(struct frag_hdr) for Fragment headers and by ipv6_authlen() for AH, and stop at the Fragment header if its offset is non-zero, as ipv6_find_hdr() does.

---
 net/openvswitch/flow.c |   19 ++++++++++++++++++-
 1 file changed, 18 insertions(+), 1 deletion(-)
net/openvswitch/flow.c +18 -1
@@ -370,11 +370,28 @@ static void get_ipv6_ext_hdrs(struct sk_
 			return;
 		}
 
+		if (next_type == IPPROTO_FRAGMENT) {
+			struct frag_hdr _fh, *fh;
+
+			fh = skb_header_pointer(skb, start, sizeof(_fh), &_fh);
+			if (!fh)
+				break;
+			/* Only the first fragment has the headers that follow. */
+			if (fh->frag_off & htons(IP6_OFFSET))
+				break;
+			start += sizeof(_fh);
+			next_type = fh->nexthdr;
+			continue;
+		}
+
 		hp = skb_header_pointer(skb, start, sizeof(_hdr), &_hdr);
 		if (!hp)
 			break;
+		if (next_type == IPPROTO_AH)
+			start += ipv6_authlen(hp);
+		else
+			start += ipv6_optlen(hp);
 		next_type = hp->nexthdr;
-		start += ipv6_optlen(hp);
 	}
 }
 
author maintainer
#736 lore raw

PATCH 735/990 perf/core: Do not resurrect cpuctx->cgrp after last cgroup event exit

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Phat Dinh <[email protected]>

commit 59f1398140869432c7171b9a2a279ca315467c4e upstream.

perf_cgroup_switch() relies on:

/*
* cpuctx->cgrp is set when the first cgroup event enabled,
* and is cleared when the last cgroup event disabled. */

It computes the next task's cgroup, schedules out the CPU context and then assigns cpuctx->cgrp unconditionally:

    ctx_sched_out(&cpuctx->ctx, NULL, EVENT_ALL|EVENT_CGROUP);
    /*
     * must not be done before ctxswout due
     * to update_cgrp_time_from_cpuctx() in
     * ctx_sched_out()
     */
    cpuctx->cgrp = cgrp;

However, ctx_sched_out() can disable events itself. If a cgroup event has a pending disable from perf_event_disable_inatomic() (e.g. its PERF_EVENT_IOC_REFRESH limit ran out) that the irq_work has not handled yet, event_sched_out() consumes it inline:

    if (event->pending_disable) {
        event->pending_disable = 0;
        perf_cgroup_event_disable(event, ctx);
        state = PERF_EVENT_STATE_OFF;
    }

If that was the last cgroup event, perf_cgroup_event_disable() clears cpuctx->cgrp:

    if (--ctx->nr_cgroups)
        return;

    cpuctx->cgrp = NULL;

and perf_cgroup_switch() then sets it again. cpuctx->cgrp is left non-NULL with ctx.nr_cgroups == 0, so the NULL check in perf_cgroup_switch() no longer catches it and the next switch trips:

    WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);

cpuctx->cgrp does not hold a reference on the cgroup. Once that cgroup is removed, the next ctx_sched_in() dereferences the stale pointer:

  BUG: KASAN: slab-use-after-free in ctx_sched_in+0xb1f/0xfa0
  Read of size 8 at addr ffff8881008972d0 by task swapper/3/0

  Tainted: [W]=WARN
  Call Trace:
   <IRQ>
   ctx_sched_in+0xb1f/0xfa0
   perf_event_sched_in+0x1a/0x70
   ctx_resched+0x32b/0xac0
   __perf_install_in_context+0x475/0xab0
   remote_function+0x105/0x200
   __flush_smp_call_function_queue+0x179/0x8d0
   __sysvec_call_function_single+0x1b/0x1c0
   sysvec_call_function_single+0x66/0x80
   </IRQ>
   <TASK>
   asm_sysvec_call_function_single+0x1a/0x20

Only assign cpuctx->cgrp when cgroup events remain after the context has been scheduled out, so that it stays NULL as the invariant requires.

Fixes e19cd0b6fa59 ("perf/core: Always set cpuctx cgrp when enable cgroup event")
---
 kernel/events/core.c |    7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
kernel/events/core.c +6 -1
@@ -971,8 +971,13 @@ static void perf_cgroup_switch(struct ta
 	 * must not be done before ctxswout due
 	 * to update_cgrp_time_from_cpuctx() in
 	 * ctx_sched_out()
+	 *
+	 * ctx_sched_out() can consume a pending disable and drop the last cgroup
+	 * event, which clear the cpuctx->cgrp. Cgroup tracking follow active cgroup
+	 * event, so do not resurrect it
 	 */
-	cpuctx->cgrp = cgrp;
+	if (cpuctx->ctx.nr_cgroups)
+		cpuctx->cgrp = cgrp;
 	/*
 	 * set cgrp before ctxsw in to allow
 	 * perf_cgroup_set_timestamp() in ctx_sched_in()
author maintainer
#737 lore raw

PATCH 736/990 perf/hw_breakpoint: Clear stop state in hw_breakpoint_add()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Paolo Bertinetti <[email protected]>

commit 6bea5e29daf123a78ae58cb5926023f4705f396f upstream.

Since commit 18dbcbfabfff ("perf: Fix the POLL_HUP delivery breakage"), __perf_event_overflow() stops the event with pmu->stop() and disables it when the PERF_EVENT_IOC_REFRESH limit is reached. When userspace re-arms the event with PERF_EVENT_IOC_REFRESH, the event is enabled again and pmu->add() is called with PERF_EF_START.

hw_breakpoint_add() sets PERF_HES_STOPPED when PERF_EF_START is missing, but never clears it. The flag set by pmu->stop() stays, and perf_bp_event() drops every later hit, so a breakpoint re-armed this way delivers only its first overflow.

Set the state from PERF_EF_START on every add, as perf_swevent_add() does.

Fixes 18dbcbfabfff ("perf: Fix the POLL_HUP delivery breakage")
Assisted-by LLM
---
 kernel/events/hw_breakpoint.c |    3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
kernel/events/hw_breakpoint.c +1 -2
@@ -967,8 +967,7 @@ static int hw_breakpoint_event_init(stru
 
 static int hw_breakpoint_add(struct perf_event *bp, int flags)
 {
-	if (!(flags & PERF_EF_START))
-		bp->hw.state = PERF_HES_STOPPED;
+	bp->hw.state = (flags & PERF_EF_START) ? 0 : PERF_HES_STOPPED;
 
 	if (is_sampling_event(bp)) {
 		bp->hw.last_period = bp->hw.sample_period;
author maintainer
#738 lore raw

PATCH 737/990 PM: runtime: Update last_busy in rpm_resume() for active devices

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Rafael J. Wysocki <[email protected]>

commit 55b2b8af704f845e01fa2f31ee259b07641ce3a9 upstream.

Setting an autosuspend delay for a device can be expected to cause a runtime suspend of the device after calling, say, pm_runtime_put() to be deferred, so the time between the last successful attempt to resume the device and its subsequent suspend is at least equal to the autosuspend delay.

However, that expectation is only met after the device has been actually resumed in rpm_resume() by invoking its runtime resume callback. If the runtime PM status of the device is already "active" when rpm_resume() runs for it, the device's last_busy timestamp is not updated which may allow a subsequent pm_runtime_put() invocation (or similar) to suspend it right away.

This is arguably inconsistent and confusing, so make rpm_resume() also update the device's last_busy timestamp when it finds that the device is already "active" and it is about to return 1 early.

---
 drivers/base/power/runtime.c |    6 ++++++
 1 file changed, 6 insertions(+)
drivers/base/power/runtime.c +6 -0
@@ -822,6 +822,12 @@ static int rpm_resume(struct device *dev
 		pm_runtime_deactivate_timer(dev);
 
 	if (dev->power.runtime_status == RPM_ACTIVE) {
+		/*
+		 * The attempt to resume the device means that it is needed for
+		 * something, so update its last_busy timestamp as in the case
+		 * in which it actually resumes below.
+		 */
+		pm_runtime_mark_last_busy(dev);
 		retval = 1;
 		goto out;
 	}
author maintainer
#739 lore raw

PATCH 738/990 ASoC: SOF: ipc4-topology: Fix pin format leak in process widget setup

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Baoli Zhang <[email protected]>

commit e5c09fe3f9c8d9da33b177ee432db15b6ab46884 upstream.

sof_ipc4_widget_setup_comp_process() allocates the input and output pin format arrays via sof_ipc4_get_audio_fmt(). When the following sof_ipc4_widget_setup_msg() fails, e.g. because the firmware does not provide a module matching the widget UUID, the error path jumps to the 'err' label, which frees the process struct and clears swidget->private but skips sof_ipc4_free_audio_fmt(). The arrays are then unreachable and are reported by kmemleak:

    sof_ipc4_get_audio_fmt+0xc9/0x420 [snd_sof]
    sof_ipc4_widget_setup_comp_process+0x8e/0x200 [snd_sof]
    snd_sof_load_topology+0x71a/0x840 [snd_sof]
    sof_pcm_probe+0x77/0x120 [snd_sof]
    snd_soc_component_probe+0x21/0x60 [snd_soc_core]
    ...

Jump to 'free_available_fmt' instead, as the other process widget error paths after sof_ipc4_get_audio_fmt() already do.

The other IPC4 widget setup functions (pga, mixer, src, asrc) free the audio formats in their common error label and are not affected.

Fixes f9efae954905 ("ASoC: SOF: ipc4-topology: Add support for base config extension")
---
 sound/soc/sof/ipc4-topology.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
sound/soc/sof/ipc4-topology.c +1 -1
@@ -1205,7 +1205,7 @@ static int sof_ipc4_widget_setup_comp_pr
 
 	ret = sof_ipc4_widget_setup_msg(swidget, &process->msg);
 	if (ret)
-		goto err;
+		goto free_available_fmt;
 
 	/* parse process init module payload config type from module info */
 	fw_module = swidget->module_info;
author maintainer
#740 lore raw

PATCH 739/990 Bluetooth: hci_qca: fix use-after-free in ibs debugfs files

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: YuanZhe Liu <[email protected]>

commit eeca795cec6d9c6c193c2c1bd0cb26cde44f9fc3 upstream.

qca_debugfs_init() creates an "ibs" directory under hdev->debugfs and stores pointers to fields of struct qca_data in the debugfs files. qca_close() frees qca_data without removing that directory, while hdev->debugfs is only removed when the HCI device is released. The HCI device can outlive the driver data, for example when an HCI socket still references it, so reading or writing one of the ibs files then dereferences freed memory.

Store the directory dentry in struct qca_data and remove the directory with debugfs_remove_recursive() before qca_data is freed. debugfs_remove() waits for callers that are already inside the file operations, and any later access fails with -EIO instead of reaching the debugfs helpers. This covers the two writable files as well.

---
 drivers/bluetooth/hci_qca.c |    5 +++++
 1 file changed, 5 insertions(+)
drivers/bluetooth/hci_qca.c +5 -0
@@ -162,6 +162,7 @@ struct qca_data {
 	struct delayed_work ctrl_memdump_timeout;
 	struct qca_memdump_info *qca_memdump;
 	unsigned long flags;
+	struct dentry *debugfs_ibs_dir;
 	struct completion drop_ev_comp;
 	wait_queue_head_t suspend_wait_q;
 	enum qca_memdump_states memdump_state;
@@ -667,6 +668,7 @@ static void qca_debugfs_init(struct hci_
 		return;
 
 	ibs_dir = debugfs_create_dir("ibs", hdev->debugfs);
+	qca->debugfs_ibs_dir = ibs_dir;
 
 	/* read only */
 	mode = 0444;
@@ -742,6 +744,9 @@ static int qca_close(struct hci_uart *hu
 
 	hu->priv = NULL;
 
+	debugfs_remove_recursive(qca->debugfs_ibs_dir);
+	qca->debugfs_ibs_dir = NULL;
+
 	kfree(qca);
 
 	return 0;
author maintainer
#741 lore raw

PATCH 740/990 Bluetooth: L2CAP: Keep recvmsg from resuming a closed channel

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Zhao Li <[email protected]>

commit 1f2ac56137c51be0601e18a163d817e02a15913f upstream.

Reading buffered ERTM data after ACL link loss can clear local busy and send a supervisory frame after l2cap_conn_del() has destroyed the HCI channel, which oopses on a NULL pointer in hci_send_acl(). The socket still owns its L2CAP channel, so its lifetime does not protect the underlying HCI channel.

Require BT_CONNECTED before clearing local busy in recvmsg. The socket lock already held here serializes this check and send with teardown, which closes the socket before the HCI channel is destroyed. Continue to allow buffered data to be read after disconnection.

AI assistance was used.

Fixes 61aa4f5b9f43 ("Bluetooth: Use the transmit state machine for busy state changes")
Cc [email protected] # needs adjustments for 5.15
---
 net/bluetooth/l2cap_sock.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
net/bluetooth/l2cap_sock.c +2 -1
@@ -1289,7 +1289,8 @@ static int l2cap_sock_recvmsg(struct soc
 	 * available.  This avoids resending large numbers of
 	 * frames.
 	 */
-	if (test_bit(CONN_LOCAL_BUSY, &pi->chan->conn_state) &&
+	if (sk->sk_state == BT_CONNECTED &&
+	    test_bit(CONN_LOCAL_BUSY, &pi->chan->conn_state) &&
 	    atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf >> 1)
 		l2cap_chan_busy(pi->chan, 0);
 
author maintainer
#742 lore raw

PATCH 741/990 cgroup/cpuset: Dont revive invalid partition without active CPU on hotplug

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Ridong Chen <[email protected]>

commit acec9637e03ca54bd3c3a0c1a6ad5c6dfa07c0df upstream.

When a CPU hotplug leaves no CPU outside of the partitions for the top cpuset, cpuset_handle_hotplug() clears subpartitions_cpus and gives all the active CPUs back to the top cpuset. cpuset_hotplug_update_tasks() then walks the hierarchy and invalidates the partitions, as subpartitions_cpus is empty.

However, an invalid partition visited in the same walk may be revived if its effective_xcpus is not empty. tasks_nocpu_error() doesn't catch it when its CPUs are all offline but it has no task. Its CPUs are put back into subpartitions_cpus, and the valid partitions visited after it are no longer invalidated, as subpartitions_cpus is not empty any more. The top cpuset is left with CPUs overlapping with these partitions.

It can be reproduced on a system with 8 CPUs:

  # cd /sys/fs/cgroup
  # echo +cpuset > cgroup.subtree_control
  # mkdir A1 B1
  # echo 1 > A1/cpuset.cpus
  # echo 1 > A1/cpuset.cpus.exclusive
  # echo 0,2-7 > B1/cpuset.cpus
  # echo root > B1/cpuset.cpus.partition
  # echo root > A1/cpuset.cpus.partition
  # cat A1/cpuset.cpus.partition
  root invalid (Parent unable to distribute cpu downstream)
  # echo 0 > /sys/devices/system/cpu/cpu1/online
  # cat A1/cpuset.cpus.partition B1/cpuset.cpus.partition
  root
  root
  # cat cpuset.cpus.effective
  0,2-7

A1 can't take CPU 1, the last CPU of the root cgroup which has tasks. When CPU 1 is offlined, A1 is revived without any active CPU, and B1 stays valid while its CPUs are also in the effective CPUs of the root cgroup, which triggers

  WARNING: kernel/cgroup/cpuset.c:919 at rebuild_sched_domains_locked

Only revive an invalid partition in hotplug if its effective_xcpus has an active CPU, the same as what is required to create a partition with tasks. With that, A1 and B1 are both invalidated in the above case.

---
 kernel/cgroup/cpuset.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/cgroup/cpuset.c +2 -2
@@ -4164,10 +4164,10 @@ retry:
 		partcmd = partcmd_invalidate;
 	/*
 	 * On the other hand, an invalid partition root may be transitioned
-	 * back to a regular one with a non-empty effective xcpus.
+	 * back to a regular one if its effective xcpus has an active CPU.
 	 */
 	else if (is_partition_valid(parent) && is_partition_invalid(cs) &&
-		 !cpumask_empty(cs->effective_xcpus))
+		 cpumask_intersects(cs->effective_xcpus, cpu_active_mask))
 		partcmd = partcmd_update;
 
 	if (partcmd >= 0) {
author maintainer
#743 lore raw

PATCH 742/990 crypto: caam - reject overlong RSA CRT parameters

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jérémy Jean <[email protected]>

commit 828c3b265b6df877dced3dde56ea41daa2e6181e upstream.

caam_read_rsa_crt() right-aligns dP, dQ, and qInv in buffers sized from the corresponding prime. rsa_parse_priv_key() only bounds these integers against n, so a malformed key can provide, for example, a two-byte dP with a one-byte p. dstlen - nbytes then underflows and memcpy() writes outside the allocation during set_priv_key(). KASAN reports a slab-out-of-bounds write in caam_read_rsa_crt().

Reject empty or overlong CRT parameters after stripping leading zeros. qInv is consumed by CAAM as a p-sized value, so size it from p rather than q to match the DMA mapping in set_rsa_priv_f3_pdb(). Let the top-level key cleanup handle partial form-3 allocations and return the specific error to the caller.

Also test nbytes before dereferencing it while stripping zeros, so an all-zero integer does not read one byte beyond its input.

Fixes 4a651b122adb ("crypto: caam - add support for RSA key form 3")
Assisted-by LLM
---
 drivers/crypto/caam/caampkc.c |   79 +++++++++++++++++-------------------------
 1 file changed, 32 insertions(+), 47 deletions(-)
drivers/crypto/caam/caampkc.c +32 -47
@@ -880,7 +880,7 @@ static void caam_rsa_free_key(struct caa
 
 static void caam_rsa_drop_leading_zeros(const u8 **ptr, size_t *nbytes)
 {
-	while (!**ptr && *nbytes) {
+	while (*nbytes && !**ptr) {
 		(*ptr)++;
 		(*nbytes)--;
 	}
@@ -896,22 +896,22 @@ static void caam_rsa_drop_leading_zeros(
  * @ptr   : pointer to {dP, dQ, qInv} CRT member
  * @nbytes: length in bytes of {dP, dQ, qInv} CRT member
  * @dstlen: length in bytes of corresponding p or q prime factor
+ * @dst   : pointer to the zero-padded output buffer
  */
-static u8 *caam_read_rsa_crt(const u8 *ptr, size_t nbytes, size_t dstlen)
+static int caam_read_rsa_crt(const u8 *ptr, size_t nbytes, size_t dstlen,
+			     u8 **dst)
 {
-	u8 *dst;
-
 	caam_rsa_drop_leading_zeros(&ptr, &nbytes);
-	if (!nbytes)
-		return NULL;
+	if (!nbytes || nbytes > dstlen)
+		return -EINVAL;
 
-	dst = kzalloc(dstlen, GFP_KERNEL);
-	if (!dst)
-		return NULL;
+	*dst = kzalloc(dstlen, GFP_KERNEL);
+	if (!*dst)
+		return -ENOMEM;
 
-	memcpy(dst + (dstlen - nbytes), ptr, nbytes);
+	memcpy(*dst + (dstlen - nbytes), ptr, nbytes);
 
-	return dst;
+	return 0;
 }
 
 /**
@@ -991,6 +991,7 @@ static int caam_rsa_set_priv_key_form(st
 	size_t p_sz = raw_key->p_sz;
 	size_t q_sz = raw_key->q_sz;
 	unsigned aligned_size;
+	int ret;
 
 	rsa_key->p = caam_read_raw_data(raw_key->p, &p_sz);
 	if (!rsa_key->p)
@@ -999,57 +1000,39 @@ static int caam_rsa_set_priv_key_form(st
 
 	rsa_key->q = caam_read_raw_data(raw_key->q, &q_sz);
 	if (!rsa_key->q)
-		goto free_p;
+		return -ENOMEM;
 	rsa_key->q_sz = q_sz;
 
 	aligned_size = ALIGN(raw_key->p_sz, dma_get_cache_alignment());
 	rsa_key->tmp1 = kzalloc(aligned_size, GFP_KERNEL);
 	if (!rsa_key->tmp1)
-		goto free_q;
+		return -ENOMEM;
 
 	aligned_size = ALIGN(raw_key->q_sz, dma_get_cache_alignment());
 	rsa_key->tmp2 = kzalloc(aligned_size, GFP_KERNEL);
 	if (!rsa_key->tmp2)
-		goto free_tmp1;
+		return -ENOMEM;
 
 	rsa_key->priv_form = FORM2;
 
-	rsa_key->dp = caam_read_rsa_crt(raw_key->dp, raw_key->dp_sz, p_sz);
-	if (!rsa_key->dp)
-		goto free_tmp2;
-
-	rsa_key->dq = caam_read_rsa_crt(raw_key->dq, raw_key->dq_sz, q_sz);
-	if (!rsa_key->dq)
-		goto free_dp;
-
-	rsa_key->qinv = caam_read_rsa_crt(raw_key->qinv, raw_key->qinv_sz,
-					  q_sz);
-	if (!rsa_key->qinv)
-		goto free_dq;
+	ret = caam_read_rsa_crt(raw_key->dp, raw_key->dp_sz, p_sz,
+				&rsa_key->dp);
+	if (ret)
+		return ret;
+
+	ret = caam_read_rsa_crt(raw_key->dq, raw_key->dq_sz, q_sz,
+				&rsa_key->dq);
+	if (ret)
+		return ret;
+
+	ret = caam_read_rsa_crt(raw_key->qinv, raw_key->qinv_sz, p_sz,
+				&rsa_key->qinv);
+	if (ret)
+		return ret;
 
 	rsa_key->priv_form = FORM3;
 
 	return 0;
-
-free_dq:
-	kfree_sensitive(rsa_key->dq);
-	rsa_key->dq = NULL;
-free_dp:
-	kfree_sensitive(rsa_key->dp);
-	rsa_key->dp = NULL;
-free_tmp2:
-	kfree_sensitive(rsa_key->tmp2);
-	rsa_key->tmp2 = NULL;
-free_tmp1:
-	kfree_sensitive(rsa_key->tmp1);
-	rsa_key->tmp1 = NULL;
-free_q:
-	kfree_sensitive(rsa_key->q);
-	rsa_key->q = NULL;
-free_p:
-	kfree_sensitive(rsa_key->p);
-	rsa_key->p = NULL;
-	return -ENOMEM;
 }
 
 static int caam_rsa_set_priv_key(struct crypto_akcipher *tfm, const void *key,
@@ -1067,6 +1050,8 @@ static int caam_rsa_set_priv_key(struct
 	if (ret)
 		return ret;
 
+	ret = -ENOMEM;
+
 	/* Copy key in DMA zone */
 	rsa_key->d = kmemdup(raw_key.d, raw_key.d_sz, GFP_KERNEL);
 	if (!rsa_key->d)
@@ -1103,7 +1088,7 @@ static int caam_rsa_set_priv_key(struct
 
 err:
 	caam_rsa_free_key(rsa_key);
-	return -ENOMEM;
+	return ret;
 }
 
 static unsigned int caam_rsa_max_size(struct crypto_akcipher *tfm)
author maintainer
#744 lore raw

PATCH 743/990 crypto: essiv - fix use-after-free in AEAD path

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jérémy Jean <[email protected]>

commit e9ce64dce975a14700e835003847415e29918474 upstream.

The request that ESSIV submits to its wrapped AEAD transform may finish before crypto_aead_encrypt() or crypto_aead_decrypt() returns. In case this happens, essiv_aead_done() calls aead_request_complete() on the original ESSIV request, which can end up freeing the request before essiv_aead_crypt() resumes, creating a UAF:

  BUG: KASAN: slab-use-after-free in essiv_aead_crypt+0x8e6/0x950
  Read of size 8 at addr ffff888102af1360 by task init/66

Check the return status before dereferencing rctx after submitting that request. If the operation did not return -EINPROGRESS or -EBUSY, then the request cannot have been freed yet.

Fixes be1eb7f78aa8 ("crypto: essiv - create wrapper template for ESSIV generation")
Assisted-by LLM
---
 crypto/essiv.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
crypto/essiv.c +1 -1
@@ -250,7 +250,7 @@ static int essiv_aead_crypt(struct aead_
 	err = enc ? crypto_aead_encrypt(subreq) :
 		    crypto_aead_decrypt(subreq);
 
-	if (rctx->assoc && err != -EINPROGRESS && err != -EBUSY)
+	if (err != -EINPROGRESS && err != -EBUSY)
 		kfree(rctx->assoc);
 	return err;
 }
author maintainer
#745 lore raw

PATCH 744/990 dcache: let d_invalidate() wait for a d_set_mounted() in flight

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Christian Brauner <[email protected]>

commit 20a6a9ec19e522ae85f87337886b3fb47efce5f3 upstream.

d_invalidate() and d_set_mounted() are supposed to exclude each other. Either the mount fails with -ENOENT because an ancestor of the mountpoint was unhashed or d_invalidate() finds the mountpoint and detaches the mount. d_invalidate() unhashes the dentry first and then searches the subtree with d_walk() which starts out lockless and only looks at the seqcount of rename_lock.

Since d_set_mounted() switched to read_seqlock_excl() nothing makes that walk wait or retry:

CPU0: mount on A/M CPU1: d_invalidate(A)
d_set_mounted(M)

    read_seqlock_excl(&rename_lock)
    A is hashed, go on
                                     __d_drop(A)
                                     shrink_dcache_parent(A)
                                     d_walk(A, find_submount)
                                       read_seqbegin(&rename_lock)
                                       M is not a mountpoint
                                       need_seqretry() == false
                                     return
    M->d_flags |= DCACHE_MOUNTED
    return 0

mount gets attached to M

The mount ends up below an unhashed dentry. It can't be reached anymore and pins the subtree until its parent mount or the mount namespace goes away. The window grows with the depth of the mountpoint. With a FUSE directory 3000 levels deep a bind mount racing with FUSE_NOTIFY_INVAL_ENTRY for the parent of the mountpoint survived in 151 of 200 attempts.

Before 5e317d23f6c6 the seqcount bump made the walk wait while d_set_mounted() ran and retry under the lock when one had run in the meantime. That was the right thing to wait for on the wrong counter:
every rename_lock reader paid for it, d_lookup(), d_path(), the ".." step of the RCU walk.

So give d_set_mounted() a seqlock of its own. It is the only writer and d_invalidate() is the only reader. After unhashing the dentry d_invalidate() runs an empty read_seqbegin()/read_seqretry() section on it. That spins while the count is odd, i.e. while a d_set_mounted() is between its ancestor check and its flag, and goes round once more if one started in the meantime. Nobody else retries anything. The ordering comes from the locks both already take:

- If that d_set_mounted() saw the dentry hashed its check ran under the dentry's d_lock before __d_drop() took it. So the count is odd by the time d_invalidate() reads it and d_invalidate() waits.

- Once the count is even again the flag has been set under the mountpoint's d_lock and the walk takes that lock to look at it.

A d_set_mounted() that starts after the unhash fails its ancestor check and never touches the flag. So the only flag the walk can pick up belongs to the one mount that saw the dentry hashed and is still in flight, and there is at most one of those because namespace_sem serializes mounts. Either it gets attached and detach_mounts() takes it off after waiting for namespace_sem or it fails later on and drops the flag again. In that case the walk goes round once more and finds nothing. The same goes for the mountpoint that attach_recursive_mnt() preallocates on the root of the tree it attaches. IOW, d_invalidate() does at most one extra round, which the removed-name trap (cf. [1]) relies on.

Note that on PREEMPT_RT read_seqbegin() takes the lock instead of spinning on a preempted d_set_mounted().

The cost is a seqlock around the ancestor walk for every new mountpoint and two loads of a cacheline that only d_set_mounted() writes for every d_invalidate() of a positive dentry. Walking the ancestors a second time after setting the flag would close the race as well but doubles the cost of d_set_mounted() with the depth of the mountpoint: about 1us at 64 levels and 75us at 4096 levels.

[1]: https://patch.msgid.link/[email protected]

Fixes 5e317d23f6c6 ("d_set_mounted(): we don't need to bump seqcount component of rename_lock")
Cc [email protected] # v6.17+
---
 fs/dcache.c |   19 +++++++++++++++----
 1 file changed, 15 insertions(+), 4 deletions(-)
fs/dcache.c +15 -4
@@ -1437,21 +1437,25 @@ int path_has_submounts(const struct path
 }
 EXPORT_SYMBOL(path_has_submounts);
 
+/* odd while d_set_mounted() runs, d_invalidate() waits on it */
+static __cacheline_aligned_in_smp DEFINE_SEQLOCK(d_set_mounted_lock);
+
 /*
  * Called by mount code to set a mountpoint and check if the mountpoint is
  * reachable (e.g. NFS can unhash a directory dentry and then the complete
  * subtree can become unreachable).
  *
  * Only one of d_invalidate() and d_set_mounted() must succeed.  For
- * this reason take rename_lock and d_lock on dentry and ancestors.
- * Likewise for dont_mount() which marks a dentry that is being removed
- * under d_lock.
+ * this reason take rename_lock, d_set_mounted_lock and d_lock on dentry
+ * and ancestors.  Likewise for dont_mount() which marks a dentry that
+ * is being removed under d_lock.
  */
 int d_set_mounted(struct dentry *dentry)
 {
 	struct dentry *p;
 	int ret = -ENOENT;
 	read_seqlock_excl(&rename_lock);
+	write_seqlock(&d_set_mounted_lock);
 	for (p = dentry->d_parent; !IS_ROOT(p); p = p->d_parent) {
 		/* Need exclusion wrt. d_invalidate() */
 		spin_lock(&p->d_lock);
@@ -1469,8 +1473,9 @@ int d_set_mounted(struct dentry *dentry)
 			ret = 0;
 		}
 	}
- 	spin_unlock(&dentry->d_lock);
+	spin_unlock(&dentry->d_lock);
 out:
+	write_sequnlock(&d_set_mounted_lock);
 	read_sequnlock_excl(&rename_lock);
 	return ret;
 }
@@ -1674,6 +1679,7 @@ static enum d_walk_ret find_submount(voi
 void d_invalidate(struct dentry *dentry)
 {
 	bool had_submounts = false;
+	unsigned seq;
 	spin_lock(&dentry->d_lock);
 	if (d_unhashed(dentry)) {
 		spin_unlock(&dentry->d_lock);
@@ -1686,6 +1692,11 @@ void d_invalidate(struct dentry *dentry)
 	if (!dentry->d_inode)
 		return;
 
+	/* wait for a d_set_mounted() that saw us hashed to set its flag */
+	do {
+		seq = read_seqbegin(&d_set_mounted_lock);
+	} while (read_seqretry(&d_set_mounted_lock, seq));
+
 	shrink_dcache_parent(dentry);
 	for (;;) {
 		struct dentry *victim = NULL;
author maintainer
#746 lore raw

PATCH 745/990 fs/adfs: bound directory entry name length in adfs_fplus_getnext()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: HyeongJun An <[email protected]>

commit ebf5025b0d989f95542fc9da899b7de2fec499f2 upstream.

adfs_fplus_getnext() reads the per-entry name length bigdirobnamelen straight from the on-disk big directory and passes it to adfs_dir_copyfrom() as the copy length into obj->name[], a fixed ADFS_MAX_NAME_LEN (260) byte buffer. adfs_dir_copyfrom() only bounds the copy against the number of directory buffers, not the size of the destination, so a crafted image with bigdirobnamelen larger than the buffer overflows the stack-allocated object_info::name that adfs_fplus_iterate() passes in.

adfs_object_fixup() may additionally append a four byte ",xyz" filetype suffix, so the accepted length must also leave room for that.

The old-style directory parser (dir_f.c) already clamps names to ADFS_F_NAME_LEN, and adfs_fplus_validate_header() validates the header name fields, but the per-entry name length in the big directory format was never checked. Reject over-long entries, using -EIO as elsewhere in this file for a corrupt big directory.

---
 fs/adfs/dir_fplus.c |    2 ++
 1 file changed, 2 insertions(+)
fs/adfs/dir_fplus.c +2 -0
@@ -192,6 +192,8 @@ adfs_fplus_getnext(struct adfs_dir *dir,
 	obj->indaddr  = le32_to_cpu(bde.bigdirindaddr);
 	obj->attr     = le32_to_cpu(bde.bigdirattr);
 	obj->name_len = le32_to_cpu(bde.bigdirobnamelen);
+	if (obj->name_len > ADFS_MAX_NAME_LEN - 4)	/* leave room for ,xyz suffix */
+		return -EIO;
 
 	offset = adfs_fplus_offset(h, le32_to_cpu(h->bigdirentries));
 	offset += le32_to_cpu(bde.bigdirobnameptr);
author maintainer
#747 lore raw

PATCH 746/990 fs/proc: fix the write length returned by proc_sys_call_handler()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Cheng Yongkang <[email protected]>

commit fbdc020ee1b82079102e493aaa7200de5f497a38 upstream.

proc_sys_call_handler() reads the write length from iov_iter_count() and copies that many bytes from the iterator into kbuf. A cgroup/sysctl BPF program can replace the new value through bpf_sysctl_set_new_value() and update count to the length of the replacement value. The handler then returns that adjusted count as the number of bytes written, even though the iterator originally held a different number of bytes.

If the replacement value is longer than the original input, ->write_iter() reports more bytes than the iterator held. splice(2) passes that value to iter_file_splice_write(), which subtracts it from the pipe length and walks past the pipe head:

Splice Exceeded! ret=7 tot=1 left=0

  Oops: general protection fault
  RIP: 0010:iter_file_splice_write+0xb6f/0x1170

The write path consumes at most the original iterator length in copy_from_iter_full() before the BPF hook runs. Return the smaller of the adjusted and original counts on the write path, so an expanded BPF value cannot exceed the iterator while a handler that reports a shorter parsed length still produces a short write. The read path keeps using the adjusted count for copy_to_iter().

---
 fs/proc/proc_sysctl.c |    5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
fs/proc/proc_sysctl.c +4 -1
@@ -557,6 +557,8 @@ static ssize_t proc_sys_call_handler(str
 	struct ctl_table_header *head = grab_header(inode);
 	const struct ctl_table *table = PROC_I(inode)->sysctl_entry;
 	size_t count = iov_iter_count(iter);
+	/* ->write_iter() must never report more than the iterator held */
+	size_t orig_count = count;
 	char *kbuf;
 	ssize_t error;
 
@@ -607,7 +609,8 @@ static ssize_t proc_sys_call_handler(str
 			goto out_free_buf;
 	}
 
-	error = count;
+	/* the write path consumed at most the original iterator length */
+	error = write ? min(count, orig_count) : count;
 out_free_buf:
 	kvfree(kbuf);
 out:
author maintainer
#748 lore raw

PATCH 747/990 fs/splice: clamp an over-reported write_iter result

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Cheng Yongkang <[email protected]>

commit 2d956723e82cddae8ff8e9da99a666217b02065f upstream.

iter_file_splice_write() builds a bvec iterator of at most sd.total_len - left bytes and passes it to ->write_iter(). It then subtracts the returned length from sd.total_len and walks the pipe buffers by that length. A ->write_iter() implementation that reports more bytes than the iterator held makes sd.total_len underflow and the dismissal loop advance pipe->tail past pipe->head, releasing a zeroed pipe buffer:

Splice Exceeded! ret=7 tot=1 left=0

  Oops: general protection fault
  RIP: 0010:iter_file_splice_write+0xb6f/0x1170

Commit a3de58b12ce0 ("netfs: Fix unbuffered write error handling") added the warning for this condition but only reports it. Clamp the return value to the size of the iterator that was actually handed to ->write_iter(), so the pipe accounting stays consistent even when a producer violates the iterator contract.

---
 fs/splice.c |    9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
fs/splice.c +6 -3
@@ -739,9 +739,12 @@ iter_file_splice_write(struct pipe_inode
 		sd.pos = kiocb.ki_pos;
 		if (ret <= 0)
 			break;
-		WARN_ONCE(ret > sd.total_len - left,
-			  "Splice Exceeded! ret=%zd tot=%zu left=%zu\n",
-			  ret, sd.total_len, left);
+		if (unlikely(ret > sd.total_len - left)) {
+			WARN_ONCE(1,
+				  "Splice Exceeded! ret=%zd tot=%zu left=%zu\n",
+				  ret, sd.total_len, left);
+			ret = sd.total_len - left;
+		}
 
 		sd.num_spliced += ret;
 		sd.total_len -= ret;
author maintainer
#749 lore raw

PATCH 748/990 arm64/gcs: Ignore attempts to change GCS mode during signal return

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Mark Brown <[email protected]>

commit d395db3dcd4c590d26a2f3d581d8d5b7ddbfa478 upstream.

If userspace tries to update the GCS mode as part of signal return then we update the thread state but don't update GCSCRE0_EL1, meaning the change does not take effect. We may also get issues for other tasks on context switch since we suppress writes of the register if the two tasks have the same mode.

Since no currently known userspace tries to use this functionality close this by ignoring any attempt to change the mode through signal return. The GCS mode for the current thread can be changed using the prctl() interface and will be preserved on signal return, allowing updates to the mode from the signal handler.

---
 Documentation/arch/arm64/gcs.rst |   13 ++++---------
 arch/arm64/kernel/signal.c       |   22 +---------------------
 2 files changed, 5 insertions(+), 30 deletions(-)
Documentation/arch/arm64/gcs.rst +4 -9
@@ -179,9 +179,8 @@ intended to be exhaustive.
 
 When returning from a signal handler:
 
-* If there is a gcs_context record in the signal frame then the GCS flags
-  and GCSPR_EL0 will be restored from that context prior to further
-  validation.
+* If there is a gcs_context record in the signal frame then GCSPR_EL0
+  will be restored from that context prior to further validation.
 
 * If there is no gcs_context record in the signal frame then the GCS
   configuration will be unchanged.
@@ -190,12 +189,8 @@ When returning from a signal handler:
   point to a valid GCS signal cap record, this will be popped from the
   GCS prior to signal return.
 
-* If the GCS configuration is locked when returning from a signal then any
-  attempt to change the GCS configuration will be treated as an error.  This
-  is true even if GCS was not enabled prior to signal entry.
-
-* GCS may be disabled via signal return but any attempt to enable GCS via
-  signal return will be rejected.
+* The features_enabled in the signal return context will be ignored; any
+  changes made using the prctl() in the signal handler will be preserved.
 
 
 6.  ptrace extensions
arch/arm64/kernel/signal.c +1 -21
@@ -741,36 +741,16 @@ static int preserve_gcs_context(struct g
 
 static int restore_gcs_context(struct user_ctxs *user)
 {
-	u64 gcspr, enabled;
+	u64 gcspr;
 	int err = 0;
 
 	if (user->gcs_size != sizeof(*user->gcs))
 		return -EINVAL;
 
 	__get_user_error(gcspr, &user->gcs->gcspr, err);
-	__get_user_error(enabled, &user->gcs->features_enabled, err);
 	if (err)
 		return err;
 
-	/* Don't allow unknown modes */
-	if (enabled & ~PR_SHADOW_STACK_SUPPORTED_STATUS_MASK)
-		return -EINVAL;
-
-	err = gcs_check_locked(current, enabled);
-	if (err != 0)
-		return err;
-
-	/* Don't allow enabling */
-	if (!task_gcs_el0_enabled(current) &&
-	    (enabled & PR_SHADOW_STACK_ENABLE))
-		return -EINVAL;
-
-	/* If we are disabling disable everything */
-	if (!(enabled & PR_SHADOW_STACK_ENABLE))
-		enabled = 0;
-
-	current->thread.gcs_el0_mode = enabled;
-
 	/*
 	 * We let userspace set GCSPR_EL0 to anything here, we will
 	 * validate later in gcs_restore_signal().
author maintainer
#750 lore raw

PATCH 749/990 arm64: errata: Add Cortex-A715/A720 AMU core counter workaround

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Beata Michalska <[email protected]>

commit be777145858218f591b4d9d19f3d40d3ecea9de3 upstream.

On Cortex-A715 (erratum 2738462) and Cortex-A720 (erratum 2738461), the AMEVCNTR00 counter may continue incrementing while the core remains in WFE with the clocks being enabled. The resulting core cycle count may become unreliable.

Add a workaround that effectively treats the AMU counter as unavailable.

---
 Documentation/arch/arm64/silicon-errata.rst |    4 +++
 arch/arm64/Kconfig                          |   32 ++++++++++++++++++++++++++++
 arch/arm64/kernel/cpu_errata.c              |   20 +++++++++++++++++
 arch/arm64/kernel/cpufeature.c              |    3 +-
 arch/arm64/kernel/topology.c                |    3 +-
 arch/arm64/tools/cpucaps                    |    1 
 6 files changed, 61 insertions(+), 2 deletions(-)
Documentation/arch/arm64/silicon-errata.rst +4 -0
@@ -162,8 +162,12 @@ stable kernels.
 +----------------+-----------------+-----------------+-----------------------------+
 | ARM            | Cortex-A715     | #2645198        | ARM64_ERRATUM_2645198       |
 +----------------+-----------------+-----------------+-----------------------------+
+| ARM            | Cortex-A715     | #2738462        | ARM64_ERRATUM_2738461       |
++----------------+-----------------+-----------------+-----------------------------+
 | ARM            | Cortex-A715     | #3456084        | ARM64_ERRATUM_3194386       |
 +----------------+-----------------+-----------------+-----------------------------+
+| ARM            | Cortex-A720     | #2738461        | ARM64_ERRATUM_2738461       |
++----------------+-----------------+-----------------+-----------------------------+
 | ARM            | Cortex-A720     | #3456091        | ARM64_ERRATUM_3194386       |
 +----------------+-----------------+-----------------+-----------------------------+
 | ARM            | Cortex-A725     | #3456106        | ARM64_ERRATUM_3194386       |
arch/arm64/Kconfig +32 -0
@@ -1057,6 +1057,38 @@ config ARM64_WORKAROUND_BROKEN_AMU_CONST
 	# making it unreliable. As a result, AMU users should treat it as
 	# unavailable rather than relying on misleading counter values.
 
+config ARM64_WORKAROUND_BROKEN_AMU_CORECNT
+	bool
+	# Targeting errata affecting AMEVCNTR00, the AMU core cycle counter.
+	# On affected CPUs the counter may continue incrementing while core
+	# remains in WFE with the clocks enabled.
+	# This may lead to readings of said counter being unreliable.
+	# How much though depends on the sampling intervals.
+
+config ARM64_ERRATUM_2738461
+	bool "Cortex-A715/Cortex-A720: workaround for AMEVCNTR00 incrementing incorrectly"
+	depends on ARM64_AMU_EXTN
+	select ARM64_WORKAROUND_BROKEN_AMU_CORECNT
+	default y
+	help
+	  This option adds the workaround for the following errata:
+
+	  * ARM Cortex-A715 erratum 2738462
+	  * ARM Cortex-A720 erratum 2738461
+
+	  On affected cores the AMEVCNTR00 counter (AMU core frequency cycles
+	  counter) may continue incrementing while the core remains in WFE
+	  with the clocks being enabled.
+	  This may result in inaccurate counter readings, with the magnitude
+	  of the discrepancy depending on the sampling interval.
+
+	  With this workaround, reads of the affected counter return 0 in
+	  the relevant paths. This causes users of the counter to treat it
+	  as unavailable and is functionally equivalent to firmware disabling
+	  the affected counter.
+
+	  If unsure, say Y.
+
 config ARM64_ERRATUM_2457168
 	bool "Cortex-A510: 2457168: workaround for AMEVCNTR01 incrementing incorrectly"
 	depends on ARM64_AMU_EXTN
arch/arm64/kernel/cpu_errata.c +20 -0
@@ -367,6 +367,18 @@ static const struct midr_range workaroun
 };
 #endif /* CONFIG_ARM64_WORKAROUND_BROKEN_AMU_CONSTCNT */
 
+#ifdef CONFIG_ARM64_WORKAROUND_BROKEN_AMU_CORECNT
+static const struct midr_range workaround_amu_corecnt_list[] = {
+#ifdef CONFIG_ARM64_ERRATUM_2738461
+	/* Cortex-A715 r0p0 - r1p3 */
+	MIDR_RANGE(MIDR_CORTEX_A715, 0, 0, 1, 3),
+	/* Cortex-A720 r0p0 - r0p1 */
+	MIDR_RANGE(MIDR_CORTEX_A720, 0, 0, 0, 1),
+#endif
+	{}
+};
+#endif /* CONFIG_ARM64_WORKAROUND_BROKEN_AMU_CORECNT */
+
 #ifdef CONFIG_CAVIUM_ERRATUM_23154
 static const struct midr_range cavium_erratum_23154_cpus[] = {
 	MIDR_ALL_VERSIONS(MIDR_THUNDERX),
@@ -891,6 +903,14 @@ const struct arm64_cpu_capabilities arm6
 		CAP_MIDR_RANGE_LIST(workaround_amu_constcnt_list)
 	},
 #endif
+#ifdef CONFIG_ARM64_WORKAROUND_BROKEN_AMU_CORECNT
+	{
+		.desc = "Broken AMU AMEVCNTR00 (core cycle counter)",
+		.capability = ARM64_WORKAROUND_BROKEN_AMU_CORECNT,
+		.type = ARM64_CPUCAP_WEAK_LOCAL_CPU_FEATURE,
+		CAP_MIDR_RANGE_LIST(workaround_amu_corecnt_list)
+	},
+#endif
 #ifdef CONFIG_ARM64_ERRATUM_2038923
 	{
 		.desc = "ARM erratum 2038923",
arch/arm64/kernel/cpufeature.c +2 -1
@@ -2054,7 +2054,8 @@ static void cpu_amu_enable(struct arm64_
 		cpumask_set_cpu(smp_processor_id(), &amu_cpus);
 
 		/* 0 reference values signal broken/disabled counters */
-		if (!this_cpu_has_cap(ARM64_WORKAROUND_BROKEN_AMU_CONSTCNT))
+		if (!this_cpu_has_cap(ARM64_WORKAROUND_BROKEN_AMU_CONSTCNT) &&
+		    !this_cpu_has_cap(ARM64_WORKAROUND_BROKEN_AMU_CORECNT))
 			update_freq_counters_refs();
 	}
 }
arch/arm64/kernel/topology.c +2 -1
@@ -420,7 +420,8 @@ static void cpu_read_corecnt(void *val)
 	 * counter read is properly handled as an error case by the users of the
 	 * counter.
 	 */
-	*(u64 *)val = read_corecnt();
+	*(u64 *)val = this_cpu_has_cap(ARM64_WORKAROUND_BROKEN_AMU_CORECNT) ?
+		      0UL : read_corecnt();
 }
 
 static void cpu_read_constcnt(void *val)
arch/arm64/tools/cpucaps +1 -0
@@ -122,3 +122,4 @@ WORKAROUND_SPECULATIVE_AT
 WORKAROUND_SPECULATIVE_SSBS
 WORKAROUND_SPECULATIVE_UNPRIV_LOAD
 WORKAROUND_BROKEN_AMU_CONSTCNT
+WORKAROUND_BROKEN_AMU_CORECNT
author maintainer
#751 lore raw

PATCH 750/990 arm64: kexec_file: Do not use CMA for images with a non-zero text_offset

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Jinjie Ruan <[email protected]>

commit 18f2d01bfce99a885511c451cba95234eea190bc upstream.

image_load() adds text_offset to kernel_segment->mem and subtracts it from kernel_segment->memsz. For CMA backed segments this breaks the load path: the payload is copied to page_address(cma), which is the CMA base, while image->start is set to the adjusted address, so kexec jumps into the middle of the kernel. kimage_map_segment() has the same mismatch when a segment has been moved.

The adjusted memsz also breaks the release path: the CMA pages are freed using segment->memsz >> PAGE_SHIFT, which is fewer than were allocated, leaking the tail of the allocation.

Both problems are specific to CMA segments, which are accessed through page_address(cma) and ignore segment->mem. The normal load path uses segment->mem, so the text_offset adjustment stays consistent there. Keep honoring text_offset, but load such images from regular memory by setting image->no_cma: they lose the CMA contiguous allocation, but keep working.

---
 arch/arm64/kernel/kexec_image.c |    7 +++++++
 1 file changed, 7 insertions(+)
arch/arm64/kernel/kexec_image.c +7 -0
@@ -82,6 +82,13 @@ static void *image_load(struct kimage *i
 	kbuf.mem = KEXEC_BUF_MEM_UNKNOWN;
 	kbuf.memsz = le64_to_cpu(h->image_size);
 	text_offset = le64_to_cpu(h->text_offset);
+	/*
+	 * A CMA segment is loaded and mapped through page_address(cma), which
+	 * is the CMA base and cannot represent the text_offset adjustment
+	 * below.  Load images with a non-zero text_offset from normal memory.
+	 */
+	if (text_offset)
+		image->no_cma = true;
 	kbuf.buf_align = MIN_KIMG_ALIGN;
 
 	/* Adjust kernel segment with TEXT_OFFSET */
author maintainer
#752 lore raw

PATCH 751/990 arm64: ptrace: dont warn on missing siginfo in a group-stop

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Zhao Gongyi <[email protected]>

commit 5306f124f3171289b2ef5bac1e08aad175f66d1e upstream.

PTRACE_ATTACH to a group-stopped child can enter do_jobctl_trap(), which calls ptrace_stop() without siginfo. If the tracer writes NT_ARM_SYSTEM_CALL, system_call_set() can change syscallno from NO_SYSCALL before update_syscall_orig_x0_after_ptrace() checks last_siginfo. WARN_ON_ONCE(!info) then fires for a valid ptrace stop.

Keep the early return when siginfo is absent, but remove the warning. This leaves orig_x0 untouched at a non-seized group-stop and preserves the existing syscall-exit-stop handling.

Fixes 88b839ce497c ("arm64: ptrace: Keep 'orig_x0' in-sync with x0 on syscall entry")
[[email protected]: modified comment as per Will's suggestion]
---
 arch/arm64/kernel/ptrace.c |    8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
arch/arm64/kernel/ptrace.c +6 -2
@@ -573,8 +573,12 @@ static void update_syscall_orig_x0_after
 	if (regs->syscallno == NO_SYSCALL)
 		return;
 
-	/* We should only be called when target is in a ptrace stop */
-	if (WARN_ON_ONCE(!info))
+	/*
+	 * For exit-stops, info is always non-NULL, but that's not true for other
+	 * stops such as non-seized group-stops. In those cases, just return early
+	 * as there's no need to update orig_x0 anyway.
+	 */
+	if (!info)
 		return;
 
 	/*
author maintainer
#753 lore raw

PATCH 752/990 arm64: suspend: Save POR_EL0 over suspend

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Mark Brown <[email protected]>

commit 2386c3dcf13e39d7576eae821af66537332c02de upstream.

POR_EL0 is a live EL0 register on systems with S1POE but it is not saved and restored by cpu_do_suspend()/cpu_do_resume(). This means that the task that initiated suspend can return to userspace with an UNKNOWN value. Fix this by saving and restoring the value over suspend.

This increases the size of struct cpu_suspend_ctx.

Fixes bf83dae90fbc ("arm64: enable the Permission Overlay Extension for EL0")
---
 arch/arm64/include/asm/suspend.h |    2 +-
 arch/arm64/mm/proc.S             |    8 ++++++++
 2 files changed, 9 insertions(+), 1 deletion(-)
arch/arm64/include/asm/suspend.h +1 -1
@@ -2,7 +2,7 @@
 #ifndef __ASM_SUSPEND_H
 #define __ASM_SUSPEND_H
 
-#define NR_CTX_REGS 15
+#define NR_CTX_REGS 16
 #define NR_CALLEE_SAVED_REGS 12
 
 /*
arch/arm64/mm/proc.S +8 -0
@@ -108,6 +108,10 @@ alternative_if ARM64_SME
 	mrs_s	x2, SYS_TPIDR2_EL0
 	str	x2, [x0, #112]
 alternative_else_nop_endif
+alternative_if ARM64_HAS_S1POE
+	mrs	x2, REG_POR_EL0
+	str	x2, [x0, #120]
+alternative_else_nop_endif
 	ret
 SYM_FUNC_END(cpu_do_suspend)
 
@@ -150,6 +154,10 @@ alternative_if ARM64_SME
 	ldr	x2, [x0, #112]
 	msr_s	SYS_TPIDR2_EL0, x2
 alternative_else_nop_endif
+alternative_if ARM64_HAS_S1POE
+	ldr	x2, [x0, #120]
+	msr	REG_POR_EL0, x2
+alternative_else_nop_endif
 
 	msr	sctlr_el1, x12
 	set_this_cpu_offset x13
author maintainer
#754 lore raw

PATCH 753/990 arm64: suspend: Save GCS state over suspend

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Mark Brown <[email protected]>

commit 7ca488055c69eed71219546deb805811854aca35 upstream.

GCSCRE0_EL1 and GCSPR_EL0 are live registers for EL0 on systems with GCS but are not saved and restored by cpu_do_suspend()/cpu_do_resume(). This means that the task that initiated suspend can return to userspace with UNKNOWN or incorrect values for GCSPR_EL0 and GCSCRE0_EL1 (many fields in GCSCRE0_EL1 reset to 0). This will in turn lead to ongoing corruption, including not restoring mode until a task with a different GCS mode is run. Fix this by saving and restoring the values over suspend.

This increases the size of struct cpu_suspend_ctx by 16 bytes.

Fixes 5d8b172e7005 ("arm64: Add Kconfig for Guarded Control Stack (GCS)")
---
 arch/arm64/include/asm/suspend.h |    2 +-
 arch/arm64/mm/proc.S             |   12 ++++++++++++
 2 files changed, 13 insertions(+), 1 deletion(-)
arch/arm64/include/asm/suspend.h +1 -1
@@ -2,7 +2,7 @@
 #ifndef __ASM_SUSPEND_H
 #define __ASM_SUSPEND_H
 
-#define NR_CTX_REGS 16
+#define NR_CTX_REGS 18
 #define NR_CALLEE_SAVED_REGS 12
 
 /*
arch/arm64/mm/proc.S +12 -0
@@ -112,6 +112,12 @@ alternative_if ARM64_HAS_S1POE
 	mrs	x2, REG_POR_EL0
 	str	x2, [x0, #120]
 alternative_else_nop_endif
+alternative_if ARM64_HAS_GCS
+	mrs	x2, REG_GCSPR_EL0
+	str	x2, [x0, #128]
+	mrs	x2, REG_GCSCRE0_EL1
+	str	x2, [x0, #136]
+alternative_else_nop_endif
 	ret
 SYM_FUNC_END(cpu_do_suspend)
 
@@ -158,6 +164,12 @@ alternative_if ARM64_HAS_S1POE
 	ldr	x2, [x0, #120]
 	msr	REG_POR_EL0, x2
 alternative_else_nop_endif
+alternative_if ARM64_HAS_GCS
+	ldr	x2, [x0, #128]
+	msr	REG_GCSPR_EL0, x2
+	ldr	x2, [x0, #136]
+	msr	REG_GCSCRE0_EL1, x2
+alternative_else_nop_endif
 
 	msr	sctlr_el1, x12
 	set_this_cpu_offset x13
author maintainer
#755 lore raw

PATCH 754/990 cpufreq: acpi-cpufreq: fix P-state index mismatch in extract_io()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Li RongQing <[email protected]>

commit 6bc092a0fc4d331a4adbbb664078af149c580834 upstream.

When policy->freq_table is built in acpi_cpufreq_cpu_init(), entries that are not lower in frequency than the previous one are skipped. For each remaining entry, freq_table[].driver_data stores the original ACPI P-state index, so the index space of freq_table no longer matches perf->states[].

extract_io() currently walks perf->states[] with index i and uses the same i to index policy->freq_table[i]. When duplicate frequencies exist, this can associate a P-state status with the frequency of a different P-state. It can also access an invalid or sentinel entry in freq_table when the number of entries in perf->states[] is greater than the number of entries remaining in the frequency table.

extract_io() is used on ACPI_ADR_SPACE_SYSTEM_IO platforms by the frequency verification path, which is enabled by the acpi_pstate_strict module parameter. With the mismatched lookup, check_freqs() can fail to match the frequency of the P-state that drv_write() has already programmed. It then sleeps through all 100 iterations - at least ~1 ms of usleep_range() plus 100 cross-CPU calls and I/O port reads, all with policy->rwsem held, and .target_index() returns -EAGAIN, leaving perf->state at its previous value while the hardware is running at the newly requested P-state.

The cpufreq core consequently keeps policy->cur at the old frequency. Since __cpufreq_driver_target() returns early when the requested frequency equals policy->cur, the driver is not called again for that frequency and the control register is not rewritten. The hardware can therefore remain at a frequency that differs from the frequency known to the cpufreq core.

Fix this by iterating over policy->freq_table and using pos->driver_data as the original ACPI P-state index when accessing perf->states[], as extract_msr() already does.

Fixes fe27cb358835 ("[CPUFREQ][2/8] acpi: reorganize code to make MSR support addition easier")
Cc All applicable <[email protected]>
---
 drivers/cpufreq/acpi-cpufreq.c |    9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)
drivers/cpufreq/acpi-cpufreq.c +4 -5
@@ -197,14 +197,13 @@ static unsigned extract_io(struct cpufre
 {
 	struct acpi_cpufreq_data *data = policy->driver_data;
 	struct acpi_processor_performance *perf;
-	int i;
+	struct cpufreq_frequency_table *pos;
 
 	perf = to_perf_data(data);
 
-	for (i = 0; i < perf->state_count; i++) {
-		if (value == perf->states[i].status)
-			return policy->freq_table[i].frequency;
-	}
+	cpufreq_for_each_entry(pos, policy->freq_table)
+		if (value == perf->states[pos->driver_data].status)
+			return pos->frequency;
 	return 0;
 }
 
author maintainer
#756 lore raw

PATCH 755/990 cpufreq: Improve suspend-resume synchronization

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Rafael J. Wysocki <[email protected]>

commit eee2a44e4e2b41c0699919a550d41cc38daa4f42 upstream.

The suspend-resume synchronization in the cpufreq core is not perfect because the global cpufreq_suspended variable is set at the end of cpufreq_suspend() after stopping governors for all of the active policies, so the governor .limits() callback may run via cpufreq_governor_limits() after stopping the governor and before setting cpufreq_suspended which is questionable. Likewise, the governor .limits() callback may run between clearing cpufreq_suspended in cpufreq_resume() and starting the governor.

Address this by adding a per-policy "suspended" flag that is always read under the policy rwsem and is updated under it when the governor is stopped in cpufreq_suspend() and when the governor is restarted in cpufreq_resume().

Also make cpufreq_resume() use the cpus_read_lock guard to reflect what is done in cpufreq_suspend() and call cpufreq_exit_governor() for policies that were suspended during a system suspend transition and are inactive during the subsequent system resume (to avoid leaking an inactive policy with a stopped governor that has not exited yet).

Fixes 8e30444e1530 ("cpufreq: fix cpufreq suspend/resume for intel_pstate")
Fixes b1b12babe3b7 ("cpufreq: update 'cpufreq_suspended' after stopping governors")
Cc All applicable <[email protected]>
---
 drivers/cpufreq/cpufreq.c |   86 +++++++++++++++++++++++++++++++++-------------
 include/linux/cpufreq.h   |    3 +
 2 files changed, 66 insertions(+), 23 deletions(-)
drivers/cpufreq/cpufreq.c +63 -23
@@ -35,6 +35,9 @@
 static LIST_HEAD(cpufreq_policy_list);
 
 /* Macros to iterate over CPU policies */
+#define for_each_policy(__policy)	\
+	list_for_each_entry(__policy, &cpufreq_policy_list, policy_list)
+
 #define for_each_suitable_policy(__policy, __active)			 \
 	list_for_each_entry(__policy, &cpufreq_policy_list, policy_list) \
 		if ((__active) == !policy_is_inactive(__policy))
@@ -1962,6 +1965,14 @@ int cpufreq_generic_suspend(struct cpufr
 }
 EXPORT_SYMBOL(cpufreq_generic_suspend);
 
+static void cpufreq_suspend_policy(struct cpufreq_policy *policy)
+{
+	guard(cpufreq_policy_write)(policy);
+
+	cpufreq_stop_governor(policy);
+	policy->suspended = true;
+}
+
 /**
  * cpufreq_suspend() - Suspend CPUFreq governors.
  *
@@ -1984,11 +1995,8 @@ void cpufreq_suspend(void)
 	pr_debug("%s: Suspending Governors\n", __func__);
 
 	for_each_active_policy(policy) {
-		if (has_target()) {
-			scoped_guard(cpufreq_policy_write, policy) {
-				cpufreq_stop_governor(policy);
-			}
-		}
+		if (has_target())
+			cpufreq_suspend_policy(policy);
 
 		if (cpufreq_driver->suspend && cpufreq_driver->suspend(policy))
 			pr_err("%s: Failed to suspend driver: %s\n", __func__,
@@ -2000,6 +2008,32 @@ suspend:
 	cpus_read_unlock();
 }
 
+static void cpufreq_resume_policy(struct cpufreq_policy *policy, bool start)
+{
+	guard(cpufreq_policy_write)(policy);
+
+	if (!policy->suspended)
+		return;
+
+	policy->suspended = false;
+
+	if (policy_is_inactive(policy)) {
+		/*
+		 * The policy was active when it was suspended, so its governor
+		 * is still there.  Let the governor go.
+		 */
+		cpufreq_exit_governor(policy);
+		return;
+	}
+
+	if (!start)
+		return;
+
+	if (cpufreq_start_governor(policy))
+		pr_err("%s: Failed to start governor for CPU%u's policy\n",
+		       __func__, policy->cpu);
+}
+
 /**
  * cpufreq_resume() - Resume CPUFreq governors.
  *
@@ -2009,11 +2043,12 @@ suspend:
 void cpufreq_resume(void)
 {
 	struct cpufreq_policy *policy;
-	int ret;
 
 	if (!cpufreq_driver)
 		return;
 
+	guard(cpus_read_lock)();
+
 	if (unlikely(!cpufreq_suspended))
 		return;
 
@@ -2024,19 +2059,18 @@ void cpufreq_resume(void)
 
 	pr_debug("%s: Resuming Governors\n", __func__);
 
-	for_each_active_policy(policy) {
-		if (cpufreq_driver->resume && cpufreq_driver->resume(policy)) {
-			pr_err("%s: Failed to resume driver: %s\n", __func__,
-				cpufreq_driver->name);
-		} else if (has_target()) {
-			scoped_guard(cpufreq_policy_write, policy) {
-				ret = cpufreq_start_governor(policy);
-			}
+	for_each_policy(policy) {
+		int ret = 0;
 
+		if (cpufreq_driver->resume && !policy_is_inactive(policy)) {
+			ret = cpufreq_driver->resume(policy);
 			if (ret)
-				pr_err("%s: Failed to start governor for CPU%u's policy\n",
-				       __func__, policy->cpu);
+				pr_err("%s: Failed to resume driver: %s\n", __func__,
+				       cpufreq_driver->name);
 		}
+
+		if (has_target())
+			cpufreq_resume_policy(policy, ret == 0);
 	}
 }
 
@@ -2410,12 +2444,17 @@ __weak struct cpufreq_governor *cpufreq_
 	return NULL;
 }
 
+static bool cpufreq_is_suspended(struct cpufreq_policy *policy)
+{
+	return cpufreq_suspended || policy->suspended;
+}
+
 static int cpufreq_init_governor(struct cpufreq_policy *policy)
 {
 	int ret;
 
-	/* Don't start any governor operations if we are entering suspend */
-	if (cpufreq_suspended)
+	/* Don't start any governor operations for suspended policies. */
+	if (cpufreq_is_suspended(policy))
 		return 0;
 	/*
 	 * Governor might not be initiated here if ACPI _PPC changed
@@ -2458,7 +2497,7 @@ static int cpufreq_init_governor(struct
 
 static void cpufreq_exit_governor(struct cpufreq_policy *policy)
 {
-	if (cpufreq_suspended || !policy->governor)
+	if (cpufreq_is_suspended(policy) || !policy->governor)
 		return;
 
 	pr_debug("%s: for CPU %u\n", __func__, policy->cpu);
@@ -2473,7 +2512,7 @@ int cpufreq_start_governor(struct cpufre
 {
 	int ret;
 
-	if (cpufreq_suspended)
+	if (cpufreq_is_suspended(policy))
 		return 0;
 
 	if (!policy->governor)
@@ -2497,7 +2536,7 @@ int cpufreq_start_governor(struct cpufre
 
 void cpufreq_stop_governor(struct cpufreq_policy *policy)
 {
-	if (cpufreq_suspended || !policy->governor)
+	if (cpufreq_is_suspended(policy) || !policy->governor)
 		return;
 
 	pr_debug("%s: for CPU %u\n", __func__, policy->cpu);
@@ -2508,7 +2547,7 @@ void cpufreq_stop_governor(struct cpufre
 
 static void cpufreq_governor_limits(struct cpufreq_policy *policy)
 {
-	if (cpufreq_suspended || !policy->governor)
+	if (cpufreq_is_suspended(policy) || !policy->governor)
 		return;
 
 	pr_debug("%s: for CPU %u\n", __func__, policy->cpu);
@@ -2736,7 +2775,8 @@ static void cpufreq_policy_refresh(struc
 	 * -> ask driver for current freq and notify governors about a change
 	 */
 	if (cpufreq_driver->get && has_target() &&
-	    (cpufreq_suspended || WARN_ON(!cpufreq_verify_current_freq(policy, false))))
+	    (cpufreq_is_suspended(policy) ||
+	     WARN_ON(!cpufreq_verify_current_freq(policy, false))))
 		return;
 
 	refresh_frequency_limits(policy);
include/linux/cpufreq.h +3 -0
@@ -145,6 +145,9 @@ struct cpufreq_policy {
 	/* Per policy boost supported flag. */
 	bool			boost_supported;
 
+	/* The policy has been suspended. */
+	bool			suspended;
+
 	 /* Cached frequency lookup from cpufreq_driver_resolve_freq. */
 	unsigned int cached_target_freq;
 	unsigned int cached_resolved_idx;
author maintainer
#757 lore raw

PATCH 756/990 cpufreq: intel_pstate: Clear last written P-state value on suspend

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Rafael J. Wysocki <[email protected]>

commit 02e77af824d5be3a94fdd885835a352f90d24c5c upstream.

Preserving cpu->pstate.current_pstate across system suspend-resume cycles, when running in the passive mode with HWP disabled, is a mistake because its value from before system suspend may become stale after the subsequent system resume and in some cases it prevents MSR_IA32_PERF_CTL from being updated properly after system resume [1].

Address this by clearing cpu->pstate.current_pstate after the governor has been stopped during system suspend.

Fixes 001c76f05b01 ("cpufreq: intel_pstate: Generic governors support")
Fixes 4adcf2e5829f ("cpufreq: intel_pstate: Add ->offline and ->online callbacks")
Cc All applicable <[email protected]> # 342d3a73c5db cpufreq: Force passing target frequency to driver during resume
---
 drivers/cpufreq/intel_pstate.c |   14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)
drivers/cpufreq/intel_pstate.c +13 -1
@@ -3412,10 +3412,11 @@ static void intel_cpufreq_cpu_exit(struc
 
 static int intel_cpufreq_suspend(struct cpufreq_policy *policy)
 {
+	struct cpudata *cpu = all_cpu_data[policy->cpu];
+
 	intel_pstate_suspend(policy);
 
 	if (hwp_active) {
-		struct cpudata *cpu = all_cpu_data[policy->cpu];
 		u64 value = READ_ONCE(cpu->hwp_req_cached);
 
 		/*
@@ -3426,6 +3427,17 @@ static int intel_cpufreq_suspend(struct
 		value &= ~HWP_DESIRED_PERF(~0L);
 		wrmsrq_on_cpu(cpu->cpu, MSR_HWP_REQUEST, value);
 		WRITE_ONCE(cpu->hwp_req_cached, value);
+	} else {
+		/*
+		 * Invalidate the cached P-state value that may be stale when
+		 * the governor is started again during resume and may prevent
+		 * MSR_IA32_PERF_CTL from being updated.
+		 *
+		 * This does not require synchronization because the core
+		 * prevents frequency updates for suspended policies from
+		 * occurring.
+		 */
+		cpu->pstate.current_pstate = 0;
 	}
 
 	return 0;
author maintainer
#758 lore raw

PATCH 757/990 cpufreq: intel_pstate: Use rdmsrq_safe() to read MSR_MISC_PWR_MGMT

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Li Zhaoxin <[email protected]>

commit 2c0e6f2858d235c99f7ba4621bd176cd67226f00 upstream.

Commit ed7cad0504e3 ("cpufreq: intel_pstate: Relocate platform preference check") moved the intel_pstate_platform_pwr_mgmt_exists() call to the beginning of intel_pstate_init(), right after the vendor check, so it now runs before "no_load" (intel_pstate=disable) and the other checks.

MSR_MISC_PWR_MGMT is model-specific and KVM does not emulate it. In a KVM guest using a CPU model listed in intel_pstate_cpu_oob_ids[] (for example "-cpu host" on Emerald Rapids), reading it raises #GP and the unchecked rdmsrq() emits a warning with a call trace on every boot, even with intel_pstate=disable:

unchecked MSR access error: RDMSR from 0x1aa at rIP: 0xffffffffa4009342 (native_read_msr+0x2/0x50)

  Call Trace:
   <TASK>
   intel_pstate_platform_pwr_mgmt_exists+0x3b/0x220
   intel_pstate_init+0x1e/0x500
   do_one_initcall+0x59/0x350
   ...

Before that commit, such guests typically returned from intel_pstate_init() earlier, either because of intel_pstate=disable or because intel_pstate_msrs_not_valid() failed on the zero ratios that KVM reports in MSR_PLATFORM_INFO by default, so the MSR was not read.

Use rdmsrq_safe() and treat a failing read as "no OOB mode". The exception fixup already zeroes the result of a failed unchecked read, so apart from the warning going away there is no functional change.

Fixes ed7cad0504e3 ("cpufreq: intel_pstate: Relocate platform preference check")
Cc All applicable <[email protected]>
---
 drivers/cpufreq/intel_pstate.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/cpufreq/intel_pstate.c +2 -2
@@ -3683,12 +3683,12 @@ static struct acpi_platform_list plat_in
 static bool __init intel_pstate_platform_pwr_mgmt_exists(void)
 {
 	const struct x86_cpu_id *id;
-	u64 misc_pwr;
+	u64 misc_pwr = 0;
 	int idx;
 
 	id = x86_match_cpu(intel_pstate_cpu_oob_ids);
 	if (id) {
-		rdmsrq(MSR_MISC_PWR_MGMT, misc_pwr);
+		rdmsrq_safe(MSR_MISC_PWR_MGMT, &misc_pwr);
 		if (misc_pwr & BITMASK_OOB) {
 			pr_debug("Bit 8 or 18 in the MISC_PWR_MGMT MSR set\n");
 			pr_debug("P states are controlled in Out of Band mode by the firmware/hardware\n");
author maintainer
#759 lore raw

PATCH 758/990 cpufreq: Cache post-resolution target frequency in __resolve_freq()

In reply to Greg Kroah-Hartman

6.18-stable review patch. If anyone has any objections, please let me know.

------------------

From: Rafael J. Wysocki <[email protected]>

commit 166207cac45191637c47a457a5c16ca6b6773a16 upstream.

get_next_freq() in the schedutil governor returns the resolved frequency from cpufreq_driver_resolve_freq(), and that resolved value is then passed to cpufreq_driver_fast_switch(). The only reader of cached_target_freq, acpi_cpufreq_fast_switch(), compares it with the post-resolution target frequency, but it holds the pre-resolution clamped frequency, so any request that falls between table entries misses the cache and falls back to a table scan.

Address this by making __resolve_freq() store the post-resolution frequency in cached_target_freq.

---
 drivers/cpufreq/cpufreq.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/cpufreq/cpufreq.c +2 -2
@@ -509,8 +509,8 @@ static unsigned int __resolve_freq(struc
 
 	idx = cpufreq_frequency_table_target(policy, target_freq, min, max, relation);
 	policy->cached_resolved_idx = idx;
-	policy->cached_target_freq = target_freq;
-	return policy->freq_table[idx].frequency;
+	policy->cached_target_freq = policy->freq_table[idx].frequency;
+	return policy->cached_target_freq;
 }
 
 /**