Skip to contentSkip to conversation

7.3.2-rc1 review

PATCH In review Greg Kroah-Hartman 17 participants 573 messages Nov 4 – Nov 7 Page 2 of 5

Subsystems (5)
lore
Share & tools
lore
author maintainer
#113 lore raw

PATCH 113/547 ksmbd: accept share config responses from ksmbd-tools before 3.5.3

In reply to Greg Kroah-Hartman

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

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

From: Michail Andreas Michalopoulos <[email protected]>

commit 4f1ce9ffb996a524acf864316479a7806ae500c6 upstream.

ksmbd-tools releases before 3.5.2 do not have the payload_sz field in struct ksmbd_share_config_response; the field occupies the last word of their reserved[] area, so the kernel always sees payload_sz == 0 from them. ipc_validate_msg() and share_config_request() used to treat payload_sz == 0 as "legacy userspace" and skip the payload size checks.

That case was removed by
commit f25e93768fcc ("ksmbd: prevent out-of-bounds reads in share config responses").
With payload_sz == 0:

- the IPC$ (pipe) response fails the final message size comparison:
these tools always send a one-byte payload, so msg_sz is sizeof(*resp) + 1, but the expected size is now computed as sizeof(*resp) + 0;
- every other share fails "payload_sz <= veto_list_sz".

In addition, ksmbd-tools before 3.5.3 copy a global "veto files" setting into the IPC$ response, so with such a configuration IPC$ also fails the now unconditional "veto_list_sz > payload_sz" check, even though pipe shares never use a veto list.

ksmbd_ipc_share_config_request() then returns NULL and every tree connect fails with STATUS_BAD_NETWORK_NAME, so ksmbd cannot serve any share when used with these ksmbd-tools releases, for example the 3.5.1 package shipped by Ubuntu 24.04. Login still works, which makes the failure look like a configuration problem:

CIFS: VFS: BAD_NETWORK_NAME: \\127.0.0.1\IPC$
CIFS: VFS: \\127.0.0.1 failed to connect to IPC (rc=-2)

When payload_sz is zero, derive it from the size of the message actually received and store it back in the response, so that the checks in ipc_validate_msg() and the path and veto list parsing in share_config_request() all use the same bound. The response is the kernel's own copy made by handle_response(), and msg_sz has already been checked to be at least sizeof(*resp), so this cannot underflow. All checks added by that commit then apply unchanged, bounded by the bytes that really arrived, and newer ksmbd-tools that fill in payload_sz are unaffected. Also skip the veto list size check for pipe shares:
share_config_request() reads neither the path nor the veto list for them.

Tested in QEMU with ksmbd-tools 3.5.1 and 3.5.7 and the in-kernel SMB client over loopback, with and without a global "veto files" setting.

Fixes f25e93768fcc ("ksmbd: prevent out-of-bounds reads in share config responses")
Assisted-by LLM
---
 fs/smb/server/transport_ipc.c |   16 +++++++++++++++-
 1 file changed, 15 insertions(+), 1 deletion(-)
fs/smb/server/transport_ipc.c +15 -1
@@ -532,11 +532,25 @@ static int ipc_validate_msg(struct ipc_m
 		if (entry->msg_sz < sizeof(struct ksmbd_share_config_response))
 			return -EINVAL;
 
+		/*
+		 * ksmbd-tools releases before 3.5.2 leave payload_sz zero.
+		 * Derive it from the size of the message actually received so
+		 * the checks below bound the payload for those releases too.
+		 */
+		if (!resp->payload_sz)
+			resp->payload_sz = entry->msg_sz -
+				sizeof(struct ksmbd_share_config_response);
+
 		if (strnlen(resp->share_name, sizeof(resp->share_name)) ==
 		    sizeof(resp->share_name))
 			return -EINVAL;
 
-		if (resp->veto_list_sz > resp->payload_sz)
+		/*
+		 * Pipe shares carry no veto list, but ksmbd-tools before 3.5.3
+		 * copy a global "veto files" setting into the IPC$ response.
+		 */
+		if (!(resp->flags & KSMBD_SHARE_FLAG_PIPE) &&
+		    resp->veto_list_sz > resp->payload_sz)
 			return -EINVAL;
 
 		if (resp->flags != KSMBD_SHARE_FLAG_INVALID &&
author maintainer
#114 lore raw

PATCH 114/547 ksmbd: avoid restoring only in-memory EOF after allocation change

In reply to Greg Kroah-Hartman

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

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

From: DaeMyung Kang <[email protected]>

commit 9455e920aebe41217cabff3f81e90da4c407fdb6 upstream.

When SetAllocation requests a size below the allocated block count but above EOF, ksmbd truncates the file to that size and restores only the in-memory i_size. The larger EOF remains on disk and reappears after a reboot. A 3-byte file preallocated to 64 KiB can acquire a 4 KiB EOF after reducing its allocation to 4 KiB. Extending EOF this way is not a reliable way to reclaim the preallocation beyond the old EOF either.

Only use this truncate path when the requested allocation is at or below the observed EOF. A truncate to the existing EOF still lets filesystems release preallocated blocks beyond EOF. Remove the in-memory-only i_size restoration. The size check still precedes vfs_truncate() taking the inode lock, so a concurrent shrink can make the truncate extend EOF; that race also existed in the original path.

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
---
 fs/smb/server/smb2pdu.c |   15 ++++-----------
 1 file changed, 4 insertions(+), 11 deletions(-)
fs/smb/server/smb2pdu.c +4 -11
@@ -8241,24 +8241,17 @@ static int set_file_allocation_info(stru
 			pr_err("vfs_fallocate is failed : %d\n", rc);
 			return rc;
 		}
-	} else if (alloc_blks < stat.blocks) {
-		loff_t size;
-
+	} else if (alloc_blks < stat.blocks &&
+		   alloc_blks * 512 <= i_size_read(inode)) {
 		/*
-		 * Allocation size could be smaller than original one
-		 * which means allocated blocks in file should be
-		 * deallocated. use truncate to cut out it, but inode
-		 * size is also updated with truncate offset.
-		 * inode size is retained by backup inode size.
+		 * Truncate at or below EOF to discard excess allocation.
+		 * Truncating above EOF would extend the file on disk.
 		 */
-		size = i_size_read(inode);
 		rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
 		if (rc) {
 			pr_err("truncate failed!, err %d\n", rc);
 			return rc;
 		}
-		if (size < alloc_blks * 512)
-			i_size_write(inode, size);
 	}
 
 	fp->allocation_size = le64_to_cpu(file_alloc_info->AllocationSize);
author maintainer
#115 lore raw

PATCH 115/547 ksmbd: defer connection scavenging while session locks are busy

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

commit b4bae7af1154089be87c7475218264fcbfd16d10 upstream.

The expiration worker holds conn_list_lock for reading while checking for authenticated sessions. Without this change, the check can wait for conn->session_lock or sessions_table_lock.

In destroy_previous_session(), the status updates after ksmbd_conn_wait_idle_sess() run with both session locks held for writing. Both the KSMBD_SESS_GOOD error path and the KSMBD_SESS_NEED_SETUP success path call ksmbd_all_conn_set_status(), which takes conn_list_lock for reading.

A writer queued on conn_list_lock can block these new read acquisitions. The worker then waits for a session lock held by destroy_previous_session(), which waits behind the writer. The writer cannot proceed until the worker releases conn_list_lock.

Try both session locks instead of waiting in the scavenging check. Keep the connection when either lock is busy and let the periodic worker retry later.

Fixes d7fd1f98607f ("ksmbd: follow SMB2 session expiration semantics")
---
 fs/smb/server/mgmt/user_session.c |   10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
fs/smb/server/mgmt/user_session.c +8 -2
@@ -532,7 +532,12 @@ bool ksmbd_conn_has_valid_or_expired_ses
 	int state, bkt;
 	bool found = false;
 
-	down_read(&conn->session_lock);
+	/*
+	 * The expiration worker holds conn_list_lock, which session teardown
+	 * takes after the session locks. Defer scavenging if either is busy.
+	 */
+	if (!down_read_trylock(&conn->session_lock))
+		return true;
 	xa_for_each(&conn->sessions, id, sess) {
 		state = READ_ONCE(sess->state);
 		if (state == SMB2_SESSION_VALID ||
@@ -546,7 +551,8 @@ bool ksmbd_conn_has_valid_or_expired_ses
 		return true;
 
 	/* A session bound through SMB3 multichannel is not in conn->sessions. */
-	down_read(&sessions_table_lock);
+	if (!down_read_trylock(&sessions_table_lock))
+		return true;
 	hash_for_each(sessions_table, bkt, sess, hlist) {
 		state = READ_ONCE(sess->state);
 		if (state != SMB2_SESSION_VALID &&
author maintainer
#116 lore raw

PATCH 116/547 ksmbd: deny access for an empty DACL instead of granting the request

In reply to Greg Kroah-Hartman

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

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

From: Aamir Ahmed <[email protected]>

commit de0cffef897c1c232ed973f89928cd6c93d0b1e3 upstream.

smb_check_perm_dacl() returns the access mask it computes to the SMB2 CREATE handler, which uses it as the granted access for the open. For a security descriptor whose DACL is present but contains no ACEs, the function is supposed to deny access: an empty (non-NULL) DACL grants no access to anyone except the object owner's implicit READ_CONTROL and WRITE_DAC (MS-DTYP 2.4.5).

The empty-DACL branch only denies when both

- the DACL has no trailing bytes (pdacl_size == sizeof(struct smb_acl)), and
- the request contains bits beyond READ_CONTROL / WRITE_DAC.

In every other case it takes the shared "goto err_out" with rc still 0, which returns success without modifying *pdaccess, so the caller grants the full requested access. Three problems follow:

- The READ_CONTROL / WRITE_DAC carve-out models the owner's implicit rights, but the check runs before is_owner is computed, so those rights are handed to *every* caller, not just the owner. For READ_CONTROL the SMB2 CREATE path does not fall back to inode_permission(), so any user can read the security descriptor of an object whose empty DACL is meant to deny them.

- A request of exactly READ_CONTROL and/or WRITE_DAC is granted to any caller. WRITE_DAC lets the handle rewrite the DACL.

- A DACL that declares zero ACEs but carries trailing bytes (pdacl_size > sizeof(struct smb_acl)) skips the deny entirely and is granted whatever was requested.

On shares where the NT ACL is the authoritative access control -- e.g. "force user" shares, where every client maps to one POSIX identity so POSIX cannot distinguish users -- this is an access-control bypass.

Compute is_owner before the empty-DACL branch and deny access from an empty DACL unless the caller is the owner requesting no more than READ_CONTROL / WRITE_DAC.

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
Assisted-by LLM
---
 fs/smb/server/smbacl.c |   24 +++++++++++++++---------
 1 file changed, 15 insertions(+), 9 deletions(-)
fs/smb/server/smbacl.c +15 -9
@@ -1490,21 +1490,27 @@ int smb_check_perm_dacl(struct ksmbd_con
 	if (pdacl_size > acl_size || pdacl_size < sizeof(struct smb_acl))
 		goto err_out;
 
-	if (!pdacl->num_aces) {
-		if (!(pdacl_size - sizeof(struct smb_acl)) &&
-		    *pdaccess & ~(FILE_READ_CONTROL_LE | FILE_WRITE_DAC_LE)) {
-			rc = -EACCES;
-			goto err_out;
-		}
-		goto err_out;
-	}
-
 	if (!uid)
 		sid_type = SIDUNIX_USER;
 	id_to_sid(uid, sid_type, &sid);
 	vfsuid = i_uid_into_vfsuid(idmap, d_inode(path->dentry));
 	is_owner = uid == from_kuid(&init_user_ns, vfsuid_into_kuid(vfsuid));
 
+	if (!pdacl->num_aces) {
+		/*
+		 * An empty (present, zero-ACE) DACL grants no access to
+		 * anyone except the object owner's implicit READ_CONTROL
+		 * and WRITE_DAC (MS-DTYP 2.4.5). Deny every other caller,
+		 * deny the owner any access beyond those two bits, and do
+		 * not let trailing bytes after a zero-ACE DACL become an
+		 * implicit grant.
+		 */
+		if (!is_owner ||
+		    (*pdaccess & ~(FILE_READ_CONTROL_LE | FILE_WRITE_DAC_LE)))
+			rc = -EACCES;
+		goto err_out;
+	}
+
 	if (*pdaccess & FILE_MAXIMAL_ACCESS_LE) {
 		ace = (struct smb_ace *)((char *)pdacl + sizeof(struct smb_acl));
 		aces_size = pdacl_size - sizeof(struct smb_acl);
author maintainer
#117 lore raw

PATCH 117/547 ksmbd: drain session procfs readers before dropping table references

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

commit 1c087cf7d5386c708d8984b263280b42b3daada0 upstream.

Session registration failure and connection cleanup can drop the table reference while the per-session procfs entry is still accessible. If a reader holds the last remaining reference, its final put calls proc_remove() from its own callback and waits for that callback to finish.

Remove the procfs entry before dropping the table reference in the registration failure path. Queue sessions removed during connection cleanup and drain their procfs readers after releasing both session locks, then return their table references. Keep the global hash node unhashed while a session is queued so a concurrent unregister cannot drop the reference again.

Previous-session replacement also destroys the file table before the session is finally freed. Detach the idr under the lock used by procfs file counters, and report zero files after it has been detached. This prevents a reader from accessing the idr during or after its destruction.

Fixes d7fd1f98607f ("ksmbd: follow SMB2 session expiration semantics")
---
 fs/smb/server/mgmt/user_session.c |   15 +++++++++------
 fs/smb/server/vfs_cache.c         |    9 +++++++--
 2 files changed, 16 insertions(+), 8 deletions(-)
fs/smb/server/mgmt/user_session.c +9 -6
@@ -95,8 +95,10 @@ static unsigned int session_open_file_co
 	unsigned int id;
 
 	read_lock(&session->file_table.lock);
-	idr_for_each_entry(session->file_table.idr, fp, id)
-		count++;
+	if (session->file_table.idr) {
+		idr_for_each_entry(session->file_table.idr, fp, id)
+			count++;
+	}
 	read_unlock(&session->file_table.lock);
 	return count;
 }
@@ -477,6 +479,7 @@ int ksmbd_session_register(struct ksmbd_
 		down_write(&sessions_table_lock);
 		ksmbd_session_remove_from_table(sess);
 		up_write(&sessions_table_lock);
+		delete_proc_session(sess);
 		ksmbd_user_session_put(sess);
 	}
 
@@ -604,6 +607,7 @@ static int ksmbd_chann_del(struct ksmbd_
 
 void ksmbd_conn_sessions_cleanup(struct ksmbd_conn *conn)
 {
+	LIST_HEAD(dispose);
 	struct ksmbd_session *sess;
 	unsigned long id;
 	struct hlist_node *tmp;
@@ -617,8 +621,7 @@ void ksmbd_conn_sessions_cleanup(struct
 			down_write(&conn->session_lock);
 			xa_erase(&conn->sessions, sess->id);
 			up_write(&conn->session_lock);
-			if (atomic_dec_and_test(&sess->refcnt))
-				ksmbd_session_destroy(sess);
+			list_add_tail(&sess->dispose_entry, &dispose);
 		}
 	}
 
@@ -628,12 +631,12 @@ void ksmbd_conn_sessions_cleanup(struct
 		if (xa_empty(&sess->ksmbd_chann_list)) {
 			xa_erase(&conn->sessions, sess->id);
 			ksmbd_session_remove_from_table(sess);
-			if (atomic_dec_and_test(&sess->refcnt))
-				ksmbd_session_destroy(sess);
+			list_add_tail(&sess->dispose_entry, &dispose);
 		}
 	}
 	up_write(&conn->session_lock);
 	up_write(&sessions_table_lock);
+	ksmbd_dispose_sessions(&dispose);
 }
 
 bool is_ksmbd_session_in_connection(struct ksmbd_conn *conn,
fs/smb/server/vfs_cache.c +7 -2
@@ -1975,14 +1975,19 @@ int ksmbd_init_file_table(struct ksmbd_f
 void ksmbd_destroy_file_table(struct ksmbd_session *sess)
 {
 	struct ksmbd_file_table *ft = &sess->file_table;
+	struct idr *idr;
 
 	if (!ft->idr)
 		return;
 
 	__close_file_table_ids(sess, NULL, session_fd_check, true);
-	idr_destroy(ft->idr);
-	kfree(ft->idr);
+	/* Stop procfs readers before freeing the detached file table. */
+	write_lock(&ft->lock);
+	idr = ft->idr;
 	ft->idr = NULL;
+	write_unlock(&ft->lock);
+	idr_destroy(idr);
+	kfree(idr);
 }
 
 int ksmbd_init_file_cache(void)
author maintainer
#118 lore raw

PATCH 118/547 ksmbd: fix extended session security negotiation for raw NTLMSSP

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

commit 6868f857514bbfd2ed10b9b566664dc4a8ca039d upstream.

ksmbd_build_ntlmssp_challenge_blob() only advertises extended session security when conn->use_spnego is true. As a result, raw NTLMSSP negotiation drops NTLMSSP_NEGOTIATE_EXTENDED_SEC from the challenge even when the client requested it.

A Windows capture shows an initial SPNEGO authentication succeeding, followed by a raw NTLMSSP negotiation on the same TCP connection. The raw challenge omits extended session security, and the client does not send an AUTHENTICATE message. The unfinished session then occupies the pending session slot, causing subsequent SESSION_SETUP requests to fail with STATUS_INSUFFICIENT_RESOURCES.

Set NTLMSSP_NEGOTIATE_EXTENDED_SEC whenever the client requests it, independently of the SPNEGO wrapper, as required by [MS-NLMP].

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
---
 fs/smb/server/auth.c |    3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
fs/smb/server/auth.c +1 -2
@@ -336,8 +336,7 @@ ksmbd_build_ntlmssp_challenge_blob(struc
 	if (cflags & NTLMSSP_REQUEST_TARGET)
 		flags |= NTLMSSP_REQUEST_TARGET;
 
-	if (conn->use_spnego &&
-	    (cflags & NTLMSSP_NEGOTIATE_EXTENDED_SEC))
+	if (cflags & NTLMSSP_NEGOTIATE_EXTENDED_SEC)
 		flags |= NTLMSSP_NEGOTIATE_EXTENDED_SEC;
 
 	if (cflags & NTLMSSP_NEGOTIATE_KEY_XCH)
author maintainer
#119 lore raw

PATCH 119/547 ksmbd: fix OOB read and cross-share confusion in ksmbd_validate_name_reconnect()

In reply to Greg Kroah-Hartman

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

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

From: Dairui Zhang <[email protected]>

commit 783a7fc454991544bf92268d8f2413af1a7c7eb8 upstream.

ksmbd_validate_name_reconnect() indexes ab_pathname[share->path_sz + 1] without checking that the path is longer than share->path_sz + 1 (d_path() fills the buffer from the end). A durable fp is not bound to its original share, so a client can preserve a file from a short-path share and reconnect it on a long-path share, making strcmp() read past the PATH_MAX buffer - with a long enough share path this oopses the kernel, and on a mapped page it also gives a byte-equality oracle on adjacent heap (the reconnect succeeds exactly when the out-of-bounds string equals the requested name). A same-share variant with the durable fp at the share root reads 1 byte past the buffer (strlen(ab_pathname) == share->path_sz).

Check before comparing: the path must be longer than share->path_sz, it must start with share->path, and the next character must be '/'. The share root itself is accepted only for an empty name.

Fixes c8efcc786146 ("ksmbd: add support for durable handles v1/v2")
Assisted-by LLM
---
 fs/smb/server/vfs_cache.c |   18 +++++++++++++++---
 1 file changed, 15 insertions(+), 3 deletions(-)
fs/smb/server/vfs_cache.c +15 -3
@@ -1877,9 +1877,21 @@ int ksmbd_validate_name_reconnect(struct
 		return -EACCES;
 	}
 
-	if (name && strcmp(&ab_pathname[share->path_sz + 1], name)) {
-		ksmbd_debug(SMB, "invalid name reconnect %s\n", name);
-		ret = -EINVAL;
+	if (name) {
+		size_t len = strlen(ab_pathname);
+
+		if (len == share->path_sz && !strncmp(ab_pathname, share->path, len)) {
+			/* the durable fp is the share root itself */
+			if (name[0])
+				ret = -EINVAL;
+		} else if (len <= share->path_sz ||
+			   strncmp(ab_pathname, share->path, share->path_sz) ||
+			   ab_pathname[share->path_sz] != '/' ||
+			   strcmp(&ab_pathname[share->path_sz + 1], name)) {
+			ret = -EINVAL;
+		}
+		if (ret)
+			ksmbd_debug(SMB, "invalid name reconnect %s\n", name);
 	}
 
 	kfree(pathname);
author maintainer
#120 lore raw

PATCH 120/547 ksmbd: fix overflow in dacloffset bounds check in build_sec_desc()

In reply to Greg Kroah-Hartman

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

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

From: Giorgi Kobakhia <[email protected]>

commit eb96e2a0e817807c48dc8387ca6a5249fdeae3a0 upstream.

When the large dacl_offset is provided, dacl_offset + sizeof(struct smb_acl) overflows on 32-bit builds and the check is passed, Which makes le16_to_cpu(ppdacl_ptr->size) read out-of-bounds. This only happens for dacl_offset in range [0xFFFFFFF8, 0xFFFFFFFF]. So the oob read is max 8 bytes preceding the allocated ppntsd.

    unsigned int dacl_offset = le32_to_cpu(ppntsd->dacloffset);
    int ppdacl_size, ntacl_size = ppntsd_size - dacl_offset;

    if (!dacl_offset ||
	(dacl_offset + sizeof(struct smb_acl) > ppntsd_size))
	    goto out;

Commit beff0bc9d69b ("ksmbd: fix overflow in dacloffset bounds check") fixes similar checks in other functions. But leaves this one out, because it is only valid for 32-bit builds.

Reproduced on 32-bit ARM with KASAN, by a client sending SMB2 SET_INFO(SEC) with dacloffset=0xfffffff8, then QUERY_INFO(SEC) on the same file:

 BUG: KASAN: slab-out-of-bounds in build_sec_desc (fs/smb/server/smbacl.c:1105)
 Read of size 2 at addr c2a273fa by task kworker/1:1/35
 CPU: 1 UID: 0 PID: 35 Comm: kworker/1:1 Not tainted 7.3.0-rc2+ #5
 Workqueue: ksmbd-io handle_ksmbd_work
 Call trace:
  kasan_check_range from build_sec_desc (fs/smb/server/smbacl.c:1105)
  build_sec_desc from smb2_query_info (fs/smb/server/smb2pdu.c:7676)
  smb2_query_info from handle_ksmbd_work (fs/smb/server/server.c:160)
  handle_ksmbd_work from process_one_work (kernel/workqueue.c:3401)
  process_one_work from worker_thread (kernel/workqueue.c:3473)
  worker_thread from kthread (kernel/kthread.c:436)

Add overflow check.

Fixes 8f0541186e9a ("ksmbd: fix heap-based overflow in set_ntacl_dacl()")
Assisted-by LLM claude
---
 fs/smb/server/smbacl.c |    5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
fs/smb/server/smbacl.c +4 -1
@@ -1096,9 +1096,12 @@ int build_sec_desc(struct mnt_idmap *idm
 			struct smb_acl *ppdacl_ptr;
 			unsigned int dacl_offset = le32_to_cpu(ppntsd->dacloffset);
 			int ppdacl_size, ntacl_size = ppntsd_size - dacl_offset;
+			size_t dacl_struct_end;
 
 			if (!dacl_offset ||
-			    (dacl_offset + sizeof(struct smb_acl) > ppntsd_size))
+			    check_add_overflow(dacl_offset, sizeof(struct smb_acl),
+					       &dacl_struct_end) ||
+			    dacl_struct_end > (size_t)ppntsd_size)
 				goto out;
 
 			ppdacl_ptr = (struct smb_acl *)((char *)ppntsd + dacl_offset);
author maintainer
#121 lore raw

PATCH 121/547 ksmbd: fix parent dentry lifetime in directory enumeration

In reply to Greg Kroah-Hartman

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

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

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

commit 171df27077fb49b4af2c53ad2cedcd0e39664fe8 upstream.

ksmbd_populate_dot_dotdot_entries() builds the ".." entry from the open directory's d_parent and passes that pointer to ksmbd_vfs_fill_dentry_attrs() without taking a reference. That pointer is only valid while the directory stays under this parent. If a concurrent rename moves the directory elsewhere, the old parent loses its last reference; a following rmdir then turns it into a negative dentry with d_inode cleared, and after the RCU grace period the dentry itself is freed. The worker still holds the raw pointer and dereferences d_inode through vfs_getattr() and vfs_getxattr().

A remote SMB client, authenticated or guest, triggers this by listing a directory while that directory is moved under a new parent and the old parent is deleted. It can be done by the client itself with write access or by other concurrent writers, triggering null-ptr-deref and slab-use-after-free on a KASAN build.

  KASAN: null-ptr-deref in range
      [0x0000000000000000-0x0000000000000007]
  Workqueue: ksmbd-io handle_ksmbd_work
  RIP: 0010:xattr_permission+0x9d/0x160
  Call Trace:
   vfs_getxattr+0x9c/0x1b0
   ksmbd_vfs_getxattr+0x82/0x100
   ksmbd_vfs_get_dos_attrib_xattr+0x7f/0x130
   ksmbd_vfs_fill_dentry_attrs+0x435/0x650
   ksmbd_populate_dot_dotdot_entries+0x25e/0x630
   smb2_query_dir+0xcf9/0x1a20
   handle_ksmbd_work+0x5f1/0x1c80
   process_one_work+0x90b/0x19d0

Fix by using the dentry reference counting APIs: take the parent with dget_parent(), take a matching dget() on ".", and dput() the dentry once ksmbd_vfs_fill_dentry_attrs() has returned or the pattern does not match.

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
---
 fs/smb/server/smb_common.c |    6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
fs/smb/server/smb_common.c +4 -2
@@ -478,16 +478,17 @@ int ksmbd_populate_dot_dotdot_entries(st
 			if (i == 0) {
 				d_info->name = ".";
 				d_info->name_len = 1;
-				dentry = dir->filp->f_path.dentry;
+				dentry = dget(dir->filp->f_path.dentry);
 			} else {
 				d_info->name = "..";
 				d_info->name_len = 2;
-				dentry = dir->filp->f_path.dentry->d_parent;
+				dentry = dget_parent(dir->filp->f_path.dentry);
 			}
 
 			if (!match_pattern(d_info->name, d_info->name_len,
 					   search_pattern)) {
 				dir->dot_dotdot[i] = 1;
+				dput(dentry);
 				continue;
 			}
 
@@ -496,6 +497,7 @@ int ksmbd_populate_dot_dotdot_entries(st
 							 idmap,
 							 dentry,
 							 &ksmbd_kstat);
+			dput(dentry);
 			if (rc)
 				break;
 
author maintainer
#122 lore raw

PATCH 122/547 ksmbd: fix session reference leak on compounded SESSION_SETUP

In reply to Greg Kroah-Hartman

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

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

From: Ian Bridges <[email protected]>

commit 03bd8f5279e490e15e0c0f0fa388ffbd2fbacd65 upstream.

A compound request can place SESSION_SETUP after another command. That earlier command leaves a reference to its session in work->sess. smb2_sess_setup() then overwrites work->sess with the session it looks up or creates, and the dispatcher later puts work->sess only once. The inherited reference is never dropped. That leaks the session, together with its setup connection and socket, and every repeat of the compound leaks another.

unreferenced object (size 512):

    __kmalloc_cache_noprof+0x32c/0x3a0
    ksmbd_smb2_session_create+0xf6/0x9c0 [ksmbd]
    smb2_sess_setup+0xda4/0x6280 [ksmbd]
    handle_ksmbd_work+0x88c/0x1cb0 [ksmbd]

Save the inherited session on entry. After the request has been processed, release it once, but only when smb2_sess_setup() has replaced work->sess with its own session or cleared it. Do this after ksmbd_conn_unlock() so the put does not run under srv_mutex. An error path may instead leave the inherited session in work->sess. Keep it there, so the dispatcher still puts it and the error response is still signed or encrypted with it as before.

Fixes 7aa8804c0b67 ("ksmbd: fix user-after-free from session log off")
---
 fs/smb/server/smb2pdu.c |   12 ++++++++++++
 1 file changed, 12 insertions(+)
fs/smb/server/smb2pdu.c +12 -0
@@ -2438,6 +2438,8 @@ int smb2_sess_setup(struct ksmbd_work *w
 	struct smb2_sess_setup_req *req;
 	struct smb2_sess_setup_rsp *rsp;
 	struct ksmbd_session *sess = NULL;
+	struct ksmbd_session *prev_sess = work->sess;
+	bool installed = false;
 	struct negotiate_message *negblob;
 	unsigned int negblob_len, negblob_off;
 	int rc = 0;
@@ -2547,6 +2549,7 @@ int smb2_sess_setup(struct ksmbd_work *w
 			int sign_ret;
 
 			work->sess = sess;
+			installed = true;
 			if (sess->dialect >= SMB30_PROT_ID)
 				sign_ret = smb3_check_sign_req(work);
 			else
@@ -2599,6 +2602,7 @@ int smb2_sess_setup(struct ksmbd_work *w
 		conn->binding = false;
 	}
 	work->sess = sess;
+	installed = true;
 
 	negblob_off = le16_to_cpu(req->SecurityBufferOffset);
 	negblob_len = le16_to_cpu(req->SecurityBufferLength);
@@ -2786,6 +2790,14 @@ out_err:
 	}
 
 	ksmbd_conn_unlock(conn);
+
+	/*
+	 * Later in a compound, work->sess holds the reference that an
+	 * earlier command took. Drop it once this request has installed
+	 * its own session there or cleared it.
+	 */
+	if (prev_sess && (installed || !work->sess))
+		ksmbd_user_session_put(prev_sess);
 	return rc;
 }
 
author maintainer
#123 lore raw

PATCH 123/547 ksmbd: hold a connection reference for each session channel

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

commit add8d7fb04efe564193df73581889c62fc0016f1 upstream.

ksmbd_session_unregister() removes a session from the global and per- connection tables before dropping the table reference. A concurrent reference holder can keep the session and its channel list alive after those removals.

Connection cleanup can no longer find the unpublished session to remove its channels. Since a channel only stores a raw conn pointer, the connection can be freed while another session reference holder is still accessing it, for example during SMB3.1.1 binding or a procfs read.

Take a connection reference when registering a channel and release it on insertion failure, channel removal, or final session destruction. Keep the channels and signing keys until the session is destroyed so a response can still be signed after the session has been unregistered.

Fixes d7fd1f98607f ("ksmbd: follow SMB2 session expiration semantics")
---
 fs/smb/server/mgmt/user_session.c |    2 ++
 fs/smb/server/smb2pdu.c           |    3 ++-
 2 files changed, 4 insertions(+), 1 deletion(-)
fs/smb/server/mgmt/user_session.c +2 -0
@@ -273,6 +273,7 @@ static void free_channel_list(struct ksm
 	down_write(&sess->chann_lock);
 	xa_for_each(&sess->ksmbd_chann_list, index, chann) {
 		xa_erase(&sess->ksmbd_chann_list, index);
+		ksmbd_conn_put(chann->conn);
 		kfree_sensitive(chann);
 	}
 
@@ -601,6 +602,7 @@ static int ksmbd_chann_del(struct ksmbd_
 	if (!chann)
 		return -ENOENT;
 
+	ksmbd_conn_put(chann->conn);
 	kfree_sensitive(chann);
 	return 0;
 }
fs/smb/server/smb2pdu.c +2 -1
@@ -116,11 +116,12 @@ static int register_session_channel(stru
 		goto out;
 	}
 
-	chann->conn = conn;
+	chann->conn = ksmbd_conn_get(conn);
 	memcpy(chann->sess_key, sess_key, sizeof(chann->sess_key));
 	old = xa_store(&sess->ksmbd_chann_list, (long)conn, chann,
 		       KSMBD_DEFAULT_GFP);
 	if (xa_is_err(old)) {
+		ksmbd_conn_put(chann->conn);
 		kfree_sensitive(chann);
 		rc = xa_err(old);
 	}
author maintainer
#124 lore raw

PATCH 124/547 ksmbd: ignore network devices of other namespaces

In reply to Greg Kroah-Hartman

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

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

From: Jan Koester <[email protected]>

commit 1f5ce2b8b9164b3fcb93a18fe1e7b451c2fc6eea upstream.

With no interface list configured, ksmbd binds every interface that comes up. ksmbd_netdev_event() does not look at the device's namespace, and create_socket() opens the listener in the namespace of the task raising NETDEV_UP. A container with its own address on a bridge brings up its interface and finds port 445 in its namespace already taken by ksmbd, so an SMB server running inside the container fails with "Address already in use".

Interfaces are also matched by name only, so a container's eth0 going down would stop the listener on the host's eth0.

Only handle netdev events for devices in init_net.

Fixes 0626e6641f6b ("cifsd: add server handler for central processing and tranport layers")
---
 fs/smb/server/transport_tcp.c |    9 +++++++++
 1 file changed, 9 insertions(+)
fs/smb/server/transport_tcp.c +9 -0
@@ -577,6 +577,15 @@ static int ksmbd_netdev_event(struct not
 	struct interface *iface;
 	int ret;
 
+	/*
+	 * ksmbd serves the initial namespace only. create_socket() listens in
+	 * the namespace of the task raising the event, so a container bringing
+	 * up its own interface would get a listener on its port 445, and the
+	 * name-only interface lookup would let its interfaces stop ours.
+	 */
+	if (!net_eq(dev_net(netdev), &init_net))
+		return NOTIFY_DONE;
+
 	switch (event) {
 	case NETDEV_UP:
 		if (netif_is_bridge_port(netdev))
author maintainer
#125 lore raw

PATCH 125/547 ksmbd: limit sessions on each connection

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

commit dc6aa1ba8b7fff8800ad9bf143f17d308e02ec68 upstream.

The pending setup limit only counts InProgress sessions. A client can complete authentication repeatedly and retain an unbounded number of Valid sessions on one connection.

Reserve a connection slot before allocating a session and retain a connection reference while authentication is in progress. The first SMB3 channel takes over that reservation; binding to another connection reserves one slot there. Reauthentication and authentication continuation reuse the existing reservation. Return slots on allocation or insertion failure, channel removal, and final session destruction.

Accept max_sessions_per_connection in reserved startup-request space and default to 64 when older tools leave it zero. Keep the request size and existing field offsets unchanged. Expose the configured limit in procfs. The existing connection limits bound the aggregate number of sessions without a separate global session allocation limit.

Fixes d7fd1f98607f ("ksmbd: follow SMB2 session expiration semantics")
---
 fs/smb/server/connection.c        |    1 
 fs/smb/server/connection.h        |    2 +
 fs/smb/server/ksmbd_netlink.h     |    3 +-
 fs/smb/server/mgmt/user_session.c |   50 +++++++++++++++++++++++++++++++-------
 fs/smb/server/mgmt/user_session.h |    6 +++-
 fs/smb/server/proc.c              |    2 +
 fs/smb/server/server.c            |    2 +
 fs/smb/server/server.h            |    3 ++
 fs/smb/server/smb2pdu.c           |   16 +++++++++++-
 fs/smb/server/transport_ipc.c     |    7 +++++
 10 files changed, 80 insertions(+), 12 deletions(-)
fs/smb/server/connection.c +1 -0
@@ -306,6 +306,7 @@ struct ksmbd_conn *ksmbd_conn_alloc(void
 	atomic_set(&conn->req_running, 0);
 	atomic_set(&conn->r_count, 0);
 	atomic_set(&conn->refcnt, 1);
+	atomic64_set(&conn->session_count, 0);
 	conn->total_credits = 1;
 	conn->outstanding_credits = 0;
 
fs/smb/server/connection.h +2 -0
@@ -77,6 +77,8 @@ struct ksmbd_conn {
 	struct rw_semaphore		session_lock;
 	/* smb session 1 per user */
 	struct xarray			sessions;
+	/* New sessions and SMB3 channels each reserve one connection slot. */
+	atomic64_t			session_count;
 	unsigned long			creation_time;
 	unsigned long			last_active;
 	/* How many request are running currently */
fs/smb/server/ksmbd_netlink.h +2 -1
@@ -114,7 +114,8 @@ struct ksmbd_startup_request {
 	__s8	bind_interfaces_only;
 	__u32	max_ip_connections;	/* Number of maximum connection per ip address */
 	__s8	aapl_model[32];		/* AAPL model string for Finder icon, e.g. "Xserve" */
-	__s8	reserved[467];		/* Reserved room */
+	__u32	max_sessions_per_connection; /* Maximum sessions per connection */
+	__s8	reserved[463];		/* Reserved room */
 	__u32	ifc_list_sz;		/* interfaces list size */
 	__s8	____payload[];
 } __packed;
fs/smb/server/mgmt/user_session.c +41 -9

126 lines not on this page · raw message

fs/smb/server/mgmt/user_session.h +5 -1
@@ -37,6 +37,8 @@ struct ksmbd_session {
 	char				ClientGUID[SMB2_CLIENT_GUID_SIZE];
 
 	struct ksmbd_user		*user;
+	/* Holds the connection slot until an SMB3 channel takes it over. */
+	struct ksmbd_conn		*setup_conn;
 	unsigned int			sequence_number;
 	unsigned int			flags;
 
@@ -89,7 +91,9 @@ static inline void clear_session_flag(st
 	sess->flags &= ~bit;
 }
 
-struct ksmbd_session *ksmbd_smb2_session_create(void);
+struct ksmbd_session *ksmbd_smb2_session_create(struct ksmbd_conn *conn);
+int ksmbd_session_reserve_slot(struct ksmbd_conn *conn);
+void ksmbd_session_release_slot(struct ksmbd_conn *conn);
 
 void ksmbd_session_destroy(struct ksmbd_session *sess);
 
fs/smb/server/proc.c +2 -0
@@ -161,6 +161,8 @@ static int proc_show_ksmbd_stats(struct
 	seq_printf(m, "max_connections:\t%u\n", server_conf.max_connections);
 	seq_printf(m, "max_connections_per_ip:\t%u\n",
 		   server_conf.max_ip_connections);
+	seq_printf(m, "max_sessions_per_connection:\t%u\n",
+		   server_conf.max_sessions_per_connection);
 	seq_printf(m, "max_inflight_requests:\t%u\n",
 		   server_conf.max_inflight_req);
 	seq_printf(m, "deadtime_seconds:\t%lu\n", server_conf.deadtime / HZ);
fs/smb/server/server.c +2 -0
@@ -456,6 +456,8 @@ static int server_conf_init(void)
 				KSMBD_AUTH_MSKRB5;
 #endif
 	server_conf.max_inflight_req = SMB2_MAX_CREDITS;
+	server_conf.max_sessions_per_connection =
+		KSMBD_DEFAULT_MAX_SESSIONS_PER_CONNECTION;
 	return 0;
 }
 
fs/smb/server/server.h +3 -0
@@ -8,6 +8,8 @@
 
 #include "smbacl.h"
 
+#define KSMBD_DEFAULT_MAX_SESSIONS_PER_CONNECTION	64
+
 /*
  * Server state type
  */
@@ -44,6 +46,7 @@ struct ksmbd_server_config {
 	unsigned int		max_connections;
 	unsigned int		max_inflight_req;
 	unsigned int		max_ip_connections;
+	unsigned int		max_sessions_per_connection;
 
 	char			*conf[SERVER_CONF_WORK_GROUP + 1];
 	struct task_struct	*dh_task;
fs/smb/server/smb2pdu.c +15 -1
@@ -116,14 +116,28 @@ static int register_session_channel(stru
 		goto out;
 	}
 
+	if (sess->setup_conn != conn) {
+		rc = ksmbd_session_reserve_slot(conn);
+		if (rc) {
+			kfree_sensitive(chann);
+			goto out;
+		}
+	}
+
 	chann->conn = ksmbd_conn_get(conn);
 	memcpy(chann->sess_key, sess_key, sizeof(chann->sess_key));
 	old = xa_store(&sess->ksmbd_chann_list, (long)conn, chann,
 		       KSMBD_DEFAULT_GFP);
 	if (xa_is_err(old)) {
+		if (sess->setup_conn != conn)
+			ksmbd_session_release_slot(conn);
 		ksmbd_conn_put(chann->conn);
 		kfree_sensitive(chann);
 		rc = xa_err(old);
+	} else if (sess->setup_conn == conn) {
+		/* Transfer the initial reservation and reference to this channel. */
+		sess->setup_conn = NULL;
+		ksmbd_conn_put(conn);
 	}
 out:
 	up_write(&sess->chann_lock);
@@ -2461,7 +2475,7 @@ int smb2_sess_setup(struct ksmbd_work *w
 
 	ksmbd_conn_lock(conn);
 	if (!req->hdr.SessionId) {
-		sess = ksmbd_smb2_session_create();
+		sess = ksmbd_smb2_session_create(conn);
 		if (!sess) {
 			rc = -ENOMEM;
 			goto out_err;
fs/smb/server/transport_ipc.c +7 -0
@@ -353,6 +353,13 @@ static int ipc_server_config_on_startup(
 	if (req->max_ip_connections)
 		server_conf.max_ip_connections = req->max_ip_connections;
 
+	if (req->max_sessions_per_connection)
+		server_conf.max_sessions_per_connection =
+			req->max_sessions_per_connection;
+	else
+		server_conf.max_sessions_per_connection =
+			KSMBD_DEFAULT_MAX_SESSIONS_PER_CONNECTION;
+
 	ret = ksmbd_set_netbios_name(req->netbios_name);
 	ret |= ksmbd_set_server_string(req->server_string);
 	ret |= ksmbd_set_work_group(req->work_group);
author maintainer
#126 lore raw

PATCH 126/547 ksmbd: preserve unreadable named streams on open

In reply to Greg Kroah-Hartman

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

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

From: DaeMyung Kang <[email protected]>

commit 80c816c047f7cae3c99cc75740c1f5d2c4d97b45 upstream.

A write-only client can open an existing named stream with FILE_OPEN_IF without permission to read the underlying file. The case-insensitive lookup finds the xattr name, but querying its value length then fails with -EACCES. smb2_set_stream_name_xattr() treats every negative result as a missing stream and replaces the existing xattr with an empty value.

A failed xattr list is not proof that the stream is absent either:
for example, -ENOMEM can lead to the same empty replacement. Preserve listing errors and create a stream only for -ENOENT or -ENODATA. The latter can occur if the xattr is removed between listing its name and querying its value. Return other lookup errors without changing the stream.

A write-only FILE_OPEN now reports access denied instead of name not found. FILE_OVERWRITE_IF and FILE_SUPERSEDE on an unreadable stream also fail instead of appearing to replace it. Stream writes and EOF changes already need to read the old value, so such handles cannot update the stream after opening either.

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
---
 fs/smb/server/smb2pdu.c |    2 ++
 fs/smb/server/vfs.c     |    6 +++++-
 2 files changed, 7 insertions(+), 1 deletion(-)
fs/smb/server/smb2pdu.c +2 -0
@@ -3428,6 +3428,8 @@ static noinline int smb2_set_stream_name
 				     xattr_stream_size);
 	if (rc >= 0)
 		return 0;
+	if (rc != -ENOENT && rc != -ENODATA)
+		return rc;
 
 	if (fp->cdoption == FILE_OPEN_LE) {
 		if (!strcmp(stream_name, "AFP_AfpInfo") &&
fs/smb/server/vfs.c +5 -1
@@ -1912,7 +1912,11 @@ ssize_t ksmbd_vfs_casexattr_len(struct m
 	ssize_t value_len = -ENOENT, xattr_list_len;
 
 	xattr_list_len = ksmbd_vfs_listxattr(dentry, &xattr_list);
-	if (xattr_list_len <= 0)
+	if (xattr_list_len < 0) {
+		value_len = xattr_list_len;
+		goto out;
+	}
+	if (!xattr_list_len)
 		goto out;
 
 	for (name = xattr_list; name - xattr_list < xattr_list_len;
author maintainer
#127 lore raw

PATCH 127/547 ksmbd: prevent session binding in compound requests

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

commit 19f8fd6b5ced33b02a083759e6901f9d6e8076df upstream.

A failed multichannel binding can retain its target session on the work item so that the error response can be signed. Subsequent compound commands can then use that session together with a tree connection left over from an earlier command.

Limit binding SESSION_SETUP requests to standalone messages during message validation, before smb2_sess_setup() can replace work->sess. Check both NextCommand and the current request offset to cover binding in the first, middle and last positions of a compound. The existing validation error path returns STATUS_INVALID_PARAMETER and stops processing the remaining commands.

This intentionally limits support for compounded binding. It is not a protocol requirement that binding be standalone. Standalone binding and non-binding compounds retain their existing behavior, without changing session, tree or response encryption handling.

Fixes 4b706360ffb7 ("ksmbd: fix multichannel binding and enforce channel limit")
---
 fs/smb/server/smb2misc.c |    8 ++++++++
 1 file changed, 8 insertions(+)
fs/smb/server/smb2misc.c +8 -0
@@ -501,6 +501,14 @@ int ksmbd_smb2_check_message(struct ksmb
 	if (req_struct_size > len + 1)
 		return 1;
 
+	if (command == SMB2_SESSION_SETUP_HE &&
+	    (work->next_smb2_rcv_hdr_off || next_cmd)) {
+		struct smb2_sess_setup_req *req = (void *)hdr;
+
+		if (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)
+			return 1;
+	}
+
 	if (smb2_calc_size(hdr, &clc_len))
 		return 1;
 
author maintainer
#128 lore raw

PATCH 128/547 ksmbd: prevent share root removal through empty paths

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

commit 9fd1fcbbf84986a7bcf601a2b90540899069d263 upstream.

A FileLinkInformation request can supply "/" as the new link name. smb2_get_name() strips the trailing slash and passes an empty string to ksmbd_vfs_kern_path_start_removing().

ksmbd_vfs_path_lookup() resolves an empty pathname as the configured share path, without LOOKUP_BENEATH. With ReplaceIfExists set, smb2_create_link() can therefore remove the share root from its parent before link creation fails. An authenticated client with a writable share and DELETE access to a file can trigger this if the share root is empty and the mapped user has write and search permission on its parent directory.

Return -EINVAL for empty pathnames when for_remove is set, before resolving the share path or acquiring removal resources. Ordinary lookups continue to accept empty pathnames for opening the share root.

Fixes 74d7970febf7 ("ksmbd: fix racy issue from using ->d_parent and ->d_name")
---
 fs/smb/server/vfs.c |    4 ++++
 1 file changed, 4 insertions(+)
fs/smb/server/vfs.c +4 -0
@@ -61,6 +61,10 @@ static int ksmbd_vfs_path_lookup(struct
 	struct dentry *d;
 
 	if (pathname[0] == '\0') {
+		/* The share root must never be removed. */
+		if (for_remove)
+			return -EINVAL;
+
 		pathname = share_conf->path;
 		root_share_path = NULL;
 	} else {
author maintainer
#129 lore raw

PATCH 129/547 ksmbd: prevent stale data from being written by SMB2 WRITE requests

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

commit bc0e0f5ac1d7b044d403f859406b4b66d4b1ce9b upstream.

Initialize the compatibility byte in request buffers without zeroing the entire allocation. Keep the one-byte compatibility exception for SMB2 messages so valid zero-length WRITE requests remain compatible, and validate the data range in the WRITE handlers against the current compound request before accessing it.

This prevents stale request-buffer data from being written to files or sent to IPC pipes.

Fixes 443d61d1fa9f ("ksmbd: allocate one more byte for implied bcc[0]")
---
 fs/smb/server/compress.c   |    1 +
 fs/smb/server/connection.c |    1 +
 fs/smb/server/smb2pdu.c    |   27 ++++++++++++++++++---------
 3 files changed, 20 insertions(+), 9 deletions(-)
fs/smb/server/compress.c +1 -0
@@ -65,6 +65,7 @@ static int __ksmbd_decompress_request(st
 		return -ENOMEM;
 
 	*(__be32 *)out = cpu_to_be32(out_size);
+	out[out_size + 4] = 0;
 	rc = smb_compression_decompress(conn->compress_algorithm,
 					conn->compress_chained,
 					conn->compress_pattern,
fs/smb/server/connection.c +1 -0
@@ -753,6 +753,7 @@ recheck:
 		if (!conn->request_buf)
 			break;
 
+		conn->request_buf[pdu_size + 4] = 0;
 		memcpy(conn->request_buf, hdr_buf, sizeof(hdr_buf));
 
 		/*
fs/smb/server/smb2pdu.c +18 -9
@@ -9303,23 +9303,25 @@ static noinline int smb2_write_pipe(stru
 	int err = 0, ret = 0;
 	char *data_buf;
 	size_t length;
+	unsigned int data_offset, req_len;
 
 	WORK_BUFFERS(work, req, rsp);
 
 	length = le32_to_cpu(req->Length);
 	id = req->VolatileFileId;
+	data_offset = le16_to_cpu(req->DataOffset);
+	req_len = smb2_current_req_len(work, &req->hdr);
 
-	if ((u64)le16_to_cpu(req->DataOffset) + length >
-	    get_rfc1002_len(work->request_buf)) {
-		pr_err("invalid write data offset %u, smb_len %u\n",
-		       le16_to_cpu(req->DataOffset),
-		       get_rfc1002_len(work->request_buf));
+	if (data_offset < offsetof(struct smb2_write_req, Buffer) ||
+	    data_offset > req_len || length > req_len - data_offset) {
+		pr_err("invalid write data offset %u, length %zu, req_len %u\n",
+		       data_offset, length, req_len);
 		err = -EINVAL;
 		goto out;
 	}
 
 	data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
-			   le16_to_cpu(req->DataOffset));
+			   data_offset);
 
 	rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
 	if (rpc_resp) {
@@ -9606,14 +9608,21 @@ int smb2_write(struct ksmbd_work *work)
 		writethrough = true;
 
 	if (is_rdma_channel == false) {
-		if (le16_to_cpu(req->DataOffset) <
-		    offsetof(struct smb2_write_req, Buffer)) {
+		unsigned int data_offset = le16_to_cpu(req->DataOffset);
+		unsigned int req_len = smb2_current_req_len(work, &req->hdr);
+
+		if (data_offset < offsetof(struct smb2_write_req, Buffer) ||
+		    data_offset > req_len ||
+		    length > req_len - data_offset) {
+			ksmbd_debug(SMB,
+				    "invalid write data offset %u, length %zu, req_len %u\n",
+				    data_offset, length, req_len);
 			err = -EINVAL;
 			goto out;
 		}
 
 		data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
-				    le16_to_cpu(req->DataOffset));
+				    data_offset);
 
 		ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
 			    fp->filp, offset, length);
author maintainer
#130 lore raw

PATCH 130/547 ksmbd: reclaim ended sessions on logoff and expiration

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

commit 26534ef335e92b028eb58e44d98d46a0e26af0ec upstream.

LOGOFF and previous-session replacement leave sessions Expired with a zero credential expiry. Ended sessions can retain their memory and connection slots when no further setup arrives on the owning connection.

Unpublish a logged-off session while the request reference keeps its response signing and encryption keys alive. Remove its procfs entry before dropping the table reference so a reader cannot remove its own entry on the last put. Clear proc_entry after removal to avoid removing it twice.

Reclaim ended sessions from the global table in the existing expiration worker before it acquires conn_list_lock. Only select Expired sessions with zero credential expiry and no references beyond the table reference. Keep sessions whose Kerberos credentials expired available for reauthentication.

Unlink the session from its setup connection and all channel connections, so SMB2 sessions and sessions with only secondary SMB3 channels are covered. The session already holds connection references, and sessions_table_lock prevents concurrent channel removal. Queue sessions on a separate disposal list, leaving their hash nodes unhashed, and remove procfs entries and drop table references outside the locks.

Keep the pending setup check before allocating a new session so abandoned InProgress sessions can release their slots even at the connection limit. Retain the timeout and reference checks and dispose of those sessions outside the locks. Leave ended Expired sessions to the expiration worker.

Fixes d7fd1f98607f ("ksmbd: follow SMB2 session expiration semantics")
---
 fs/smb/server/connection.c        |    1 
 fs/smb/server/mgmt/user_session.c |   94 ++++++++++++++++++++++++++++++--------
 fs/smb/server/mgmt/user_session.h |    3 +
 fs/smb/server/smb2pdu.c           |    7 ++
 4 files changed, 86 insertions(+), 19 deletions(-)
fs/smb/server/connection.c +1 -0
@@ -642,6 +642,7 @@ static void ksmbd_session_expiration_wor
 		goto reschedule;
 
 	ksmbd_expire_sessions();
+	ksmbd_reclaim_ended_sessions();
 
 	/*
 	 * An old connection without a Valid or Expired session must be
fs/smb/server/mgmt/user_session.c +75 -19

171 lines not on this page · raw message

fs/smb/server/mgmt/user_session.h +3 -0
@@ -53,6 +53,7 @@ struct ksmbd_session {
 	u64				kerberos_expiry;
 
 	struct hlist_node		hlist;
+	struct list_head		dispose_entry;
 	struct rw_semaphore		chann_lock;
 	struct xarray			ksmbd_chann_list;
 	struct xarray			tree_conns;
@@ -102,6 +103,7 @@ struct ksmbd_session *ksmbd_session_look
 					   unsigned long long id);
 bool is_ksmbd_session_in_connection(struct ksmbd_conn *conn,
 				     unsigned long long id);
+bool ksmbd_too_many_session_setups(struct ksmbd_conn *conn);
 int ksmbd_session_register(struct ksmbd_conn *conn,
 			   struct ksmbd_session *sess);
 void ksmbd_session_unregister(struct ksmbd_conn *conn,
@@ -109,6 +111,7 @@ void ksmbd_session_unregister(struct ksm
 void ksmbd_conn_sessions_cleanup(struct ksmbd_conn *conn);
 bool ksmbd_conn_has_valid_or_expired_session(struct ksmbd_conn *conn);
 void ksmbd_expire_sessions(void);
+void ksmbd_reclaim_ended_sessions(void);
 struct ksmbd_session *__session_lookup(unsigned long long id);
 struct ksmbd_session *ksmbd_session_lookup_all(struct ksmbd_conn *conn,
 					       unsigned long long id);
fs/smb/server/smb2pdu.c +7 -0
@@ -2475,6 +2475,11 @@ int smb2_sess_setup(struct ksmbd_work *w
 
 	ksmbd_conn_lock(conn);
 	if (!req->hdr.SessionId) {
+		/* Bound abandoned SessionId-zero authentication exchanges. */
+		if (ksmbd_too_many_session_setups(conn)) {
+			rc = -ENOSPC;
+			goto out_err;
+		}
 		sess = ksmbd_smb2_session_create(conn);
 		if (!sess) {
 			rc = -ENOMEM;
@@ -3173,6 +3178,8 @@ int smb2_session_logoff(struct ksmbd_wor
 	up_write(&conn->session_lock);
 
 	ksmbd_all_conn_set_status(sess, KSMBD_SESS_NEED_SETUP);
+	/* Drop the table reference while work->sess pins the response keys. */
+	ksmbd_session_unregister(conn, sess);
 
 	if (err)
 		return err;
author maintainer
#131 lore raw

PATCH 131/547 ksmbd: reserve space for the UTF-16 terminator in stream info

In reply to Greg Kroah-Hartman

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

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

From: Abdifatah Suruur <[email protected]>

commit a025c4991a7d83edc4dd339e3ea86d8ff6226eca upstream.

smb_strtoUTF16() always writes a terminating zero UTF-16 unit after the converted characters, but get_file_stream_info() budgets only sizeof(struct smb2_file_stream_info) + streamlen * 2 for a stream entry and sizeof(struct smb2_file_stream_info) + 7 * 2 for the trailing "::$DATA" entry. When an entry exactly fills the 448-byte small response buffer, the terminator is written two bytes past the allocation.

Reserve one extra UTF-16 unit in both budget checks. The terminator is not part of the wire format, so the reported lengths are unchanged.

---
 fs/smb/server/smb2pdu.c |    5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
fs/smb/server/smb2pdu.c +3 -2
@@ -6936,7 +6936,8 @@ static int get_file_stream_info(struct k
 				     ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
 
 		next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
-		if (next > buf_free_len) {
+		/* smbConvertToUTF16() also writes a terminating UTF-16 unit. */
+		if (next + sizeof(__le16) > buf_free_len) {
 			kfree(stream_buf);
 			break;
 		}
@@ -6970,7 +6971,7 @@ static int get_file_stream_info(struct k
 
 out:
 	if (!S_ISDIR(stat.mode) &&
-	    buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
+	    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,
author maintainer
#132 lore raw

PATCH 132/547 ksmbd: restore Kerberos logins with released ksmbd-tools

In reply to Greg Kroah-Hartman

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

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

From: Michail Andreas Michalopoulos <[email protected]>

commit 0fec4c24e1979032d7b7c159d9e5c45c7444e0f2 upstream.

Commit a47634cd729b ("ksmbd: expire SMB sessions when Kerberos tickets expire") added a __u64 session_expiry field to struct ksmbd_spnego_authen_response, growing it from 156 to 168 bytes. ipc_validate_msg() requires the response to have exactly that size, so the 156-byte response of every released ksmbd-tools, up to 3.5.7, is dropped and Kerberos session setup fails with STATUS_LOGON_FAILURE. The other way round, kernels without that commit, including the stable trees, drop the 168-byte response of current ksmbd-tools master, and ksmbd-tools has no way to tell which layout a kernel expects.

Pass the expiry in the reserved area of the embedded struct ksmbd_login_response instead. ksmbd-tools releases with that area (3.4.4 and later) allocate the response zeroed and never write to it, so they send an expiry of 0, which ksmbd already treats as no expiry. The response is 156 bytes again, so it works with those releases, and every kernel also accepts a response that sets the expiry. Use two __u32 halves, as the reserved area is only 4-byte aligned.

---
 fs/smb/server/auth.c          | 3 ++-
 fs/smb/server/ksmbd_netlink.h | 5 +++--
 2 files changed, 5 insertions(+), 3 deletions(-)
fs/smb/server/auth.c +2 -1
index 88953315b160..0c51ca0cb14d 100644
@@ -463,7 +463,8 @@ int ksmbd_krb5_authenticate(struct ksmbd_session *sess, char *in_blob,
 	memcpy(out_blob, resp->payload + resp->session_key_len,
 	       resp->spnego_blob_len);
 	*out_len = resp->spnego_blob_len;
-	sess->kerberos_expiry = resp->session_expiry;
+	sess->kerberos_expiry = (u64)resp->login_response.session_expiry_hi << 32 |
+				resp->login_response.session_expiry_lo;
 	retval = 0;
 out:
 	kvfree_sensitive(resp, sizeof(*resp) + resp->session_key_len +
fs/smb/server/ksmbd_netlink.h +3 -2
index 93ebf3f6fbef..ad050988659e 100644
@@ -149,7 +149,9 @@ struct ksmbd_login_response {
 	__u16	status;
 	__u16	hash_sz;			/* hash size */
 	__s8	hash[KSMBD_REQ_MAX_HASH_SZ];	/* password hash */
-	__u32	reserved[16];			/* Reserved room */
+	__u32	session_expiry_lo;	/* Kerberos ticket expiry, SPNEGO only */
+	__u32	session_expiry_hi;
+	__u32	reserved[14];			/* Reserved room */
 };
 
 /*
@@ -287,7 +289,6 @@ struct ksmbd_spnego_authen_response {
 				  * stored in SecurityBuffer of SMB2 SESSION
 				  * SETUP response
 				  */
-	__u64	session_expiry;	/* Kerberos ticket expiry time */
 	__u8	payload[]; /* session key + AP_REP */
 };
 
Signature · 1 line
2.56.0
author maintainer
#133 lore raw

PATCH 133/547 ksmbd: return end of file for reads past a named streams data

In reply to Greg Kroah-Hartman

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

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

From: DaeMyung Kang <[email protected]>

commit 626611dc22a3b63b3264a7a797d9dbc530234fcd upstream.

A READ on a non-empty named stream at or beyond its end fails with STATUS_INVALID_PARAMETER. ksmbd_vfs_stream_read() returns -EINVAL when the offset is not below the stream length, and smb2_read() maps -EINVAL to that status.

smb2_read() already turns a zero-byte read into STATUS_END_OF_FILE, the status a regular file returns at its end, and an empty stream already takes that path. Return 0 instead of -EINVAL so that non-empty streams do the same. Clients that read a stream until end of file otherwise get an error once they have read all of its data.

The buffered copychunk path converts a zero-byte source read to -EIO, as it does for a regular file that shrinks during copying.

Fixes 2ae1a6cc4302 ("cifsd: fix potential read overflow in ksmbd_vfs_stream_read()")
---
 fs/smb/server/vfs.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/smb/server/vfs.c +1 -1
@@ -272,7 +272,7 @@ static int ksmbd_vfs_stream_read(struct
 		return (int)v_len;
 
 	if (v_len <= *pos) {
-		count = -EINVAL;
+		count = 0;
 		goto free_buf;
 	}
 
author maintainer
#134 lore raw

PATCH 134/547 ksmbd: use u8 for SMB2 oplock level values

In reply to Greg Kroah-Hartman

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

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

From: Karl Mehltretter <[email protected]>

commit f622fedabbb58c8006ee21373968ae07bf8a9467 upstream.

The SMB2 oplock level is an unsigned 8-bit wire value, but smb20_oplock_break_ack() stores it in a plain char. On architectures where plain char is signed, the value 0xff becomes -1 and cannot compare equal to SMB2_OPLOCK_LEVEL_LEASE (0xff). The acknowledgment is consequently rejected with STATUS_INVALID_OPLOCK_PROTOCOL instead of the intended STATUS_INVALID_PARAMETER.

Use u8 for the request and response oplock-level variables. This preserves all wire values in their original representation.

Fixes 80a56d4a826c ("ksmbd: align SMB2 oplock break ack handling")
Assisted-by LLM
---
 fs/smb/server/smb2pdu.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/smb/server/smb2pdu.c +1 -1
@@ -11488,7 +11488,7 @@ static void smb20_oplock_break_ack(struc
 	__le32 status = STATUS_SUCCESS;
 	int ret;
 	u64 volatile_id, persistent_id;
-	char req_oplevel = 0, rsp_oplevel = 0;
+	u8 req_oplevel = 0, rsp_oplevel = 0;
 
 	WORK_BUFFERS(work, req, rsp);
 
author maintainer
#135 lore raw

PATCH 135/547 ksmbd: validate AppInstanceId takeover target

In reply to Greg Kroah-Hartman

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

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

From: Sung Byeongchan <[email protected]>

commit e0386cd6498b9c63f8c6d10b3e08670b92c0f3f1 upstream.

AppInstanceId lookup currently selects the first open with the matching identifier. CREATE for an unrelated share or path can therefore force-close another session's open before authorization of the new target. Matching only the base path also conflates alternate data streams with the unnamed stream.

MS-SMB2 requires the old open to match the share and path, belong to a different ClientGuid, and be closed only when the requester has GENERIC_READ access. Search all opens with the ID and match share, resolved path, stream, and the current connection's client GUID. Retain a share configuration reference in ksmbd_file and reuse its name instead of allocating a name for every open. This keeps matching safe during tree connection teardown and preserves name-based matching across configuration updates.

Refresh the share reference on durable reconnect and restore the old reference if reopening fails. Serialize connection and share comparisons with durable disconnect/reconnect, and recheck the target before closing it. Keep the original ClientGuid for durable replay and lease checks.

Check AppInstanceVersion before querying access, even when GENERIC_READ is absent, and before disconnected delete-on-close cleanup. Rejected CREATE must leave other durable opens untouched. Calculate maximal access on the matched open's referenced path so a rename cannot substitute another file's authorization. Require read access with the effective VFS credentials as well as the NT DACL before takeover. Access denial only skips takeover and leaves CREATE to its normal access checks. Restore filesystem credentials before returning a takeover error.

Handle takeover before checking FILE_CREATE collisions, and re-resolve the path after closing the old open. This lets delete-on-close remove the old file before a new one is created. Include SYNCHRONIZE in the baseline maximal-access mask so read-only files report GENERIC_READ correctly.

Fixes 16c30649709d ("ksmbd: handle durable v2 app instance id")
Assisted-by LLM
---
 fs/smb/server/smb2pdu.c   |  123 ++++++++++++++++++++++++++++++++++++++++------
 fs/smb/server/vfs.c       |    5 +
 fs/smb/server/vfs_cache.c |   77 ++++++++++++++++++++--------
 fs/smb/server/vfs_cache.h |   10 ++-
 4 files changed, 175 insertions(+), 40 deletions(-)
fs/smb/server/smb2pdu.c +108 -15
@@ -4116,18 +4116,76 @@ static int parse_app_instance_version(st
 	return 0;
 }
 
-static int smb2_handle_app_instance_id(struct smb2_create_rsp *rsp,
-				       struct durable_info *dh_info)
+static int smb2_app_instance_stream_matches(struct ksmbd_file *fp,
+					    char *stream_name, int s_type,
+					    bool *matches)
 {
+	char *xattr_stream_name;
+	size_t xattr_stream_size;
+	int rc;
+
+	if (!stream_name) {
+		*matches = !ksmbd_stream_fd(fp);
+		return 0;
+	}
+
+	rc = ksmbd_vfs_xattr_stream_name(stream_name, &xattr_stream_name,
+					 &xattr_stream_size, s_type);
+	if (rc)
+		return rc;
+
+	*matches = fp->stream.name && fp->stream.size >= 0 &&
+		   (size_t)fp->stream.size == xattr_stream_size &&
+		   !strncasecmp(fp->stream.name, xattr_stream_name,
+				xattr_stream_size);
+	kfree(xattr_stream_name);
+	return 0;
+}
+
+static int smb2_handle_app_instance_id(struct ksmbd_work *work,
+				       struct smb2_create_rsp *rsp,
+				       struct durable_info *dh_info,
+				       const struct path *path,
+				       char *stream_name, int s_type,
+				       bool *closed)
+{
+	struct ksmbd_conn *conn = work->conn;
 	struct ksmbd_file *old_fp;
-	bool reject = false;
+	const struct path *old_path;
+	char *app_instance_id;
+	__le32 maximal_access = FILE_MAXIMAL_ACCESS_LE;
+	bool reject = false, stream_matches;
+	int cursor = 0, rc;
 
+	*closed = false;
 	if (!dh_info->app_instance_id)
 		return 0;
+	app_instance_id = dh_info->AppInstanceId;
 
-	old_fp = ksmbd_lookup_fd_app_instance_id(dh_info->AppInstanceId);
-	if (!old_fp)
-		return 0;
+	while (true) {
+		old_fp = ksmbd_lookup_fd_app_instance_id_next(app_instance_id,
+							      &cursor);
+		if (!old_fp)
+			return 0;
+
+		if (!ksmbd_app_instance_id_matches(work, old_fp) ||
+		    !path_equal(&old_fp->filp->f_path, path)) {
+			ksmbd_put_durable_fd(old_fp);
+			continue;
+		}
+
+		rc = smb2_app_instance_stream_matches(old_fp, stream_name,
+						      s_type, &stream_matches);
+		if (rc) {
+			ksmbd_put_durable_fd(old_fp);
+			return rc;
+		}
+		if (!stream_matches) {
+			ksmbd_put_durable_fd(old_fp);
+			continue;
+		}
+		break;
+	}
 
 	if (dh_info->app_instance_version_valid) {
 		if (old_fp->app_instance_version_valid &&
@@ -4142,13 +4200,34 @@ static int smb2_handle_app_instance_id(s
 		reject = true;
 	}
 
-	ksmbd_put_durable_fd(old_fp);
 	if (reject) {
+		ksmbd_put_durable_fd(old_fp);
 		rsp->hdr.Status = STATUS_FILE_FORCED_CLOSED;
 		return -EIO;
 	}
 
-	return ksmbd_close_fd_app_instance_id(dh_info->AppInstanceId);
+	/* Authorize the referenced open even if its name changes meanwhile. */
+	old_path = &old_fp->filp->f_path;
+	rc = smb_check_perm_dacl(conn, old_path, &maximal_access, 0,
+				 work->sess->user->uid, false);
+	if (rc) {
+		/* Access denial prevents takeover, not the CREATE itself. */
+		ksmbd_put_durable_fd(old_fp);
+		return rc == -EACCES ? 0 : rc;
+	}
+	if (maximal_access == FILE_MAXIMAL_ACCESS_LE)
+		ksmbd_vfs_query_maximal_access(mnt_idmap(old_path->mnt),
+					       old_path->dentry, &maximal_access);
+	/* Also require read access with the effective VFS credentials. */
+	if ((le32_to_cpu(maximal_access) & GENERIC_READ_FLAGS) !=
+	    GENERIC_READ_FLAGS ||
+	    inode_permission(mnt_idmap(old_path->mnt),
+			     d_inode(old_path->dentry), MAY_OPEN | MAY_READ)) {
+		ksmbd_put_durable_fd(old_fp);
+		return 0;
+	}
+
+	return ksmbd_close_fd_app_instance_id(work, old_fp, closed);
 }
 
 /**
@@ -4188,6 +4267,7 @@ int smb2_open(struct ksmbd_work *work)
 	char *name = NULL;
 	char *stream_name = NULL;
 	bool file_present = false, created = false, already_permitted = false;
+	bool app_instance_id_checked = false, app_instance_closed;
 	int share_ret, need_truncate = 0;
 	u64 time, alloc_size = 0;
 	umode_t posix_mode = 0;
@@ -4362,13 +4442,6 @@ int smb2_open(struct ksmbd_work *work)
 		}
 	}
 
-	if (dh_info.app_instance_id && !dh_info.reconnected &&
-	    !dh_info.replay) {
-		rc = smb2_handle_app_instance_id(rsp, &dh_info);
-		if (rc)
-			goto err_out2;
-	}
-
 	if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
 		pr_err("Invalid impersonationlevel : 0x%x\n",
 		       le32_to_cpu(req->ImpersonationLevel));
@@ -4481,9 +4554,29 @@ int smb2_open(struct ksmbd_work *work)
 		goto err_out2;
 	}
 
+resolve_path:
+	file_present = false;
+	maximal_access = 0;
 	rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS,
 				 &path, 1);
 
+	/* Validate takeover before disconnected delete-on-close cleanup. */
+	if (!rc && dh_info.app_instance_id && !dh_info.reconnected &&
+	    !dh_info.replay && !app_instance_id_checked) {
+		app_instance_id_checked = true;
+		rc = smb2_handle_app_instance_id(work, rsp, &dh_info, &path,
+						 stream_name, s_type,
+						 &app_instance_closed);
+		if (rc) {
+			path_put(&path);
+			goto err_out1;
+		}
+		if (app_instance_closed) {
+			path_put(&path);
+			goto resolve_path;
+		}
+	}
+
 	/*
 	 * A durable handle opened with delete-on-close is preserved across a
 	 * disconnect so it can be reclaimed by a durable reconnect.  When a new
fs/smb/server/vfs.c +3 -2
@@ -122,10 +122,11 @@ static int ksmbd_vfs_path_lookup(struct
 void ksmbd_vfs_query_maximal_access(struct mnt_idmap *idmap,
 				   struct dentry *dentry, __le32 *daccess)
 {
-	*daccess = cpu_to_le32(FILE_READ_ATTRIBUTES | READ_CONTROL);
+	*daccess = cpu_to_le32(FILE_READ_ATTRIBUTES | READ_CONTROL |
+			       SYNCHRONIZE);
 
 	if (!inode_permission(idmap, d_inode(dentry), MAY_OPEN | MAY_WRITE))
-		*daccess |= cpu_to_le32(WRITE_DAC | WRITE_OWNER | SYNCHRONIZE |
+		*daccess |= cpu_to_le32(WRITE_DAC | WRITE_OWNER |
 				FILE_WRITE_DATA | FILE_APPEND_DATA |
 				FILE_WRITE_EA | FILE_WRITE_ATTRIBUTES |
 				FILE_DELETE_CHILD);
fs/smb/server/vfs_cache.c +56 -21

166 lines not on this page · raw message

fs/smb/server/vfs_cache.h +8 -2
@@ -102,6 +102,8 @@ struct ksmbd_file {
 	struct oplock_info __rcu	*f_opinfo;
 	struct ksmbd_conn		*conn;
 	struct ksmbd_tree_connect	*tcon;
+	/* Own a share reference independently of tcon; rebind under f_lock. */
+	struct ksmbd_share_config	*share_conf;
 
 	atomic_t			refcount;
 	__le32				daccess;
@@ -213,8 +215,12 @@ void ksmbd_put_durable_fd(struct ksmbd_f
 int ksmbd_invalidate_durable_fd(unsigned long long id);
 bool ksmbd_has_other_active_fd(struct ksmbd_file *fp);
 bool ksmbd_has_stream_without_delete_share(struct ksmbd_file *fp);
-struct ksmbd_file *ksmbd_lookup_fd_app_instance_id(char *app_instance_id);
-int ksmbd_close_fd_app_instance_id(char *app_instance_id);
+bool ksmbd_app_instance_id_matches(struct ksmbd_work *work,
+				   struct ksmbd_file *fp);
+struct ksmbd_file *
+ksmbd_lookup_fd_app_instance_id_next(char *app_instance_id, int *cursor);
+int ksmbd_close_fd_app_instance_id(struct ksmbd_work *work,
+				 struct ksmbd_file *fp, bool *closed);
 struct ksmbd_file *ksmbd_lookup_fd_cguid(char *cguid);
 struct ksmbd_file *ksmbd_lookup_fd_inode(struct dentry *dentry);
 bool ksmbd_has_other_nonposix_open(struct dentry *dentry);
author maintainer
#136 lore raw

PATCH 136/547 ksmbd: validate security descriptor offsets before pointer arithmetic

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

commit 3474e1a304fbf9f7c996b24adcd519e031227a90 upstream.

parse_sec_desc() constructs SID and DACL pointers by adding untrusted 32-bit offsets to the security descriptor before checking their bounds. The existing checks reject offsets into the descriptor header, but do not reject offsets beyond the descriptor's length.

On a 32-bit kernel, a large offset can wrap the pointer before the descriptor. The end-only checks in parse_sid() and parse_dacl() can then accept it, allowing an authenticated SMB2 SET_INFO request to access memory outside the security descriptor and fault the kernel.

Check each nonzero offset against acl_len before constructing its pointer. Initialize the optional owner and group SID pointers to NULL so an omitted SID remains absent when parsing the DACL.

Fixes 0626e6641f6b ("cifsd: add server handler for central processing and tranport layers")
---
 fs/smb/server/smbacl.c |   20 +++++++++++---------
 1 file changed, 11 insertions(+), 9 deletions(-)
fs/smb/server/smbacl.c +11 -9
@@ -899,7 +899,7 @@ int parse_sec_desc(struct mnt_idmap *idm
 		   int acl_len, struct smb_fattr *fattr)
 {
 	int rc = 0;
-	struct smb_sid *owner_sid_ptr, *group_sid_ptr;
+	struct smb_sid *owner_sid_ptr = NULL, *group_sid_ptr = NULL;
 	struct smb_acl *dacl_ptr; /* no need for SACL ptr */
 	char *end_of_acl = ((char *)pntsd) + acl_len;
 	__u32 dacloffset;
@@ -911,12 +911,7 @@ int parse_sec_desc(struct mnt_idmap *idm
 	if (acl_len < sizeof(struct smb_ntsd))
 		return -EINVAL;
 
-	owner_sid_ptr = (struct smb_sid *)((char *)pntsd +
-			le32_to_cpu(pntsd->osidoffset));
-	group_sid_ptr = (struct smb_sid *)((char *)pntsd +
-			le32_to_cpu(pntsd->gsidoffset));
 	dacloffset = le32_to_cpu(pntsd->dacloffset);
-	dacl_ptr = (struct smb_acl *)((char *)pntsd + dacloffset);
 	ksmbd_debug(SMB,
 		    "revision %d type 0x%x ooffset 0x%x goffset 0x%x sacloffset 0x%x dacloffset 0x%x\n",
 		    pntsd->revision, pntsd->type, le32_to_cpu(pntsd->osidoffset),
@@ -932,9 +927,12 @@ int parse_sec_desc(struct mnt_idmap *idm
 	pntsd->type = cpu_to_le16(DACL_PRESENT);
 
 	if (pntsd->osidoffset) {
-		if (le32_to_cpu(pntsd->osidoffset) < sizeof(struct smb_ntsd))
+		if (le32_to_cpu(pntsd->osidoffset) < sizeof(struct smb_ntsd) ||
+		    le32_to_cpu(pntsd->osidoffset) >= acl_len)
 			return -EINVAL;
 
+		owner_sid_ptr = (struct smb_sid *)((char *)pntsd +
+				le32_to_cpu(pntsd->osidoffset));
 		rc = parse_sid(owner_sid_ptr, end_of_acl);
 		if (rc) {
 			pr_err("%s: Error %d parsing Owner SID\n", __func__, rc);
@@ -950,9 +948,12 @@ int parse_sec_desc(struct mnt_idmap *idm
 	}
 
 	if (pntsd->gsidoffset) {
-		if (le32_to_cpu(pntsd->gsidoffset) < sizeof(struct smb_ntsd))
+		if (le32_to_cpu(pntsd->gsidoffset) < sizeof(struct smb_ntsd) ||
+		    le32_to_cpu(pntsd->gsidoffset) >= acl_len)
 			return -EINVAL;
 
+		group_sid_ptr = (struct smb_sid *)((char *)pntsd +
+				le32_to_cpu(pntsd->gsidoffset));
 		rc = parse_sid(group_sid_ptr, end_of_acl);
 		if (rc) {
 			pr_err("%s: Error %d mapping Owner SID to gid\n",
@@ -974,9 +975,10 @@ int parse_sec_desc(struct mnt_idmap *idm
 		pntsd->type |= cpu_to_le16(DACL_PROTECTED);
 
 	if (dacloffset) {
-		if (dacloffset < sizeof(struct smb_ntsd))
+		if (dacloffset < sizeof(struct smb_ntsd) || dacloffset >= acl_len)
 			return -EINVAL;
 
+		dacl_ptr = (struct smb_acl *)((char *)pntsd + dacloffset);
 		rc = parse_dacl(idmap, dacl_ptr, end_of_acl,
 				owner_sid_ptr, group_sid_ptr, fattr);
 		if (rc)
author maintainer
#137 lore raw

PATCH 137/547 ksmbd: verify transform SessionId matches the decrypted header

In reply to Greg Kroah-Hartman

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

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

From: Dairui Zhang <[email protected]>

commit 798214e6fafcdcc29f5ba2661a473232b5e70cfb upstream.

When an encrypted request comes in, the decryption key is picked by the SessionId in the transform header, but the request is then authorized under whatever session the decrypted inner header names. Nothing ever compares the two, so on a connection with more than one session a client can get a request decrypted with one session's key and run it as another session. Encrypted requests are exempt from signing too, so a valid AEAD tag is the only proof of session identity, and it is checked against the wrong session.

MS-SMB2 says the server must check that the transform SessionId matches the one in the decrypted SMB2 header and treat a mismatch as a protocol error. Add that check in __handle_ksmbd_work() after decryption, before dispatching: the message has to be at least one fixed SMB2 header, the first operation must not set SMB2_FLAGS_RELATED_OPERATIONS and its SessionId must match the transform SessionId, and every following non-related operation in a compound chain must carry the same SessionId. NextCommand offsets must be 8-byte aligned and stay inside the message; the bounds check is done by subtraction so it cannot wrap.

When the decrypted payload is a compression transform, the existing decompression step runs first and the decompressed SMB2 message is checked instead, since a compression transform header carries no SessionId.

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
Assisted-by LLM
---
 fs/smb/server/server.c  |   16 ++++++++++++++
 fs/smb/server/smb2pdu.c |   54 ++++++++++++++++++++++++++++++++++++++++++++++++
 fs/smb/server/smb2pdu.h |    1 
 3 files changed, 71 insertions(+)
fs/smb/server/server.c +16 -0
@@ -187,6 +187,16 @@ static void __handle_ksmbd_work(struct k
 
 	if (conn->ops->is_transform_hdr &&
 	    conn->ops->is_transform_hdr(work->request_buf)) {
+		u64 tr_sess_id;
+
+		if (get_rfc1002_len(work->request_buf) <
+		    sizeof(struct smb2_transform_hdr)) {
+			ksmbd_conn_abort(conn);
+			return;
+		}
+		tr_sess_id = le64_to_cpu(((struct smb2_transform_hdr *)
+				smb_get_msg(work->request_buf))->SessionId);
+
 		rc = conn->ops->decrypt_req(work);
 		if (rc < 0) {
 			ksmbd_conn_abort(conn);
@@ -215,6 +225,12 @@ static void __handle_ksmbd_work(struct k
 			ksmbd_conn_abort(conn);
 			return;
 		}
+
+		rc = ksmbd_check_transform_session(work, tr_sess_id);
+		if (rc < 0) {
+			ksmbd_conn_abort(conn);
+			return;
+		}
 	}
 
 	if (conn->ops->allocate_rsp_buf(work))
fs/smb/server/smb2pdu.c +54 -0

60 lines not on this page · raw message

fs/smb/server/smb2pdu.h +1 -0
@@ -420,6 +420,7 @@ struct channel *lookup_chann_list(struct
 void smb3_preauth_hash_rsp(struct ksmbd_work *work);
 bool smb3_is_transform_hdr(void *buf);
 int smb3_decrypt_req(struct ksmbd_work *work);
+int ksmbd_check_transform_session(struct ksmbd_work *work, u64 tr_sess_id);
 int smb3_encrypt_resp(struct ksmbd_work *work);
 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work);
 int smb2_set_rsp_credits(struct ksmbd_work *work);
author maintainer
#138 lore raw

PATCH 138/547 vlan: restore HW VLAN tag insertion with reorder_hdr off

In reply to Greg Kroah-Hartman

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

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

From: Eric Dumazet <[email protected]>

[ Upstream commit c2124f80be4ceb6ec566ca3b5fc87f84ea9c36e0 ]

Commit 447cbe95ebb9 ("vlan: fix skb_under_panic and races when toggling HW VLAN offload") replaced vlan_passthru_header_ops with vlan_header_ops unconditionally to avoid lockless data races when modifying hard_header_len dynamically under RTNL.

Prior to that commit, vlan devices on top of a real device capable of HW VLAN TX offload used vlan_passthru_header_ops, which never inserted the 802.1Q header in the frame.

Now, with reorder_hdr=off (as done by Home Assistant OS / NetworkManager when flags are omitted over D-Bus), vlan_dev_hard_header() always pushes an in-band 802.1Q header, and vlan_dev_hard_start_xmit() hands the frame to the real device as is, even if the real device supports HW VLAN TX offload.

This is a regression for r8169 users (Realtek RTL8168h), who report transmit queue timeouts (NETDEV WATCHDOG): this NIC stalls when asked to offload checksum and/or TSO for frames carrying an in-band tag. Users of r8152 based USB adapters were affected as well.

Reverting the blamed commit, disabling TX checksum offload (which also disables TSO), or setting reorder_hdr=on were all reported to work around the issue.

Keep vlan_dev_hard_header() as is: the in-band header keeps the frame layout seen at the vlan device egress (taps, tc, netfilter) unchanged, and is relied upon by stacked vlans (Q-in-Q) and by AF_PACKET SOCK_DGRAM users sending ETH_P_8021Q frames.

Instead, when vlan_dev_hard_start_xmit() gets a frame carrying an in-band tag with our protocol and the real device can insert tags, move that tag to skb->vlan_tci with __skb_vlan_pop(), so that the real device inserts it. Frames sent on the wire are unchanged, except that frames shorter than 64 bytes with their tag now get up to 4 bytes of extra padding, as with reorder_hdr=on and before 447cbe95ebb9.

skb_reset_mac_header() is needed first, because not all ndo_start_xmit() callers set the mac header (e.g. AF_XDP copy mode, which uses __dev_direct_xmit()).

vlan_set_encap_proto() may read the two bytes after the vlan header, so frames whose linear part is shorter than VLAN_ETH_HLEN + 2 are sent unchanged, as before. This also makes sure h_vlan_proto, read earlier in the function, was in the linear part. Shared skbs (e.g. from pktgen) are also sent unchanged, since popping the tag modifies the skb, as are skbs already carrying a hwaccel tag (e.g. from generic XDP redirect), whose tag must not be overwritten, skbs carrying XDP metadata, which the pop would have to move, and CHECKSUM_PARTIAL skbs whose csum_start lies within the first VLAN_ETH_HLEN bytes (only possible with bogus offsets, e.g. from AF_XDP tx metadata), which the pop would leave before skb->data.
If popping the header fails (memory allocation failure), the frame is dropped and counted in tx_dropped, rather than handing the real device a frame with an in-band tag.

tx_bytes is now sampled before the pop, so the vlan device statistics do not change.

This also applies to frames provided by the sender with our tag (AF_PACKET SOCK_RAW, or frames redirected from another reorder_hdr=off vlan): the real device now inserts their tag too.

---
 net/8021q/vlan_dev.c | 33 ++++++++++++++++++++++++++++++++-
 1 file changed, 32 insertions(+), 1 deletion(-)
net/8021q/vlan_dev.c +32 -1
index c949c6a829456..2d775b4c84ce6 100644
@@ -110,6 +110,8 @@ static netdev_tx_t vlan_dev_hard_start_xmit(struct sk_buff *skb,
 	unsigned int len;
 	int ret;
 
+	len = skb->len;
+
 	/* Handle non-VLAN frames if they are sent to us, for example by DHCP.
 	 *
 	 * NOTE: THIS ASSUMES DIX ETHERNET, SPECIFICALLY NOT SUPPORTING
@@ -121,10 +123,39 @@ static netdev_tx_t vlan_dev_hard_start_xmit(struct sk_buff *skb,
 		vlan_tci = vlan->vlan_id;
 		vlan_tci |= vlan_dev_get_egress_qos_mask(dev, skb->priority);
 		__vlan_hwaccel_put_tag(skb, vlan->vlan_proto, vlan_tci);
+	} else if (skb_headlen(skb) >= VLAN_ETH_HLEN + sizeof(__be16) &&
+		   !skb_shared(skb) && !skb_vlan_tag_present(skb) &&
+		   !skb_metadata_len(skb) &&
+		   (skb->ip_summed != CHECKSUM_PARTIAL ||
+		    skb_checksum_start_offset(skb) >= VLAN_ETH_HLEN) &&
+		   vlan_hw_offload_capable(READ_ONCE(vlan->real_dev->features),
+					   vlan->vlan_proto)) {
+		u16 vlan_tci;
+
+		/* The frame carries its outer tag in-band, either inserted
+		 * by vlan_dev_hard_header() or provided by the sender.
+		 * Let the real device insert it: some NICs can not offload
+		 * checksum or TSO for frames carrying an in-band tag.
+		 * Not all ndo_start_xmit() callers set the mac header.
+		 * vlan_set_encap_proto() may read two bytes after the vlan
+		 * header, so frames with a shorter linear part are sent
+		 * unchanged, as are shared skbs (e.g. from pktgen), skbs
+		 * already carrying a hwaccel tag (e.g. from generic XDP
+		 * redirect), skbs carrying XDP metadata, and CHECKSUM_PARTIAL
+		 * skbs whose checksum starts within the header to be popped.
+		 * On allocation failure, drop the frame rather than handing
+		 * it to the real device with an in-band tag.
+		 */
+		skb_reset_mac_header(skb);
+		if (unlikely(__skb_vlan_pop(skb, &vlan_tci))) {
+			dev_kfree_skb_any(skb);
+			this_cpu_inc(vlan->vlan_pcpu_stats->tx_dropped);
+			return NETDEV_TX_OK;
+		}
+		__vlan_hwaccel_put_tag(skb, vlan->vlan_proto, vlan_tci);
 	}
 
 	skb->dev = vlan->real_dev;
-	len = skb->len;
 	if (unlikely(netpoll_tx_running(dev)))
 		return vlan_netpoll_send_skb(vlan, skb);
 
Signature · 1 line
2.53.0
author maintainer
#139 lore raw

PATCH 139/547 cgroup: serialize migrations of newly forked processes

In reply to Greg Kroah-Hartman

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

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

From: Daehyeon Ko <[email protected]>

[ Upstream commit bf6fbf46b5ff68c4eebad5aa52309eb124f4509c ]

With favordynmods enabled, a cgroup.procs migration takes the target threadgroup's cgroup_threadgroup_rwsem for writing. A process fork holds the forking threadgroup's semaphore for reading. These are different semaphores when fork creates a new process.

copy_process() publishes the child's PID before cgroup_post_fork() links the child to its css_set. A writer can find the child in that interval, take its uncontended semaphore, and migrate it while child->cgroups still points to init_css_set and child->cg_list is empty. Migration links the node into init_css_set.mg_tasks. cgroup_post_fork() then adds the same node to the intended css_set as though it were unlinked, corrupting both task lists and their css_set ownership.

This regresses the fork/migration race fixed by commit b12b533fa523 ("cgroups: add lock for child->cgroups in cgroup_post_fork()") and restored again in 2012 after the lock had been removed. The old task_lock protection was later superseded by global css_set and cgroup threadgroup locking. The change identified by the Fixes tag narrowed only the migration side back to a per-threadgroup lock, recreating the different-process exclusion failure.

Take the new threadgroup's semaphore for reading before the child becomes visible and hold it through cgroup_post_fork(). Use a nested lock subclass because fork already holds the parent's semaphore. CLONE_THREAD children share the parent's signal_struct and remain covered by the existing lock. Migrations of unrelated, fully initialized threadgroups remain concurrent.

An AI coding assistant was used to identify and reproduce the regression and to develop and test this fix.

Fixes 0568f89d4fb8 ("cgroup: replace global percpu_rwsem with per threadgroup resem when writing to cgroup.procs")
---
 kernel/cgroup/cgroup.c | 28 ++++++++++++++++++++++++++++
 1 file changed, 28 insertions(+)
kernel/cgroup/cgroup.c +28 -0
index 227d09704ca59..42cc77dfa1c8a 100644
@@ -6844,6 +6844,31 @@ static struct cgroup *cgroup_get_from_file(struct file *f)
 	return cgrp;
 }
 
+/*
+ * A new threadgroup gets its own cgroup_threadgroup_rwsem.  Once its PID is
+ * visible, a cgroup.procs writer can find the child and lock that rwsem even
+ * though cgroup_post_fork() has not linked the child to its css_set yet.
+ *
+ * cgroup_can_fork() already holds the global read lock, which keeps
+ * cgroup_enable_per_threadgroup_rwsem stable.  Lock the child's rwsem as a
+ * nested instance until cgroup_post_fork() finishes.  Threads share their
+ * parent's signal_struct and are covered by the existing read lock.
+ */
+static void cgroup_fork_child_lock(struct task_struct *child)
+{
+	if (cgroup_enable_per_threadgroup_rwsem &&
+	    child->signal != current->signal)
+		down_read_nested(&child->signal->cgroup_threadgroup_rwsem,
+				 SINGLE_DEPTH_NESTING);
+}
+
+static void cgroup_fork_child_unlock(struct task_struct *child)
+{
+	if (cgroup_enable_per_threadgroup_rwsem &&
+	    child->signal != current->signal)
+		up_read(&child->signal->cgroup_threadgroup_rwsem);
+}
+
 /**
  * cgroup_css_set_fork - find or create a css_set for a child process
  * @kargs: the arguments passed to create the child process
@@ -7009,6 +7034,7 @@ int cgroup_can_fork(struct task_struct *child, struct kernel_clone_args *kargs)
 			goto out_revert;
 	} while_each_subsys_mask();
 
+	cgroup_fork_child_lock(child);
 	return 0;
 
 out_revert:
@@ -7043,6 +7069,7 @@ void cgroup_cancel_fork(struct task_struct *child,
 		if (ss->cancel_fork)
 			ss->cancel_fork(child, kargs->cset);
 
+	cgroup_fork_child_unlock(child);
 	cgroup_css_set_put_fork(kargs);
 }
 
@@ -7140,6 +7167,7 @@ void cgroup_post_fork(struct task_struct *child,
 	if (unlikely(kill))
 		do_send_sig_info(SIGKILL, SEND_SIG_NOINFO, child, PIDTYPE_TGID);
 
+	cgroup_fork_child_unlock(child);
 	cgroup_css_set_put_fork(kargs);
 }
 
Signature · 1 line
2.53.0
author maintainer
#140 lore raw

PATCH 140/547 wifi: b43: fix use-after-free in b43_bcma_remove()

In reply to Greg Kroah-Hartman

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

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

From: Andreas Wendleder <[email protected]>

commit c6c8bc355657115664131b38c53c5ddf7d93b072 upstream.

b43_one_core_detach() frees the struct b43_wldev it is given the bus device of. b43_bcma_remove() then reads wldev->dev again to free the bus device, which is a read of freed memory.

b43_ssb_remove() does not have the problem: it takes a copy of wldev->dev at the start. Do the same here.

Fixes 96838d61102a ("b43: Fix memory leaks in b43_bus_dev_ssb_init and b43_bus_dev_bcma_init")
---
 drivers/net/wireless/broadcom/b43/main.c |    5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/net/wireless/broadcom/b43/main.c +3 -2
@@ -5677,6 +5677,7 @@ static void b43_bcma_remove(struct bcma_
 {
 	struct b43_wldev *wldev = bcma_get_drvdata(core);
 	struct b43_wl *wl = wldev->wl;
+	struct b43_bus_dev *dev = wldev->dev;
 
 	/* We must cancel any work here before unregistering from ieee80211,
 	 * as the ieee80211 unreg will destroy the workqueue. */
@@ -5691,14 +5692,14 @@ static void b43_bcma_remove(struct bcma_
 		ieee80211_unregister_hw(wl->hw);
 	}
 
-	b43_one_core_detach(wldev->dev);
+	b43_one_core_detach(dev);
 
 	/* Unregister HW RNG driver */
 	b43_rng_exit(wl);
 
 	b43_leds_unregister(wl);
 	ieee80211_free_hw(wl->hw);
-	kfree(wldev->dev);
+	kfree(dev);
 }
 
 static struct bcma_driver b43_bcma_driver = {
author maintainer
#141 lore raw

PATCH 141/547 SUNRPC: fix netns use-after-free in write_gssp()

In reply to Greg Kroah-Hartman

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

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

From: Zijing Yin <[email protected]>

commit e7a8721b7edb54a157623f9e31d71345333b5fb9 upstream.

While fuzzing with a customized syzkaller, I hit a refcount warning in xprt_alloc(), reached from a write to /proc/net/rpc/use-gss-proxy:

refcount_t: addition on 0; use-after-free.

  WARNING: lib/refcount.c:25 at refcount_warn_saturate+0xf8/0x120
  CPU: 0 PID: 10404 Comm: syz.0.17 Not tainted 7.3.0-rc1-00096-gcfebfd3db73d
  Call Trace:
   <TASK>
   xprt_alloc+0x83f/0x9d0
   xs_setup_xprt+0xaf/0x3c0
   xs_setup_local+0x47/0x7f0
   xprt_create_transport+0x16c/0x730
   rpc_create+0x38e/0x7f0
   gssp_rpc_create+0xe2/0x180
   set_gssp_clnt+0xba/0x1b0
   write_gssp+0x200/0x310
   proc_reg_write+0x240/0x330
   vfs_write+0x2aa/0x1050
   ksys_write+0x12a/0x250
   do_syscall_64+0x117/0x750
   entry_SYSCALL_64_after_hwframe+0x77/0x7f
   </TASK>

create_use_gss_proxy_proc_entry() stores the struct net pointer as the proc entry's private data without taking a reference on it, and an open file descriptor does not pin the namespace either, as procfs only pins the proc_dir_entry. write_gssp() reads that pointer back with pde_data() and hands it to set_gssp_clnt(), which reaches xprt_init():

	xprt->xprt_net = get_net_track(net, &xprt->ns_tracker, GFP_KERNEL);

get_net_track() -> get_net() -> refcount_inc() is unconditional, so rpc_create() assumes its caller holds a reference on args.net. write_gssp() does not.

Dropping the last ns.count reference does not make the file go away. __put_net() only queues cleanup_net() on a workqueue, and the remove_proc_entry() that fences off further writes runs from the rpcsec_gss pernet .exit method, that is, from inside cleanup_net(). A write landing between those two points increments a refcount that is already zero. cleanup_net() does not re-read ns.count, so the namespace is freed anyway and the rpc_xprt -- along with the AF_LOCAL socket opened for it -- is left pointing at freed memory. The resurrected count is visible to the rest of that teardown too: with CONFIG_IPV6_MROUTE the same cleanup_net() worker then trips !mr_can_free_table() in ip6mr_free_table(), which tests check_net() on the namespace it is freeing.

It reduces to opening /proc/net/rpc/use-gss-proxy inside a new network namespace, calling setns() back to the original one to drop the last reference, and then writing "1" to the still-open descriptor.

Take the reference in write_gssp() itself and refuse the write when the namespace is already gone. This is what procfs does for every other /proc/net file: get_proc_net() is maybe_get_net(PDE_NET(PDE(inode))) and seq_open_net() returns -ENXIO when it fails. PDE_NET() cannot be reused here because the parent directory /proc/net/rpc carries no namespace pointer. Adding a .pre_exit to rpcsec_gss_net_ops so the entry is removed earlier would only narrow the window, since pre_exit also runs from cleanup_net().

Live namespaces are unaffected: a write still returns the error from set_gssp_clnt(), a write of "2" still returns -EINVAL, and reads are untouched.

Fixes 030d794bf498 ("SUNRPC: Use gssproxy upcall for server RPCGSS authentication.")
---
 net/sunrpc/auth_gss/svcauth_gss.c |   14 +++++++++++---
 1 file changed, 11 insertions(+), 3 deletions(-)
net/sunrpc/auth_gss/svcauth_gss.c +11 -3
@@ -1420,10 +1420,18 @@ static ssize_t write_gssp(struct file *f
 		return res;
 	if (i != 1)
 		return -EINVAL;
+
+	/*
+	 * Neither the proc entry nor an open descriptor pins @net, so it
+	 * might already be dying when rpc_create() takes its reference.
+	 */
+	if (!maybe_get_net(net))
+		return -ENXIO;
+
 	res = set_gssp_clnt(net);
-	if (res)
-		return res;
-	res = set_gss_proxy(net, 1);
+	if (!res)
+		res = set_gss_proxy(net, 1);
+	put_net(net);
 	if (res)
 		return res;
 	return count;
author maintainer
#142 lore raw

PATCH 142/547 spmi: Fix potential use-after-free by grabbing of_node reference

In reply to Greg Kroah-Hartman

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

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

From: AngeloGioacchino Del Regno <[email protected]>

commit f7aa9de4f2b197cdd704cdc476901b68ee128433 upstream.

As noticed by Sashiko during a review run of an unrelated patch, in of_spmi_register_devices(), for_each_available_child_of_node() is used to loop through children, and to also assign a node to a newly created SPMI child device.

Problem is that the refcount is dropped at every iteration so, in the specific case of DT overlays, a use-after-free may occur when an overlay is dynamically unloaded!

To resolve this, increase the of_node refcount when assigning (in function of_spmi_register_devices) and release the reference in spmi_device_remove().

---
 drivers/spmi/spmi.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/spmi/spmi.c +2 -1
@@ -24,6 +24,7 @@ static void spmi_dev_release(struct devi
 {
 	struct spmi_device *sdev = to_spmi_device(dev);
 
+	of_node_put(dev->of_node);
 	kfree(sdev);
 }
 
@@ -517,7 +518,7 @@ static void of_spmi_register_devices(str
 		if (!sdev)
 			continue;
 
-		device_set_node(&sdev->dev, of_fwnode_handle(node));
+		device_set_node(&sdev->dev, of_fwnode_handle(of_node_get(node)));
 		sdev->usid = (u8)reg[0];
 
 		err = spmi_device_add(sdev);
author maintainer
#143 lore raw

PATCH 143/547 smb: client: fix use-after-free infoleak via the readdir resume name

In reply to Greg Kroah-Hartman

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

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

From: Diego Oliva <[email protected]>

commit 59131dd72f62b198fc9ea1489ad9d3573154f684 upstream.

CIFSFindNext() copies the resume name that cifs_save_resume_key() recorded from the last entry of the previous response into its request; psrch_inf->presume_name points into the response buffer that entry came from, and nothing ever clears it. find_cifs_entry() records a new name only from a response with a usable last entry, and cifs_readdir() only from an entry it walks to, so a response that carries no entries and leaves last_entry NULL, because CIFSFindFirst() or CIFSFindNext() rejected LastNameOffset, refreshes neither and presume_name keeps pointing into the previous response. That buffer has already been
released: by CIFSFindNext() before it installs the new response, or by find_cifs_entry() when it rewinds the search, which does not drop the name either and can then fail in initiate_cifs_search() before a new response replaces it. The next CIFSFindNext() then copies up to PATH_MAX - 1 bytes of the resume name out of the released buffer into its request and sends them to the server: a use-after-free read that leaks kernel memory to a malicious or compromised server, which can provoke it with a single FindNext response that carries no entries and a LastNameOffset above CIFSMaxBufSize, which is all the existing check rejects.

With KASAN enabled, a server that answers a listing that way gives:

CIFS: VFS: ignoring corrupt resume name
==================================================================

 BUG: KASAN: slab-use-after-free in CIFSFindNext+0x8ca/0x14c0
 Read of size 4080 at addr ffff88807c823f98 by task ls/83

 CPU: 0 UID: 0 PID: 83 Comm: ls Tainted: G    B               7.3.0-rc4-00457-gf14572c203d5 #69 PREEMPT(lazy)
 Tainted: [B]=BAD_PAGE
 Call Trace:
  <TASK>
  kasan_report+0xdf/0x1a0
  kasan_check_range+0x10f/0x1e0
  __asan_memcpy+0x23/0x60
  CIFSFindNext+0x8ca/0x14c0
  cifs_readdir+0xf51/0x29c0
  iterate_dir+0x1c0/0x570
  __x64_sys_getdents64+0x133/0x270
  do_syscall_64+0x109/0x5d0
  entry_SYSCALL_64_after_hwframe+0x77/0x7f
  </TASK>

 Allocated by task 83 on cpu 1 at 13.497119s:
  cifs_buf_get+0x36/0x90
  smb_init+0x4f/0x110
  CIFSFindNext+0xf7/0x14c0
  cifs_readdir+0xf51/0x29c0

 Freed by task 83 on cpu 0 at 13.584018s:
  cifs_buf_release+0x41/0x80
  CIFSFindNext+0xfce/0x14c0
  cifs_readdir+0xf51/0x29c0

The buggy address is located 16280 bytes inside of
freed 16588-byte region [ffff88807c820000, ffff88807c8240cc)
==================================================================

The same memcpy() first reads past the end of that object while it is still live, a slab-out-of-bounds read that the following patches bound; that is the taint the report above carries.

SMB1 is not negotiated by default; reaching this code requires an explicit vers=1.0 mount.

Clear presume_name and resume_name_len whenever a new response is installed and when the rewind path releases the search buffer, so that the name never outlives the buffer it points into, and reset resume_key with them, since it was taken from the same entry and would otherwise be sent with an empty name. A response without a usable last entry then continues the search with an empty resume name rather than a stale one; CIFSFindNext() skips the copy of a zero-length name so that it never runs on the NULL pointer.

The next patch in the series leaves last_entry NULL for a response that carries no entries, and bounds LastNameOffset against the received response rather than against CIFSMaxBufSize. Responses that are given a last entry today then take the path fixed here, so that patch must not be applied without this one.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
Fixes b77d753c413e ("[CIFS] Check that last search entry resume key is valid")
Assisted-by Bynario AI
---
 fs/smb/client/cifssmb.c |   11 ++++++++++-
 fs/smb/client/readdir.c |    3 +++
 2 files changed, 13 insertions(+), 1 deletion(-)
fs/smb/client/cifssmb.c +10 -1
@@ -4543,6 +4543,9 @@ findFirstRetry:
 	psrch_inf->entries_in_buffer = le16_to_cpu(parms->SearchCount);
 	psrch_inf->index_of_last_entry = 2 /* skip . and .. */ +
 		psrch_inf->entries_in_buffer;
+	psrch_inf->presume_name = NULL;
+	psrch_inf->resume_name_len = 0;
+	psrch_inf->resume_key = 0;
 	lnoff = le16_to_cpu(parms->LastNameOffset);
 	if (CIFSMaxBufSize < lnoff) {
 		cifs_dbg(VFS, "ignoring corrupt resume name\n");
@@ -4607,7 +4610,10 @@ int CIFSFindNext(const unsigned int xid,
 	name_len = psrch_inf->resume_name_len;
 	params += name_len;
 	if (name_len < PATH_MAX) {
-		memcpy(pSMB->ResumeFileName, psrch_inf->presume_name, name_len);
+		if (name_len) {
+			memcpy(pSMB->ResumeFileName,
+			       psrch_inf->presume_name, name_len);
+		}
 		byte_count += name_len;
 		/* 14 byte parm len above enough for 2 byte null terminator */
 		pSMB->ResumeFileName[name_len] = 0;
@@ -4662,6 +4668,9 @@ int CIFSFindNext(const unsigned int xid,
 	psrch_inf->endOfSearch = !!parms->EndofSearch;
 	psrch_inf->entries_in_buffer = le16_to_cpu(parms->SearchCount);
 	psrch_inf->index_of_last_entry += psrch_inf->entries_in_buffer;
+	psrch_inf->presume_name = NULL;
+	psrch_inf->resume_name_len = 0;
+	psrch_inf->resume_key = 0;
 	lnoff = le16_to_cpu(parms->LastNameOffset);
 	if (CIFSMaxBufSize < lnoff) {
 		cifs_dbg(VFS, "ignoring corrupt resume name\n");
fs/smb/client/readdir.c +3 -0
@@ -752,6 +752,9 @@ find_cifs_entry(const unsigned int xid,
 			cfile->srch_inf.ntwrk_buf_start = NULL;
 			cfile->srch_inf.srch_entries_start = NULL;
 			cfile->srch_inf.last_entry = NULL;
+			cfile->srch_inf.presume_name = NULL;
+			cfile->srch_inf.resume_name_len = 0;
+			cfile->srch_inf.resume_key = 0;
 		}
 		rc = initiate_cifs_search(xid, file, full_path);
 		if (rc) {
author maintainer
#144 lore raw

PATCH 144/547 smb: client: fix use-after-free in cifs_ses_add_channel()

In reply to Greg Kroah-Hartman

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

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

From: Henry Martin <[email protected]>

commit 031278577380e7875d95aed81a2b2bcac39be923 upstream.

The error path of cifs_ses_add_channel() calls cifs_put_tcp_session() before cifs_chan_clear_need_reconnect(). The latter reaches cifs_ses_get_chan_index(), which dereferences server->terminate; if the put was the final reference, TCP_Server_Info is already freed and this is a use-after-free. Same put-then-use pattern as the recently fixed sibling in commit 717e0a25036b ("cifs: Fix server use-after-free in cifs_chan_skip_or_disable()").

Move the put last, but do not read chan->server after dropping
chan_lock: chan points into ses->chans[], and once chan_count is decremented a concurrent add_channel can reuse the slot and overwrite the pointer, so the put would act on the new channel's server. Cache the pointer under chan_lock, clear the reconnect bit and decrement chan_count while still holding the reference, and release it after the unlock.

This issue was discovered by Tencent CodeBuddy Security.

Fixes ee1d21794e55a ("cifs: handle when server stops supporting multichannel")
---
 fs/smb/client/sess.c |    6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
fs/smb/client/sess.c +4 -2
@@ -626,12 +626,13 @@ cifs_ses_add_channel(struct cifs_ses *se
 
 out:
 	if (rc && chan->server) {
-		cifs_put_tcp_session(chan->server, 0);
+		struct TCP_Server_Info *pserver;
 
 		spin_lock(&ses->chan_lock);
+		pserver = chan->server;
 
 		/* we rely on all bits beyond chan_count to be clear */
-		cifs_chan_clear_need_reconnect(ses, chan->server);
+		cifs_chan_clear_need_reconnect(ses, pserver);
 		ses->chan_count--;
 		/*
 		 * chan_count should never reach 0 as at least the primary
@@ -639,6 +640,7 @@ out:
 		 */
 		WARN_ON(ses->chan_count < 1);
 		spin_unlock(&ses->chan_lock);
+		cifs_put_tcp_session(pserver, 0);
 	}
 
 	kfree(ctx->UNC);
author maintainer
#145 lore raw

PATCH 145/547 sched_ext: Fix use-after-free of a local reenq node left on an inactive cpu

In reply to Greg Kroah-Hartman

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

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

From: Tejun Heo <[email protected]>

commit 43e1ef14a47257ebf7e3bb3ab9a6df9c6f817c5f upstream.

A local DSQ reenq is queued on the rq through a per-sched node and run from deferred work. When the reenq is requested from dispatch, the work is a balance callback queued once dispatch is done. A cpu going down installs balance push early in its teardown, and queue_balance_callback() refuses new callbacks from then on. ops.dispatch() keeps running on that cpu until the rq goes offline after an RCU grace period, so a reenq it requests in that window may never run. The IMMED handling in dispatch_one() requests one the same way.

A reenq requested from elsewhere for a cpu that is already offline goes through irq_work_queue_on(), which warns, and its work doesn't run until the cpu comes back.

Either way the node stays on the rq's list. When the scheduler is freed, scx_sched_free_rcu_work() warns and frees the pcpu with the node still linked, and the list is walked again once the cpu comes back.

An inactive cpu's local DSQ holds only tasks that are bound to it or are being moved off, so the reenq is pointless. Ignore reenqs of an inactive cpu's local DSQ.

The test is lockless. The hotplug thread of a cpu going down runs on that cpu, and it marks the cpu inactive before it installs balance push. A dispatch on the cpu runs to completion before that thread can run there, so a dispatch that saw the cpu active has queued its callback by then. Requests from outside dispatch run from the wakeup path or through irq_work, which balance push doesn't affect. The grace period after the cpu goes inactive waits for any requester that saw it active, so that irq_work is queued while the cpu is online.

Fixes 238eba8c210d ("sched_ext: Use schedule_deferred_locked() in schedule_dsq_reenq()")
Fixes 76edc2761ab8 ("sched_ext: Use irq_work_queue_on() in schedule_deferred()")
---
 kernel/sched/ext/ext.c |   15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)
kernel/sched/ext/ext.c +14 -1
@@ -1103,6 +1103,18 @@ void schedule_dsq_reenq(struct scx_sched
 		rq = container_of(dsq, struct rq, scx.local_dsq);
 
 		/*
+		 * An inactive cpu's local DSQ holds only tasks that are bound
+		 * to it or are being moved off, so a reenq of it is pointless.
+		 * Once balance push is installed, queue_balance_callback() also
+		 * drops the callback that would run a reenq requested from
+		 * dispatch, and irq_work_queue_on() can't reach an offline cpu.
+		 * The reenq's node would then stay on this rq's list after
+		 * @sch's pcpu is freed.
+		 */
+		if (unlikely(!cpu_active(cpu_of(rq))))
+			return;
+
+		/*
 		 * A sub-sched lacking baseline access on the target cid has no
 		 * business triggering IPIs. The lockless test is fine: slipping
 		 * through right after a revoke is harmless and a wrong denial
@@ -10020,7 +10032,8 @@ __bpf_kfunc struct task_struct *scx_bpf_
  * - Local DSQs (%SCX_DSQ_LOCAL or %SCX_DSQ_LOCAL_ON | $cpu)
  * - User DSQs
  *
- * Re-enqueues are performed asynchronously. Can be called from anywhere.
+ * Re-enqueues are performed asynchronously. Can be called from anywhere. A
+ * re-enqueue of an inactive cpu's local DSQ is ignored.
  *
  * %SCX_DSQ_LOCAL resolves to the local DSQ of the rq the current scheduler
  * operation is locked to - e.g. the rq being dispatched for in ops.dispatch() -
author maintainer
#146 lore raw

PATCH 146/547 RDMA/uverbs: Fix DMABUF use-after-free during ufile cleanup

In reply to Greg Kroah-Hartman

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

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

From: Deep Shah <[email protected]>

commit 2854f9025d4ef6c4566f71e52d7f496d9a0f5737 upstream.

The DMABUF release can race with ufile cleanup. When the cleanup holds hw_destroy_rwsem for write, uverbs_uobject_release() fails its trylock and leaves the uobject on the ufile list, but the dma_buf is freed as soon as the release returns. The cleanup then destroys the uobject and uses the freed dma_buf:

  BUG: KASAN: slab-use-after-free in uverbs_dmabuf_fd_destroy_uobj+0x46/0x200
  Read of size 8 at addr ff11000109cf14b0 by task repro/435
  Call Trace:
   uverbs_dmabuf_fd_destroy_uobj+0x46/0x200
   destroy_hw_fd_uobject+0x3f/0x50
   uverbs_destroy_uobject+0xc5/0x380
   __uverbs_cleanup_ufile+0x1a8/0x260
   uverbs_destroy_ufile_hw+0x54/0x160
   ib_uverbs_close+0x34/0x110
  Allocated by task 435:
   dma_buf_export+0x1b5/0x530
   ib_uverbs_handler_UVERBS_METHOD_DMABUF_ALLOC+0x223/0x3f0
  Freed by task 436:
   kfree+0x301/0x530
   dentry_kill+0x14c/0x560
   __fput+0x23a/0x4a0

rdma_user_mmap_entry_remove() dereferences the same pointer.

Protect the stored dma_buf pointer with a mutex and clear it before release returns. Use a shared revoke helper so uobject destruction and mmap entry removal both skip a cleared pointer. Hold a temporary uobject reference across uverbs_uobject_release() and the pointer update.

Use a separate mutex because uobject destruction can free the mmap entry before release finishes. Map and unmap use attachment->dmabuf directly, so they do not need to take the new mutex while holding the reservation lock.

Fixes 0ac6f4056c4a ("RDMA/uverbs: Add DMABUF object type and operations")
Assisted-by LLM
---
 drivers/infiniband/core/ib_core_uverbs.c          |   10 -----
 drivers/infiniband/core/uverbs.h                  |   37 ++++++++++++++++++++
 drivers/infiniband/core/uverbs_std_types_dmabuf.c |   39 ++++++++++++----------
 3 files changed, 61 insertions(+), 25 deletions(-)
drivers/infiniband/core/ib_core_uverbs.c +1 -9
@@ -244,16 +244,8 @@ void rdma_user_mmap_entry_remove(struct
 	entry->driver_removed = true;
 	xa_unlock(&entry->ucontext->mmap_xa);
 	list_for_each_entry_safe(uverbs_dmabuf, tmp, &entry->dmabufs, dmabufs_elm) {
-		dma_resv_lock(uverbs_dmabuf->dmabuf->resv, NULL);
 		list_del(&uverbs_dmabuf->dmabufs_elm);
-		uverbs_dmabuf->revoked = true;
-		dma_buf_invalidate_mappings(uverbs_dmabuf->dmabuf);
-		dma_resv_wait_timeout(uverbs_dmabuf->dmabuf->resv,
-				      DMA_RESV_USAGE_BOOKKEEP, false,
-				      MAX_SCHEDULE_TIMEOUT);
-		dma_resv_unlock(uverbs_dmabuf->dmabuf->resv);
-		kref_put(&uverbs_dmabuf->kref, ib_uverbs_dmabuf_done);
-		wait_for_completion(&uverbs_dmabuf->comp);
+		ib_uverbs_dmabuf_revoke(uverbs_dmabuf);
 	}
 	mutex_unlock(&entry->dmabufs_lock);
 
drivers/infiniband/core/uverbs.h +37 -0
@@ -42,6 +42,8 @@
 #include <linux/mutex.h>
 #include <linux/completion.h>
 #include <linux/cdev.h>
+#include <linux/dma-buf.h>
+#include <linux/dma-resv.h>
 
 #include <rdma/ib_verbs.h>
 #include <rdma/ib_umem.h>
@@ -135,6 +137,13 @@ struct ib_uverbs_completion_event_file {
 
 struct ib_uverbs_dmabuf_file {
 	struct ib_uobject uobj;
+	/*
+	 * Serializes users of dmabuf with the dma_buf's release, which sets it
+	 * to NULL. The uobject can outlive the dma_buf while it waits to be
+	 * destroyed. The map and unmap callbacks use attachment->dmabuf
+	 * instead of taking this lock.
+	 */
+	struct mutex dmabuf_release_lock;
 	struct dma_buf *dmabuf;
 	struct list_head dmabufs_elm;
 	struct rdma_user_mmap_entry *mmap_entry;
@@ -359,6 +368,34 @@ static inline void ib_uverbs_dmabuf_done
 	complete(&priv->comp);
 }
 
+/*
+ * Revoke the dmabuf and wait for all of its DMA mappings to be gone. Must be
+ * called with the mmap entry's dmabufs_lock held, after the dmabuf has been
+ * removed from the entry's dmabufs list, so it runs once per dmabuf. Lock
+ * order is dmabufs_lock, dmabuf_release_lock, then the dma_resv lock.
+ */
+static inline void ib_uverbs_dmabuf_revoke(struct ib_uverbs_dmabuf_file *priv)
+{
+	mutex_lock(&priv->dmabuf_release_lock);
+	if (priv->dmabuf) {
+		dma_resv_lock(priv->dmabuf->resv, NULL);
+		priv->revoked = true;
+		dma_buf_invalidate_mappings(priv->dmabuf);
+		dma_resv_wait_timeout(priv->dmabuf->resv,
+				      DMA_RESV_USAGE_BOOKKEEP, false,
+				      MAX_SCHEDULE_TIMEOUT);
+		dma_resv_unlock(priv->dmabuf->resv);
+	} else {
+		/* A released dma_buf has no attachments left to invalidate */
+		priv->revoked = true;
+	}
+	mutex_unlock(&priv->dmabuf_release_lock);
+
+	kref_put(&priv->kref, ib_uverbs_dmabuf_done);
+	/* Wait till all DMA unmaps are completed */
+	wait_for_completion(&priv->comp);
+}
+
 int __uverbs_cleanup_ufile(struct ib_uverbs_file *ufile,
 			   enum rdma_remove_reason reason);
 
drivers/infiniband/core/uverbs_std_types_dmabuf.c +23 -16
@@ -28,7 +28,7 @@ uverbs_dmabuf_map(struct dma_buf_attachm
 	struct ib_uverbs_dmabuf_file *priv = attachment->dmabuf->priv;
 	struct sg_table *ret;
 
-	dma_resv_assert_held(priv->dmabuf->resv);
+	dma_resv_assert_held(attachment->dmabuf->resv);
 
 	if (priv->revoked)
 		return ERR_PTR(-ENODEV);
@@ -49,7 +49,7 @@ static void uverbs_dmabuf_unmap(struct d
 {
 	struct ib_uverbs_dmabuf_file *priv = attachment->dmabuf->priv;
 
-	dma_resv_assert_held(priv->dmabuf->resv);
+	dma_resv_assert_held(attachment->dmabuf->resv);
 	dma_buf_free_sgt(attachment, sgt, dir);
 	kref_put(&priv->kref, ib_uverbs_dmabuf_done);
 }
@@ -73,7 +73,25 @@ static void uverbs_dmabuf_release(struct
 	if (!priv->uobj.context)
 		return;
 
+	/*
+	 * uverbs_uobject_release() may drop the last reference to the uobject,
+	 * keep it around until the dmabuf pointer below has been cleared.
+	 */
+	uverbs_uobject_get(&priv->uobj);
 	uverbs_uobject_release(&priv->uobj);
+
+	/*
+	 * The dma_buf is freed once this function returns. If the uobject was
+	 * not destroyed above, because the ufile is concurrently being cleaned
+	 * up, it is still reachable through the ufile's uobjects list and the
+	 * mmap entry's dmabufs list. Make sure those paths are not in the
+	 * middle of using the dma_buf and cannot use it afterwards.
+	 */
+	mutex_lock(&priv->dmabuf_release_lock);
+	priv->dmabuf = NULL;
+	mutex_unlock(&priv->dmabuf_release_lock);
+
+	uverbs_uobject_put(&priv->uobj);
 }
 
 static const struct dma_buf_ops uverbs_dmabuf_ops = {
@@ -99,6 +117,8 @@ static int UVERBS_HANDLER(UVERBS_METHOD_
 	off_t pg_off;
 	int ret;
 
+	mutex_init(&uverbs_dmabuf->dmabuf_release_lock);
+
 	ret = uverbs_get_const(&pg_off, attrs, UVERBS_ATTR_ALLOC_DMABUF_PGOFF);
 	if (ret)
 		return ret;
@@ -162,24 +182,11 @@ static void uverbs_dmabuf_fd_destroy_uob
 {
 	struct ib_uverbs_dmabuf_file *uverbs_dmabuf =
 		container_of(uobj, struct ib_uverbs_dmabuf_file, uobj);
-	bool wait_for_comp = false;
 
 	mutex_lock(&uverbs_dmabuf->mmap_entry->dmabufs_lock);
-	dma_resv_lock(uverbs_dmabuf->dmabuf->resv, NULL);
 	if (!uverbs_dmabuf->revoked) {
-		uverbs_dmabuf->revoked = true;
 		list_del(&uverbs_dmabuf->dmabufs_elm);
-		dma_buf_invalidate_mappings(uverbs_dmabuf->dmabuf);
-		dma_resv_wait_timeout(uverbs_dmabuf->dmabuf->resv,
-				      DMA_RESV_USAGE_BOOKKEEP, false,
-				      MAX_SCHEDULE_TIMEOUT);
-		wait_for_comp = true;
-	}
-	dma_resv_unlock(uverbs_dmabuf->dmabuf->resv);
-	if (wait_for_comp) {
-		kref_put(&uverbs_dmabuf->kref, ib_uverbs_dmabuf_done);
-		/* Let's wait till all DMA unmap are completed. */
-		wait_for_completion(&uverbs_dmabuf->comp);
+		ib_uverbs_dmabuf_revoke(uverbs_dmabuf);
 	}
 	mutex_unlock(&uverbs_dmabuf->mmap_entry->dmabufs_lock);
 
author maintainer
#147 lore raw

PATCH 147/547 RDMA/irdma: avoid use-after-free in icrdma_remove

In reply to Greg Kroah-Hartman

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

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

From: Guangshuo Li <[email protected]>

commit 8a8088b899e4cdfe558428cd6113d45df81625be upstream.

icrdma_remove() dereferences iwdev after calling
irdma_ib_unregister_device():

irdma_ib_unregister_device(iwdev)

    -> ib_unregister_device(&iwdev->ibdev)
      -> __ib_unregister_device()
        -> ib_dealloc_device()

irdma registers irdma_ib_dealloc_device() as the dealloc_driver callback in its ib_device_ops. The RDMA core explicitly documents ib_unregister_device() that when ops.dealloc_driver is used, ib_dev will be freed upon return from the function.

The ib_device is embedded in struct irdma_device and iwdev itself was allocated by ib_alloc_device(irdma_device, ibdev). Consequently, once irdma_ib_unregister_device() returns, iwdev must no longer be dereferenced.

However, icrdma_remove() currently accesses iwdev->rf afterwards when deinitializing interrupts, destroying ah_tbl_lock, and freeing rf. Although the final ib_device storage is released with kfree_rcu(), the object lifetime has already ended and callers must not rely on the RCU grace period to continue dereferencing iwdev.

Save iwdev->rf before unregistering the RDMA device and use the saved pointer for the remaining cleanup.

This issue was found by manual code inspection.

Fixes 8498a30e1b94 ("RDMA/irdma: Register auxiliary driver and implement private channel OPs")
---
 drivers/infiniband/hw/irdma/icrdma_if.c |    9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)
drivers/infiniband/hw/irdma/icrdma_if.c +5 -4
@@ -318,14 +318,15 @@ static void icrdma_remove(struct auxilia
 		container_of(aux_dev, struct iidc_rdma_core_auxiliary_dev, adev);
 	struct iidc_rdma_core_dev_info *cdev_info = idc_adev->cdev_info;
 	struct irdma_device *iwdev = auxiliary_get_drvdata(aux_dev);
-	u8 rdma_ver = iwdev->rf->rdma_ver;
+	struct irdma_pci_f *rf = iwdev->rf;
+	u8 rdma_ver = rf->rdma_ver;
 
 	ice_rdma_update_vsi_filter(cdev_info, iwdev->vsi_num, false);
 	irdma_ib_unregister_device(iwdev);
-	icrdma_deinit_interrupts(iwdev->rf, cdev_info);
-	mutex_destroy(&iwdev->rf->ah_tbl_lock);
+	icrdma_deinit_interrupts(rf, cdev_info);
+	mutex_destroy(&rf->ah_tbl_lock);
 
-	kfree(iwdev->rf);
+	kfree(rf);
 
 	pr_debug("INIT: Gen[%d] func[%d] device remove success\n",
 		 rdma_ver, PCI_FUNC(cdev_info->pdev->devfn));
author maintainer
#148 lore raw

PATCH 148/547 rapidio: mport_cdev: fix use-after-free in mport_mm_close()

In reply to Greg Kroah-Hartman

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

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

From: James Kim <[email protected]>

commit 0f2cd84858e67cf8e02438bf28243bcdc67aa49a upstream.

A use-after-free vulnerability was identified in mport_mm_close() in drivers/rapidio/devices/rio_mport_cdev.c, identical to the pattern previously addressed in dma_req_free().

This is observable from userspace when an application creates an mmap mapping via the RapidIO character device and subsequently unmaps it (or terminates, triggering exit_mmap()). During munmap, mport_mm_close() is invoked and drops the mapping reference via kref_put().

If kref_put() drops the last reference, mport_release_mapping() is called, which frees the underlying rio_mport_mapping structure. The subsequent mutex_unlock() then dereferences map->md to unlock buf_mutex, leading to a use-after-free:

   mport_mm_close()
     -> mutex_lock(&map->md->buf_mutex);
     ...
     -> kref_put(&map->ref, mport_release_mapping); /* map is freed */
     -> mutex_unlock(&map->md->buf_mutex);          /* UAF: map used */

Fix this by caching map->md before kref_put() and using the cached pointer for mutex unlocking, ensuring that freed memory is not accessed.

Fixes e8de370188d0 ("rapidio: add mport char device driver")
Cc Alexandre Bounine <[email protected]>
Cc Dan Carpenter <[email protected]>
Cc Greg Kroah-Hartman <[email protected]>
Cc Matt Porter <[email protected]>
---
 drivers/rapidio/devices/rio_mport_cdev.c |    5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/rapidio/devices/rio_mport_cdev.c +3 -2
@@ -2167,11 +2167,12 @@ static void mport_mm_open(struct vm_area
 static void mport_mm_close(struct vm_area_struct *vma)
 {
 	struct rio_mport_mapping *map = vma->vm_private_data;
+	struct mport_dev *md = map->md;
 
 	rmcd_debug(MMAP, "%pad", &map->phys_addr);
-	mutex_lock(&map->md->buf_mutex);
+	mutex_lock(&md->buf_mutex);
 	kref_put(&map->ref, mport_release_mapping);
-	mutex_unlock(&map->md->buf_mutex);
+	mutex_unlock(&md->buf_mutex);
 }
 
 static const struct vm_operations_struct vm_ops = {
author maintainer
#149 lore raw

PATCH 149/547 pps: generators: fix use-after-free when closing a removed device

In reply to Greg Kroah-Hartman

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

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

From: Danish Khateeb <[email protected]>

commit d19552611cb2eb6329826871565e5309bec2f288 upstream.

The cdev of a PPS generator is embedded in struct pps_gen_device, but nothing ties the lifetime of that structure to the cdev: pps_gen is freed by the release function of its device, and an open file holds a device reference only until pps_gen_cdev_release() drops it.

When the generator is unregistered while /dev/pps-genN is open, that put_device() drops the last reference and frees pps_gen, and __fput() then calls cdev_put() on the freed cdev:

  BUG: KASAN: slab-use-after-free in cdev_put+0x53/0x60
  Read of size 8 at addr ffff88801383e138 by task ppsgen64/149
  Call Trace:
   cdev_put+0x53/0x60
   __fput+0x745/0xad0
   fput_close_sync+0xd9/0x1b0
   __x64_sys_close+0x86/0xf0
  ...
  Freed by task 149:
   kfree+0x25a/0x6d0
   device_release+0xca/0x3c0
   kobject_put+0x169/0x320
   pps_gen_cdev_release+0x51/0x80
   __fput+0x36a/0xad0

pps.c had the same bug, fixed in commit c79a39dc8d06 ("pps: Fix a use-after-free").

Fix it the usual way: embed the struct device in pps_gen_device and register both with cdev_device_add(). This makes the device the parent of the cdev, so the cdev holds a device reference until the last file is closed.

---
 drivers/pps/generators/pps_gen.c |   63 +++++++++++++++++++--------------------
 include/linux/pps_gen_kernel.h   |    2 -
 2 files changed, 32 insertions(+), 33 deletions(-)
drivers/pps/generators/pps_gen.c +31 -32
@@ -63,7 +63,7 @@ static long pps_gen_cdev_ioctl(struct fi
 
 	switch (cmd) {
 	case PPS_GEN_SETENABLE:
-		dev_dbg(pps_gen->dev, "PPS_GEN_SETENABLE\n");
+		dev_dbg(&pps_gen->dev, "PPS_GEN_SETENABLE\n");
 
 		ret = get_user(status, uiuarg);
 		if (ret)
@@ -77,7 +77,7 @@ static long pps_gen_cdev_ioctl(struct fi
 		break;
 
 	case PPS_GEN_USESYSTEMCLOCK:
-		dev_dbg(pps_gen->dev, "PPS_GEN_USESYSTEMCLOCK\n");
+		dev_dbg(&pps_gen->dev, "PPS_GEN_USESYSTEMCLOCK\n");
 
 		ret = put_user(pps_gen->info->use_system_clock, uiuarg);
 		if (ret)
@@ -89,12 +89,12 @@ static long pps_gen_cdev_ioctl(struct fi
 		struct pps_gen_event info;
 		unsigned int ev = pps_gen->last_ev;
 
-		dev_dbg(pps_gen->dev, "PPS_GEN_FETCHEVENT\n");
+		dev_dbg(&pps_gen->dev, "PPS_GEN_FETCHEVENT\n");
 
 		ret = wait_event_interruptible(pps_gen->queue,
 				ev != pps_gen->last_ev);
 		if (ret == -ERESTARTSYS) {
-			dev_dbg(pps_gen->dev, "pending signal caught\n");
+			dev_dbg(&pps_gen->dev, "pending signal caught\n");
 			return -EINTR;
 		}
 
@@ -121,7 +121,7 @@ static int pps_gen_cdev_open(struct inod
 	struct pps_gen_device *pps_gen = container_of(inode->i_cdev,
 				struct pps_gen_device, cdev);
 
-	get_device(pps_gen->dev);
+	get_device(&pps_gen->dev);
 	file->private_data = pps_gen;
 	return 0;
 }
@@ -130,7 +130,7 @@ static int pps_gen_cdev_release(struct i
 {
 	struct pps_gen_device *pps_gen = file->private_data;
 
-	put_device(pps_gen->dev);
+	put_device(&pps_gen->dev);
 	return 0;
 }
 
@@ -151,19 +151,15 @@ static void pps_gen_device_destruct(stru
 {
 	struct pps_gen_device *pps_gen = dev_get_drvdata(dev);
 
-	cdev_del(&pps_gen->cdev);
-
 	pr_debug("deallocating pps-gen%d\n", pps_gen->id);
 	ida_free(&pps_gen_ida, pps_gen->id);
 
-	kfree(dev);
 	kfree(pps_gen);
 }
 
 static int pps_gen_register_cdev(struct pps_gen_device *pps_gen)
 {
 	int err;
-	dev_t devt;
 
 	err = ida_alloc_max(&pps_gen_ida, PPS_GEN_MAX_SOURCES - 1, GFP_KERNEL);
 	if (err < 0) {
@@ -171,46 +167,52 @@ static int pps_gen_register_cdev(struct
 			pr_err("too many PPS sources in the system\n");
 			err = -EBUSY;
 		}
+		kfree(pps_gen);
 		return err;
 	}
 	pps_gen->id = err;
 
-	devt = MKDEV(MAJOR(pps_gen_devt), pps_gen->id);
+	/*
+	 * From here on pps_gen belongs to its device and is freed by
+	 * pps_gen_device_destruct(). The cdev holds a reference to the
+	 * device, so pps_gen stays around until the last file is closed.
+	 */
+	device_initialize(&pps_gen->dev);
+	pps_gen->dev.class = &pps_gen_class;
+	pps_gen->dev.parent = pps_gen->info->parent;
+	pps_gen->dev.devt = MKDEV(MAJOR(pps_gen_devt), pps_gen->id);
+	pps_gen->dev.release = pps_gen_device_destruct;
+	dev_set_drvdata(&pps_gen->dev, pps_gen);
 
 	cdev_init(&pps_gen->cdev, &pps_gen_cdev_fops);
 	pps_gen->cdev.owner = pps_gen->info->owner;
 
-	err = cdev_add(&pps_gen->cdev, devt, 1);
+	err = dev_set_name(&pps_gen->dev, "pps-gen%d", pps_gen->id);
+	if (err)
+		goto put_dev;
+
+	err = cdev_device_add(&pps_gen->cdev, &pps_gen->dev);
 	if (err) {
 		pr_err("failed to add char device %d:%d\n",
 				MAJOR(pps_gen_devt), pps_gen->id);
-		goto free_ida;
+		goto put_dev;
 	}
-	pps_gen->dev = device_create(&pps_gen_class, pps_gen->info->parent, devt,
-				     pps_gen, "pps-gen%d", pps_gen->id);
-	if (IS_ERR(pps_gen->dev)) {
-		err = PTR_ERR(pps_gen->dev);
-		goto del_cdev;
-	}
-	pps_gen->dev->release = pps_gen_device_destruct;
-	dev_set_drvdata(pps_gen->dev, pps_gen);
 
 	pr_debug("generator got cdev (%d:%d)\n",
 			MAJOR(pps_gen_devt), pps_gen->id);
 
 	return 0;
 
-del_cdev:
-	cdev_del(&pps_gen->cdev);
-free_ida:
-	ida_free(&pps_gen_ida, pps_gen->id);
+put_dev:
+	put_device(&pps_gen->dev);
 	return err;
 }
 
 static void pps_gen_unregister_cdev(struct pps_gen_device *pps_gen)
 {
 	pr_debug("unregistering pps-gen%d\n", pps_gen->id);
-	device_destroy(&pps_gen_class, pps_gen->dev->devt);
+	cdev_device_del(&pps_gen->cdev, &pps_gen->dev);
+	put_device(&pps_gen->dev);
 }
 
 /*
@@ -244,18 +246,15 @@ struct pps_gen_device *pps_gen_register_
 	init_waitqueue_head(&pps_gen->queue);
 	spin_lock_init(&pps_gen->lock);
 
-	/* Create the char device */
+	/* Create the char device, this frees pps_gen on failure */
 	err = pps_gen_register_cdev(pps_gen);
 	if (err < 0) {
 		pr_err(" unable to create char device\n");
-		goto kfree_pps_gen;
+		goto pps_gen_register_source_exit;
 	}
 
 	return pps_gen;
 
-kfree_pps_gen:
-	kfree(pps_gen);
-
 pps_gen_register_source_exit:
 	pr_err("unable to register generator\n");
 
@@ -289,7 +288,7 @@ void pps_gen_event(struct pps_gen_device
 {
 	unsigned long flags;
 
-	dev_dbg(pps_gen->dev, "PPS generator event %u\n", event);
+	dev_dbg(&pps_gen->dev, "PPS generator event %u\n", event);
 
 	spin_lock_irqsave(&pps_gen->lock, flags);
 
include/linux/pps_gen_kernel.h +1 -1
@@ -54,7 +54,7 @@ struct pps_gen_device {
 
 	unsigned int id;			/* PPS generator unique ID */
 	struct cdev cdev;
-	struct device *dev;
+	struct device dev;
 	struct fasync_struct *async_queue;	/* fasync method */
 	spinlock_t lock;
 };
author maintainer
#150 lore raw

PATCH 150/547 PM: EM: Fix use-after-free of perf domain in netlink doit handlers

In reply to Greg Kroah-Hartman

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

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

From: Fan Wu <[email protected]>

commit f58dacfbadb7be7c7dbb2b95e9341ad56710849e upstream.

The doit handlers dropped em_pd_list_mutex before dereferencing the perf domain, so a concurrent device unregister could free it while the reply was being built.

Encode the reply from em_perf_domain_for_id() callbacks, which run under the mutex, and allocate the skb outside of it, like the dumpit path already does.

This issue was found by an in-house static analysis tool.

Fixes 380ff27af25e ("PM: EM: Add dump to get-perf-domains in the EM YNL spec")
Fixes f2d2946eaa5c ("PM: EM: Implement em_nl_get_pd_table_doit()")
Cc All applicable <[email protected]>
---
 kernel/power/em_netlink.c   |  122 +++++++++++++++++++++++++++-----------------
 kernel/power/em_netlink.h   |    8 +-
 kernel/power/energy_model.c |    8 +-
 3 files changed, 87 insertions(+), 51 deletions(-)
kernel/power/em_netlink.c +77 -45
@@ -95,41 +95,62 @@ static int __em_nl_get_pd_for_dump(struc
 	return ret;
 }
 
+struct em_nl_doit_ctx {
+	struct genl_info *info;
+	int cmd;
+	struct sk_buff *msg;
+};
+
+static int __em_nl_get_pd_doit_fill(struct em_perf_domain *pd, void *data)
+{
+	struct em_nl_doit_ctx *ctx = data;
+	void *hdr;
+
+	hdr = genlmsg_put_reply(ctx->msg, ctx->info, &dev_energymodel_nl_family, 0,
+				ctx->cmd);
+	if (!hdr)
+		return -EMSGSIZE;
+
+	if (__em_nl_get_pd(pd, ctx->msg)) {
+		genlmsg_cancel(ctx->msg, hdr);
+		return -EMSGSIZE;
+	}
+
+	genlmsg_end(ctx->msg, hdr);
+	return 0;
+}
+
 int dev_energymodel_nl_get_perf_domains_doit(struct sk_buff *skb,
-					      struct genl_info *info)
+					     struct genl_info *info)
 {
-	int id, ret = -EMSGSIZE, msg_sz = 0;
-	int cmd = info->genlhdr->cmd;
-	struct em_perf_domain *pd;
+	struct em_nl_doit_ctx ctx = {
+		.info = info,
+		.cmd = info->genlhdr->cmd,
+	};
 	struct sk_buff *msg;
-	void *hdr;
+	int id, ret, msg_sz = 0;
 
 	if (!info->attrs[DEV_ENERGYMODEL_A_PERF_DOMAIN_PERF_DOMAIN_ID])
 		return -EINVAL;
 
 	id = nla_get_u32(info->attrs[DEV_ENERGYMODEL_A_PERF_DOMAIN_PERF_DOMAIN_ID]);
-	pd = em_perf_domain_get_by_id(id);
-	if (!pd)
-		return -EINVAL;
 
-	__em_nl_get_pd_size(pd, &msg_sz);
+	/* Encode under em_pd_list_mutex, like the dumpit path. */
+	ret = em_perf_domain_for_id(id, __em_nl_get_pd_size, &msg_sz);
+	if (ret)
+		return ret;
+
 	msg = genlmsg_new(msg_sz, GFP_KERNEL);
 	if (!msg)
 		return -ENOMEM;
 
-	hdr = genlmsg_put_reply(msg, info, &dev_energymodel_nl_family, 0, cmd);
-	if (!hdr)
-		goto out_free_msg;
-
-	ret = __em_nl_get_pd(pd, msg);
+	ctx.msg = msg;
+	ret = em_perf_domain_for_id(id, __em_nl_get_pd_doit_fill, &ctx);
 	if (ret)
-		goto out_cancel_msg;
-	genlmsg_end(msg, hdr);
+		goto out_free_msg;
 
 	return genlmsg_reply(msg, info);
 
-out_cancel_msg:
-	genlmsg_cancel(msg, hdr);
 out_free_msg:
 	nlmsg_free(msg);
 	return ret;
@@ -148,19 +169,6 @@ int dev_energymodel_nl_get_perf_domains_
 	return for_each_em_perf_domain(__em_nl_get_pd_for_dump, &ctx);
 }
 
-static struct em_perf_domain *__em_nl_get_pd_table_id(struct nlattr **attrs)
-{
-	struct em_perf_domain *pd;
-	int id;
-
-	if (!attrs[DEV_ENERGYMODEL_A_PERF_TABLE_PERF_DOMAIN_ID])
-		return NULL;
-
-	id = nla_get_u32(attrs[DEV_ENERGYMODEL_A_PERF_TABLE_PERF_DOMAIN_ID]);
-	pd = em_perf_domain_get_by_id(id);
-	return pd;
-}
-
 static int __em_nl_get_pd_table_size(const struct em_perf_domain *pd)
 {
 	int id_sz, ps_sz;
@@ -245,34 +253,58 @@ out_err:
 	return -EMSGSIZE;
 }
 
+static int __em_nl_get_pd_table_size_cb(struct em_perf_domain *pd, void *data)
+{
+	*(int *)data = __em_nl_get_pd_table_size(pd);
+	return 0;
+}
+
+static int __em_nl_get_pd_table_doit_fill(struct em_perf_domain *pd,
+					  void *data)
+{
+	struct em_nl_doit_ctx *ctx = data;
+	void *hdr;
+
+	hdr = genlmsg_put_reply(ctx->msg, ctx->info, &dev_energymodel_nl_family, 0,
+				ctx->cmd);
+	if (!hdr)
+		return -EMSGSIZE;
+
+	if (__em_nl_get_pd_table(ctx->msg, pd))
+		return -EMSGSIZE;
+
+	genlmsg_end(ctx->msg, hdr);
+	return 0;
+}
+
 int dev_energymodel_nl_get_perf_table_doit(struct sk_buff *skb,
-					    struct genl_info *info)
+					   struct genl_info *info)
 {
-	int cmd = info->genlhdr->cmd;
-	int msg_sz, ret = -EMSGSIZE;
-	struct em_perf_domain *pd;
+	struct em_nl_doit_ctx ctx = {
+		.info = info,
+		.cmd = info->genlhdr->cmd,
+	};
 	struct sk_buff *msg;
-	void *hdr;
+	int id, ret, msg_sz;
 
-	pd = __em_nl_get_pd_table_id(info->attrs);
-	if (!pd)
+	if (!info->attrs[DEV_ENERGYMODEL_A_PERF_TABLE_PERF_DOMAIN_ID])
 		return -EINVAL;
 
-	msg_sz = __em_nl_get_pd_table_size(pd);
+	id = nla_get_u32(info->attrs[DEV_ENERGYMODEL_A_PERF_TABLE_PERF_DOMAIN_ID]);
+
+	ret = em_perf_domain_for_id(id, __em_nl_get_pd_table_size_cb, &msg_sz);
+	if (ret)
+		return ret;
 
 	msg = genlmsg_new(msg_sz, GFP_KERNEL);
 	if (!msg)
 		return -ENOMEM;
 
-	hdr = genlmsg_put_reply(msg, info, &dev_energymodel_nl_family, 0, cmd);
-	if (!hdr)
-		goto out_free_msg;
-
-	ret = __em_nl_get_pd_table(msg, pd);
+	ctx.msg = msg;
+	ret = em_perf_domain_for_id(id, __em_nl_get_pd_table_doit_fill, &ctx);
 	if (ret)
 		goto out_free_msg;
 
-	genlmsg_end(msg, hdr);
 	return genlmsg_reply(msg, info);
 
 out_free_msg:
kernel/power/em_netlink.h +5 -3
@@ -12,7 +12,8 @@
 #if defined(CONFIG_ENERGY_MODEL) && defined(CONFIG_NET)
 int for_each_em_perf_domain(int (*cb)(struct em_perf_domain*, void *),
 			    void *data);
-struct em_perf_domain *em_perf_domain_get_by_id(int id);
+int em_perf_domain_for_id(int id, int (*cb)(struct em_perf_domain *, void *),
+			  void *data);
 void em_notify_pd_created(const struct em_perf_domain *pd);
 void em_notify_pd_deleted(const struct em_perf_domain *pd);
 void em_notify_pd_updated(const struct em_perf_domain *pd);
@@ -24,9 +25,10 @@ int for_each_em_perf_domain(int (*cb)(st
 	return -EINVAL;
 }
 static inline
-struct em_perf_domain *em_perf_domain_get_by_id(int id)
+int em_perf_domain_for_id(int id, int (*cb)(struct em_perf_domain *, void *),
+			  void *data)
 {
-	return NULL;
+	return -EINVAL;
 }
 
 static inline void em_notify_pd_created(const struct em_perf_domain *pd) {}
kernel/power/energy_model.c +5 -3
@@ -1031,7 +1031,9 @@ int for_each_em_perf_domain(int (*cb)(st
 	return 0;
 }
 
-struct em_perf_domain *em_perf_domain_get_by_id(int id)
+/* Run @cb on the matching domain with em_pd_list_mutex held. */
+int em_perf_domain_for_id(int id, int (*cb)(struct em_perf_domain *, void *),
+			  void *data)
 {
 	struct em_perf_domain *pd;
 
@@ -1040,9 +1042,9 @@ struct em_perf_domain *em_perf_domain_ge
 
 	list_for_each_entry(pd, &em_pd_list, node) {
 		if (pd->id == id)
-			return pd;
+			return cb(pd, data);
 	}
 
-	return NULL;
+	return -EINVAL;
 }
 #endif
author maintainer
#151 lore raw

PATCH 151/547 platform/x86: asus-wmi: fix use-after-free unregistering kbd_led led

In reply to Greg Kroah-Hartman

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

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

From: Denis Benato <[email protected]>

commit 639bc2254816b7c4e7a9801a7b3aa71bfa3f915c upstream.

kbd_led_update_all() registers asus->kbd_led with devm_led_classdev_register() on the platform device, but kbd_led is embedded in struct asus_wmi, which asus_wmi_remove() frees at its end. The driver core calls .remove() before devres_release_all(), so the deferred devres release runs led_classdev_unregister() on memory that has already been freed. Whether that faults depends on whether the slab has been reused in between, which makes the crash on module unload intermittent and silently corrupts the led classdev state in the remaining runs.

Unregister the led classdev explicitly in asus_wmi_led_exit(), after the led workqueue has been destroyed: kbd_led_work can then neither run nor be queued anymore, since asus_ref.asus is NULL too, so kbd_led_registered is stable and the classdev can be released while the memory embedding it is still alive. devm_led_classdev_unregister() also drops the devres entry, leaving nothing to run at unbind cleanup time; it warns when no devres entry exists, hence the kbd_led_registered check.

---
 drivers/platform/x86/asus-wmi.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)
drivers/platform/x86/asus-wmi.c +12 -0
index c2af1f049b67..0eb43ca44119 100644
@@ -2088,6 +2088,18 @@ static void asus_wmi_led_exit(struct asus_wmi *asus)
 
 	if (asus->led_workqueue)
 		destroy_workqueue(asus->led_workqueue);
+
+	/*
+	 * kbd_led is registered lazily by kbd_led_work: now that the
+	 * workqueue is destroyed and asus_ref.asus is NULL, the work can
+	 * neither run nor be queued anymore, furthermore leaving it to
+	 * devres would run the unregister from devres_release_all(),
+	 * after .remove() returned and the struct asus_wmi embedding
+	 * kbd_led has been freed.
+	 */
+	if (asus->kbd_led_registered)
+		devm_led_classdev_unregister(&asus->platform_device->dev,
+					     &asus->kbd_led);
 }
 
 static int asus_wmi_led_init(struct asus_wmi *asus)
Signature · 1 line
2.56.0
author maintainer
#152 lore raw

PATCH 152/547 platform/x86/amd: hfi: Fix a use-after-free when unloading the driver

In reply to Greg Kroah-Hartman

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

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

From: Mario Limonciello <[email protected]>

commit 55d8406dfa2fa8ad8ac2f053c2a53a97d8b0ce48 upstream.

amd_hfi_probe() registers CPU hotplug callbacks with cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, ...) and schedules the static sched_amd_hfi_itmt_work work item, but amd_hfi_remove() tears down neither. The dynamically assigned hotplug state returned by cpuhp_setup_state() is discarded, so cpuhp_remove_state() can never be called, and the pending work is never cancelled.

After the module is unloaded and its memory is freed, any subsequent CPU hotplug event or execution of the scheduled work dereferences the stale callback and work function pointers, resulting in a use-after-free and kernel panic.

Store the hotplug state returned by cpuhp_setup_state() and, on removal, call cpuhp_remove_state() to unregister the callbacks and cancel_work_sync() to flush the scheduled work before the module memory goes away.

Fixes bb20421c05fc ("platform/x86: hfi: Add online and offline callback support")
---
 drivers/platform/x86/amd/hfi/hfi.c |    5 +++++
 1 file changed, 5 insertions(+)
drivers/platform/x86/amd/hfi/hfi.c +5 -0
@@ -76,6 +76,8 @@ struct amd_hfi_data {
 	struct amd_shmem_info	*shmem;
 
 	struct dentry *dbgfs_dir;
+
+	int cpuhp_state;
 };
 
 /**
@@ -244,6 +246,8 @@ static void amd_hfi_remove(struct platfo
 {
 	struct amd_hfi_data *dev = platform_get_drvdata(pdev);
 
+	cpuhp_remove_state(dev->cpuhp_state);
+	cancel_work_sync(&sched_amd_hfi_itmt_work);
 	debugfs_remove_recursive(dev->dbgfs_dir);
 }
 
@@ -494,6 +498,7 @@ static int amd_hfi_probe(struct platform
 				amd_hfi_online, amd_hfi_offline);
 	if (ret < 0)
 		return ret;
+	amd_hfi_data->cpuhp_state = ret;
 
 	schedule_work(&sched_amd_hfi_itmt_work);
 
author maintainer
#153 lore raw

PATCH 153/547 nvmet: fix use-after-free of the old registrant in nvmet_pr_preempt()

In reply to Greg Kroah-Hartman

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

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

From: Daejun Park <[email protected]>

commit f316aa7f018840523939183425394931b373e4d7 upstream.

nvmet_pr_preempt() handles a preempt sent by the reservation holder by changing the reservation type with nvmet_pr_update_reg_attr(), unless the reservation is of an All Registrants type. For the holder that helper does not modify the registrant in place: it puts a copy on the registrant list, points pr->holder to the copy and passes the old registrant to kfree_rcu().

If the reservation type changed, nvmet_pr_preempt() then hands &reg->hostid of that old registrant to nvmet_pr_resv_released(). Unless the reservation released notification is masked, that function takes subsys->lock and compares the host id against every controller of the subsystem. The caller only holds pr->pr_sem and is not in an RCU read-side critical section, so nothing keeps the old registrant alive while it is read.

The result is a read of 16 freed bytes that decides which controllers get the notification. Found by code inspection. kfree_rcu() defers the free, so it usually happens after the read; when the pending free is forced to run before the read, KASAN reports the host id as freed memory.

Pass the host id of the controller that sent the command instead. The registrant was looked up by that host id, and the controller outlives the request.

Fixes 5a47c2080a73 ("nvmet: support reservation feature")
---
 drivers/nvme/target/pr.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/nvme/target/pr.c +1 -1
@@ -593,7 +593,7 @@ static u16 nvmet_pr_preempt(struct nvmet
 		status = nvmet_pr_update_reg_attr(pr, holder,
 				nvmet_pr_update_holder_rtype, &rtype);
 		if (!status && original_rtype != rtype)
-			nvmet_pr_resv_released(pr, &reg->hostid);
+			nvmet_pr_resv_released(pr, &ctrl->hostid);
 		return status;
 	}
 
author maintainer
#154 lore raw

PATCH 154/547 nvmet-fc: fix use-after-free in nvmet_fc_ls_create_connection()

In reply to Greg Kroah-Hartman

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

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

From: Yehyeong Lee <[email protected]>

commit 2c29f8c9b9e598c09fa50aa02200136a107f6b3f upstream.

nvmet_fc_ls_create_connection() looks up the association with nvmet_fc_find_target_assoc(), which returns it with a reference held, and drops that reference as soon as the target queue has been allocated. iod->assoc is then dereferenced again by nvmet_fc_makeconnid() while building the connection id.

The queue only borrows the pointer and takes no reference of its own. Once the lookup reference is dropped the association is kept alive solely by the reference taken when it was created, so a disconnect LS or a remote port unregister running concurrently can free it before nvmet_fc_makeconnid() reads it:

BUG: KASAN: slab-use-after-free in nvmet_fc_handle_ls_rqst_work (drivers/nvme/target/fc.c:193 drivers/nvme/target/fc.c:1841 drivers/nvme/target/fc.c:1995 drivers/nvme/target/fc.c:2021)
Read of size 8 at addr ffff888179f1b000 by task kworker/u9:2/1167

Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
Workqueue: nvmet-wq nvmet_fc_handle_ls_rqst_work
Call Trace:
 <TASK>
 dump_stack_lvl (lib/dump_stack.c:94 lib/dump_stack.c:120)
 print_report (mm/kasan/report.c:378 mm/kasan/report.c:482)
 kasan_report (mm/kasan/report.c:595)
 nvmet_fc_handle_ls_rqst_work (drivers/nvme/target/fc.c:193 drivers/nvme/target/fc.c:1841 drivers/nvme/target/fc.c:1995 drivers/nvme/target/fc.c:2021)
 process_scheduled_works (kernel/workqueue.c:3322 kernel/workqueue.c:3405)
 worker_thread (kernel/workqueue.c:3486)
 kthread (kernel/kthread.c:436)
 ret_from_fork (archkernel/process.c:158)
 ret_from_fork_asm (arch/x86/entry/entry_64.S:245)
 </TASK>

Freed by task 1167 on cpu 0 at 405.998150s:
 kasan_save_track (mm/kasan/common.c:57 mm/kasan/common.c:78)
 kasan_save_free_info (mm/kasan/generic.c:584)
 __kasan_slab_free (mm/kasan/common.c:253 mm/kasan/common.c:285)
 kfree (include/linux/kasan.h:235 mm/slub.c:2705 mm/slub.c:6405 mm/slub.c:6720)
 nvmet_fc_handle_ls_rqst_work (drivers/nvme/target/fc.c:1808 drivers/nvme/target/fc.c:1995 drivers/nvme/target/fc.c:2021)
 process_scheduled_works (kernel/workqueue.c:3322 kernel/workqueue.c:3405)
 worker_thread (kernel/workqueue.c:3486)
 kthread (kernel/kthread.c:436)
 ret_from_fork (archkernel/process.c:158)
 ret_from_fork_asm (arch/x86/entry/entry_64.S:245)

The buggy address belongs to the object at ffff888179f1b000
 which belongs to the cache kmalloc-2k of size 2048

The buggy address is located 0 bytes inside of
freed 2048-byte region [ffff888179f1b000, ffff888179f1b800)

Hold the lookup reference until the response has been built, and drop it on the error path as well.

---
 drivers/nvme/target/fc.c |    8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
drivers/nvme/target/fc.c +5 -3
@@ -1796,9 +1796,6 @@ nvmet_fc_ls_create_connection(struct nvm
 					be16_to_cpu(rqst->connect_cmd.sqsize));
 			if (!queue)
 				ret = VERR_QUEUE_ALLOC_FAIL;
-
-			/* release get taken in nvmet_fc_find_target_assoc */
-			nvmet_fc_tgt_a_put(iod->assoc);
 		}
 	}
 
@@ -1812,6 +1809,8 @@ nvmet_fc_ls_create_connection(struct nvm
 					FCNVME_RJT_RC_INV_ASSOC :
 					FCNVME_RJT_RC_LOGIC,
 				FCNVME_RJT_EXP_NONE, 0);
+		if (iod->assoc)
+			nvmet_fc_tgt_a_put(iod->assoc);
 		return;
 	}
 
@@ -1833,6 +1832,9 @@ nvmet_fc_ls_create_connection(struct nvm
 	acc->connectid.connection_id =
 			cpu_to_be64(nvmet_fc_makeconnid(iod->assoc,
 				be16_to_cpu(rqst->connect_cmd.qid)));
+
+	/* release get taken in nvmet_fc_find_target_assoc */
+	nvmet_fc_tgt_a_put(iod->assoc);
 }
 
 /*
author maintainer
#155 lore raw

PATCH 155/547 iommufd: Fix event queue release use-after-free

In reply to Greg Kroah-Hartman

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

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

From: Nirmoy Das <[email protected]>

commit 440ca8a4b69f40088065b9e05ef11373292a254e upstream.

iommufd_eventq_fops_release() drops the file's users reference before reading eventq->ictx. Once that reference is dropped, IOMMU_DESTROY in another thread can remove and free the event queue, so the later load accesses freed memory.

Read ictx while the users reference still pins the event queue, then drop the reference and put the saved context. The context reference taken by iommufd_eventq_init() keeps ictx valid until the put. Fault and vEVENTQ file descriptors share this release path.

Fixes 07838f7fd529 ("iommufd: Add iommufd fault object")
Assisted-by LLM, Specula
---
 drivers/iommu/iommufd/eventq.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/iommu/iommufd/eventq.c +3 -1
@@ -396,9 +396,11 @@ static __poll_t iommufd_eventq_fops_poll
 static int iommufd_eventq_fops_release(struct inode *inode, struct file *filep)
 {
 	struct iommufd_eventq *eventq = filep->private_data;
+	/* eventq may be freed once the users reference is dropped. */
+	struct iommufd_ctx *ictx = eventq->ictx;
 
 	refcount_dec(&eventq->obj.users);
-	iommufd_ctx_put(eventq->ictx);
+	iommufd_ctx_put(ictx);
 	return 0;
 }
 
author maintainer
#156 lore raw

PATCH 156/547 landlock: Fix superblock use-after-free in release_inode()

In reply to Greg Kroah-Hartman

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

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

From: Günther Noack <[email protected]>

commit 3e271a27c46fd591d1011c7de5a644a41e2010f1 upstream.

Without this fix, release_inode() (task 1) can race with a umount operation in hook_sb_delete() (task 2). The order of operations in which the race occurs is:

* task 2: hook_sb_delete() arrives at the end of the function, waiting for landlock_superblock(sb)->inode_refs to become zero.
* task 1: release_inode(): does atomic_long_dec_and_test(), decrementing inode_refs to zero.
* task 2: gets woken up through some other means, sees that inode_refs is zero and returns. The caller is the unmount operation and proceeds to release the superblock.
* task 1: Runs wake_up_var(&landlock_superblock(sb)->inode_refs), *dereferencing the sb_security on the freed-up superblock*.

Notably, wake_up_var() does not dereference the pointer passed to it, and only uses it to determine an overapproximated set of tasks to wake up. So while it's potentially possible for an attacker to provide a different value for that pointer, this only results in the wrong set of tasks getting woken up, and in this scenario, no further tasks are actually waiting.

Nevertheless, KASAN detects it as a slab-use-after-free read on sb->s_security:

  BUG: KASAN: slab-use-after-free in release_inode+0x196/0x290
  Read of size 8 at addr ffff888103b6c0a8 by task repro/217
   release_inode+0x196/0x290
   landlock_put_object+0x71/0x90
   landlock_free_rules+0x38/0xc0
   landlock_put_ruleset+0x47/0x130
   fop_ruleset_release+0x33/0x40
   __fput+0x305/0x780
  Freed by task 54:
   kfree+0x11c/0x390
   process_scheduled_works+0x766/0xe50
   worker_thread+0x7bc/0xb20

The fix is to determine &landlock_superblock(inode->i_sb)->inode_refs only once earlier in release_inode(), and later use that precalculated address for the wake_up_var() call, without having to dereference through the superblock.

Fixes cb2c7d1a1776 ("landlock: Support filesystem access-control")
Assisted-by LLM
---
 security/landlock/fs.c |   10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
security/landlock/fs.c +5 -5
@@ -61,7 +61,7 @@ static void release_inode(struct landloc
 	__releases(object->lock)
 {
 	struct inode *const inode = object->underobj;
-	struct super_block *sb;
+	atomic_long_t *inode_refs;
 
 	if (!inode) {
 		spin_unlock(&object->lock);
@@ -77,8 +77,8 @@ static void release_inode(struct landloc
 	 * Makes sure that if the filesystem is concurrently unmounted,
 	 * hook_sb_delete() will wait for us to finish iput().
 	 */
-	sb = inode->i_sb;
-	atomic_long_inc(&landlock_superblock(sb)->inode_refs);
+	inode_refs = &landlock_superblock(inode->i_sb)->inode_refs;
+	atomic_long_inc(inode_refs);
 	spin_unlock(&object->lock);
 	/*
 	 * Because object->underobj was not NULL, hook_sb_delete() and
@@ -92,8 +92,8 @@ static void release_inode(struct landloc
 	 */
 
 	iput(inode);
-	if (atomic_long_dec_and_test(&landlock_superblock(sb)->inode_refs))
-		wake_up_var(&landlock_superblock(sb)->inode_refs);
+	if (atomic_long_dec_and_test(inode_refs))
+		wake_up_var(inode_refs);
 }
 
 static const struct landlock_object_underops landlock_fs_underops = {
author maintainer
#157 lore raw

PATCH 157/547 lockd: Fix use-after-free in nlmsvc_retry_blocked

In reply to Greg Kroah-Hartman

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

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

From: Chuck Lever <[email protected]>

commit f5b7634f0f213299a07b461fb10385c8639a4ab8 upstream.

nlmsvc_retry_blocked() examines the block at the head of nlm_blocked under nlm_blocked_lock, then releases the lock before calling nlmsvc_grant_blocked() or retry_deferred_block(). The nlm_blocked list reference is all that keeps the block alive across that window. nlmsvc_grant_blocked() does take one of its own, but not until after the lock has been dropped. Unmounting the nfsd filesystem while a lock request is still blocked reaches nlmsvc_traverse_blocks(), which drops the list reference and frees the block along with the nlm_rqst hanging off it.

  BUG: KASAN: slab-use-after-free in nlm_async_call+0xd6/0x230
  Read of size 8 at addr ffff88811b04c808 by task lockd/8377
    nlm_async_call+0xd6/0x230
    nlmsvc_retry_blocked+0x61c/0x800
    lockd+0x144/0x1c0
  Freed by task 8392:
    nlmsvc_release_block+0x231/0x290
    nlmsvc_traverse_blocks+0x139/0x1b0
    nlm_traverse_files+0x1aa/0xa00
    nlmsvc_free_host_resources+0x12/0x60
    nlm_shutdown_hosts_net+0x127/0x280
    lockd_down+0xd5/0x1c0

Take a reference before releasing nlm_blocked_lock and drop it once the retry has run.

---
 fs/lockd/svclock.c |    2 ++
 1 file changed, 2 insertions(+)
fs/lockd/svclock.c +2 -0
@@ -1023,6 +1023,7 @@ nlmsvc_retry_blocked(struct svc_rqst *rq
 			timeout = block->b_when - jiffies;
 			break;
 		}
+		kref_get(&block->b_count);
 		spin_unlock(&nlm_blocked_lock);
 
 		dprintk("nlmsvc_retry_blocked(%p, when=%ld)\n",
@@ -1033,6 +1034,7 @@ nlmsvc_retry_blocked(struct svc_rqst *rq
 			retry_deferred_block(block);
 		} else
 			nlmsvc_grant_blocked(block);
+		nlmsvc_release_block(block);
 		spin_lock(&nlm_blocked_lock);
 	}
 	spin_unlock(&nlm_blocked_lock);
author maintainer
#158 lore raw

PATCH 158/547 media: au0828: fix use-after-free in bulk_timeout timer on disconnect

In reply to Greg Kroah-Hartman

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

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

From: Fan Wu <[email protected]>

commit 521030837bee352515d5ea57cc6a29581db3506e upstream.

start_urb_transfer() arms dev->bulk_timeout, whose callback au0828_bulk_timeout() queues dev->restart_streaming; that work in turn calls start_urb_transfer() and re-arms the timer.

au0828_dvb_unregister() cancels restart_streaming on disconnect but does not sync bulk_timeout. au0828_usb_release() then frees dev with kfree(), so a timer still armed or pending at that point can fire after the free and dereference dev through timer_container_of().

Sync the timer with timer_shutdown_sync() before cancel_work_sync(). The timer callback queues the work, so the timer must be stopped first; the shutdown variant is needed because the work re-arms the timer through start_urb_transfer(). The dvb->frontend == NULL early return guards the register-failure path where the timer was never set up.

This bug was found by static analysis.

Fixes 53460c53b761 ("[media] au0828: Add timer to restart TS stream if no data arrives on bulk endpoint")
Assisted-by Codex:gpt-5.6
---
 drivers/media/usb/au0828/au0828-dvb.c |    1 +
 1 file changed, 1 insertion(+)
drivers/media/usb/au0828/au0828-dvb.c +1 -0
@@ -537,6 +537,7 @@ void au0828_dvb_unregister(struct au0828
 	if (dvb->frontend == NULL)
 		return;
 
+	timer_shutdown_sync(&dev->bulk_timeout);
 	cancel_work_sync(&dev->restart_streaming);
 
 	dvb_net_release(&dvb->net);
author maintainer
#159 lore raw

PATCH 159/547 media: cx23885: Fix use-after-free in cx23885_finidev due to race condition

In reply to Greg Kroah-Hartman

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

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

From: Pei Xiao <[email protected]>

commit 75016a992d9b03f5cc6df1414d1da35840d4feeb upstream.

In cx23885_v4l2_dev_notify_init, &dev->cx25840_work is bound with cx23885_av_work_handler, and &dev->ir_rx_work and &dev->ir_tx_work are bound with cx23885_ir_rx_work_handler and cx23885_ir_tx_work_handler. cx23885_irq can schedule these works on system_wq when an AV_CORE interrupt is received, and the IR subdevice can also schedule the IR works from its interrupt service routine via the v4l2_device notify callback.

If we remove the device, cx23885_finidev makes cleanup and the memory allocated for dev is released by kfree(dev), while the works mentioned above may still be pending or running. The sequence of operations that may lead to a UAF bug is as follows:

CPU0 CPU1

                                          | cx23885_irq
                                          | schedule_work(&dev->cx25840_work)
cx23885_finidev                           |
cx23885_input_fini(dev)                   |
cx23885_ir_fini(dev)                      |
cx23885_shutdown(dev)                     |
free_irq(pci_dev->irq, dev)               |
pci_disable_device(pci_dev)               |
cx23885_dev_unregister(dev)               |
v4l2_device_unregister(v4l2_dev)          |
kfree(dev)                                |
// dev is freed                           |
                                          | cx23885_av_work_handler
                                          | // use dev (use-after-free)

Fix it by canceling the works after the IRQ handler that can schedule them has been stopped, and before proceeding with the remaining cleanup in cx23885_finidev.

Note that the flush_work() calls in cx23885_input_ir_stop() do not close this race: they only wait for works that are already queued or running at that moment, they do not prevent the IRQ handler, which is still registered at that point, from scheduling the works again afterwards, and they are skipped entirely when dev->sd_ir is NULL. The cancel_work_sync() calls are therefore placed after free_irq(), the only point at which no new work can be scheduled.

Fixes e5514f104d87 ("V4L/DVB: cx23885: Move AV Core irq handling to a work handler")
Assisted-by Codex:deepseek-v4-flash
---
 drivers/media/pci/cx23885/cx23885-core.c |    4 ++++
 1 file changed, 4 insertions(+)
drivers/media/pci/cx23885/cx23885-core.c +4 -0
@@ -2246,6 +2246,10 @@ static void cx23885_finidev(struct pci_d
 	/* unregister stuff */
 	free_irq(pci_dev->irq, dev);
 
+	cancel_work_sync(&dev->cx25840_work);
+	cancel_work_sync(&dev->ir_rx_work);
+	cancel_work_sync(&dev->ir_tx_work);
+
 	pci_disable_device(pci_dev);
 
 	cx23885_dev_unregister(dev);
author maintainer
#160 lore raw

PATCH 160/547 media: hackrf: fix use-after-free in hackrf_alloc_urbs() error path

In reply to Greg Kroah-Hartman

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

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

From: Anuj Bolewar <[email protected]>

commit 6802ad4b6b267dda02209b5811edac7825c8a5f6 upstream.

hackrf_alloc_urbs() frees the URBs it allocated so far when one allocation fails, but leaves the entries in dev->urb_list[] and dev->urbs_initialized untouched. The caller, hackrf_start_streaming(), then calls hackrf_free_urbs() on the error path, which walks dev->urbs_initialized entries and calls usb_free_urb() a second time on the already-freed URBs, causing a use-after-free (slab-use-after-free Write in usb_free_urb()).

Drop the redundant cleanup loop inside hackrf_alloc_urbs() and let hackrf_free_urbs(), which the caller already invokes on error, own the cleanup of the successfully allocated URBs.

---
 drivers/media/usb/hackrf/hackrf.c |    7 ++-----
 1 file changed, 2 insertions(+), 5 deletions(-)
drivers/media/usb/hackrf/hackrf.c +2 -5
@@ -665,7 +665,7 @@ static int hackrf_free_urbs(struct hackr
 
 static int hackrf_alloc_urbs(struct hackrf_dev *dev, bool rcv)
 {
-	int i, j;
+	int i;
 	unsigned int pipe;
 	usb_complete_t complete;
 
@@ -681,11 +681,8 @@ static int hackrf_alloc_urbs(struct hack
 	for (i = 0; i < MAX_BULK_BUFS; i++) {
 		dev_dbg(dev->dev, "alloc urb=%d\n", i);
 		dev->urb_list[i] = usb_alloc_urb(0, GFP_KERNEL);
-		if (!dev->urb_list[i]) {
-			for (j = 0; j < i; j++)
-				usb_free_urb(dev->urb_list[j]);
+		if (!dev->urb_list[i])
 			return -ENOMEM;
-		}
 		usb_fill_bulk_urb(dev->urb_list[i],
 				dev->udev,
 				pipe,
author maintainer
#161 lore raw

PATCH 161/547 media: imon: fix use-after-free in display_close via dev_dbg

In reply to Greg Kroah-Hartman

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

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

From: Deepanshu Kartikey <[email protected]>

commit 118a3590a4080c71c565265b05b3f92e814d7647 upstream.

ictx->dev is a raw pointer to the usb_interface's embedded device. On disconnect, usb_disconnect() can drop the last reference on the interface and free it while a userspace fd for /dev/lcd0 is still open. When that fd is later closed, display_close() dereferences the now-freed ictx->dev via dev_dbg(), causing a use-after-free.

Remove the dev_dbg() calls that dereference ictx->dev in display_close() and free_imon_context(), rather than taking a reference on the device.

---
 drivers/media/rc/imon.c |    5 -----
 1 file changed, 5 deletions(-)
drivers/media/rc/imon.c +0 -5
@@ -492,16 +492,12 @@ MODULE_PARM_DESC(pad_thresh, "Threshold
 
 static void free_imon_context(struct imon_context *ictx)
 {
-	struct device *dev = ictx->dev;
-
 	usb_free_urb(ictx->tx_urb);
 	WARN_ON(ictx->dev_present_intf0);
 	usb_free_urb(ictx->rx_urb_intf0);
 	WARN_ON(ictx->dev_present_intf1);
 	usb_free_urb(ictx->rx_urb_intf1);
 	kfree_rcu(ictx, rcu);
-
-	dev_dbg(dev, "%s: iMON context freed\n", __func__);
 }
 
 /*
@@ -577,7 +573,6 @@ static int display_close(struct inode *i
 		retval = -EIO;
 	} else {
 		ictx->display_isopen = false;
-		dev_dbg(ictx->dev, "display port closed\n");
 	}
 
 	mutex_unlock(&ictx->lock);
author maintainer
#162 lore raw

PATCH 162/547 media: ipu-bridge: Fix use-after-free in IVSC error path

In reply to Greg Kroah-Hartman

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

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

From: Yibo Tan <[email protected]>

commit 3d42d1c82717f0853379b516a7fab54b636e09cc upstream.

ipu_bridge_get_ivsc_acpi_dev() returns an ACPI device with a reference held. If no matching CSI device is found, ipu_bridge_check_ivsc_dev() drops that reference before passing the device to dev_err(). Concurrent CSI device and ACPI namespace removal can drop the other references, making this the final put. dev_err() then reads the freed struct acpi_device and its kobject name.

This was reproduced without kprobes by racing normal CSI platform-device unregistration and ACPI configfs table removal against the production ipu_bridge_init() entry. KASAN reported the final free through device_release(), followed by invalid reads through _dev_err().

Emit the error message while the lookup reference is still held, then drop the reference as before.

Source reproducers and vulnerable/fixed serial logs, with only the build hostname redacted, are available at:
https://github.com/kimaiden1984-boop/linux-ipu-bridge-acpi-uaf-reproducer

The fixed target builds with W=1 on x86-64. This was not tested on physical IPU hardware. The tests establish runtime reachability but do not measure occurrence frequency on shipping systems or establish exploitability.

Fixes c66821f381ae ("media: pci: intel: Add IVSC support for IPU bridge driver")
Assisted-by Codex:GPT-5
---
 drivers/media/pci/intel/ipu-bridge.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/media/pci/intel/ipu-bridge.c +1 -1
@@ -326,8 +326,8 @@ static int ipu_bridge_check_ivsc_dev(str
 	if (adev) {
 		csi_dev = ipu_bridge_get_ivsc_csi_dev(adev);
 		if (!csi_dev) {
-			acpi_dev_put(adev);
 			dev_err(ADEV_DEV(adev), "Failed to find MEI or CVS CSI dev\n");
+			acpi_dev_put(adev);
 			return -ENODEV;
 		}
 
author maintainer
#163 lore raw

PATCH 163/547 mm/hugetlb: fix use-after-free in hugetlb_mfill_atomic_pte()

In reply to Greg Kroah-Hartman

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

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

From: David Hildenbrand (Arm) <[email protected]>

commit d8a9cd7fd2fb01211430c933932da58839b8ca65 upstream.

Let's fix another instance where we use a folio after dropping the PTL, where someone else could e.g., MADV_DONTNEED it once we drop the PTL, making us trigger a use-after-free on the folio.

Fixes cb6acd01e2e4 ("hugetlbfs: fix races and page leaks during migration")
Fixes 1c9e8def43a3 ("userfaultfd: hugetlbfs: add UFFDIO_COPY support for shared mappings")
Cc Liam R. Howlett <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Jann Horn <[email protected]>
Cc Pedro Falcato <[email protected]>
Cc Oscar Salvador <[email protected]>
Cc Miaohe Lin <[email protected]>
Cc Naoya Horiguchi <[email protected]>
Cc Adam Litke <[email protected]>
Cc Mel Gorman <[email protected]>
Cc Rik van Riel <[email protected]>
Cc Peter Xu <[email protected]>
Cc Kiryl Shutsemau <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Josef Bacik <[email protected]>
---
 mm/hugetlb.c |    7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
mm/hugetlb.c +6 -1
@@ -6474,11 +6474,16 @@ int hugetlb_mfill_atomic_pte(pte_t *dst_
 	/* No need to invalidate - it was non-present before */
 	update_mmu_cache(dst_vma, dst_addr, dst_pte);
 
-	spin_unlock(ptl);
 	if (!is_continue)
 		folio_set_hugetlb_migratable(folio);
 	if (vm_shared || is_continue)
 		folio_unlock(folio);
+
+	/*
+	 * Hold the PTL until we're done with the folio: the page table owns the
+	 * folio reference now.
+	 */
+	spin_unlock(ptl);
 	ret = 0;
 out:
 	return ret;
author maintainer
#164 lore raw

PATCH 164/547 mm/hugetlb: fix use-after-free of a new anon folio

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

commit 824cc56bf43c714319992bad3558803cac6e77c0 upstream.

For a fault in a private mapping with nothing in the page cache, hugetlb_no_page() allocates a folio, locks it and maps it. The folio has one reference, which belongs to the page table entry from then on. After dropping the page table lock the function still sets the migratable flag of the folio and unlocks it.

Whoever zaps the entry in between frees the folio. The fault holds the fault mutex and the lock of the vma. MADV_DONTNEED and the first unmap of a hole punch, hugetlb_vmdelete_list(), do not take the fault mutex, and a private vma only has a lock if it owns a reservation map: not with MAP_NORESERVE, and not in the child after fork().

Then the flag is set in, and folio_unlock() is called on, a folio that is free or has a new owner. A surplus page goes back to the page allocator while it is locked:

  BUG: Bad page state in process init  pfn:108e00
  flags: 0x200000000000059(locked|uptodate|dirty|head|node=0|zone=2)
  page dumped because: PAGE_FLAGS_CHECK_AT_FREE flag(s) set

A page of the pool can be given to the next user, of any file, who locks it and loses the lock to the late folio_unlock():

kernel BUG at mm/filemap.c:1532!

   hugetlb_no_page+0x111b/0x23e0
   hugetlb_fault+0x3a9/0x14a0

An unprivileged process is enough: threads that write to a MAP_PRIVATE | MAP_NORESERVE hugetlb mapping, threads that call MADV_DONTNEED on it, and one that takes the freed pages for another file.

Until commit 3a47c54f09c4 ("hugetlbfs: revert use i_mmap_rwsem for more pmd sharing synchronization") the fault held i_mmap_rwsem for reading, which everybody who zaps takes for writing. The lock that commit bf4916922c60 ("hugetlbfs: extend hugetlb_vma_lock to private VMAs") gave to private vmas closed the window again, but only for those with a reservation map.

Be done with the folio before the page table lock is dropped, as hugetlb_wp() is with its copy. The function already unlocks page cache folios under that lock.

Original fix generated by an LLM and sent in private by Josef.

[[email protected]: simplify+move comment]
Fixes 3a47c54f09c4 ("hugetlbfs: revert use i_mmap_rwsem for more pmd sharing synchronization")
Cc Liam R. Howlett <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Jann Horn <[email protected]>
Cc Pedro Falcato <[email protected]>
Cc Oscar Salvador <[email protected]>
Cc Miaohe Lin <[email protected]>
Cc Naoya Horiguchi <[email protected]>
Cc Adam Litke <[email protected]>
Cc Mel Gorman <[email protected]>
Cc Rik van Riel <[email protected]>
Cc Peter Xu <[email protected]>
Cc Kiryl Shutsemau <[email protected]>
Cc Mike Rapoport <[email protected]>
---
 mm/hugetlb.c |    8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
mm/hugetlb.c +6 -2
@@ -5949,8 +5949,6 @@ static vm_fault_t hugetlb_no_page(struct
 		ret = hugetlb_wp(vmf);
 	}
 
-	spin_unlock(vmf->ptl);
-
 	/*
 	 * Only set hugetlb_migratable in newly allocated pages.  Existing pages
 	 * found in the pagecache may not have hugetlb_migratable if they have
@@ -5961,6 +5959,12 @@ static vm_fault_t hugetlb_no_page(struct
 
 	if (folio_locked)
 		folio_unlock(folio);
+
+	/*
+	 * Hold the PTL until we're done with the folio: the page table owns the
+	 * folio reference now.
+	 */
+	spin_unlock(vmf->ptl);
 out:
 	hugetlb_vma_unlock_read(vma);
 
author maintainer
#165 lore raw

PATCH 165/547 apparmor: fix a use-after-free in aa_lookupn_ns()

In reply to Greg Kroah-Hartman

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

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

From: Binbin Deng <[email protected]>

commit f292873ceb4bd3a1a0f75f884361cd556e457692 upstream.

aa_lookupn_ns() takes a reference on the namespace it finds with aa_get_ns(), which is kref_get() on the reference count that the namespace is released through, without checking whether the namespace is still in use. A concurrent removal of a ":"-prefixed namespace looks the same namespace up and only then takes the parent lock to remove it, so the last reference can be dropped between the lookup and the aa_get_ns() call: the reference count then reports the increment on a zero count and the kernel classifies the following use of the object as a use-after-free. A user with CAP_MAC_ADMIN can trigger this by writing a ":<name>" removal and a ":<name>/<profile>" removal to /sys/kernel/security/apparmor/.remove concurrently.

refcount_t: addition on 0; use-after-free.

WARNING: lib/refcount.c:25 at refcount_warn_saturate+0xc0/0xe0, CPU#6
Call Trace:
 <TASK>
 aa_lookupn_ns+0xa9/0xc0
 aa_remove_profiles+0x4fb/0x730
 ? __kvmalloc_node_noprof+0x219/0x5c0
 ? __pfx_aa_remove_profiles+0x10/0x10
 ? aa_loaddata_alloc+0x65/0x1f0
 ? _copy_from_user+0x2d/0x80
 ? aa_loaddata_alloc+0x111/0x1f0
 profile_remove+0x2ee/0x4a0
 vfs_write+0x21e/0xcf0
 ? rcu_core+0x29c/0x1740
 ? timerqueue_linked_add+0x1f4/0x3d0
 ? __pfx_vfs_write+0x10/0x10
 ? mutex_lock+0x81/0xe0
 ? __pfx_mutex_lock+0x10/0x10
 ? __pfx_rcu_core+0x10/0x10
 ? __pfx_hrtimer_update_next_event+0x10/0x10
 ? mutex_unlock+0x7b/0xd0
 ? fdget_pos+0x24d/0x4b0
 ksys_write+0xf7/0x1c0
 ? __pfx_ksys_write+0x10/0x10
 ? restore_fpregs_from_fpstate+0x37/0xc0
 do_syscall_64+0xf9/0x540
 entry_SYSCALL_64_after_hwframe+0x77/0x7f
 </TASK>

Fix by rejecting a namespace whose reference count is zero.

Fixes 3664268f19ea0 ("apparmor: add namespace lookup fns()")
---
 security/apparmor/include/policy_ns.h |   16 ++++++++++++++++
 security/apparmor/policy_ns.c         |    2 +-
 2 files changed, 17 insertions(+), 1 deletion(-)
security/apparmor/include/policy_ns.h +16 -0
@@ -118,6 +118,22 @@ static inline struct aa_ns *aa_get_ns(st
 }
 
 /**
+ * aa_get_ns_not0 - increment references count on @ns found via lookup
+ * @ns: namespace to increment reference count of (MAYBE NULL)
+ *
+ * Returns: pointer to @ns, if @ns is NULL returns NULL,
+ *          NULL if @ns is being freed
+ * Requires: @ns must be held with valid refcount when called
+ */
+static inline struct aa_ns *aa_get_ns_not0(struct aa_ns *ns)
+{
+	if (ns && aa_get_profile_not0(ns->unconfined))
+		return ns;
+
+	return NULL;
+}
+
+/**
  * aa_put_ns - decrement refcount on @ns
  * @ns: namespace to put reference of
  *
security/apparmor/policy_ns.c +1 -1
@@ -207,7 +207,7 @@ struct aa_ns *aa_lookupn_ns(struct aa_ns
 	struct aa_ns *ns = NULL;
 
 	rcu_read_lock();
-	ns = aa_get_ns(__aa_lookupn_ns(view, name, n));
+	ns = aa_get_ns_not0(__aa_lookupn_ns(view, name, n));
 	rcu_read_unlock();
 
 	return ns;
author maintainer
#166 lore raw

PATCH 166/547 ASoC: audio-graph-card2: Fix use-after-free in audio_graph2_link_c2c()

In reply to Greg Kroah-Hartman

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

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

From: Wentao Liang <[email protected]>

commit 5ea495bccfd746b063bc6702064f167467717b41 upstream.

of_graph_get_next_port() consumes the reference of its prev argument. port0 is only borrowed from the caller's iterator, so the call drops a reference the function does not own, and port0 is dereferenced again afterwards. Pass an extra reference, as graph_count_c2c() does, so the reference the callee consumes is the one taken here.

Fixes 5f281c3e82b1 ("ASoC: audio-graph-card2: use __free(device_node) for device node")
---
 sound/soc/generic/audio-graph-card2.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
sound/soc/generic/audio-graph-card2.c +2 -1
@@ -969,7 +969,8 @@ int audio_graph2_link_c2c(struct simple_
 	struct snd_soc_dai_link *dai_link = simple_priv_to_link(priv, li->link);
 	struct device_node *port0 = lnk;
 	struct device_node *ports __free(device_node) = port_to_ports(port0);
-	struct device_node *port1 __free(device_node) = of_graph_get_next_port(ports, port0);
+	struct device_node *port1 __free(device_node) =
+		of_graph_get_next_port(ports, of_node_get(port0));
 	u32 val = 0;
 	int ret = -EINVAL;
 
author maintainer
#167 lore raw

PATCH 167/547 ata: sata_fsl: Fix use-after-free of host_priv on probe() failure

In reply to Greg Kroah-Hartman

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

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

From: Niklas Cassel <[email protected]>

commit 70b1196740d61aabda13b2ad0e9c1dfa2ef9cfa3 upstream.

sata_fsl_host_stop() releases hcr_base and host_priv:

	static void sata_fsl_host_stop(struct ata_host *host)
	{
		struct sata_fsl_host_priv *host_priv = host->private_data;

		iounmap(host_priv->hcr_base);
		kfree(host_priv);
	}

->host_stop() is called by the driver core through the ata_host_stop() devres action which ata_host_start() registers, so it is called both when the device is unbound and when probe() fails after the host has been started.

The error_exit_with_cleanup label of sata_fsl_probe() releases hcr_base and host_priv as well, and it is reachable from the two device_create_file() calls which are done after the host has been activated. In that case sata_fsl_host_stop() runs on an already freed host_priv, resulting in a use-after-free and a double iounmap()/kfree().

Add a separate error label for the failures happening after the host has been activated, which only detaches the host and leaves hcr_base and host_priv to sata_fsl_host_stop().

Note that ata_host_detach() is dropped from error_exit_with_cleanup, as that label is now only reachable while host is still NULL.

Fixes 6c8ad7e8cf29 ("sata_fsl: fix UAF in sata_fsl_port_stop when rmmod sata_fsl")
---
 drivers/ata/sata_fsl.c |   18 +++++++++++++-----
 1 file changed, 13 insertions(+), 5 deletions(-)
drivers/ata/sata_fsl.c +13 -5
@@ -1500,7 +1500,7 @@ static int sata_fsl_probe(struct platfor
 	host_priv->intr_coalescing.attr.mode = S_IRUGO | S_IWUSR;
 	retval = device_create_file(host->dev, &host_priv->intr_coalescing);
 	if (retval)
-		goto error_exit_with_cleanup;
+		goto error_exit_detach;
 
 	host_priv->rx_watermark.show = fsl_sata_rx_watermark_show;
 	host_priv->rx_watermark.store = fsl_sata_rx_watermark_store;
@@ -1510,16 +1510,24 @@ static int sata_fsl_probe(struct platfor
 	retval = device_create_file(host->dev, &host_priv->rx_watermark);
 	if (retval) {
 		device_remove_file(&ofdev->dev, &host_priv->intr_coalescing);
-		goto error_exit_with_cleanup;
+		goto error_exit_detach;
 	}
 
 	return 0;
 
-error_exit_with_cleanup:
+error_exit_detach:
+	/*
+	 * Once the host has been activated, hcr_base and host_priv are
+	 * released by sata_fsl_host_stop(), which is called by the driver core
+	 * through the ata_host_stop() devres action registered by
+	 * ata_host_start(). Releasing them here as well would result in a
+	 * double iounmap() and a use-after-free.
+	 */
+	ata_host_detach(host);
 
-	if (host)
-		ata_host_detach(host);
+	return retval;
 
+error_exit_with_cleanup:
 	if (hcr_base)
 		iounmap(hcr_base);
 	kfree(host_priv);
author maintainer
#168 lore raw

PATCH 168/547 drm/msm: Fix vm_bo use-after-free in with_vm_locks()

In reply to Greg Kroah-Hartman

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

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

From: Wentao Liang <[email protected]>

commit 81878aa1a2f551f51a3d3aef2a9509503ec34d8b upstream.

The unwind loop drops the vm_bo reference taken while locking before advancing to the next entry. drm_gpuvm_bo_put() may drop the last reference, removing and freeing the vm_bo, after which the plain list iterator dereferences freed memory to advance.

Use the safe iterator, which saves the next entry before the body runs.

Fixes fe4952b5f27cca5d ("drm/msm: Convert vm locking")

Patchwork: https://patchwork.freedesktop.org/patch/754331/
Message-ID: <[email protected]>

---
 drivers/gpu/drm/msm/msm_gem_shrinker.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/gpu/drm/msm/msm_gem_shrinker.c +2 -1
@@ -51,6 +51,7 @@ with_vm_locks(void (*fn)(struct drm_gem_
 	 * success paths
 	 */
 	struct drm_gpuvm_bo *vm_bo, *last_locked = NULL;
+	struct drm_gpuvm_bo *next;
 	bool locked = true;
 
 	drm_gem_for_each_gpuvm_bo (vm_bo, obj) {
@@ -82,7 +83,7 @@ with_vm_locks(void (*fn)(struct drm_gem_
 
 out_unlock:
 	if (last_locked) {
-		drm_gem_for_each_gpuvm_bo (vm_bo, obj) {
+		drm_gem_for_each_gpuvm_bo_safe(vm_bo, next, obj) {
 			struct dma_resv *resv = drm_gpuvm_resv(vm_bo->vm);
 
 			if (resv == obj->resv)
author maintainer
#169 lore raw

PATCH 169/547 s390/pci: Fix double-free and NULL deref in zpci MSI domain cleanup

In reply to Greg Kroah-Hartman

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

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

From: Tobias Schumacher <[email protected]>

commit 31c66bd273303590fe69fad370e72a12faa0bf76 upstream.

zpci_remove_parent_msi_domain() dereferences zbus->msi_parent_domain unconditionally and does not clear it afterwards.

zpci_bus_create_pci_bus() removes the domain when pci_create_root_bus() fails, then zpci_bus_release() removes it again on the last kref_put(), reading ->fwnode from the freed irq_domain and freeing it twice.

If zpci_alloc_domain() or zpci_create_parent_msi_domain() fails, no domain is created at all; zbus is kzalloc'd, so the same release path dereferences NULL.

Return early when there is no domain, and clear the pointer after removing one.

Fixes f770950a4709 ("s390/pci: Migrate s390 IRQ logic to IRQ domain API")
---
 arch/s390/pci/pci_irq.c |    4 ++++
 1 file changed, 4 insertions(+)
arch/s390/pci/pci_irq.c +4 -0
@@ -533,9 +533,13 @@ void zpci_remove_parent_msi_domain(struc
 {
 	struct fwnode_handle *fn;
 
+	if (!zbus->msi_parent_domain)
+		return;
+
 	fn = zbus->msi_parent_domain->fwnode;
 	irq_domain_remove(zbus->msi_parent_domain);
 	irq_domain_free_fwnode(fn);
+	zbus->msi_parent_domain = NULL;
 }
 
 static void __init cpu_enable_directed_irq(void *unused)
author maintainer
#170 lore raw

PATCH 170/547 s390/pci: Fix MSI directed-mode teardown IRQ bit count

In reply to Greg Kroah-Hartman

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

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

From: Tobias Schumacher <[email protected]>

commit 1844913582fec337c54b54fdd3c92ce225930515 upstream.

On s390 with directed interrupts enabled, zpci_msi_teardown_directed() frees the platform's maximum number of MSI bits (zdev->max_msi) instead of the actual allocated count (zdev->msi_nr_irqs). This corrupts the shared IRQ bitmap used by all PCI functions, causing lost interrupts and heap corruption. Fix zpci_msi_teardown_directed() to only free the actual allocated IRQ bit count.

Fixes f770950a4709 ("s390/pci: Migrate s390 IRQ logic to IRQ domain API")
---
 arch/s390/pci/pci_irq.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/s390/pci/pci_irq.c +1 -1
@@ -339,7 +339,7 @@ static struct airq_struct zpci_airq = {
 
 static void zpci_msi_teardown_directed(struct zpci_dev *zdev)
 {
-	airq_iv_free(zpci_ibv[0], zdev->msi_first_bit, zdev->max_msi);
+	airq_iv_free(zpci_ibv[0], zdev->msi_first_bit, zdev->msi_nr_irqs);
 	zdev->msi_first_bit = -1U;
 	zdev->msi_nr_irqs = 0;
 }
author maintainer
#171 lore raw

PATCH 171/547 s390/pci: Fix resource leak in zpci MSI setup

In reply to Greg Kroah-Hartman

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

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

From: Tobias Schumacher <[email protected]>

commit 4a185d99179a307d856dc43610cfe72395d0c42a upstream.

If airq_iv_create() fails in __alloc_airq(), the zpci_sbv bit allocated by airq_iv_alloc_bit() is never freed. This permanently leaks one of the ZPCI_NR_DEVICES summary bits, reducing system capacity with each failed device hotplug. In systems with repeated device insertion failures or under memory pressure, all summary bits can be exhausted, preventing new PCI devices from being added until reboot.

Add proper error handling to free the zpci_sbv bit and reset zdev->aisb if the AIBV creation fails.

Fixes f770950a4709 ("s390/pci: Migrate s390 IRQ logic to IRQ domain API")
---
 arch/s390/pci/pci_irq.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
arch/s390/pci/pci_irq.c +4 -1
index c9520a16ca75..134f8f4a5cfa 100644
@@ -313,8 +313,11 @@ static int __alloc_airq(struct zpci_dev *zdev, int msi_vecs,
 		zdev->aibv = airq_iv_create(msi_vecs,
 					    AIRQ_IV_PTR | AIRQ_IV_DATA | AIRQ_IV_BITLOCK,
 					    NULL);
-		if (!zdev->aibv)
+		if (!zdev->aibv) {
+			airq_iv_free_bit(zpci_sbv, *bit);
+			zdev->aisb = -1UL;
 			return -ENOMEM;
+		}
 
 		/* Wire up shortcut pointer */
 		zpci_ibv[*bit] = zdev->aibv;
Signature · 1 line
2.56.0
author maintainer
#172 lore raw

PATCH 172/547 s390/pci: Fix use-after-free race in zpci floating interrupt cleanup

In reply to Greg Kroah-Hartman

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

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

From: Tobias Schumacher <[email protected]>

commit 422d75ad5bc96b8eb9cb3cfd9d68fc685a0a9b75 upstream.

zpci_clear_irq() stops the adapter from raising new interrupts for the function, but a zpci_floating_irq_handler() already running on another CPU can still be scanning zdev->aibv when zpci_msi_teardown_floating() releases it.

Clear the zpci_ibv[] entry so no further handler picks the vector up, then wait for a grace period before releasing it. The handler runs inside the rcu_read_lock() section that do_airq_interrupt() holds across airq->handler(), so synchronize_rcu() drains any handler still in flight. Release the vector and free the summary bit only after the grace period, so neither can be reused while a reader still holds the old pointer.

zpci_ibv served both delivery modes, indexed by function under FLOATING and by cpu under DIRECTED. Only the floating vectors are published to and torn down under the interrupt handler, so split the directed vectors out into zpci_dibv and annotate zpci_ibv __rcu, which lets sparse check the accessors above.

Fixes f770950a4709 ("s390/pci: Migrate s390 IRQ logic to IRQ domain API")
---
 arch/s390/pci/pci_irq.c | 58 +++++++++++++++++++++++------------------
 1 file changed, 32 insertions(+), 26 deletions(-)
arch/s390/pci/pci_irq.c +32 -26
index d5763c5feb09..c5fabad38139 100644
@@ -22,12 +22,11 @@ static enum {FLOATING, DIRECTED} irq_delivery;
  */
 static struct airq_iv *zpci_sbv;
 
-/*
- * interrupt bit vectors
- * FLOATING - interrupt bit vector per function
- * DIRECTED - interrupt bit vector per cpu
- */
-static struct airq_iv **zpci_ibv;
+/* FLOATING - interrupt bit vector per function */
+static struct airq_iv __rcu **zpci_ibv;
+
+/* DIRECTED - interrupt bit vector per cpu */
+static struct airq_iv **zpci_dibv;
 
 /* Modify PCI: Register floating adapter interruptions */
 static int zpci_set_airq(struct zpci_dev *zdev)
@@ -169,7 +168,7 @@ static struct irq_chip zpci_irq_chip = {
 
 static void zpci_handle_cpu_local_irq(bool rescan)
 {
-	struct airq_iv *dibv = zpci_ibv[smp_processor_id()];
+	struct airq_iv *dibv = zpci_dibv[smp_processor_id()];
 	union zpci_sic_iib iib = {{0}};
 	struct irq_domain *msi_domain;
 	irq_hw_number_t hwirq;
@@ -279,7 +278,9 @@ static void zpci_floating_irq_handler(struct airq_struct *airq,
 		}
 
 		/* Scan the adapter interrupt vector for this device. */
-		aibv = zpci_ibv[si];
+		aibv = rcu_dereference(zpci_ibv[si]);
+		if (!aibv)
+			continue;
 		for (ai = 0;;) {
 			ai = airq_iv_scan(aibv, ai, airq_iv_end(aibv));
 			if (ai == -1UL)
@@ -299,7 +300,7 @@ static int __alloc_airq(struct zpci_dev *zdev, int msi_vecs,
 {
 	if (irq_delivery == DIRECTED) {
 		/* Allocate cpu vector bits */
-		*bit = airq_iv_alloc(zpci_ibv[0], msi_vecs);
+		*bit = airq_iv_alloc(zpci_dibv[0], msi_vecs);
 		if (*bit == -1UL)
 			return -EIO;
 	} else {
@@ -320,7 +321,7 @@ static int __alloc_airq(struct zpci_dev *zdev, int msi_vecs,
 		}
 
 		/* Wire up shortcut pointer */
-		zpci_ibv[*bit] = zdev->aibv;
+		rcu_assign_pointer(zpci_ibv[*bit], zdev->aibv);
 		/* Each function has its own interrupt vector */
 		*bit = 0;
 	}
@@ -342,13 +343,16 @@ static struct airq_struct zpci_airq = {
 
 static void zpci_msi_teardown_directed(struct zpci_dev *zdev)
 {
-	airq_iv_free(zpci_ibv[0], zdev->msi_first_bit, zdev->msi_nr_irqs);
+	airq_iv_free(zpci_dibv[0], zdev->msi_first_bit, zdev->msi_nr_irqs);
 	zdev->msi_first_bit = -1U;
 	zdev->msi_nr_irqs = 0;
 }
 
 static void zpci_msi_teardown_floating(struct zpci_dev *zdev)
 {
+	rcu_assign_pointer(zpci_ibv[zdev->aisb], NULL);
+	synchronize_rcu();
+
 	airq_iv_release(zdev->aibv);
 	zdev->aibv = NULL;
 	airq_iv_free_bit(zpci_sbv, zdev->aisb);
@@ -428,9 +432,9 @@ static int zpci_msi_domain_alloc(struct irq_domain *domain, unsigned int virq,
 
 		if (irq_delivery == DIRECTED) {
 			for_each_possible_cpu(cpu) {
-				airq_iv_set_ptr(zpci_ibv[cpu], bit + i,
+				airq_iv_set_ptr(zpci_dibv[cpu], bit + i,
 						(unsigned long)zbus->msi_parent_domain);
-				airq_iv_set_data(zpci_ibv[cpu], bit + i, hwirq + i);
+				airq_iv_set_data(zpci_dibv[cpu], bit + i, hwirq + i);
 			}
 		} else {
 			airq_iv_set_ptr(zdev->aibv, bit + i,
@@ -455,8 +459,8 @@ static void zpci_msi_clear_airq(struct irq_data *d, int i)
 
 	if (irq_delivery == DIRECTED) {
 		for_each_possible_cpu(cpu) {
-			airq_iv_set_ptr(zpci_ibv[cpu], bit + i, 0);
-			airq_iv_set_data(zpci_ibv[cpu], bit + i, 0);
+			airq_iv_set_ptr(zpci_dibv[cpu], bit + i, 0);
+			airq_iv_set_data(zpci_dibv[cpu], bit + i, 0);
 		}
 	} else {
 		airq_iv_set_ptr(zdev->aibv, bit + i, 0);
@@ -550,7 +554,7 @@ static void __init cpu_enable_directed_irq(void *unused)
 	union zpci_sic_iib iib = {{0}};
 	union zpci_sic_iib ziib = {{0}};
 
-	iib.cdiib.dibv_addr = virt_to_phys(zpci_ibv[smp_processor_id()]->vector);
+	iib.cdiib.dibv_addr = virt_to_phys(zpci_dibv[smp_processor_id()]->vector);
 
 	zpci_set_irq_ctrl(SIC_IRQ_MODE_SET_CPU, 0, &iib);
 	zpci_set_irq_ctrl(SIC_IRQ_MODE_D_SINGLE, PCI_ISC, &ziib);
@@ -570,8 +574,8 @@ static int __init zpci_directed_irq_init(void)
 	iib.diib.disb_addr = virt_to_phys(zpci_sbv->vector);
 	zpci_set_irq_ctrl(SIC_IRQ_MODE_DIRECT, 0, &iib);
 
-	zpci_ibv = kzalloc_objs(*zpci_ibv, num_possible_cpus());
-	if (!zpci_ibv)
+	zpci_dibv = kzalloc_objs(*zpci_dibv, num_possible_cpus());
+	if (!zpci_dibv)
 		return -ENOMEM;
 
 	for_each_possible_cpu(cpu) {
@@ -579,12 +583,12 @@ static int __init zpci_directed_irq_init(void)
 		 * Per CPU IRQ vectors look the same but bit-allocation
 		 * is only done on the first vector.
 		 */
-		zpci_ibv[cpu] = airq_iv_create(cache_line_size() * BITS_PER_BYTE,
-					       AIRQ_IV_PTR |
-					       AIRQ_IV_DATA |
-					       AIRQ_IV_CACHELINE |
-					       (!cpu ? AIRQ_IV_ALLOC : 0), NULL);
-		if (!zpci_ibv[cpu])
+		zpci_dibv[cpu] = airq_iv_create(cache_line_size() * BITS_PER_BYTE,
+						AIRQ_IV_PTR |
+						AIRQ_IV_DATA |
+						AIRQ_IV_CACHELINE |
+						(!cpu ? AIRQ_IV_ALLOC : 0), NULL);
+		if (!zpci_dibv[cpu])
 			return -ENOMEM;
 	}
 	on_each_cpu(cpu_enable_directed_irq, NULL, 1);
@@ -660,10 +664,12 @@ void __init zpci_irq_exit(void)
 
 	if (irq_delivery == DIRECTED) {
 		for_each_possible_cpu(cpu) {
-			airq_iv_release(zpci_ibv[cpu]);
+			airq_iv_release(zpci_dibv[cpu]);
 		}
+		kfree(zpci_dibv);
+	} else {
+		kfree(zpci_ibv);
 	}
-	kfree(zpci_ibv);
 	if (zpci_sbv)
 		airq_iv_release(zpci_sbv);
 	unregister_adapter_interrupt(&zpci_airq);
Signature · 1 line
2.56.0
author maintainer
#173 lore raw

PATCH 173/547 s390/pci: Add error cleanup in zpci_directed_irq_init()

In reply to Greg Kroah-Hartman

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

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

From: Tobias Schumacher <[email protected]>

commit 769f66f595c11185c66913ea5d96420504bfebc3 upstream.

If per-CPU airq_iv allocation fails in the loop, previously allocated vectors and arrays leak. Add proper error path to release all resources on failure.

The error path frees zpci_sbv, but SIC_IRQ_MODE_DIRECT has already programmed its address into the hardware. Set the directed interrupt mode only after all allocations have succeeded, so a failed init leaves no freed memory registered with the hardware.

Fixes e979ce7bced2 ("s390/pci: provide support for CPU directed interrupts")
---
 arch/s390/pci/pci_irq.c | 26 +++++++++++++++++++-------
 1 file changed, 19 insertions(+), 7 deletions(-)
arch/s390/pci/pci_irq.c +19 -7
index c5fabad38139..bcf11585df8d 100644
@@ -569,14 +569,9 @@ static int __init zpci_directed_irq_init(void)
 	if (!zpci_sbv)
 		return -ENOMEM;
 
-	iib.diib.isc = PCI_ISC;
-	iib.diib.nr_cpus = num_possible_cpus();
-	iib.diib.disb_addr = virt_to_phys(zpci_sbv->vector);
-	zpci_set_irq_ctrl(SIC_IRQ_MODE_DIRECT, 0, &iib);
-
 	zpci_dibv = kzalloc_objs(*zpci_dibv, num_possible_cpus());
 	if (!zpci_dibv)
-		return -ENOMEM;
+		goto out_free_sbv;
 
 	for_each_possible_cpu(cpu) {
 		/*
@@ -589,13 +584,30 @@ static int __init zpci_directed_irq_init(void)
 						AIRQ_IV_CACHELINE |
 						(!cpu ? AIRQ_IV_ALLOC : 0), NULL);
 		if (!zpci_dibv[cpu])
-			return -ENOMEM;
+			goto out_free_dibv;
 	}
+
+	iib.diib.isc = PCI_ISC;
+	iib.diib.nr_cpus = num_possible_cpus();
+	iib.diib.disb_addr = virt_to_phys(zpci_sbv->vector);
+	zpci_set_irq_ctrl(SIC_IRQ_MODE_DIRECT, 0, &iib);
 	on_each_cpu(cpu_enable_directed_irq, NULL, 1);
 
 	zpci_irq_chip.irq_set_affinity = zpci_set_irq_affinity;
 
 	return 0;
+
+out_free_dibv:
+	for_each_possible_cpu(cpu) {
+		if (zpci_dibv[cpu])
+			airq_iv_release(zpci_dibv[cpu]);
+	}
+	kfree(zpci_dibv);
+	zpci_dibv = NULL;
+out_free_sbv:
+	airq_iv_release(zpci_sbv);
+	zpci_sbv = NULL;
+	return -ENOMEM;
 }
 
 static int __init zpci_floating_irq_init(void)
Signature · 1 line
2.56.0
author maintainer
#174 lore raw

PATCH 174/547 s390/cpum_cf: Check session mask before cpu offline

In reply to Greg Kroah-Hartman

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

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

From: Sumanth Korikkar <[email protected]>

commit 99a95985dfc85eecad97f0991a2401d2fcef294c upstream.

cfset_offline_cpu() stops counter sets for every active session without checking whether the outgoing cpu belongs to the session mask.

For example, run an hwctr session on cpu0 and a cpu bound perf event on cpu1:

lshwc -l 9999 -i 5 0:b
perf stat -C 1 -e cpum_cf/CPU_CYCLES/ sleep 120
chcpu -d 1
chcpu -e 1

Although the hwctr session does not include cpu1, cfset_offline_cpu() decrements its counter set reference count. The subsequent perf teardown decrements it again, causing it to underflow.

The perf event keeps the percpu state alive across hotplug. When cpu1 comes online, the hwctr session is started there and the reference count moves from -1 to 0. Stopping the hwctr session then decrements it to -1 again, so the zero triggered counter set disable path is skipped.

Check the session mask before stopping counter sets on the outgoing cpu. This prevents the unmatched decrement and the resulting reference count underflow.

Fixes a029a4eab39e ("s390/cpumf: Allow concurrent access for CPU Measurement Counter Facility")
Cc [email protected] # v5.14+
---
 arch/s390/kernel/perf_cpum_cf.c |    3 +++
 1 file changed, 3 insertions(+)
arch/s390/kernel/perf_cpum_cf.c +3 -0
@@ -1797,6 +1797,9 @@ static int cfset_offline_cpu(unsigned in
 
 	if (!list_empty(&cfset_session.head)) {
 		list_for_each_entry(rp, &cfset_session.head, node) {
+			if (!cpumask_test_cpu(cpu, &rp->mask))
+				continue;
+
 			p.sets = rp->ctrset;
 			cfset_ioctl_off(&p);
 			cpumask_clear_cpu(cpu, &rp->mask);
author maintainer
#175 lore raw

PATCH 175/547 s390/extable: Fix mvcos instruction decoding

In reply to Greg Kroah-Hartman

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

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

From: Heiko Carstens <[email protected]>

commit 4044466ff004c7ad5fd47be717cd933077e6e874 upstream.

If either the b1 or b2 field of the mvcos instruction is zero, register zero is not used for address computation; zero is used instead, according to the architecture. ex_handler_ua_mvcos() incorrectly uses the real contents of register zero. Fix this.

This shouldn't be a problem for any generated code, since the compiler would only generate such code if it is possible to prove at compile time that either the source or destination address is within the first 4kb of the designated address space. Such code should not exist (also confirmed by an allyesconfig build and decoding all ~7000 mvcos instructions).

Fixes c488f5187a24 ("s390/uaccess: Shorten raw_copy_from_user() / raw_copy_to_user() inline assemblies")
---
 arch/s390/mm/extable.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
arch/s390/mm/extable.c +2 -2
@@ -106,9 +106,9 @@ static bool ex_handler_ua_mvcos(const st
 	regs->psw.addr = extable_fixup(ex);
 	insn = (struct insn_ssf *)regs->psw.addr;
 	if (from)
-		uaddr = regs->gprs[insn->b2] + insn->d2;
+		uaddr = (insn->b2 ? regs->gprs[insn->b2] : 0) + insn->d2;
 	else
-		uaddr = regs->gprs[insn->b1] + insn->d1;
+		uaddr = (insn->b1 ? regs->gprs[insn->b1] : 0) + insn->d1;
 	remainder = PAGE_SIZE - (uaddr & (PAGE_SIZE - 1));
 	if (regs->gprs[insn->r3] <= remainder)
 		remainder = 0;
author maintainer
#176 lore raw

PATCH 176/547 s390/kprobes: Prevent kprobes on instructions with exception table entry

In reply to Greg Kroah-Hartman

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

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

From: Heiko Carstens <[email protected]>

commit fc9bb0ecd310b53af5116415952a1fb89d4660b9 upstream.

The mvcos exception handler ex_handler_ua_mvcos() decodes the faulting instruction, assuming it is an mvcos instruction. In case the instruction is kprobed the decoded instruction is a breakpoint instruction instead, which leads to incorrect instruction decoding and potential register corruption.

Fix this by simply preventing to set a kprobe on such instructions, similar like arm64 is doing it.

Fixes c488f5187a24 ("s390/uaccess: Shorten raw_copy_from_user() / raw_copy_to_user() inline assemblies")
---
 arch/s390/kernel/kprobes.c |    3 +++
 1 file changed, 3 insertions(+)
arch/s390/kernel/kprobes.c +3 -0
@@ -85,6 +85,9 @@ static bool can_probe(unsigned long padd
 	if (!kallsyms_lookup_size_offset(paddr, NULL, &offset))
 		return false;
 
+	if (s390_search_extables(paddr))
+		return false;
+
 	/* Decode instructions */
 	addr = paddr - offset;
 	while (addr < paddr) {
author maintainer
#177 lore raw

PATCH 177/547 s390/probes: Fix wrong opcode for cgrb fixup

In reply to Greg Kroah-Hartman

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

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

From: Heiko Carstens <[email protected]>

commit d7ccab11a13475e656b9d2277900422c1bfc12c5 upstream.

The last byte of the cgrb instruction is 0xe4, however the probes code compares against 0xe6. Fix it.

Fixes 6b169ac9b434 ("s390/kprobes: add support for compare and branch instructions")
---
 arch/s390/lib/probes.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/s390/lib/probes.c +1 -1
@@ -99,8 +99,8 @@ int probe_get_fixup_type(u16 *insn)
 		break;
 	case 0xec:
 		switch (insn[2] & 0xff) {
+		case 0xe4: /* cgrb  */
 		case 0xe5: /* clgrb */
-		case 0xe6: /* cgrb  */
 		case 0xf6: /* crb   */
 		case 0xf7: /* clrb  */
 		case 0xfc: /* cgib  */
author maintainer
#178 lore raw

PATCH 178/547 s390/signal: Fix incorrect return address in signal frame

In reply to Greg Kroah-Hartman

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

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

From: Heiko Carstens <[email protected]>

commit adc9e872f7350e3ac29c1818d8c68b0760b4ba23 upstream.

exit_to_user_mode_loop() can call arch_do_signal_or_restart() multiple times when signals are pending.

If the first call set up a vDSO system call restart by saving the real user return address and adjusting psw.addr so it points to the vDSO stub, a second call builds the signal frame with the wrong return address.

Restore psw.addr from arch_data, and set the return code to -EINTR before building the signal frame.

This requires restart_block.arch_data to be properly initialized for all tasks. Move the initialization in copy_thread() in front of the kernel thread check, so that it also covers kernel threads and their children (PID 1, usermode helpers). Only PID 0 is left uninitialized, since it never returns to user space.

Fixes df29a7440c4b ("s390/signal: switch to using vdso for sigreturn and syscall restart")
---
 arch/s390/kernel/process.c |   12 ++++++------
 arch/s390/kernel/signal.c  |    6 +++++-
 2 files changed, 11 insertions(+), 7 deletions(-)
arch/s390/kernel/process.c +6 -6
@@ -131,6 +131,12 @@ int copy_thread(struct task_struct *p, c
 	p->thread.hardirq_timer = 0;
 	p->thread.softirq_timer = 0;
 	p->thread.last_break = 1;
+	/*
+	 * s390 stores the svc return address in arch_data when calling
+	 * sigreturn()/restart_syscall() via vdso. 1 means no valid address
+	 * stored.
+	 */
+	p->restart_block.arch_data = 1;
 
 	frame->sf.back_chain = 0;
 	frame->sf.gprs[11 - 6] = (unsigned long)&frame->childregs;
@@ -168,12 +174,6 @@ int copy_thread(struct task_struct *p, c
 		p->thread.acrs[0] = (unsigned int)(tls >> 32);
 		p->thread.acrs[1] = (unsigned int)tls;
 	}
-	/*
-	 * s390 stores the svc return address in arch_data when calling
-	 * sigreturn()/restart_syscall() via vdso. 1 means no valid address
-	 * stored.
-	 */
-	p->restart_block.arch_data = 1;
 	return 0;
 }
 
arch/s390/kernel/signal.c +5 -1
@@ -475,7 +475,11 @@ void arch_do_signal_or_restart(struct pt
 		}
 		/* No longer in a system call */
 		clear_pt_regs_flag(regs, PIF_SYSCALL);
-
+		if (!(current->restart_block.arch_data & 1)) {
+			regs->psw.addr = current->restart_block.arch_data;
+			current->restart_block.arch_data = 1;
+			regs->gprs[2] = -EINTR;
+		}
 		rseq_signal_deliver(&ksig, regs);
 		handle_signal(&ksig, oldset, regs);
 		return;
author maintainer
#179 lore raw

PATCH 179/547 s390/vmcp: Initialize full session info to zero

In reply to Greg Kroah-Hartman

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

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

From: Christian Borntraeger <[email protected]>

commit f63eb4ee4a30fc5d8de07a229d92310e3c8d560c upstream.

The cma_alloc bit as well as the response can contain old data. cma_release will not free the kmalloced memory in that case and the response code might leak kernel stack data to CAP_SYS_ADMIN users.

---
 drivers/s390/char/vmcp.c |    4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)
drivers/s390/char/vmcp.c +1 -3
@@ -104,13 +104,11 @@ static int vmcp_open(struct inode *inode
 	if (!capable(CAP_SYS_ADMIN))
 		return -EPERM;
 
-	session = kmalloc_obj(*session);
+	session = kzalloc_obj(*session);
 	if (!session)
 		return -ENOMEM;
 
 	session->bufsize = PAGE_SIZE;
-	session->response = NULL;
-	session->resp_size = 0;
 	mutex_init(&session->mutex);
 	file->private_data = session;
 	return nonseekable_open(inode, file);
author maintainer
#180 lore raw

PATCH 180/547 s390/zcrypt: Fix and improve zcrypt reply message verification checks

In reply to Greg Kroah-Hartman

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

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

From: Harald Freudenberger <[email protected]>

commit 5e9b339f323216d71f3ede8a0a427abf7859c486 upstream.

Add or improve checks related to buffer sizes and reply sizes to the handling of replies from the crypto cards for CCA, EP11 (AP message type 6) and ICA (AP type 50) messages. The verification code related to reply field length was not designed well and thus firmware deficiencies could lead to unexpected behavior in the zcrypt device driver. Thus improve the code to more closely inspect especially length fields at message replies.

Add length validation before accessing reply message structures in zcrypt_msgtype6_receive(), zcrypt_msgtype6_receive_ep11(), and zcrypt_msgtype50_receive() to prevent out-of-bounds reads and potential kernel memory disclosure.

Also rework these three functions to validate reply lengths more carefully before copying data back into the request buffer. Use size_t for length calculations, reject inconsistent reply sizes, and add defensive handling for short invalid replies. For XCRB replies, validate both reply segments and derive the effective message length from the covered range instead of trusting only the second segment.

Additionally improve some of the later invoked evaluation functions which further check the payload. Add comments about length assumptions and for the type50 processing rework the payload processing completely with removing a misplaced BUG_ON().

Fixes 5e55a488c87a ("s390/zcrypt: Separate msgtype implementation from card modules.")
---
 drivers/s390/crypto/zcrypt_msgtype50.c |   95 +++++++++++----
 drivers/s390/crypto/zcrypt_msgtype6.c  |  202 ++++++++++++++++++++++++---------
 2 files changed, 218 insertions(+), 79 deletions(-)
drivers/s390/crypto/zcrypt_msgtype50.c +68 -27
@@ -152,6 +152,11 @@ struct type80_hdr {
 	unsigned char	reserved3[8];
 } __packed;
 
+struct type80_reply {
+	struct type80_hdr hdr;
+	char data[];
+} __packed;
+
 int get_rsa_modex_fc(struct ica_rsa_modexpo *mex, int *fcode)
 {
 	if (!mex->inputdatalength)
@@ -340,32 +345,43 @@ static int ICACRT_msg_to_type50CRT_msg(s
  * @data: pointer to user output data
  * @length: size of user output data
  *
- * Returns 0 on success or -EFAULT.
+ * Returns 0 on success or neg. errno value on failure.
  */
 static int convert_type80(struct zcrypt_queue *zq,
 			  struct ap_message *reply,
 			  char __user *outputdata,
 			  unsigned int outputdatalength)
 {
-	struct type80_hdr *t80h = reply->msg;
-	unsigned char *data;
+	struct type80_reply *msg = reply->msg;
+	size_t payload_len;
 
-	if (t80h->len < sizeof(*t80h) + outputdatalength) {
-		/* The result is too short, the CEXxA card may not do that.. */
+	/*
+	 * reply->len is always >= sizeof(struct type80_reply) here and
+	 * outputdatalength (the modulus size) is guaranteed to be equal to
+	 * inputdatalength and 0 < outputdatalength <= CEX3A_MAX_MOD_SIZE,
+	 * also payload size may be >= outputdatalength.
+	 */
+
+	payload_len = reply->len - sizeof(msg->hdr);
+
+	if (outputdatalength > payload_len) {
+		/* We expect at least outputdatalength bytes, broken card ? */
 		zq->online = 0;
 		pr_err("Crypto dev=%02x.%04x code=0x%02x => online=0 rc=EAGAIN\n",
 		       AP_QID_CARD(zq->queue->qid),
-		       AP_QID_QUEUE(zq->queue->qid), t80h->code);
+		       AP_QID_QUEUE(zq->queue->qid), msg->hdr.code);
 		ZCRYPT_DBF_ERR("%s dev=%02x.%04x code=0x%02x => online=0 rc=EAGAIN\n",
 			       __func__, AP_QID_CARD(zq->queue->qid),
-			       AP_QID_QUEUE(zq->queue->qid), t80h->code);
+			       AP_QID_QUEUE(zq->queue->qid), msg->hdr.code);
 		ap_send_online_uevent(&zq->queue->ap_dev, zq->online);
 		return -EAGAIN;
 	}
-	BUG_ON(t80h->len > CEX3A_MAX_RESPONSE_SIZE);
-	data = reply->msg + t80h->len - outputdatalength;
-	if (copy_to_user(outputdata, data, outputdatalength))
+
+	if (copy_to_user(outputdata,
+			 msg->data + payload_len - outputdatalength,
+			 outputdatalength))
 		return -EFAULT;
+
 	return 0;
 }
 
@@ -374,14 +390,19 @@ static int convert_response(struct zcryp
 			    char __user *outputdata,
 			    unsigned int outputdatalength)
 {
-	/* Response type byte is the second byte in the response. */
-	unsigned char rtype = ((unsigned char *)reply->msg)[1];
+	struct type80_reply *msg = reply->msg;
 
-	switch (rtype) {
+	/* reply->len is always >= sizeof(struct error_hdr) here */
+
+	switch (msg->hdr.type) {
 	case TYPE82_RSP_CODE:
 	case TYPE88_RSP_CODE:
 		return convert_error(zq, reply);
 	case TYPE80_RSP_CODE:
+		if (msg->hdr.code)
+			return convert_error(zq, reply);
+		if (reply->len < sizeof(struct type80_reply))
+			return -EINVAL;
 		return convert_type80(zq, reply,
 				      outputdata, outputdatalength);
 	default: /* Unknown response type, this should NEVER EVER happen */
@@ -389,11 +410,11 @@ static int convert_response(struct zcryp
 		pr_err("Crypto dev=%02x.%04x unknown response type 0x%02x => online=0 rc=EAGAIN\n",
 		       AP_QID_CARD(zq->queue->qid),
 		       AP_QID_QUEUE(zq->queue->qid),
-		       (int)rtype);
+		       (int)msg->hdr.type);
 		ZCRYPT_DBF_ERR(
 			"%s dev=%02x.%04x unknown response type 0x%02x => online=0 rc=EAGAIN\n",
 			__func__, AP_QID_CARD(zq->queue->qid),
-			AP_QID_QUEUE(zq->queue->qid), (int)rtype);
+			AP_QID_QUEUE(zq->queue->qid), (int)msg->hdr.type);
 		ap_send_online_uevent(&zq->queue->ap_dev, zq->online);
 		return -EAGAIN;
 	}
@@ -416,26 +437,46 @@ static void zcrypt_msgtype50_receive(str
 		.reply_code = REP82_ERROR_MACHINE_FAILURE,
 	};
 	struct type80_hdr *t80h;
-	int len;
+	size_t len;
 
 	/* Copy the reply message to the request message buffer. */
 	if (!reply)
 		goto out;	/* ap_msg->rc indicates the error */
+
 	t80h = reply->msg;
-	if (t80h->type == TYPE80_RSP_CODE) {
-		len = t80h->len;
-		if (len > reply->bufsize || len > msg->bufsize ||
-		    len != reply->len) {
-			pr_debug("len mismatch => EMSGSIZE\n");
-			msg->rc = -EMSGSIZE;
+
+	if (reply->len < sizeof(*t80h) ||
+	    t80h->type != TYPE80_RSP_CODE) {
+		if (reply->len < sizeof(error_reply)) {
+			/* total broken reply, use static error reply instead */
+			memcpy(msg->msg, &error_reply, sizeof(error_reply));
+			msg->len = sizeof(error_reply);
 			goto out;
+		} else {
+			/* malformed reply, convert function will handle this */
+			len = reply->len;
+			goto copy_len_and_out;
 		}
-		memcpy(msg->msg, reply->msg, len);
-		msg->len = len;
-	} else {
-		memcpy(msg->msg, reply->msg, sizeof(error_reply));
-		msg->len = sizeof(error_reply);
 	}
+
+	len = t80h->len;
+
+copy_len_and_out:
+	if (len != reply->len) {
+		msg->rc = -EMSGSIZE;
+		pr_debug("len %zu rpl.len %zu mismatch, msg.rc=%d\n",
+			 len, reply->len, msg->rc);
+		goto out;
+	}
+	if (len > reply->bufsize || len > msg->bufsize) {
+		msg->rc = -EMSGSIZE;
+		pr_debug("len %zu exceeds buf %zu/%zu, msg.rc=%d\n",
+			 len, reply->bufsize, msg->bufsize, msg->rc);
+		goto out;
+	}
+	memcpy(msg->msg, reply->msg, len);
+	msg->len = len;
+
 out:
 	complete(&msg->response.work);
 }
drivers/s390/crypto/zcrypt_msgtype6.c +150 -52

296 lines not on this page · raw message

author maintainer
#181 lore raw

PATCH 181/547 s390/zcrypt: Fix out-of-bounds ptr advance in cca_query_crypto_facility()

In reply to Greg Kroah-Hartman

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

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

From: Harald Freudenberger <[email protected]>

commit 9fd7fca66735307fd7afa3450882a55ef80f2add upstream.

The FQ reply parser code blindly advanced the walk pointer by a length value read directly from the hardware reply payload without checking that the advance stayed within the allocated reply buffer. A corrupt or malicious device response could push ptr beyond the cprbmem region, causing an out-of-bounds dereference or kernel memory exposure via the subsequent memcpy().

Fix this by tracking the remaining reply buffer space in a variable and validating each device-supplied length field against it before advancing or dereferencing the pointer.

---
 drivers/s390/crypto/zcrypt_ccamisc.c |   22 ++++++++++++++++++++--
 1 file changed, 20 insertions(+), 2 deletions(-)
drivers/s390/crypto/zcrypt_ccamisc.c +20 -2
@@ -1627,6 +1627,7 @@ int cca_query_crypto_facility(u16 cardnr
 		u8  subfunc_code[2];
 		u8  lvdata[];
 	} __packed * prepparm;
+	size_t datalen;
 
 	/* get already prepared memory for 2 cprbs with param block each */
 	rc = alloc_and_prep_cprbmem(parmbsize, &mem,
@@ -1673,27 +1674,44 @@ int cca_query_crypto_facility(u16 cardnr
 	prepcblk->rpl_parmb = (u8 __user *)ptr;
 	prepparm = (struct fqrepparm *)ptr;
 	ptr = prepparm->lvdata;
+	datalen = parmbsize - 2 * sizeof(u8);
 
 	/* check and possibly copy reply rule array */
 	len = *((u16 *)ptr);
+	if (len > datalen) {
+		ZCRYPT_DBF_ERR("%s reply rule array len %u exceeds datalen %zu\n",
+			       __func__, len, datalen);
+		rc = -EIO;
+		goto out;
+	}
+	datalen -= sizeof(u16);
+	ptr += sizeof(u16);
 	if (len > sizeof(u16)) {
-		ptr += sizeof(u16);
 		len -= sizeof(u16);
 		if (rarray && rarraylen && *rarraylen > 0) {
 			*rarraylen = (len > *rarraylen ? *rarraylen : len);
 			memcpy(rarray, ptr, *rarraylen);
 		}
+		datalen -= len;
 		ptr += len;
 	}
 	/* check and possible copy reply var array */
 	len = *((u16 *)ptr);
+	if (len > datalen) {
+		ZCRYPT_DBF_ERR("%s reply var array len %u exceeds datalen %zu\n",
+			       __func__, len, datalen);
+		rc = -EIO;
+		goto out;
+	}
+	datalen -= sizeof(u16);
+	ptr += sizeof(u16);
 	if (len > sizeof(u16)) {
-		ptr += sizeof(u16);
 		len -= sizeof(u16);
 		if (varray && varraylen && *varraylen > 0) {
 			*varraylen = (len > *varraylen ? *varraylen : len);
 			memcpy(varray, ptr, *varraylen);
 		}
+		datalen -= len;
 		ptr += len;
 	}
 
author maintainer
#182 lore raw

PATCH 182/547 s390/zcrypt: Guard domain index uses against speculative bypass

In reply to Greg Kroah-Hartman

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

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

From: Harald Freudenberger <[email protected]>

commit 7b88e8b6d714cd1b2b6185e2963c8ec4d98542d0 upstream.

The previous array_index_nospec() placement only covered the admin permission check, leaving ap_test_config_usage_domain() and ap_test_config_ctrl_domain() in the CCA path exposed to speculative execution.

Move the sanitization to before all permission and config checks in both the CCA and EP11 paths. Hold the sanitized domain value in another variable so that the later use can choose to use either the original value (subject to speculative execution) or the sanitized value (which may in case of AUTOSEL_DOM reflect the wrong value). Before that, check the domain value to be either AUTOSEL_DOM or in range 0...AP_DOMAINS-1 and return with -EINVAL in case this check does not pass.

Fixes e935cd525af4 ("s390/zcrypt: Close speculative mem read possibility")
---
 drivers/s390/crypto/zcrypt_api.c |   35 +++++++++++++++++++++++++----------
 1 file changed, 25 insertions(+), 10 deletions(-)
drivers/s390/crypto/zcrypt_api.c +25 -10
@@ -854,7 +854,7 @@ static long _zcrypt_send_cprb(u32 xflags
 			      struct ica_xcRB *xcrb)
 {
 	bool userspace = xflags & ZCRYPT_XFLAG_USERSPACE;
-	unsigned int card, domain, func_code = 0;
+	unsigned int card, domain, _dom, func_code = 0;
 	unsigned int wgt = 0, pref_wgt = 0;
 	struct zcrypt_queue *zq, *pref_zq;
 	struct zcrypt_card *zc, *pref_zc;
@@ -877,10 +877,17 @@ static long _zcrypt_send_cprb(u32 xflags
 	print_hex_dump_debug("ccareq: ", DUMP_PREFIX_ADDRESS, 16, 1,
 			     ap_msg.msg, ap_msg.len, false);
 
+	/* Check domain for either AUTOSEL_DOM or in range 0...AP_DOMAINS-1 */
+	if (domain != AUTOSEL_DOM && domain >= AP_DOMAINS) {
+		rc = -EINVAL;
+		goto out;
+	}
+	/* Spectre-v1: sanitize domain unconditionally for later use */
+	_dom = array_index_nospec(domain, AP_DOMAINS);
+
 	if (perms != &ap_perms && domain < AP_DOMAINS) {
 		if (ap_msg.flags & AP_MSG_FLAG_ADMIN) {
-			domain = array_index_nospec(domain, AP_DOMAINS);
-			if (!test_bit_inv(domain, perms->adm)) {
+			if (!test_bit_inv(_dom, perms->adm)) {
 				rc = -ENODEV;
 				goto out;
 			}
@@ -893,10 +900,11 @@ static long _zcrypt_send_cprb(u32 xflags
 	 * If a valid target domain is set and this domain is NOT a usage
 	 * domain but a control only domain, autoselect target domain.
 	 */
-	if (domain < AP_DOMAINS &&
-	    !ap_test_config_usage_domain(domain) &&
-	    ap_test_config_ctrl_domain(domain))
-		domain = AUTOSEL_DOM;
+	if (domain < AP_DOMAINS) {
+		if (!ap_test_config_usage_domain(_dom) &&
+		    ap_test_config_ctrl_domain(_dom))
+			domain = AUTOSEL_DOM;
+	}
 
 	pref_zc = NULL;
 	pref_zq = NULL;
@@ -1041,7 +1049,7 @@ static long _zcrypt_send_ep11_cprb(u32 x
 	struct ep11_target_dev *targets = NULL;
 	unsigned short target_num;
 	unsigned int wgt = 0, pref_wgt = 0;
-	unsigned int func_code = 0, domain;
+	unsigned int func_code = 0, domain, _dom;
 	struct ap_message ap_msg;
 	int cpen, qpen, qid = 0, rc;
 	struct module *mod;
@@ -1078,10 +1086,17 @@ static long _zcrypt_send_ep11_cprb(u32 x
 	print_hex_dump_debug("ep11req: ", DUMP_PREFIX_ADDRESS, 16, 1,
 			     ap_msg.msg, ap_msg.len, false);
 
+	/* Check domain for either AUTOSEL_DOM or in range 0...AP_DOMAINS-1 */
+	if (domain != AUTOSEL_DOM && domain >= AP_DOMAINS) {
+		rc = -EINVAL;
+		goto out;
+	}
+	/* Spectre-v1: sanitize domain unconditionally for later use */
+	_dom = array_index_nospec(domain, AP_DOMAINS);
+
 	if (perms != &ap_perms && domain < AP_DOMAINS) {
 		if (ap_msg.flags & AP_MSG_FLAG_ADMIN) {
-			domain = array_index_nospec(domain, AP_DOMAINS);
-			if (!test_bit_inv(domain, perms->adm)) {
+			if (!test_bit_inv(_dom, perms->adm)) {
 				rc = -ENODEV;
 				goto out;
 			}
author maintainer
#183 lore raw

PATCH 183/547 HID: wacom: Use hdev->product in wacom_setup_touch_input_capabilities

In reply to Greg Kroah-Hartman

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

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

From: Lee Jones <[email protected]>

commit 86472508a7ef74b525e79a79d2d02d911a641d6b upstream.

Replace the lookup-dependent 'wacom_wac->shared->touch->product' references with 'hdev->product' inside wacom_setup_touch_input_capabilities() since 'hdev' is already available (via container_of) and represents the touch device itself.

---
 drivers/hid/wacom_wac.c |   18 +++++++++---------
 1 file changed, 9 insertions(+), 9 deletions(-)
drivers/hid/wacom_wac.c +9 -9
@@ -3966,8 +3966,8 @@ int wacom_setup_pen_input_capabilities(s
 int wacom_setup_touch_input_capabilities(struct input_dev *input_dev,
 					 struct wacom_wac *wacom_wac)
 {
+	struct hid_device *hdev = container_of(wacom_wac, struct wacom, wacom_wac)->hdev;
 	struct wacom_features *features = &wacom_wac->features;
-
 	if (!(features->device_type & WACOM_DEVICETYPE_TOUCH))
 		return -ENODEV;
 
@@ -3976,9 +3976,11 @@ int wacom_setup_touch_input_capabilities
 	else
 		__set_bit(INPUT_PROP_POINTER, input_dev->propbit);
 
-	if (features->type == HID_GENERIC)
+	if (features->type == HID_GENERIC) {
+		hid_dbg(hdev, "generic touch setup\n");
 		/* setup has already been done */
 		return 0;
+	}
 
 	input_dev->evbit[0] |= BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
 	__set_bit(BTN_TOUCH, input_dev->keybit);
@@ -4010,19 +4012,17 @@ int wacom_setup_touch_input_capabilities
 		input_dev->evbit[0] |= BIT_MASK(EV_SW);
 		__set_bit(SW_MUTE_DEVICE, input_dev->swbit);
 
-		if (wacom_wac->shared->touch->product == 0x361) {
+		if (hdev->product == 0x361) {
 			input_set_abs_params(input_dev, ABS_MT_POSITION_X,
 					     0, 12440, 4, 0);
 			input_set_abs_params(input_dev, ABS_MT_POSITION_Y,
 					     0, 8640, 4, 0);
-		}
-		else if (wacom_wac->shared->touch->product == 0x360) {
+		} else if (hdev->product == 0x360) {
 			input_set_abs_params(input_dev, ABS_MT_POSITION_X,
 					     0, 8960, 4, 0);
 			input_set_abs_params(input_dev, ABS_MT_POSITION_Y,
 					     0, 5920, 4, 0);
-		}
-		else if (wacom_wac->shared->touch->product == 0x393) {
+		} else if (hdev->product == 0x393) {
 			input_set_abs_params(input_dev, ABS_MT_POSITION_X,
 					     0, 6400, 4, 0);
 			input_set_abs_params(input_dev, ABS_MT_POSITION_Y,
@@ -4052,8 +4052,8 @@ int wacom_setup_touch_input_capabilities
 		fallthrough;
 
 	case WACOM_27QHDT:
-		if (wacom_wac->shared->touch->product == 0x32C ||
-		    wacom_wac->shared->touch->product == 0xF6) {
+		if (hdev->product == 0x32C ||
+		    hdev->product == 0xF6) {
 			input_dev->evbit[0] |= BIT_MASK(EV_SW);
 			__set_bit(SW_MUTE_DEVICE, input_dev->swbit);
 			wacom_wac->has_mute_touch_switch = true;
author maintainer
#184 lore raw

PATCH 184/547 HID: wacom: Advertise SW_MUTE_DEVICE capability prior to registration

In reply to Greg Kroah-Hartman

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

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

From: Lee Jones <[email protected]>

commit ba16e5ffbaa10fde960918d69af5e49f2b3fdd5e upstream.

Input subsystem guidelines require that device capabilities are advertised before the input device is registered. The Wacom driver was violating this by advertising the SW_MUTE_DEVICE capability post-registration in wacom_set_shared_values() (and duplicating it in device-specific setup cases).

Resolve this by moving the SW_MUTE_DEVICE capability setup to wacom_setup_touch_input_capabilities() for all touch devices that support it.

For generic touch devices whose capabilities depend on mute switch usages parsed from a sibling Pen/Pad interface, defer registration with -EPROBE_DEFER until the sibling has parsed its descriptors and initialized shared capabilities.

Fixes d2ec58aee8b1 ("HID: wacom: generic: support generic touch switch")
---
 drivers/hid/wacom_sys.c |   93 ++++++++++++++++++++++++++++++++++++++----------
 drivers/hid/wacom_wac.c |    5 ++
 2 files changed, 79 insertions(+), 19 deletions(-)
drivers/hid/wacom_sys.c +74 -19
@@ -908,19 +908,14 @@ static int wacom_add_shared_data(struct
 		list_add_tail(&data->list, &wacom_udev_list);
 	}
 
-	mutex_unlock(&wacom_udev_list_lock);
-
 	wacom_wac->shared = &data->shared;
 
-	retval = devm_add_action_or_reset(&hdev->dev, wacom_remove_shared_data, wacom);
-	if (retval)
-		return retval;
+	if (wacom_wac->has_mute_touch_switch)
+		WRITE_ONCE(wacom_wac->shared->has_mute_touch_switch, true);
 
-	if (wacom_wac->features.device_type & WACOM_DEVICETYPE_TOUCH)
-		wacom_wac->shared->touch = hdev;
-	else if (wacom_wac->features.device_type & WACOM_DEVICETYPE_PEN)
-		wacom_wac->shared->pen = hdev;
+	mutex_unlock(&wacom_udev_list_lock);
 
+	retval = devm_add_action_or_reset(&hdev->dev, wacom_remove_shared_data, wacom);
 	return retval;
 }
 
@@ -2344,13 +2339,12 @@ static void wacom_release_resources(stru
 
 static void wacom_set_shared_values(struct wacom_wac *wacom_wac)
 {
-	if (wacom_wac->features.device_type & WACOM_DEVICETYPE_TOUCH) {
-		wacom_wac->shared->type = wacom_wac->features.type;
-		wacom_wac->shared->touch_input = wacom_wac->touch_input;
-	}
+	struct wacom *wacom = container_of(wacom_wac, struct wacom, wacom_wac);
+
+	guard(mutex)(&wacom_udev_list_lock);
 
 	if (wacom_wac->has_mute_touch_switch) {
-		wacom_wac->shared->has_mute_touch_switch = true;
+		WRITE_ONCE(wacom_wac->shared->has_mute_touch_switch, true);
 		/* Hardware touch switch may be off. Wait until
 		 * we know the switch state to decide is_touch_on.
 		 * Softkey state should be initialized to "on" to
@@ -2360,12 +2354,67 @@ static void wacom_set_shared_values(stru
 			wacom_wac->shared->is_touch_on = true;
 	}
 
-	if (wacom_wac->shared->has_mute_touch_switch &&
-	    wacom_wac->shared->touch_input) {
-		set_bit(EV_SW, wacom_wac->shared->touch_input->evbit);
-		input_set_capability(wacom_wac->shared->touch_input, EV_SW,
-				     SW_MUTE_DEVICE);
+	if (wacom_wac->features.device_type & WACOM_DEVICETYPE_TOUCH) {
+		wacom_wac->shared->type = wacom_wac->features.type;
+		wacom_wac->shared->touch_input = wacom_wac->touch_input;
+		wacom_wac->shared->touch = wacom->hdev;
+	} else if (wacom_wac->features.device_type & WACOM_DEVICETYPE_PEN) {
+		/* Pairs with smp_load_acquire() in wacom_sibling_pending() */
+		smp_store_release(&wacom_wac->shared->pen, wacom->hdev);
+	}
+}
+
+static bool wacom_sibling_pending(struct wacom *wacom)
+{
+	const struct wacom_features *features = &wacom->wacom_wac.features;
+	struct hid_device *hdev = wacom->hdev;
+	struct usb_interface *sibling_intf;
+	int ifnum;
+
+	if (features->type != HID_GENERIC ||
+	    !(features->device_type & WACOM_DEVICETYPE_TOUCH))
+		return false;
+
+	if (wacom->wacom_wac.shared) {
+		/* Pairs with smp_store_release() in wacom_set_shared_values() */
+		if (smp_load_acquire(&wacom->wacom_wac.shared->pen))
+			return false;
 	}
+
+	if (!hid_is_usb(hdev) || !wacom->usbdev || !wacom->intf ||
+	    !wacom->intf->cur_altsetting)
+		return false;
+
+	ifnum = wacom->intf->cur_altsetting->desc.bInterfaceNumber;
+
+	/*
+	 * On composite Wacom devices, the Pen interface is always interface 0.
+	 * If the Touch interface is interface 0, there is no sibling Pen
+	 * interface on this device (standalone touch device).
+	 */
+	if (ifnum == 0)
+		return false;
+
+	/* Look for the sibling Pen interface at interface 0 */
+	sibling_intf = usb_ifnum_to_if(wacom->usbdev, 0);
+	if (!sibling_intf || !sibling_intf->cur_altsetting)
+		return false;
+
+	if (sibling_intf->cur_altsetting->desc.bInterfaceClass !=
+	    USB_INTERFACE_CLASS_HID)
+		return false;
+
+	if (sibling_intf->cur_altsetting->desc.bInterfaceSubClass == 1 &&
+	    (sibling_intf->cur_altsetting->desc.bInterfaceProtocol == 1 ||
+	     sibling_intf->cur_altsetting->desc.bInterfaceProtocol == 2))
+		return false;
+
+	/*
+	 * Interface 0 is a candidate HID interface on this composite device
+	 * whose probe has not completed yet (shared->pen is NULL). Defer until
+	 * interface 0 finishes probing and registers shared values.
+	 */
+	return true;
 }
 
 static int wacom_parse_and_register(struct wacom *wacom, bool wireless)
@@ -2445,6 +2494,11 @@ static int wacom_parse_and_register(stru
 	if (error)
 		goto fail;
 
+	if (wacom_sibling_pending(wacom)) {
+		error = -EPROBE_DEFER;
+		goto fail;
+	}
+
 	error = wacom_setup_inputs(wacom);
 	if (error)
 		goto fail;
@@ -2502,6 +2556,7 @@ static int wacom_parse_and_register(stru
 
 fail_hw_stop:
 	hid_hw_stop(hdev);
+	cancel_delayed_work_sync(&wacom->init_work);
 fail:
 	wacom_release_resources(wacom);
 	return error;
drivers/hid/wacom_wac.c +5 -0
@@ -3978,6 +3978,11 @@ int wacom_setup_touch_input_capabilities
 
 	if (features->type == HID_GENERIC) {
 		hid_dbg(hdev, "generic touch setup\n");
+		if (wacom_wac->has_mute_touch_switch ||
+		    (wacom_wac->shared && READ_ONCE(wacom_wac->shared->has_mute_touch_switch))) {
+			input_set_capability(input_dev, EV_SW, SW_MUTE_DEVICE);
+			wacom_wac->has_mute_touch_switch = true;
+		}
 		/* setup has already been done */
 		return 0;
 	}
author maintainer
#185 lore raw

PATCH 185/547 HID: wacom: Fix Use-After-Free in wacom_intuos_pad

In reply to Greg Kroah-Hartman

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

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

From: Lee Jones <[email protected]>

commit ef32877368a7013c060ef6bd03a30b6da2fe0c41 upstream.

wacom_intuos_pad() accesses wacom->shared->touch_input locklessly inside the interrupt handler context. If the Touch sibling device is disconnected, wacom_remove_shared_data() clears 'touch_input' outside any lock, creating a Time-of-Check to Time-of-Use (TOCTOU) race condition where a preempted reader in interrupt context dereferences the freed pointer, leading to a Use-After-Free.

Resolve this by introducing RCU protection for the touch_input pointer:

- Annotate 'touch_input' in wacom_shared struct with __rcu
- Wrap all lockless readers in wacom_wac.c with guard(rcu)() and rcu_dereference() using a unified wacom_report_touch_mute() helper
- Update writers in wacom_sys.c using rcu_assign_pointer()
- Call synchronize_rcu() in wacom_remove_shared_data() to ensure all active RCU readers have finished before the input device is freed

Also wrap wacom_set_shared_values() and touch/pen assignments in wacom_add_shared_data() inside the wacom_udev_list_lock to serialize concurrent probe assignments, and verify that 'shared->touch == hdev' before setting touch_input to prevent concurrent sibling probe state desynchronization.

Fixes 961794a00eab ("Input: wacom - add reporting of SW_MUTE_DEVICE events")
---
 drivers/hid/wacom_sys.c |   23 ++++++++++++++++-------
 drivers/hid/wacom_wac.c |   36 ++++++++++++++++++------------------
 drivers/hid/wacom_wac.h |    2 +-
 3 files changed, 35 insertions(+), 26 deletions(-)
drivers/hid/wacom_sys.c +16 -7
@@ -876,10 +876,16 @@ static void wacom_remove_shared_data(voi
 		data = container_of(wacom_wac->shared, struct wacom_hdev_data,
 				    shared);
 
-		if (wacom_wac->shared->touch == wacom->hdev)
-			wacom_wac->shared->touch = NULL;
-		else if (wacom_wac->shared->pen == wacom->hdev)
-			wacom_wac->shared->pen = NULL;
+		scoped_guard(mutex, &wacom_udev_list_lock) {
+			if (wacom_wac->shared->touch == wacom->hdev) {
+				wacom_wac->shared->touch = NULL;
+				rcu_assign_pointer(wacom_wac->shared->touch_input, NULL);
+			} else if (wacom_wac->shared->pen == wacom->hdev) {
+				wacom_wac->shared->pen = NULL;
+			}
+		}
+
+		synchronize_rcu();
 
 		kref_put(&data->kref, wacom_release_shared_data);
 		wacom_wac->shared = NULL;
@@ -916,6 +922,7 @@ static int wacom_add_shared_data(struct
 	mutex_unlock(&wacom_udev_list_lock);
 
 	retval = devm_add_action_or_reset(&hdev->dev, wacom_remove_shared_data, wacom);
+
 	return retval;
 }
 
@@ -2355,9 +2362,11 @@ static void wacom_set_shared_values(stru
 	}
 
 	if (wacom_wac->features.device_type & WACOM_DEVICETYPE_TOUCH) {
-		wacom_wac->shared->type = wacom_wac->features.type;
-		wacom_wac->shared->touch_input = wacom_wac->touch_input;
-		wacom_wac->shared->touch = wacom->hdev;
+		if (wacom_wac->shared->touch == wacom->hdev || !wacom_wac->shared->touch) {
+			wacom_wac->shared->type = wacom_wac->features.type;
+			wacom_wac->shared->touch = wacom->hdev;
+			rcu_assign_pointer(wacom_wac->shared->touch_input, wacom_wac->touch_input);
+		}
 	} else if (wacom_wac->features.device_type & WACOM_DEVICETYPE_PEN) {
 		/* Pairs with smp_load_acquire() in wacom_sibling_pending() */
 		smp_store_release(&wacom_wac->shared->pen, wacom->hdev);
drivers/hid/wacom_wac.c +18 -18
@@ -510,6 +510,18 @@ static void wacom_intuos_schedule_prox_e
 	}
 }
 
+static void wacom_report_touch_mute(struct wacom_wac *wacom_wac, bool mute)
+{
+	struct input_dev *touch_input;
+
+	guard(rcu)();
+	touch_input = rcu_dereference(wacom_wac->shared->touch_input);
+	if (touch_input) {
+		input_report_switch(touch_input, SW_MUTE_DEVICE, mute);
+		input_sync(touch_input);
+	}
+}
+
 static int wacom_intuos_pad(struct wacom_wac *wacom)
 {
 	struct wacom_features *features = &wacom->features;
@@ -650,12 +662,8 @@ static int wacom_intuos_pad(struct wacom
 	input_report_key(input, KEY_CONTROLPANEL, menu);
 	input_report_key(input, KEY_INFO, info);
 
-	if (wacom->shared && wacom->shared->touch_input) {
-		input_report_switch(wacom->shared->touch_input,
-				    SW_MUTE_DEVICE,
-				    !wacom->shared->is_touch_on);
-		input_sync(wacom->shared->touch_input);
-	}
+	if (wacom->shared)
+		wacom_report_touch_mute(wacom, !wacom->shared->is_touch_on);
 
 	input_report_abs(input, ABS_RX, strip1);
 	input_report_abs(input, ABS_RY, strip2);
@@ -2168,7 +2176,7 @@ static void wacom_wac_pad_event(struct h
 	 */
 	if ((equivalent_usage == WACOM_HID_WD_MUTE_DEVICE) ||
 	   (equivalent_usage == WACOM_HID_WD_TOUCHONOFF)) {
-		if (wacom_wac->shared->touch_input) {
+		if (wacom_wac->shared) {
 			bool *is_touch_on = &wacom_wac->shared->is_touch_on;
 
 			if (equivalent_usage == WACOM_HID_WD_MUTE_DEVICE && value)
@@ -2176,9 +2184,7 @@ static void wacom_wac_pad_event(struct h
 			else if (equivalent_usage == WACOM_HID_WD_TOUCHONOFF)
 				*is_touch_on = value;
 
-			input_report_switch(wacom_wac->shared->touch_input,
-					    SW_MUTE_DEVICE, !(*is_touch_on));
-			input_sync(wacom_wac->shared->touch_input);
+			wacom_report_touch_mute(wacom_wac, !(*is_touch_on));
 		}
 		return;
 	}
@@ -3396,11 +3402,8 @@ static int wacom_wireless_irq(struct wac
 
 		if ((wacom->shared->type == INTUOSHT ||
 		    wacom->shared->type == INTUOSHT2) &&
-		    wacom->shared->touch_input &&
 		    wacom->shared->touch_max) {
-			input_report_switch(wacom->shared->touch_input,
-					SW_MUTE_DEVICE, data[5] & 0x40);
-			input_sync(wacom->shared->touch_input);
+			wacom_report_touch_mute(wacom, data[5] & 0x40);
 		}
 
 		pid = get_unaligned_be16(&data[6]);
@@ -3435,11 +3438,8 @@ static int wacom_status_irq(struct wacom
 
 	if ((features->type == INTUOSHT ||
 	    features->type == INTUOSHT2) &&
-	    wacom_wac->shared->touch_input &&
 	    features->touch_max) {
-		input_report_switch(wacom_wac->shared->touch_input,
-				    SW_MUTE_DEVICE, data[8] & 0x40);
-		input_sync(wacom_wac->shared->touch_input);
+		wacom_report_touch_mute(wacom_wac, data[8] & 0x40);
 	}
 
 	if (data[9] & 0x02) { /* wireless module is attached */
drivers/hid/wacom_wac.h +1 -1
@@ -285,7 +285,7 @@ struct wacom_shared {
 	/* for wireless device to access USB interfaces */
 	unsigned touch_max;
 	int type;
-	struct input_dev *touch_input;
+	struct input_dev __rcu *touch_input;
 	struct hid_device *pen;
 	struct hid_device *touch;
 	bool has_mute_touch_switch;
author maintainer
#186 lore raw

PATCH 186/547 HID: wacom: Fix Use-After-Free in wacom_bamboo_pad

In reply to Greg Kroah-Hartman

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

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

From: Lee Jones <[email protected]>

commit 3a523ecf9ac3fdd33f5eb31c43937ee44135395b upstream.

wacom_bamboo_pad_pen_event() accesses wacom->shared->pen locklessly relative to wacom_remove_shared_data() which nullifies it. This can lead to a Use-After-Free if the sibling device is removed while events are being processed.

Resolve this by introducing RCU protection for pen and touch pointers:

- Annotate 'pen' and 'touch' in wacom_shared struct with __rcu.
- Wrap lockless readers in wacom_bamboo_pad_pen_event() with rcu_read_lock() and rcu_dereference().
- Update writers in wacom_sys.c using rcu_assign_pointer().
- Use rcu_dereference_protected for comparisons under wacom_udev_list_lock.
- Also use rcu_access_pointer in wacom_sibling_pending() and wacom_mode_change_work() to avoid warnings (while lockless access in the latter remains a pre-existing issue).

Fixes 8c97a765467c ("HID: wacom: add full support of the Wacom Bamboo PAD")
---
 drivers/hid/wacom_sys.c |   40 ++++++++++++++++++++++++++--------------
 drivers/hid/wacom_wac.c |   13 ++++++-------
 drivers/hid/wacom_wac.h |    4 ++--
 3 files changed, 34 insertions(+), 23 deletions(-)
drivers/hid/wacom_sys.c +26 -14
@@ -877,11 +877,18 @@ static void wacom_remove_shared_data(voi
 				    shared);
 
 		scoped_guard(mutex, &wacom_udev_list_lock) {
-			if (wacom_wac->shared->touch == wacom->hdev) {
-				wacom_wac->shared->touch = NULL;
+			struct hid_device *touch =
+				rcu_dereference_protected(wacom_wac->shared->touch,
+							  lockdep_is_held(&wacom_udev_list_lock));
+			struct hid_device *pen =
+				rcu_dereference_protected(wacom_wac->shared->pen,
+							  lockdep_is_held(&wacom_udev_list_lock));
+
+			if (touch == wacom->hdev) {
+				rcu_assign_pointer(wacom_wac->shared->touch, NULL);
 				rcu_assign_pointer(wacom_wac->shared->touch_input, NULL);
-			} else if (wacom_wac->shared->pen == wacom->hdev) {
-				wacom_wac->shared->pen = NULL;
+			} else if (pen == wacom->hdev) {
+				rcu_assign_pointer(wacom_wac->shared->pen, NULL);
 			}
 		}
 
@@ -2362,14 +2369,17 @@ static void wacom_set_shared_values(stru
 	}
 
 	if (wacom_wac->features.device_type & WACOM_DEVICETYPE_TOUCH) {
-		if (wacom_wac->shared->touch == wacom->hdev || !wacom_wac->shared->touch) {
+		struct hid_device *touch =
+			rcu_dereference_protected(wacom_wac->shared->touch,
+						  lockdep_is_held(&wacom_udev_list_lock));
+
+		if (touch == wacom->hdev || !touch) {
 			wacom_wac->shared->type = wacom_wac->features.type;
-			wacom_wac->shared->touch = wacom->hdev;
+			rcu_assign_pointer(wacom_wac->shared->touch, wacom->hdev);
 			rcu_assign_pointer(wacom_wac->shared->touch_input, wacom_wac->touch_input);
 		}
 	} else if (wacom_wac->features.device_type & WACOM_DEVICETYPE_PEN) {
-		/* Pairs with smp_load_acquire() in wacom_sibling_pending() */
-		smp_store_release(&wacom_wac->shared->pen, wacom->hdev);
+		rcu_assign_pointer(wacom_wac->shared->pen, wacom->hdev);
 	}
 }
 
@@ -2385,8 +2395,7 @@ static bool wacom_sibling_pending(struct
 		return false;
 
 	if (wacom->wacom_wac.shared) {
-		/* Pairs with smp_store_release() in wacom_set_shared_values() */
-		if (smp_load_acquire(&wacom->wacom_wac.shared->pen))
+		if (rcu_access_pointer(wacom->wacom_wac.shared->pen))
 			return false;
 	}
 
@@ -2853,16 +2862,19 @@ static void wacom_mode_change_work(struc
 	bool is_direct = wacom->wacom_wac.is_direct_mode;
 	int error = 0;
 
-	if (shared->pen) {
-		wacom1 = hid_get_drvdata(shared->pen);
+	struct hid_device *pen = rcu_access_pointer(shared->pen);
+	struct hid_device *touch = rcu_access_pointer(shared->touch);
+
+	if (pen) {
+		wacom1 = hid_get_drvdata(pen);
 		wacom_release_resources(wacom1);
 		hid_hw_stop(wacom1->hdev);
 		wacom1->wacom_wac.has_mode_change = true;
 		wacom1->wacom_wac.is_direct_mode = is_direct;
 	}
 
-	if (shared->touch) {
-		wacom2 = hid_get_drvdata(shared->touch);
+	if (touch) {
+		wacom2 = hid_get_drvdata(touch);
 		wacom_release_resources(wacom2);
 		hid_hw_stop(wacom2->hdev);
 		wacom2->wacom_wac.has_mode_change = true;
drivers/hid/wacom_wac.c +6 -7
@@ -3307,6 +3307,7 @@ static int wacom_bpt_irq(struct wacom_wa
 static void wacom_bamboo_pad_pen_event(struct wacom_wac *wacom,
 		unsigned char *data)
 {
+	struct hid_device *pen;
 	unsigned char prefix;
 
 	/*
@@ -3319,13 +3320,11 @@ static void wacom_bamboo_pad_pen_event(s
 	prefix = data[0];
 	data[0] = WACOM_REPORT_BPAD_PEN;
 
-	/*
-	 * actually reroute the event.
-	 * No need to check if wacom->shared->pen is valid, hid_input_report()
-	 * will check for us.
-	 */
-	hid_input_report(wacom->shared->pen, HID_INPUT_REPORT, data,
-			 WACOM_PKGLEN_PENABLED, 1);
+	guard(rcu)();
+	pen = rcu_dereference(wacom->shared->pen);
+	if (pen)
+		hid_input_report(pen, HID_INPUT_REPORT, data,
+				 WACOM_PKGLEN_PENABLED, 1);
 
 	data[0] = prefix;
 }
drivers/hid/wacom_wac.h +2 -2
@@ -286,8 +286,8 @@ struct wacom_shared {
 	unsigned touch_max;
 	int type;
 	struct input_dev __rcu *touch_input;
-	struct hid_device *pen;
-	struct hid_device *touch;
+	struct hid_device __rcu *pen;
+	struct hid_device __rcu *touch;
 	bool has_mute_touch_switch;
 	bool is_touch_on;
 };
author maintainer
#187 lore raw

PATCH 187/547 HID: wacom: Redesign shared sibling data lifecycle

In reply to Greg Kroah-Hartman

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

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

From: Lee Jones <[email protected]>

commit 480c9cb14ae81f8e112ff83f8778b3d7b9324dc8 upstream.

The Wacom driver coordinates state between sibling interfaces of the same physical device using a shared structure 'wacom_shared' inside 'wacom_hdev_data'. The driver kept a volatile representative pointer 'data->dev' pointing to a sibling 'hid_device' for physical path comparisons during sibling matching.

This pointer management is fragile. When the representative device is disconnected, wacom_remove_shared_data() failed to clear/update 'data->dev', leading to a Use-After-Free vulnerability when subsequent sibling probes dereference the dangling 'data->dev' pointer.

Resolve this issue by redesigning the sibling data lifecycle:

- Eliminate the volatile 'data->dev' representative pointer completely
- Redesign 'wacom_hdev_data' to store stable static copies of the required attributes upon first allocation: 'phys' path string, 'vendor', 'product' IDs and the sibling's 'device_type'
- Use these static attributes for stable sibling matching in wacom_are_sibling() and wacom_get_hdev_data()

This ensures sibling matching remains safe and stable even if individual siblings are dynamically added or removed.

To secure the lifecycle against concurrent probe/disconnect races:

- Switch kref_put() to kref_put_mutex() in wacom_remove_shared_data() to serialize refcount drops with list traversal and lookup
- Modify wacom_release_shared_data() to assume the list lock is already held

Also, do not accumulate the 'device_type' capability flag during subsequent sibling probes. Keeping only the first probed sibling's device_type exactly preserves the original sibling matching behavior without introducing side effects.

Fixes 4492efffffeb ("Input: wacom - share pen info with touch of the same ID")
---
 drivers/hid/wacom_sys.c |   70 +++++++++++++++++++++++++++++++-----------------
 1 file changed, 46 insertions(+), 24 deletions(-)
drivers/hid/wacom_sys.c +46 -24
@@ -758,27 +758,47 @@ static void wacom_retrieve_hid_descripto
 struct wacom_hdev_data {
 	struct list_head list;
 	struct kref kref;
-	struct hid_device *dev;
+	char phys[64];
+	__u32 vendor;
+	__u32 product;
+	__u32 device_type;
 	struct wacom_shared shared;
 };
 
+static bool wacom_compare_device_paths(struct hid_device *hdev_a,
+				       const char *phys_b, char separator)
+{
+	const char *p1 = strrchr(hdev_a->phys, separator);
+	const char *p2 = strrchr(phys_b, separator);
+	int n1, n2;
+
+	if (!p1 || !p2)
+		return false;
+
+	n1 = p1 - hdev_a->phys;
+	n2 = p2 - phys_b;
+
+	if (n1 != n2 || n1 <= 0 || n2 <= 0)
+		return false;
+
+	return !strncmp(hdev_a->phys, phys_b, n1);
+}
+
 static LIST_HEAD(wacom_udev_list);
 static DEFINE_MUTEX(wacom_udev_list_lock);
 
 static bool wacom_are_sibling(struct hid_device *hdev,
-		struct hid_device *sibling)
+		struct wacom_hdev_data *data)
 {
 	struct wacom *wacom = hid_get_drvdata(hdev);
 	struct wacom_features *features = &wacom->wacom_wac.features;
-	struct wacom *sibling_wacom = hid_get_drvdata(sibling);
-	struct wacom_features *sibling_features = &sibling_wacom->wacom_wac.features;
 	__u32 oVid = features->oVid ? features->oVid : hdev->vendor;
 	__u32 oPid = features->oPid ? features->oPid : hdev->product;
 
 	/* The defined oVid/oPid must match that of the sibling */
-	if (features->oVid != HID_ANY_ID && sibling->vendor != oVid)
+	if (features->oVid != HID_ANY_ID && data->vendor != oVid)
 		return false;
-	if (features->oPid != HID_ANY_ID && sibling->product != oPid)
+	if (features->oPid != HID_ANY_ID && data->product != oPid)
 		return false;
 
 	/*
@@ -786,11 +806,11 @@ static bool wacom_are_sibling(struct hid
 	 * device path, while those with different VID/PID must share
 	 * the same physical parent device path.
 	 */
-	if (hdev->vendor == sibling->vendor && hdev->product == sibling->product) {
-		if (!hid_compare_device_paths(hdev, sibling, '/'))
+	if (hdev->vendor == data->vendor && hdev->product == data->product) {
+		if (!wacom_compare_device_paths(hdev, data->phys, '/'))
 			return false;
 	} else {
-		if (!hid_compare_device_paths(hdev, sibling, '.'))
+		if (!wacom_compare_device_paths(hdev, data->phys, '.'))
 			return false;
 	}
 
@@ -803,7 +823,7 @@ static bool wacom_are_sibling(struct hid
 	 * devices.
 	 */
 	if ((features->device_type & WACOM_DEVICETYPE_DIRECT) &&
-	    !(sibling_features->device_type & WACOM_DEVICETYPE_DIRECT))
+	    !(data->device_type & WACOM_DEVICETYPE_DIRECT))
 		return false;
 
 	/*
@@ -811,17 +831,17 @@ static bool wacom_are_sibling(struct hid
 	 * devices.
 	 */
 	if (!(features->device_type & WACOM_DEVICETYPE_DIRECT) &&
-	    (sibling_features->device_type & WACOM_DEVICETYPE_DIRECT))
+	    (data->device_type & WACOM_DEVICETYPE_DIRECT))
 		return false;
 
 	/* Pen devices may only be siblings of touch devices */
 	if ((features->device_type & WACOM_DEVICETYPE_PEN) &&
-	    !(sibling_features->device_type & WACOM_DEVICETYPE_TOUCH))
+	    !(data->device_type & WACOM_DEVICETYPE_TOUCH))
 		return false;
 
 	/* Touch devices may only be siblings of pen devices */
 	if ((features->device_type & WACOM_DEVICETYPE_TOUCH) &&
-	    !(sibling_features->device_type & WACOM_DEVICETYPE_PEN))
+	    !(data->device_type & WACOM_DEVICETYPE_PEN))
 		return false;
 
 	/*
@@ -837,7 +857,7 @@ static struct wacom_hdev_data *wacom_get
 
 	/* Try to find an already-probed interface from the same device */
 	list_for_each_entry(data, &wacom_udev_list, list) {
-		if (hid_compare_device_paths(hdev, data->dev, '/')) {
+		if (wacom_compare_device_paths(hdev, data->phys, '/')) {
 			kref_get(&data->kref);
 			return data;
 		}
@@ -845,7 +865,7 @@ static struct wacom_hdev_data *wacom_get
 
 	/* Fallback to finding devices that appear to be "siblings" */
 	list_for_each_entry(data, &wacom_udev_list, list) {
-		if (wacom_are_sibling(hdev, data->dev)) {
+		if (wacom_are_sibling(hdev, data)) {
 			kref_get(&data->kref);
 			return data;
 		}
@@ -859,18 +879,15 @@ static void wacom_release_shared_data(st
 	struct wacom_hdev_data *data =
 		container_of(kref, struct wacom_hdev_data, kref);
 
-	mutex_lock(&wacom_udev_list_lock);
 	list_del(&data->list);
-	mutex_unlock(&wacom_udev_list_lock);
-
 	kfree(data);
 }
 
 static void wacom_remove_shared_data(void *res)
 {
-	struct wacom *wacom = res;
+	struct wacom *res_wacom = res;
 	struct wacom_hdev_data *data;
-	struct wacom_wac *wacom_wac = &wacom->wacom_wac;
+	struct wacom_wac *wacom_wac = &res_wacom->wacom_wac;
 
 	if (wacom_wac->shared) {
 		data = container_of(wacom_wac->shared, struct wacom_hdev_data,
@@ -884,17 +901,19 @@ static void wacom_remove_shared_data(voi
 				rcu_dereference_protected(wacom_wac->shared->pen,
 							  lockdep_is_held(&wacom_udev_list_lock));
 
-			if (touch == wacom->hdev) {
+			if (touch == res_wacom->hdev) {
 				rcu_assign_pointer(wacom_wac->shared->touch, NULL);
 				rcu_assign_pointer(wacom_wac->shared->touch_input, NULL);
-			} else if (pen == wacom->hdev) {
+			} else if (pen == res_wacom->hdev) {
 				rcu_assign_pointer(wacom_wac->shared->pen, NULL);
 			}
 		}
 
 		synchronize_rcu();
 
-		kref_put(&data->kref, wacom_release_shared_data);
+		if (kref_put_mutex(&data->kref, wacom_release_shared_data, &wacom_udev_list_lock))
+			mutex_unlock(&wacom_udev_list_lock);
+
 		wacom_wac->shared = NULL;
 	}
 }
@@ -917,7 +936,10 @@ static int wacom_add_shared_data(struct
 		}
 
 		kref_init(&data->kref);
-		data->dev = hdev;
+		strscpy(data->phys, hdev->phys, sizeof(data->phys));
+		data->vendor = hdev->vendor;
+		data->product = hdev->product;
+		data->device_type = wacom_wac->features.device_type;
 		list_add_tail(&data->list, &wacom_udev_list);
 	}
 
author maintainer
#188 lore raw

PATCH 188/547 HID: wacom: Setup SW_MUTE_DEVICE according to the order of input registration

In reply to Greg Kroah-Hartman

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

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

From: Ping Cheng <[email protected]>

commit 97ce491bcef2d231b8d51cee8e579183319a5ba4 upstream.

The refactored SW_MUTE_DEVICE code assumed that stylus will be the first regiestered input. In reality, touch can be registered before stylus, such as the Wacom Cintiq Pro 13 and 16.

This patch covers both touch-first and stylus-first cases.

Fixes ba16e5ffbaa1 ("HID: wacom: Advertise SW_MUTE_DEVICE capability prior to registration")
---
 drivers/hid/wacom_wac.c |   33 ++++++++++++++++++++++++++++++---
 1 file changed, 30 insertions(+), 3 deletions(-)
drivers/hid/wacom_wac.c +30 -3
@@ -3977,10 +3977,18 @@ int wacom_setup_touch_input_capabilities
 
 	if (features->type == HID_GENERIC) {
 		hid_dbg(hdev, "generic touch setup\n");
-		if (wacom_wac->has_mute_touch_switch ||
-		    (wacom_wac->shared && READ_ONCE(wacom_wac->shared->has_mute_touch_switch))) {
+
+		/*
+		 * This is to setup the touch switch for those devices that report
+		 * pen interface first. The setup can only be done here since this
+		 * routine is only called once. When we are here, the shared
+		 * has_mute_touch_switch has been set by the pad.
+
+		 * There are two ways of reporting inputs from firmware: stylus first
+		 * or touch first. This path covers the stylus input first case.
+		 */
+		if (wacom_wac->shared && READ_ONCE(wacom_wac->shared->has_mute_touch_switch)) {
 			input_set_capability(input_dev, EV_SW, SW_MUTE_DEVICE);
-			wacom_wac->has_mute_touch_switch = true;
 		}
 		/* setup has already been done */
 		return 0;
@@ -4403,7 +4411,26 @@ int wacom_setup_pad_input_capabilities(s
 		break;
 
 	case INTUOSHT3_BT:
+		break;
+
 	case HID_GENERIC:
+		if (wacom_wac->shared) {
+			/*
+			 * The setup of touch switch capability can only be done
+			 * here for those devices, such as Cintiq Pro 13 and 16,
+			 * that have touch input registered before stylus and pad
+			 * inputs.
+			 *
+			 * There are two ways of reporting inputs from firmware:
+			 * stylus first or touch first. This path covers the touch
+			 * input first case.
+			 */
+			if (wacom_wac->has_mute_touch_switch &&
+			    wacom_wac->shared->touch_input) {
+				input_set_capability(wacom_wac->shared->touch_input,
+				    EV_SW, SW_MUTE_DEVICE);
+			}
+		}
 		break;
 
 	default:
author maintainer
#189 lore raw

PATCH 189/547 HID: wacom: Write shared touch initial status only once

In reply to Greg Kroah-Hartman

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

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

From: Ping Cheng <[email protected]>

commit cae3031c691dff0be61a26bc64e31a6939010d5c upstream.

For consistency with how the shared has_mute_touch_switch is handled during registration, let's apply WRITE_ONCE to is_touch_on too.

Fixes ba16e5ffbaa1 ("HID: wacom: Advertise SW_MUTE_DEVICE capability prior to registration")
---
 drivers/hid/wacom_sys.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/hid/wacom_sys.c +1 -1
@@ -2387,7 +2387,7 @@ static void wacom_set_shared_values(stru
 		 * match historic default.
 		 */
 		if (wacom_wac->is_soft_touch_switch)
-			wacom_wac->shared->is_touch_on = true;
+			WRITE_ONCE(wacom_wac->shared->is_touch_on, true);
 	}
 
 	if (wacom_wac->features.device_type & WACOM_DEVICETYPE_TOUCH) {
author maintainer
#190 lore raw

PATCH 190/547 klist: avoid accesses after waking klist_remove()

In reply to Greg Kroah-Hartman

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

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

From: Karl Mehltretter <[email protected]>

commit 732e3e10234cbe302d0dcbaa98c91c66628209cb upstream.

klist_remove() waits until a node is unreferenced so that its caller can free the containing object. klist_release() currently publishes waiter->woken and wakes the waiter before its final accesses to the waiter and node. klist_remove() can then return, allowing its stack waiter and the containing object to be freed or reused while klist_release() is still running. In particular, bus_remove_driver() can free drv->p while __device_attach() walks the same bus klist with bus_for_each_drv().

On an arm64 Cortex-A72 system, an unpatched 7.2.0-rc3 kernel with CONFIG_PREEMPT_RT=y and CONFIG_KASAN=y reproduced the bug through the in-tree I2C/at24 path. KASAN reported a use-after-free in klist_dec_and_del() reached from klist_next()/bus_for_each_drv() while at24 was being unregistered.

Clear n_klist and take a task reference before publishing woken. Use release/acquire accesses for that publication and wake the referenced task. The task reference keeps the waiter task alive if it returns and exits before wake_up_process().

Fixes 8b0c250be489 ("[PATCH] add klist_node_attached() to determine if a node is on a list or not.")
Fixes 210272a28465 ("driver core: Remove completion from struct klist_node")
Assisted-by LLM
Cc Danilo Krummrich <[email protected]>
Cc Greg Kroah-Hartman <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc "Rafael J. Wysocki" <[email protected]>
---
 lib/klist.c |   16 ++++++++++++----
 1 file changed, 12 insertions(+), 4 deletions(-)
lib/klist.c +12 -4
@@ -36,6 +36,7 @@
 #include <linux/klist.h>
 #include <linux/export.h>
 #include <linux/sched.h>
+#include <linux/sched/task.h>
 
 /*
  * Use the lowest bit of n_klist to mark deleted nodes and exclude
@@ -187,18 +188,24 @@ static void klist_release(struct kref *k
 
 	WARN_ON(!knode_dead(n));
 	list_del(&n->n_node);
+	knode_set_klist(n, NULL);
 	spin_lock(&klist_remove_lock);
 	list_for_each_entry_safe(waiter, tmp, &klist_remove_waiters, list) {
+		struct task_struct *p;
+
 		if (waiter->node != n)
 			continue;
 
+		p = waiter->process;
+		get_task_struct(p);
 		list_del(&waiter->list);
-		waiter->woken = 1;
+		/* Publish only after the final waiter and n accesses */
+		smp_store_release(&waiter->woken, 1);
 		mb();
-		wake_up_process(waiter->process);
+		wake_up_process(p);
+		put_task_struct(p);
 	}
 	spin_unlock(&klist_remove_lock);
-	knode_set_klist(n, NULL);
 }
 
 static int klist_dec_and_del(struct klist_node *n)
@@ -250,7 +257,8 @@ void klist_remove(struct klist_node *n)
 
 	for (;;) {
 		set_current_state(TASK_UNINTERRUPTIBLE);
-		if (waiter.woken)
+		/* Pairs with the release store in klist_release() */
+		if (smp_load_acquire(&waiter.woken))
 			break;
 		schedule();
 	}
author maintainer
#191 lore raw

PATCH 191/547 objtool/rust: add one more `noreturn` Rust function for Rust 1.101.0

In reply to Greg Kroah-Hartman

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

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

From: Miguel Ojeda <[email protected]>

commit 6b704ec9007a3f23ec5ded8f320825ac444f307d upstream.

Starting with Rust 1.101.0 (expected 2026-12-24), objtool may report:

rust/kernel.o: warning: objtool: _R..._4core6result13unwrap_failed...() falls through to next function _R..._4core6result13unwrap_failed...()

(and others) due to calls to the noreturn symbol:

core::result::unwrap_failed::unwrap_failed_inner

Rust introduced this helper when making unwrap_failed generic [1]. The existing entry for unwrap_failed does not match the new helper.

Thus add the mangled one to the list so that objtool knows it is actually noreturn.

See commit 56d680dd23c3 ("objtool/rust: list noreturn Rust functions") for more details.

Cc [email protected] # Needed in 6.12.y and later (Rust is pinned in older LTSs).
Cc Josh Poimboeuf <[email protected]>
Cc Peter Zijlstra <[email protected]>
Assisted-by LLM
---
 tools/objtool/check.c |    1 +
 1 file changed, 1 insertion(+)
tools/objtool/check.c +1 -0
@@ -201,6 +201,7 @@ static bool is_rust_noreturn(const struc
 	       str_ends_with(func->name, "_4core6option13expect_failed")				||
 	       str_ends_with(func->name, "_4core6option13unwrap_failed")				||
 	       str_ends_with(func->name, "_4core6result13unwrap_failed")				||
+	       str_ends_with(func->name, "_4core6result13unwrap_failed19unwrap_failed_inner")		||
 	       str_ends_with(func->name, "_4core9panicking5panic")					||
 	       str_ends_with(func->name, "_4core9panicking9panic_fmt")					||
 	       str_ends_with(func->name, "_4core9panicking14panic_explicit")				||
author maintainer
#192 lore raw

PATCH 192/547 rust: bindings: fix `VM_MAYSHARE` blocklist entry

In reply to Greg Kroah-Hartman

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

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

From: Miguel Ojeda <[email protected]>

commit f9a6960c7b27c03becd50a2a7620273d80e4040d upstream.

Commit 2b6a3f061f11 ("mm: declare VMA flags by bit") added constant helpers for the VMA flags and blocklist entries to suppress their direct bindings. However, it listed VM_MAYEXEC twice and omitted VM_MAYSHARE.

Thus fix it.

---
 rust/bindgen_parameters |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
rust/bindgen_parameters +1 -1
@@ -50,7 +50,7 @@
 --blocklist-item VM_MAYREAD
 --blocklist-item VM_MAYWRITE
 --blocklist-item VM_MAYEXEC
---blocklist-item VM_MAYEXEC
+--blocklist-item VM_MAYSHARE
 --blocklist-item VM_PFNMAP
 --blocklist-item VM_IO
 --blocklist-item VM_DONTCOPY
author maintainer
#193 lore raw

PATCH 193/547 rust: bindings: fix VM_MAYSHARE value

In reply to Greg Kroah-Hartman

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

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

From: Lorenzo Stoakes <[email protected]>

commit 7b5ba47d845f35b04937748a191a1772ffc1f288 upstream.

Commit 2b6a3f061f11 ("mm: declare VMA flags by bit") added a number of overrides to the rust bindings helper as the change performed in the commit caused rust bindgen to not be able to automatically determine values of VMA flags.

However a typo was introduced leaving VM_MAYSHARE to be incorrectly interpreted as VM_MAYEXEC in rust code. This patch fixes the typo.

---
 rust/bindings/bindings_helper.h |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
rust/bindings/bindings_helper.h +1 -1
@@ -138,7 +138,7 @@ const vm_flags_t RUST_CONST_HELPER_VM_SH
 const vm_flags_t RUST_CONST_HELPER_VM_MAYREAD = VM_MAYREAD;
 const vm_flags_t RUST_CONST_HELPER_VM_MAYWRITE = VM_MAYWRITE;
 const vm_flags_t RUST_CONST_HELPER_VM_MAYEXEC = VM_MAYEXEC;
-const vm_flags_t RUST_CONST_HELPER_VM_MAYSHARE = VM_MAYEXEC;
+const vm_flags_t RUST_CONST_HELPER_VM_MAYSHARE = VM_MAYSHARE;
 const vm_flags_t RUST_CONST_HELPER_VM_PFNMAP = VM_PFNMAP;
 const vm_flags_t RUST_CONST_HELPER_VM_IO = VM_IO;
 const vm_flags_t RUST_CONST_HELPER_VM_DONTCOPY = VM_DONTCOPY;
author maintainer
#194 lore raw

PATCH 194/547 rust: bitmap: restrict bitmap length to at most i32::MAX

In reply to Greg Kroah-Hartman

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

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

From: Eliot Courtney <[email protected]>

commit 931790a91378f6513ba82730eb5607479c3184a0 upstream.

It is currently possible to construct a non-BitmapVec backed Bitmap using Bitmap::from_raw that is larger than i32::MAX, and it is not part of the unsafe requirements. Restricting all bitmaps (even non-BitmapVec backed ones) to a maximum size of i32::MAX simplifies a few things and matches BitmapVec::MAX_LEN. For example, copy_and_extend truncates len to u32, which is wrong for > u32::MAX size. __bitmap_set and __bitmap_clear need i32 for size and u32 for start - so they can't be run on a Bitmap with a > i32::MAX size. Rather than adding runtime checks to account for the case of a non BitmapVec backed Bitmap, just include that in the requirements for Bitmap.

Add that requirement to the unsafe requirements on Bitmap::from_raw and Bitmap::from_raw_mut, and to the invariants on Bitmap.

This also fixes u32 casts truncating in copy_and_extend, which could otherwise lead to OOB writes.

[ Added a few intra-doc links. Added backticks to C types. Capitalize
tagged comments. - Miguel ]

---
 rust/kernel/bitmap.rs |   70 +++++++++++++++++++++++++++++++++++---------------
 1 file changed, 49 insertions(+), 21 deletions(-)
rust/kernel/bitmap.rs +49 -21
@@ -17,24 +17,59 @@ use core::ptr::NonNull;
 /// # Invariants
 ///
 /// Must reference a `[c_ulong]` long enough to fit `data.len()` bits.
+/// Must not be longer than [`i32::MAX`] bits, so offsets and lengths used with
+/// [`Bitmap`] functions fit in the `int` and `unsigned int` arguments of the C bitmap API.
+/// This also matches [`BitmapVec::MAX_LEN`].
 #[cfg_attr(CONFIG_64BIT, repr(align(8)))]
 #[cfg_attr(not(CONFIG_64BIT), repr(align(4)))]
 pub struct Bitmap {
     data: [()],
 }
 
+macro_rules! bitmap_assert {
+    ($cond:expr, $($arg:tt)+) => {
+        #[cfg(CONFIG_RUST_BITMAP_HARDENED)]
+        assert!($cond, $($arg)*);
+    }
+}
+
+macro_rules! bitmap_assert_return {
+    ($cond:expr, $($arg:tt)+) => {
+        #[cfg(CONFIG_RUST_BITMAP_HARDENED)]
+        assert!($cond, $($arg)*);
+
+        #[cfg(not(CONFIG_RUST_BITMAP_HARDENED))]
+        if !($cond) {
+            pr_err!($($arg)*);
+            return
+        }
+    }
+}
+
 impl Bitmap {
     /// Borrows a C bitmap.
     ///
+    /// # Panics
+    ///
+    /// Panics if CONFIG_RUST_BITMAP_HARDENED is enabled and `nbits` exceeds [`i32::MAX`].
+    ///
     /// # Safety
     ///
     /// * `ptr` holds a non-null address of an initialized array of `unsigned long`
     ///   that is large enough to hold `nbits` bits.
+    /// * `nbits` must not exceed [`i32::MAX`].
     /// * the array must not be freed for the lifetime of this [`Bitmap`]
     /// * concurrent access only happens through atomic operations
     pub unsafe fn from_raw<'a>(ptr: *const usize, nbits: usize) -> &'a Bitmap {
+        bitmap_assert!(
+            nbits <= i32::MAX as usize,
+            "`nbits` must be <= {}, was {}",
+            i32::MAX,
+            nbits
+        );
         let data: *const [()] = core::ptr::slice_from_raw_parts(ptr.cast(), nbits);
         // INVARIANT: `data` references an initialized array that can hold `nbits` bits.
+        // INVARIANT: The caller guarantees that `nbits` does not exceed `i32::MAX`.
         // SAFETY:
         // The caller guarantees that `data` (derived from `ptr` and `nbits`)
         // points to a valid, initialized, and appropriately sized memory region
@@ -51,15 +86,27 @@ impl Bitmap {
 
     /// Borrows a C bitmap exclusively.
     ///
+    /// # Panics
+    ///
+    /// Panics if CONFIG_RUST_BITMAP_HARDENED is enabled and `nbits` exceeds [`i32::MAX`].
+    ///
     /// # Safety
     ///
     /// * `ptr` holds a non-null address of an initialized array of `unsigned long`
     ///   that is large enough to hold `nbits` bits.
+    /// * `nbits` must not exceed [`i32::MAX`].
     /// * the array must not be freed for the lifetime of this [`Bitmap`]
     /// * no concurrent access may happen.
     pub unsafe fn from_raw_mut<'a>(ptr: *mut usize, nbits: usize) -> &'a mut Bitmap {
+        bitmap_assert!(
+            nbits <= i32::MAX as usize,
+            "`nbits` must be <= {}, was {}",
+            i32::MAX,
+            nbits
+        );
         let data: *mut [()] = core::ptr::slice_from_raw_parts_mut(ptr.cast(), nbits);
         // INVARIANT: `data` references an initialized array that can hold `nbits` bits.
+        // INVARIANT: The caller guarantees that `nbits` does not exceed `i32::MAX`.
         // SAFETY:
         // The caller guarantees that `data` (derived from `ptr` and `nbits`)
         // points to a valid, initialized, and appropriately sized memory region
@@ -96,26 +143,6 @@ union BitmapRepr {
     ptr: NonNull<usize>,
 }
 
-macro_rules! bitmap_assert {
-    ($cond:expr, $($arg:tt)+) => {
-        #[cfg(CONFIG_RUST_BITMAP_HARDENED)]
-        assert!($cond, $($arg)*);
-    }
-}
-
-macro_rules! bitmap_assert_return {
-    ($cond:expr, $($arg:tt)+) => {
-        #[cfg(CONFIG_RUST_BITMAP_HARDENED)]
-        assert!($cond, $($arg)*);
-
-        #[cfg(not(CONFIG_RUST_BITMAP_HARDENED))]
-        if !($cond) {
-            pr_err!($($arg)*);
-            return
-        }
-    }
-}
-
 /// Represents an owned bitmap.
 ///
 /// Wraps underlying C bitmap API. See [`Bitmap`] for available
@@ -415,7 +442,8 @@ impl Bitmap {
     #[inline]
     pub fn copy_and_extend(&mut self, src: &Bitmap) {
         let len = core::cmp::min(src.len(), self.len());
-        // SAFETY: access to `self` and `src` is within bounds.
+        // SAFETY: Access to `self` and `src` is within bounds. Both lengths fit in `u32`
+        // because a `Bitmap` is at most `i32::MAX` bits, so the casts are lossless.
         unsafe {
             bindings::bitmap_copy_and_extend(
                 self.as_mut_ptr(),
author maintainer
#195 lore raw

PATCH 195/547 rust: block: fix `Send` bound for `GenDisk`

In reply to Greg Kroah-Hartman

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

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

From: Andreas Hindborg <[email protected]>

commit e502b667ee70a7fa2a578e7722672ecd4fe0eb81 upstream.

The Send implementation for GenDisk<T> was conditioned on T: Send. This constrains the wrong type. T is the Operations implementation, which is typically a zero-sized marker type that carries no data, so `T:
Send says nothing about whether the data a GenDisk` actually owns can be moved to another thread.

A GenDisk<T> owns the queue data T::QueueData (stored as the gendisk's queuedata and dropped when the GenDisk is dropped) and an Arc<TagSet<T>>. These are the values transferred when a GenDisk is sent across a thread boundary, so the Send bound must constrain exactly them. Bound T::QueueData: Send and Arc<TagSet<T>>: Send instead.

---
 rust/kernel/block/mq/gen_disk.rs |   10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
rust/kernel/block/mq/gen_disk.rs +8 -2
@@ -212,8 +212,14 @@ pub struct GenDisk<T: Operations> {
 }
 
 // SAFETY: `GenDisk` is an owned pointer to a `struct gendisk` and an `Arc` to a
-// `TagSet` It is safe to send this to other threads as long as T is Send.
-unsafe impl<T: Operations + Send> Send for GenDisk<T> {}
+// `TagSet`. It is safe to send this to other threads as long as these two are `Send`.
+unsafe impl<T> Send for GenDisk<T>
+where
+    T: Operations,
+    T::QueueData: Send,
+    Arc<TagSet<T>>: Send,
+{
+}
 
 impl<T: Operations> Drop for GenDisk<T> {
     fn drop(&mut self) {
author maintainer
#196 lore raw

PATCH 196/547 rust: block: require `Sync` for `Operations::QueueData`

In reply to Greg Kroah-Hartman

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

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

From: Andreas Hindborg <[email protected]>

commit 67b7a2728e4873e64405c5564fe50f7123012b71 upstream.

The queue data installed in a GenDisk is stored in the request queue and handed back to the driver as a shared borrow through the queue_rq and commit_rqs callbacks. Both callbacks obtain that borrow via ForeignOwnable::borrow and may execute concurrently on several CPUs, since the block layer runs one hardware queue per CPU. That means a shared reference to the same queue data can be live on multiple threads at once, which is only sound when the referent is Sync.

The initial GenDisk private data support omitted this bound, so a driver could install a non-Sync type as queue data and then access it concurrently from multiple CPUs without synchronization. Add a Sync bound to the QueueData associated type to rule that out.

---
 rust/kernel/block/mq/operations.rs |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
rust/kernel/block/mq/operations.rs +1 -1
@@ -30,7 +30,7 @@ type ForeignBorrowed<'a, T> = <T as Fore
 pub trait Operations: Sized {
     /// Data associated with the `struct request_queue` that is allocated for
     /// the `GenDisk` associated with this `Operations` implementation.
-    type QueueData: ForeignOwnable;
+    type QueueData: ForeignOwnable + Sync;
 
     /// Called by the kernel to queue a request with the driver. If `is_last` is
     /// `false`, the driver is allowed to defer committing the request.
author maintainer
#197 lore raw

PATCH 197/547 rust: bug: pass TAINT_WARN to warn_slowpath_fmt() on UML

In reply to Greg Kroah-Hartman

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

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

From: FUJITA Tomonori <[email protected]>

commit 951d09ca450ca76a695016ea76c3fa653bd20439 upstream.

On UML, warn_flags! calls warn_slowpath_fmt() directly. Its third argument is a taint number, but warn_on! passes its bug flags there.

As a result, add_taint() gets 2304 instead of 9 (TAINT_WARN). The warning is not recorded: /proc/sys/kernel/tainted stays 0 after warn_on! fires, where it should be 512. It also causes an out-of-bounds write in add_taint().

Pass TAINT_WARN directly, as C does on UML.

---
 rust/kernel/bug.rs |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
rust/kernel/bug.rs +2 -1
@@ -85,6 +85,7 @@ macro_rules! warn_flags {
     ($file:expr, $flags:expr) => {
         if false {
             _ = $file;
+            _ = $flags;
         }
 
         // SAFETY: It is always safe to call `warn_slowpath_fmt()`
@@ -93,7 +94,7 @@ macro_rules! warn_flags {
             $crate::bindings::warn_slowpath_fmt(
                 $crate::str::CStrExt::as_char_ptr($crate::c_str!(::core::file!())),
                 line!() as $crate::ffi::c_int,
-                $flags as $crate::ffi::c_uint,
+                $crate::bindings::TAINT_WARN,
                 ::core::ptr::null(),
             );
         }
author maintainer
#198 lore raw

PATCH 198/547 rust: bug: update the SAFETY comment for warn_slowpath_fmt() on UML

In reply to Greg Kroah-Hartman

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

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

From: FUJITA Tomonori <[email protected]>

commit 5c94956f2bfb87025c1eaded6c51d5841d38d333 upstream.

The SAFETY comment says that it is always safe to call warn_slowpath_fmt() with a valid null-terminated string. This is not true. The taint argument must also be a valid taint number. Commit 951d09ca450c ("rust: bug: pass TAINT_WARN to warn_slowpath_fmt() on UML") fixed a bug where it was not.

List each condition that the call meets: the file name, the taint number, and the null fmt.

---
 rust/kernel/bug.rs |    6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
rust/kernel/bug.rs +4 -2
@@ -88,8 +88,10 @@ macro_rules! warn_flags {
             _ = $flags;
         }
 
-        // SAFETY: It is always safe to call `warn_slowpath_fmt()`
-        // with a valid null-terminated string.
+        // SAFETY:
+        // - The file name is a null-terminated string with `'static` lifetime.
+        // - `TAINT_WARN` is a valid taint number.
+        // - `fmt` can be NULL, and NULL is passed.
         unsafe {
             $crate::bindings::warn_slowpath_fmt(
                 $crate::str::CStrExt::as_char_ptr($crate::c_str!(::core::file!())),
author maintainer
#199 lore raw

PATCH 199/547 rust: configfs: fix data offset calculation for subsystem callbacks

In reply to Greg Kroah-Hartman

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

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

From: Andreas Hindborg <[email protected]>

commit e84c9b64df615e658e47561b835c1364dc48f0c0 upstream.

get_group_data() chooses between Group::<Parent>::container_of() and Subsystem::<Parent>::container_of() based on whether this represents the root group of a configfs subsystem. It detects this by checking (*this).cg_subsys.is_null(), but link_group() in fs/configfs/dir.c unconditionally sets cg_subsys for every config_group attached anywhere in a registered subsystem, including the subsystem's own su_group. The only config_group with a NULL cg_subsys is the configfs root, on which userspace cannot trigger callbacks. The check is therefore always false at runtime, and the Subsystem branch is dead. Subsystem-level callbacks reach the Group branch and may read data at the wrong offset.

Thus change the is_root check to correctly identify whether a group is a root group by comparing this to subsys.su_group.

Fixes 446cafc295bf ("rust: configfs: introduce rust support for configfs")
[ Andreas: Fix clippy warning on 1.85.0 by moving safety comment. ]
---
 rust/kernel/configfs.rs |   43 ++++++++++++++++++++++++++++---------------
 1 file changed, 28 insertions(+), 15 deletions(-)
rust/kernel/configfs.rs +28 -15
@@ -297,26 +297,39 @@ unsafe impl<Data> HasGroup<Data> for Gro
 ///
 /// `this` must be a valid pointer.
 ///
-/// If `this` does not represent the root group of a configfs subsystem,
-/// `this` must be a pointer to a `bindings::config_group` embedded in a
-/// `Group<Parent>`.
+/// If `this` is the `su_group` field of a `bindings::configfs_subsystem`, that
+/// `configfs_subsystem` must be embedded in a `Subsystem<Parent>`.
 ///
-/// Otherwise, `this` must be a pointer to a `bindings::config_group` that
-/// is embedded in a `bindings::configfs_subsystem` that is embedded in a
-/// `Subsystem<Parent>`.
+/// Otherwise, `this` must be a pointer to a `bindings::config_group` embedded
+/// in a `Group<Parent>`.
 unsafe fn get_group_data<'a, Parent>(this: *mut bindings::config_group) -> &'a Parent {
     // SAFETY: `this` is a valid pointer.
-    let is_root = unsafe { (*this).cg_subsys.is_null() };
+    let subsys = unsafe { (*this).cg_subsys };
 
-    if !is_root {
-        // SAFETY: By C API contact,`this` was returned from a call to
-        // `make_group`. The pointer is known to be embedded within a
-        // `Group<Parent>`.
-        unsafe { &(*Group::<Parent>::container_of(this)).data }
-    } else {
-        // SAFETY: By C API contract, `this` is a pointer to the
-        // `bindings::config_group` field within a `Subsystem<Parent>`.
+    // `link_group()` in `fs/configfs/dir.c` assigns `cg_subsys` for every
+    // `config_group` attached anywhere in a registered subsystem, including
+    // the subsystem's own `su_group` (which gets a pointer to itself). The
+    // only `config_group` with a NULL `cg_subsys` is the configfs root, and
+    // userspace cannot trigger callbacks on it. The group is therefore the
+    // subsystem's `su_group` iff it equals `&cg_subsys->su_group`.
+    let is_root = !subsys.is_null()
+        && core::ptr::eq(
+            this.cast_const(),
+            // SAFETY: For every `config_group` the configfs core dispatches a
+            // callback on, `cg_subsys` was set by `link_group()` at registration time
+            // and points to a valid `configfs_subsystem` that outlives the callback.
+            unsafe { &raw const (*subsys).su_group },
+        );
+
+    if is_root {
+        // SAFETY: By the above, `this` is the `su_group` field of a
+        // `configfs_subsystem` that, by function safety requirements, is
+        // embedded in a `Subsystem<Parent>`.
         unsafe { &(*Subsystem::container_of(this)).data }
+    } else {
+        // SAFETY: By function safety requirements, `this` is a
+        // `config_group` embedded in a `Group<Parent>`.
+        unsafe { &(*Group::<Parent>::container_of(this)).data }
     }
 }
 
author maintainer
#200 lore raw

PATCH 200/547 rust: cpufreq: reject NULL from cpufreq_cpu_get()

In reply to Greg Kroah-Hartman

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

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

From: Mehmet Koseoglu <[email protected]>

commit 02c5d7bfa8724789f6620f7787532666edc891a1 upstream.

cpufreq_cpu_get() returns either a referenced policy or NULL. PolicyCpu::from_cpu() passed its return value to from_err_ptr(), which rejects ERR_PTR values but accepts NULL.

If the lookup fails, Policy::from_raw_mut() therefore constructs a mutable reference from NULL. Dropping the resulting PolicyCpu then passes the invalid pointer to cpufreq_cpu_put(), causing an oops in kobject_put().

Reject NULL with NonNull before constructing the Policy reference. Return ENODEV instead.

A KUnit negative-control run reproduced the oops with the original conversion. The same test passed with this change. The reproducer is available on request.

Fixes 6ebdd7c93177 ("rust: cpufreq: Extend abstractions for policy and driver ops")
Assisted-by LLM
---
 rust/kernel/cpufreq.rs |   22 ++++++++++++++++------
 1 file changed, 16 insertions(+), 6 deletions(-)
rust/kernel/cpufreq.rs +16 -6
@@ -14,7 +14,13 @@ use crate::{
     cpumask,
     device::{Bound, Device},
     devres,
-    error::{code::*, from_err_ptr, from_result, to_result, Result, VTABLE_DEFAULT_ERROR},
+    error::{
+        code::*,
+        from_result,
+        to_result,
+        Result,
+        VTABLE_DEFAULT_ERROR, //
+    },
     ffi::{c_char, c_ulong},
     prelude::*,
     types::ForeignOwnable,
@@ -29,7 +35,10 @@ use core::{
     marker::PhantomData,
     ops::{Deref, DerefMut},
     pin::Pin,
-    ptr,
+    ptr::{
+        self,
+        NonNull, //
+    },
 };
 
 use macros::vtable;
@@ -687,12 +696,13 @@ struct PolicyCpu<'a>(&'a mut Policy);
 impl<'a> PolicyCpu<'a> {
     fn from_cpu(cpu: CpuId) -> Result<Self> {
         // SAFETY: It is safe to call `cpufreq_cpu_get` for any valid CPU.
-        let ptr = from_err_ptr(unsafe { bindings::cpufreq_cpu_get(u32::from(cpu)) })?;
+        let ptr =
+            NonNull::new(unsafe { bindings::cpufreq_cpu_get(u32::from(cpu)) }).ok_or(ENODEV)?;
 
         Ok(Self(
-            // SAFETY: The `ptr` is guaranteed to be valid and remains valid for the lifetime of
-            // the returned reference.
-            unsafe { Policy::from_raw_mut(ptr) },
+            // SAFETY: `ptr` is non-NULL and `cpufreq_cpu_get()` took a reference on it, so it is
+            // valid for writing and remains valid for the lifetime of the returned reference.
+            unsafe { Policy::from_raw_mut(ptr.as_ptr()) },
         ))
     }
 }
author maintainer
#201 lore raw

PATCH 201/547 rust: fwctl: declare cfi_encoding for fwctl_rpc_scope

In reply to Greg Kroah-Hartman

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

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

From: Alice Ryhl <[email protected]>

commit bc6f2a284c63313e789d8cd294531e1cc2dc8c99 upstream.

Currently, VTable::fw_rpc_callback() takes scope as a u32, whereas C calls fwctl_ops::fw_rpc with enum fwctl_rpc_scope. With kCFI enabled, enum types are encoded distinctly from integers, causing every fw_rpc indirect call into a Rust fwctl driver to trip a CFI failure. Thus, generate fwctl_rpc_scope as a newtype with a cfi_encoding attribute and use it in fw_rpc_callback().

---
 rust/bindgen_parameters |    2 ++
 rust/kernel/fwctl.rs    |   12 ++++++------
 2 files changed, 8 insertions(+), 6 deletions(-)
rust/bindgen_parameters +2 -0
@@ -27,6 +27,8 @@
 --opaque-type spinlock
 
 # enums that appear in indirect function calls should specify a cfi type
+--newtype-enum fwctl_rpc_scope
+--with-attribute-custom-enum=fwctl_rpc_scope='#[cfi_encoding="15fwctl_rpc_scope"]'
 --newtype-enum lru_status
 --with-attribute-custom-enum=lru_status='#[cfi_encoding="10lru_status"]'
 
rust/kernel/fwctl.rs +6 -6
@@ -53,13 +53,13 @@ pub enum DeviceType {
 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
 pub enum RpcScope {
     /// Read/write access to device configuration.
-    Configuration = bindings::fwctl_rpc_scope_FWCTL_RPC_CONFIGURATION,
+    Configuration = bindings::fwctl_rpc_scope::FWCTL_RPC_CONFIGURATION.0,
     /// Read-only access to debug information.
-    DebugReadOnly = bindings::fwctl_rpc_scope_FWCTL_RPC_DEBUG_READ_ONLY,
+    DebugReadOnly = bindings::fwctl_rpc_scope::FWCTL_RPC_DEBUG_READ_ONLY.0,
     /// Write access to lockdown-compatible debug information.
-    DebugWrite = bindings::fwctl_rpc_scope_FWCTL_RPC_DEBUG_WRITE,
+    DebugWrite = bindings::fwctl_rpc_scope::FWCTL_RPC_DEBUG_WRITE.0,
     /// Full read/write access to all debug information (requires `CAP_SYS_RAWIO`).
-    DebugWriteFull = bindings::fwctl_rpc_scope_FWCTL_RPC_DEBUG_WRITE_FULL,
+    DebugWriteFull = bindings::fwctl_rpc_scope::FWCTL_RPC_DEBUG_WRITE_FULL.0,
 }
 
 impl TryFrom<u32> for RpcScope {
@@ -539,12 +539,12 @@ impl<T: Operations> VTable<T> {
     /// - `out_len` must be valid for reading and writing an initialised `usize`.
     unsafe extern "C" fn fw_rpc_callback(
         uctx: *mut bindings::fwctl_uctx,
-        scope: u32,
+        scope: bindings::fwctl_rpc_scope,
         rpc_in: *mut ffi::c_void,
         in_len: usize,
         out_len: *mut usize,
     ) -> *mut ffi::c_void {
-        let scope = match RpcScope::try_from(scope) {
+        let scope = match RpcScope::try_from(scope.0) {
             Ok(s) => s,
             Err(e) => return Error::to_ptr(e),
         };
author maintainer
#202 lore raw

PATCH 202/547 rust: module_param: Fix potentially incorrect access of `SetOnce<T>`

In reply to Greg Kroah-Hartman

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

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

From: Priya Bala Govindasamy <[email protected]>

commit 2e8bac09ed6d7aa2ad4e8a9a6cba67e5835865c2 upstream.

The set_param function casts kernel_param.arg to *const SetOnce<T> But the Rust module macro in rust/macros/module.rs initializes arg with #param_name.as_void_ptr(), and #param_name is a ModuleParamAccess<T>, not a SetOnce<T>.

ModuleParamAccess<T> has default Rust layout but set_param accesses its first field SetOnce<T> assuming it to be at offset 0. This is not guaranteed by Rust and could cause type confusion leading to data corruption.

Fix this by casting kernel_param.arg to ModuleParamAccess<T> and then accessing the value: SetOnce<T> field.

Fixes 0b08fc292842 ("rust: introduce module_param module")
Assisted-by LLM
---
 rust/kernel/module_param.rs |    9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
rust/kernel/module_param.rs +7 -2
@@ -74,8 +74,13 @@ where
     crate::error::from_result(|| {
         let new_value = T::try_from_param_arg(arg)?;
 
-        // SAFETY: By function safety requirements, this access is safe.
-        let container = unsafe { &*((*param).__bindgen_anon_1.arg.cast::<SetOnce<T>>()) };
+        // SAFETY: By function safety requirements, `param` is valid for read.
+        let arg = unsafe { (*param).__bindgen_anon_1.arg };
+        let param_access_ptr = arg.cast::<ModuleParamAccess<T>>();
+        // SAFETY: The `arg` field is initialized with a pointer to a `static ModuleAccessParam` by
+        // the rust module macro. Thus, the pointer is valid for use as a reference.
+        let param_access = unsafe { &*(param_access_ptr) };
+        let container = &param_access.value;
 
         container
             .populate(new_value)
author maintainer
#203 lore raw

PATCH 203/547 rust: rcpufreq_dt: add module alias

In reply to Greg Kroah-Hartman

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

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

From: Frank Zhang <[email protected]>

commit 53732733c7af437b0ed710a1df91a67a0d3dfc07 upstream.

Add the missing platform:cpufreq-dt module alias so that the driver can be automatically loaded when the platform device is registered.

Fixes 06149d8f2216 ("cpufreq: Add Rust-based cpufreq-dt driver")
---
 drivers/cpufreq/rcpufreq_dt.rs |    1 +
 1 file changed, 1 insertion(+)
drivers/cpufreq/rcpufreq_dt.rs +1 -0
@@ -225,4 +225,5 @@ module_platform_driver! {
     authors: ["Viresh Kumar <[email protected]>"],
     description: "Generic CPUFreq DT driver",
     license: "GPL v2",
+    alias: ["platform:cpufreq-dt"],
 }
author maintainer
#204 lore raw

PATCH 204/547 accel/amdxdna: clear the mailbox channel pointer when starting it fails

In reply to Greg Kroah-Hartman

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

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

From: Eva Crystal <[email protected]>

commit 2117e3d96a4fd1ee13fa28b31494ff5f5db6ccf4 upstream.

aie2_create_context() allocates a mailbox channel, starts it, and on a failed start frees it again:

	hwctx->priv->mbox_chann = xdna_mailbox_alloc_channel(ndev->mbox);
	...
	ret = xdna_mailbox_start_channel(hwctx->priv->mbox_chann, ...);
	if (ret)
		goto free_channel;
	...
free_channel:
	xdna_mailbox_free_channel(hwctx->priv->mbox_chann);

hwctx->priv->mbox_chann keeps pointing at the freed channel. That pointer is the driver's own test for whether a hardware context has a usable channel: aie2_destroy_context() returns early on NULL, aie2_sched_job_run() refuses to run a job on NULL, and the message helpers return -ENODEV on NULL. A stale pointer passes all of them.

It matters on the restart path. aie2_hwctx_restart() calls aie2_create_context() again on a hardware context that is already live, after aie2_hwctx_stop() has torn its channel down, and the context survives a failure there: aie2_sched_job_timedout() discards the return value entirely, and aie2_hwctx_resume() only propagates it. What is left is a live hardware context holding a freed channel, and every later user of it takes the non-NULL branch:

- the next job submitted reaches xdna_mailbox_send_msg() on the freed channel, via the !mbox_chann guard in aie2_sched_job_run(),
- a second command timeout reaches aie2_hwctx_stop() ->

    aie2_destroy_context(),
  - closing the device reaches aie2_hwctx_fini() ->
    aie2_release_resource() -> xrs_release_resource() ->
    aie2_xrs_unload() -> aie2_destroy_context(),

and aie2_destroy_context() then calls xdna_mailbox_stop_channel() followed by xdna_mailbox_free_channel() on memory that was already
freed: a use-after-free, and a second free of the same channel.

The AIE4 management channel already does this correctly - aie4_mailbox_start() clears ndev->aie.mgmt_chann right after freeing it. Do the same here.

The create path itself is not affected: when aie2_xrs_load() fails, xrs_allocate_resource() removes the solver node without calling ->unload, and aie2_hwctx_init() frees hwctx->priv, so the stale pointer never outlives the structure holding it.

Starting a channel can fail today without this patch: the ring buffer sizes firmware reports are rejected unless both are powers of two, and request_irq() can fail.

---
 drivers/accel/amdxdna/aie2_message.c | 1 +
 1 file changed, 1 insertion(+)
drivers/accel/amdxdna/aie2_message.c +1 -0
index b4c49259a1a2..f658760c3d48 100644
@@ -277,6 +277,7 @@ int aie2_create_context(struct amdxdna_dev_hdl *ndev, struct amdxdna_hwctx *hwct
 
 free_channel:
 	xdna_mailbox_free_channel(hwctx->priv->mbox_chann);
+	hwctx->priv->mbox_chann = NULL;
 del_ctx_req:
 	aie2_destroy_context_req(ndev, hwctx->fw_ctx_id);
 	return ret;
Signature · 1 line
2.56.0
author maintainer
#205 lore raw

PATCH 205/547 ALSA: control: Fix UAF in snd_ctl_elem_add() on card disconnect

In reply to Greg Kroah-Hartman

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

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

From: Takashi Iwai <[email protected]>

commit d4febca239be3c91498762dd0535a87d4af1eabc upstream.

A use-after-free can be triggered via SNDRV_CTL_IOCTL_ELEM_ADD when a USB audio card is disconnected while an ELEM_ADD ioctl is in flight.

The reproducer parks the ioctl thread inside copy_from_user() using userfaultfd, then tears down the USB device. Unlike every other ALSA control _user handler (ELEM_INFO, ELEM_READ, ELEM_WRITE, TLV_*), snd_ctl_elem_add_user() never calls snd_power_ref_and_wait(), so the parked thread holds no power reference. snd_card_disconnect() therefore cannot observe it via snd_power_sync_ref() and proceeds unimpeded:

1. card->shutdown is set to 1
2. device_del(&card->card_dev) drops the kobject reference on the

     parent USB interface device (card->dev = &intf->dev)

3. The USB core drops its own reference and calls device_release(), freeing the struct usb_interface, including the embedded struct device that card->dev points to

When the userfaultfd is resolved and the thread resumes, snd_ctl_elem_add() acquires controls_rwsem without checking card->shutdown and calls __snd_ctl_add_replace(). Because the reproducer pre-registered the same control, the CTL_ADD_EXCLUSIVE path calls dev_err(card->dev, ...) on the freed USB interface:

  KASAN: slab-use-after-free Read in __dev_printk

Add a card->shutdown guard immediately after acquiring controls_rwsem in snd_ctl_elem_add(). At that point card->shutdown is guaranteed to be stable: snd_card_disconnect() sets it before freeing the parent device, and it never transitions back to 0. A thread that acquired the lock before disconnect sees shutdown=0 and holds the write lock through the rest of the operation, preventing concurrent disconnect from proceeding past its own controls_rwsem-less shutdown=1 store (which happened earlier, outside the lock) from racing with dev_err().

---
 sound/core/control.c |    2 ++
 1 file changed, 2 insertions(+)
sound/core/control.c +2 -0
@@ -1802,6 +1802,8 @@ static int snd_ctl_elem_add(struct snd_c
 	alloc_size = compute_user_elem_size(private_size, count);
 
 	guard(rwsem_write)(&card->controls_rwsem);
+	if (card->shutdown)
+		return -ENODEV;
 	if (check_user_elem_overflow(card, alloc_size))
 		return -ENOMEM;
 
author maintainer
#206 lore raw

PATCH 206/547 ALSA: emux: Fix UAF of soundfont zones at note-on

In reply to Greg Kroah-Hartman

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

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

From: Takashi Iwai <[email protected]>

commit 34e3e04b8a1731a773797542f0781e99ce7cd755 upstream.

snd_emux_note_on() looks up the matching zones via snd_soundfont_search_zone(), which takes sflist->lock only during the lookup and returns the raw zone pointers after releasing it. The caller then stores them in vp->zone without any protection. Meanwhile, a concurrent SNDRV_EMUX_IOCTL_REMOVE_LAST_SAMPLES ioctl may unlink and free those zones in snd_soundfont_remove_unlocked(); this leads to a use-after-free in snd_emux_note_on(), and later at accessing the cached vp->zone, e.g. in snd_emux_send_effect().

Fix it by holding sflist->lock in snd_emux_note_on() over the whole zone lookup and voice setup, and let snd_soundfont_search_zone() require the caller to hold the lock, instead. snd_soundfont_lock_preset() takes sflist->lock for setting presets_locked, so the removal path now syncs with the note-on finish.

---
 sound/synth/emux/emux_synth.c |    3 +++
 sound/synth/emux/soundfont.c  |    9 ++++++---
 2 files changed, 9 insertions(+), 3 deletions(-)
sound/synth/emux/emux_synth.c +3 -0
@@ -60,6 +60,9 @@ snd_emux_note_on(void *p, int note, int
 		return;
 
 	key = note; /* remember the original note */
+
+	/* hold sflist->lock for protecting against concurrent free */
+	guard(spinlock_irqsave)(&emu->sflist->lock);
 	nvoices = get_zone(emu, port, &note, vel, chan, table);
 	if (! nvoices)
 		return;
sound/synth/emux/soundfont.c +6 -3
@@ -1225,6 +1225,9 @@ delete_preset(struct snd_sf_list *sflist
  * The found zones are stored on 'table' array.  max_layers defines
  * the maximum number of elements in this array.
  * This function returns the number of found zones.  0 if not found.
+ *
+ * The caller must hold sflist->lock, and keep holding it as long as
+ * the returned zones are accessed.
  */
 int
 snd_soundfont_search_zone(struct snd_sf_list *sflist, int *notep, int vel,
@@ -1234,11 +1237,11 @@ snd_soundfont_search_zone(struct snd_sf_
 {
 	int nvoices;
 
-	/* this function is supposed to be called atomically,
-	 * so we check the lock.  if it's busy, just returns 0 to
+	lockdep_assert_held(&sflist->lock);
+
+	/* if the presets are being modified, just returns 0 to
 	 * tell the caller the busy state
 	 */
-	guard(spinlock_irqsave)(&sflist->lock);
 	if (sflist->presets_locked)
 		return 0;
 	nvoices = search_zones(sflist, notep, vel, preset, bank,
author maintainer
#207 lore raw

PATCH 207/547 ALSA: pcmtest: handle multiple wraps in random capture fill

In reply to Greg Kroah-Hartman

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

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

From: Sung Byeongchan <[email protected]>

commit 6541871e8e63e721733cd120af4d9cd22c5ef62f upstream.

The random capture helpers assume that the data generated for one timer tick wraps the DMA ring at most once. However, b_rw describes 200 ms of audio because the timer runs at 5 Hz, so it can be several times larger than a small ring.

For 48 kHz, S16_LE, four-channel capture with a 512-frame buffer, the DMA ring is 4096 bytes while one tick generates 76800 bytes. After filling the 4096-byte tail, the existing code issues a second 72704-byte write from the ring base, writing 68608 bytes beyond the ring. Both interleaved and non-interleaved capture are affected.

KASAN reports the first write into the adjacent free page as a use-after-free in the random-byte generator. The underlying defect is an out-of-bounds write from the live DMA ring, not a stale DMA allocation.

Split each random write repeatedly at the interleaved ring or per-channel block boundary. Keep the hardware-pointer update exactly once after the complete logical write.

The issue reproduced on three of three clean boots. With this change, the same vulnerable geometry completed six times without a sanitizer finding. Boundary, pattern-fill, no-timer, open/close, and module-reload controls also completed normally.

snd-pcmtest is a test driver, and selecting random fill requires an administrator-controlled module parameter. The written values come from the kernel random generator; no privilege escalation or attacker-controlled write primitive was demonstrated.

Fixes 315a3d57c64c ("ALSA: Implement the new Virtual PCM Test Driver")
Assisted-by OpenAI Codex
---
 sound/drivers/pcmtest.c |   42 +++++++++++++++++++-----------------------
 1 file changed, 19 insertions(+), 23 deletions(-)
sound/drivers/pcmtest.c +19 -23
@@ -280,39 +280,35 @@ static void fill_block_pattern(struct pc
 		fill_block_pattern_n(v_iter, runtime);
 }
 
+static void fill_random_block(char *buf, size_t buf_size, size_t pos,
+			      size_t count)
+{
+	while (count) {
+		size_t chunk = min(count, buf_size - pos);
+
+		get_random_bytes(buf + pos, chunk);
+		count -= chunk;
+		pos = 0;
+	}
+}
+
 static void fill_block_rand_n(struct pcmtst_buf_iter *v_iter, struct snd_pcm_runtime *runtime)
 {
 	unsigned int channels = runtime->channels;
-	// Remaining space in all channel buffers
-	size_t bytes_remain = runtime->dma_bytes - v_iter->buf_pos;
+	size_t pos = v_iter->buf_pos / channels;
 	unsigned int i;
 
-	for (i = 0; i < channels; i++) {
-		if (v_iter->b_rw <= bytes_remain) {
-			//b_rw - count of bytes must be written for all channels at each timer tick
-			get_random_bytes(runtime->dma_area + buf_pos_n(v_iter, channels, i),
-					 v_iter->b_rw / channels);
-		} else {
-			// Write to the end of buffer and start from the beginning of it
-			get_random_bytes(runtime->dma_area + buf_pos_n(v_iter, channels, i),
-					 bytes_remain / channels);
-			get_random_bytes(runtime->dma_area + v_iter->chan_block * i,
-					 (v_iter->b_rw - bytes_remain) / channels);
-		}
-	}
+	for (i = 0; i < channels; i++)
+		fill_random_block(runtime->dma_area + v_iter->chan_block * i,
+				  v_iter->chan_block, pos,
+				  v_iter->b_rw / channels);
 	inc_buf_pos(v_iter, v_iter->b_rw, runtime->dma_bytes);
 }
 
 static void fill_block_rand_i(struct pcmtst_buf_iter *v_iter, struct snd_pcm_runtime *runtime)
 {
-	size_t in_cur_block = runtime->dma_bytes - v_iter->buf_pos;
-
-	if (v_iter->b_rw <= in_cur_block) {
-		get_random_bytes(&runtime->dma_area[v_iter->buf_pos], v_iter->b_rw);
-	} else {
-		get_random_bytes(&runtime->dma_area[v_iter->buf_pos], in_cur_block);
-		get_random_bytes(runtime->dma_area, v_iter->b_rw - in_cur_block);
-	}
+	fill_random_block(runtime->dma_area, runtime->dma_bytes,
+			  v_iter->buf_pos, v_iter->b_rw);
 	inc_buf_pos(v_iter, v_iter->b_rw, runtime->dma_bytes);
 }
 
author maintainer
#208 lore raw

PATCH 208/547 ASoC: amd: ps: fix snd_acp63_remove() teardown ordering

In reply to Greg Kroah-Hartman

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

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

From: Fan Wu <[email protected]>

commit c53791d673ed4da6759d276078627ec4d0c6536b upstream.

The ACP IRQ handlers dereference the SoundWire, SoundWire DMA, and PDM child platform devices, but snd_acp63_remove() unregisters them while the interrupt is still held by devres, which frees it only after remove returns. An interrupt in this window is a use-after-free.

Mask the ACP interrupt sources and call devm_free_irq() before the first child device is unregistered. The masking goes through the new acp_hw_ops->disable_interrupts callback, keeping the remove path platform-agnostic. The interrupt line is shared, and acp_hw_deinit() clears the sources only after the children are gone, which would leave the line raised with no handler left to ack it. The window predates the tagged refactor, which only reshaped the dereferences.

devm_free_irq() waits for in-flight handlers, but not for work the hardirq has already queued: acp63_irq_handler() schedules amd_sdw_irq_thread on the SoundWire manager. Draining that work in the manager's remove path is a soundwire-side change and follows separately.

This issue was found by an in-house static analysis tool.

Fixes eaf825037d6d ("ASoC: amd: ps: refactor acp child platform device creation code")
---
 sound/soc/amd/ps/acp63.h     |    8 ++++++++
 sound/soc/amd/ps/pci-ps.c    |    2 ++
 sound/soc/amd/ps/ps-common.c |    2 ++
 3 files changed, 12 insertions(+)
sound/soc/amd/ps/acp63.h +8 -0
@@ -294,6 +294,7 @@ struct acp63_dev_data;
  * struct acp_hw_ops - ACP PCI driver platform specific ops
  * @acp_init: ACP initialization
  * @acp_deinit: ACP de-initialization
+ * @disable_interrupts: disable ACP interrupt sources
  * @acp_get_config: function to read the acp pin configuration
  * @acp_sdw_dma_irq_thread: ACP SoundWire DMA interrupt thread
  * acp_suspend: ACP system level suspend callback
@@ -304,6 +305,7 @@ struct acp63_dev_data;
 struct acp_hw_ops {
 	int (*acp_init)(void __iomem *acp_base, struct device *dev);
 	int (*acp_deinit)(void __iomem *acp_base, struct device *dev);
+	void (*disable_interrupts)(void __iomem *acp_base);
 	void (*acp_get_config)(struct pci_dev *pci, struct acp63_dev_data *acp_data);
 	void (*acp_sdw_dma_irq_thread)(struct acp63_dev_data *acp_data);
 	int (*acp_suspend)(struct device *dev);
@@ -397,6 +399,12 @@ static inline int acp_hw_deinit(struct a
 	return -EOPNOTSUPP;
 }
 
+static inline void acp_hw_disable_interrupts(struct acp63_dev_data *adata)
+{
+	if (adata && adata->hw_ops && adata->hw_ops->disable_interrupts)
+		ACP_HW_OPS(adata, disable_interrupts)(adata->acp63_base);
+}
+
 static inline void acp_hw_get_config(struct pci_dev *pci, struct acp63_dev_data *adata)
 {
 	if (adata && adata->hw_ops && adata->hw_ops->acp_get_config)
sound/soc/amd/ps/pci-ps.c +2 -0
@@ -738,6 +738,8 @@ static void snd_acp63_remove(struct pci_
 	int ret;
 
 	adata = pci_get_drvdata(pci);
+	acp_hw_disable_interrupts(adata);
+	devm_free_irq(&pci->dev, pci->irq, adata);
 	if (adata->sdw) {
 		amd_sdw_exit(adata);
 		platform_device_unregister(adata->sdw_dma_dev);
sound/soc/amd/ps/ps-common.c +2 -0
@@ -248,6 +248,7 @@ void acp63_hw_init_ops(struct acp_hw_ops
 {
 	hw_ops->acp_init = acp63_init;
 	hw_ops->acp_deinit = acp63_deinit;
+	hw_ops->disable_interrupts = acp63_disable_interrupts;
 	hw_ops->acp_get_config = acp63_get_config;
 	hw_ops->acp_sdw_dma_irq_thread = acp63_sdw_dma_irq_thread;
 	hw_ops->acp_suspend = snd_acp63_suspend;
@@ -484,6 +485,7 @@ void acp70_hw_init_ops(struct acp_hw_ops
 {
 	hw_ops->acp_init = acp70_init;
 	hw_ops->acp_deinit = acp70_deinit;
+	hw_ops->disable_interrupts = acp70_disable_interrupts;
 	hw_ops->acp_get_config = acp70_get_config;
 	hw_ops->acp_sdw_dma_irq_thread = acp70_sdw_dma_irq_thread;
 	hw_ops->acp_suspend = snd_acp70_suspend;
author maintainer
#209 lore raw

PATCH 209/547 Bluetooth: hci_vhci: Pin module for debugfs file operations

In reply to Greg Kroah-Hartman

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

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

From: Bui Viet Dung <[email protected]>

commit 645ee6b176c958579cff1c783413d5cff65c8197 upstream.

An open debugfs file retains its file_operations pointer in the debugfs proxy state. However, force_suspend_fops, force_wakeup_fops, aosp_capable_fops, and force_devcoredump_fops have no .owner set to THIS_MODULE. As a result, full_proxy_open_regular() calls fops_get() which succeeds without taking a reference to the hci_vhci module.

When userspace opens any of these debugfs files and later closes the /dev/vhci file descriptor (triggering vhci_release() and debugfs file removal), the open debugfs file descriptor remains valid in userspace. Because the module refcount was not incremented, the hci_vhci module can be unloaded via delete_module (rmmod hci_vhci).

When the userspace process subsequently closes the debugfs file descriptor, full_proxy_release() accesses the already unmapped file_operations structure, resulting in a kernel page fault / oops:

  BUG: unable to handle page fault for address: fffffbfff846f18b
  #PF: supervisor read access in kernel mode
  #PF: error_code(0x0000) - not-present page
  Oops: Oops: 0000 [#1] SMP KASAN NOPTI
  RIP: 0010:full_proxy_release+0x8e/0x140
  Call Trace:
   <TASK>
   __fput+0x39f/0xa60
   fput_close_sync+0xff/0x200
   __x64_sys_close+0x8c/0xf0
   do_syscall_64+0xc3/0x590
   entry_SYSCALL_64_after_hwframe+0x76/0x7e
   </TASK>
  Modules linked in: ... [last unloaded: hci_vhci(E)]

The issue was discovered via manual code audit of drivers/bluetooth/hci_vhci.c and verified on a Linux 7.3-rc6 test VM with CONFIG_BT_VHCI=m by keeping a debugfs file open across controller teardown and module unload.

Set .owner = THIS_MODULE on all four file_operations structures so that debugfs pins the module until all file descriptors are closed.

Fixes 28010791193a ("Bluetooth: vhci: Prevent use-after-free by removing debugfs files early")
---
 drivers/bluetooth/hci_vhci.c |    4 ++++
 1 file changed, 4 insertions(+)
drivers/bluetooth/hci_vhci.c +4 -0
@@ -155,6 +155,7 @@ static ssize_t force_suspend_write(struc
 }
 
 static const struct file_operations force_suspend_fops = {
+	.owner		= THIS_MODULE,
 	.open		= simple_open,
 	.read		= force_suspend_read,
 	.write		= force_suspend_write,
@@ -194,6 +195,7 @@ static ssize_t force_wakeup_write(struct
 }
 
 static const struct file_operations force_wakeup_fops = {
+	.owner		= THIS_MODULE,
 	.open		= simple_open,
 	.read		= force_wakeup_read,
 	.write		= force_wakeup_write,
@@ -263,6 +265,7 @@ static ssize_t aosp_capable_write(struct
 }
 
 static const struct file_operations aosp_capable_fops = {
+	.owner		= THIS_MODULE,
 	.open		= simple_open,
 	.read		= aosp_capable_read,
 	.write		= aosp_capable_write,
@@ -386,6 +389,7 @@ static ssize_t force_devcd_write(struct
 }
 
 static const struct file_operations force_devcoredump_fops = {
+	.owner		= THIS_MODULE,
 	.open		= simple_open,
 	.write		= force_devcd_write,
 };
author maintainer
#210 lore raw

PATCH 210/547 drm/panthor: Fix TOCTOU race between GROUP_REGISTERED check and erase

In reply to Greg Kroah-Hartman

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

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

From: Osama Abdelkader <[email protected]>

commit 7764289d76a38c3a2f9b093bf17e193ab54acd70 upstream.

panthor_group_destroy() checks the GROUP_REGISTERED mark and then calls xa_erase() without holding the xarray lock across both. If the handle is destroyed by another thread in between, and a concurrent GROUP_CREATE reuses the freed ID, the first destroy erases and releases the new, still-initializing group, leading to a use-after-free in panthor_group_create().

Do the mark check and erase atomically under xa_lock().

Fixes eec7e23d848d ("drm/panthor: Prevent potential UAF in group creation")
Assisted-by Claude:claude-opus-5.5
---
 drivers/gpu/drm/panthor/panthor_sched.c |   14 ++++++++++----
 1 file changed, 10 insertions(+), 4 deletions(-)
drivers/gpu/drm/panthor/panthor_sched.c +10 -4
@@ -3794,12 +3794,18 @@ int panthor_group_destroy(struct panthor
 	struct panthor_group_pool *gpool = pfile->groups;
 	struct panthor_device *ptdev = pfile->ptdev;
 	struct panthor_scheduler *sched = ptdev->scheduler;
-	struct panthor_group *group;
+	struct panthor_group *group = NULL;
 
-	if (!xa_get_mark(&gpool->xa, group_handle, GROUP_REGISTERED))
-		return -EINVAL;
+	/*
+	 * Check the mark and erase the entry atomically, so a concurrent
+	 * destroy + create can't make us erase a group that's still being
+	 * initialized and happens to reuse the same handle.
+	 */
+	xa_lock(&gpool->xa);
+	if (xa_get_mark(&gpool->xa, group_handle, GROUP_REGISTERED))
+		group = __xa_erase(&gpool->xa, group_handle);
+	xa_unlock(&gpool->xa);
 
-	group = xa_erase(&gpool->xa, group_handle);
 	if (!group)
 		return -EINVAL;
 
author maintainer
#211 lore raw

PATCH 211/547 fbdev: atmel_lcdfb: Prevent FIFO work after removal

In reply to Greg Kroah-Hartman

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

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

From: Yibo Tan <[email protected]>

commit 20b3b97cf89cb381bf07516090d99399cc9b91fd upstream.

The LCD controller IRQ schedules sinfo->task to recover from a FIFO underflow. Probe currently requests the IRQ before initializing the work, so an early interrupt can schedule an uninitialized work item.

The probe error path and remove path cancel the work before freeing the IRQ. A FIFO-underflow interrupt can schedule the work again after that cancellation. framebuffer_release() may then free sinfo while the work is still pending.

KASAN reported a use-after-free in atmel_lcdfb_task() when an underflow interrupt occurred during removal. With the IRQ freed before the work was cancelled, the same test completed without a kernel diagnostic.

Initialize the work before requesting the IRQ. In both cleanup paths, free the IRQ before cancelling the work so that it cannot be scheduled again after cancellation.

Fixes d22579b83735 ("atmel_lcdfb: FIFO underflow management")
Assisted-by Codex:GPT-5
---
 drivers/video/fbdev/atmel_lcdfb.c |   11 +++++------
 1 file changed, 5 insertions(+), 6 deletions(-)
drivers/video/fbdev/atmel_lcdfb.c +5 -6
@@ -1146,6 +1146,9 @@ static int atmel_lcdfb_probe(struct plat
 	/* Initialize PWM for contrast or backlight ("off") */
 	init_contrast(sinfo);
 
+	/* Some LCDC recovery operations require process context. */
+	INIT_WORK(&sinfo->task, atmel_lcdfb_task);
+
 	/* interrupt */
 	ret = request_irq(sinfo->irq_base, atmel_lcdfb_interrupt, 0, pdev->name, info);
 	if (ret) {
@@ -1153,10 +1156,6 @@ static int atmel_lcdfb_probe(struct plat
 		goto unmap_mmio;
 	}
 
-	/* Some operations on the LCDC might sleep and
-	 * require a preemptible task context */
-	INIT_WORK(&sinfo->task, atmel_lcdfb_task);
-
 	ret = atmel_lcdfb_init_fbinfo(sinfo);
 	if (ret < 0) {
 		dev_err(dev, "init fbinfo failed: %d\n", ret);
@@ -1192,8 +1191,8 @@ reset_drvdata:
 	dev_set_drvdata(dev, NULL);
 	fb_dealloc_cmap(&info->cmap);
 unregister_irqs:
-	cancel_work_sync(&sinfo->task);
 	free_irq(sinfo->irq_base, info);
+	cancel_work_sync(&sinfo->task);
 unmap_mmio:
 	exit_backlight(sinfo);
 	iounmap(sinfo->mmio);
@@ -1230,6 +1229,7 @@ static void atmel_lcdfb_remove(struct pl
 		return;
 	sinfo = info->par;
 
+	free_irq(sinfo->irq_base, info);
 	cancel_work_sync(&sinfo->task);
 	exit_backlight(sinfo);
 	atmel_lcdfb_power_control(sinfo, 0);
@@ -1238,7 +1238,6 @@ static void atmel_lcdfb_remove(struct pl
 	clk_put(sinfo->lcdc_clk);
 	clk_put(sinfo->bus_clk);
 	fb_dealloc_cmap(&info->cmap);
-	free_irq(sinfo->irq_base, info);
 	iounmap(sinfo->mmio);
  	release_mem_region(info->fix.mmio_start, info->fix.mmio_len);
 	if (platform_get_resource(pdev, IORESOURCE_MEM, 1)) {
author maintainer
#212 lore raw

PATCH 212/547 fbdev: udlfb: dont rebuild the mode list while the framebuffer is in use

In reply to Greg Kroah-Hartman

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

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

From: Xiang Mei <[email protected]>

commit ac9cfa552102b8e80e88c2872e80dc9cb5f07dda upstream.

dlfb_setup_modes() frees info->modelist with fb_destroy_modelist() and rebuilds it, but fbcon holds raw pointers into that list in fb_display[i].mode and nothing un-publishes them the way do_unregister_framebuffer() and store_modes() do with fbcon_delete_modelist(). The function does refuse to install a new mode while the framebuffer has users (dlfb->fb_count != 0), but only after the list is already destroyed. Reached from the 0666 "edid" sysfs attribute, an unprivileged write to /sys/class/graphics/fb0/edid therefore fails with -EINVAL and still leaves every fb_display[i].mode dangling; the next console switch reads the freed fb_videomode in fb_videomode_to_var().

Test fb_count before touching the list. fbcon takes a reference through fbcon_open(), so that condition covers exactly the states in which fb_display[] points into the list, and the errno returned to userspace is unchanged.

  BUG: KASAN: slab-use-after-free in fb_videomode_to_var (drivers/video/fbdev/core/modedb.c:905)
  Read of size 4 at addr ffff8880107b449c by task kworker/1:1/47
  Workqueue: events console_callback
  Call Trace:
   fb_videomode_to_var (drivers/video/fbdev/core/modedb.c:905)
   display_to_var (drivers/video/fbdev/core/fbcon.c:998)
   fbcon_switch (drivers/video/fbdev/core/fbcon.c:2182)
   redraw_screen (drivers/tty/vt/vt.c:994)
   complete_change_console (drivers/tty/vt/vt_ioctl.c:1141)
   console_callback (drivers/tty/vt/vt.c:3358)
   process_one_work (kernel/workqueue.c:3396)
   worker_thread (kernel/workqueue.c:3479 kernel/workqueue.c:3560)
   kthread (kernel/kthread.c:436)
   ret_from_fork (arch/x86/kernel/process.c:158)
   ret_from_fork_asm (arch/x86/entry/entry_64.S:245)
  ...
  The buggy address is located 28 bytes inside of
   freed 96-byte region [ffff8880107b4480, ffff8880107b44e0)
---
 drivers/video/fbdev/udlfb.c |    5 +++++
 1 file changed, 5 insertions(+)
drivers/video/fbdev/udlfb.c +5 -0
@@ -1293,6 +1293,11 @@ static int dlfb_setup_modes(struct dlfb_
 		goto error;
 	}
 
+	if (dlfb->fb_count) {
+		result = -EINVAL;
+		goto error;
+	}
+
 	fb_destroy_modelist(&info->modelist);
 	memset(&info->monspecs, 0, sizeof(info->monspecs));
 
author maintainer
#213 lore raw

PATCH 213/547 filelock: keep superblock active through delegation wait

In reply to Greg Kroah-Hartman

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

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

From: Zhao Gongyi <[email protected]>

commit c206cdfee6c037b829178bb7e17e6e37ddc9aa35 upstream.

A caller may drop its path after try_break_deleg() returns a delegated inode but before break_deleg_wait() finishes. The extra inode reference held in struct delegated_inode does not keep the superblock active.

After a lazy unmount, closing the delegation holder can release the last mount reference and shut down the superblock while another task waits for the delegation break. The waiter's final iput() can then enter the filesystem's eviction code after its superblock-private state was freed. This has been observed as a KASAN use-after-free in shmem_evict_inode().

When try_break_deleg() saves a delegated inode, take an active reference to its superblock while the caller still pins the mount. Keep that reference through break_deleg_wait() and the final iput(), then release it with deactivate_super(). This protects every caller of the helpers, including the mknod, mkdir, symlink and rmdir paths that drop their path before waiting.

Fixes e12d203b8c88 ("vfs: allow mkdir to wait for delegation break on parent")
Fixes 4fa76319cd0c ("vfs: allow rmdir to wait for delegation break on parent")
Fixes c826229c6a82 ("vfs: make vfs_create break delegations on parent directory")
Fixes e8960c1b2ee9 ("vfs: make vfs_mknod break delegations on parent directory")
Fixes 92bf53577f01 ("vfs: make vfs_symlink break delegations on parent dir")
---
 include/linux/filelock.h |   13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)
include/linux/filelock.h +9 -4
@@ -530,8 +530,8 @@ static inline bool is_delegated(struct d
  *
  * Break delegations in a non-blocking fashion. If there are
  * outstanding delegations and @di is set, then an extra reference
- * will be taken on @inode and @di->di_inode will be populated so
- * that it may be waited upon.
+ * will be taken on @inode and its superblock, and @di->di_inode will
+ * be populated so that it may be waited upon.
  *
  * Returns 0 if there is no need to wait or an error. If -EWOULDBLOCK
  * is returned, then @di will be populated (if non-NULL).
@@ -545,16 +545,21 @@ static inline int try_break_deleg(struct
 	if (ret == -EWOULDBLOCK && di) {
 		di->di_inode = inode;
 		ihold(inode);
+		/* The caller may drop its mount before break_deleg_wait(). */
+		atomic_inc(&inode->i_sb->s_active);
 	}
 	return ret;
 }
 
 static inline int break_deleg_wait(struct delegated_inode *di)
 {
+	struct inode *inode = di->di_inode;
+	struct super_block *sb = inode->i_sb;
 	int ret;
 
-	ret = break_deleg(di->di_inode, 0);
-	iput(di->di_inode);
+	ret = break_deleg(inode, 0);
+	iput(inode);
+	deactivate_super(sb);
 	di->di_inode = NULL;
 	return ret;
 }
author maintainer
#214 lore raw

PATCH 214/547 fs/proc/task_mmu: pin mm_users in do_pagemap_scan()

In reply to Greg Kroah-Hartman

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

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

From: Ngoc Quy <[email protected]>

commit 4fb975471717c953f912776bb60301add1ffae11 upstream.

The PAGEMAP_SCAN ioctl takes mmap_read_lock() on an mm obtained from /proc/<pid>/pagemap without holding a reference to mm_users.

proc_mem_open() deliberately grabs only mm_count, so a consumer that touches the address space has to call mmget_not_zero() first. Every other consumer in this file does -- m_start(), do_procmap_query(), show_smaps_rollup() and pagemap_read() -- but do_pagemap_scan() does not.

Without that reference the target can reach exit_mmap() concurrently, and exit_mmap() calls unmap_vmas() while holding mmap_lock only for reading, which does not exclude the scanner. For ordinary VMAs this is harmless, as free_pgtables() and remove_vma() run afterwards under mmap_write_lock. A shared hugetlb VMA is different: __hugetlb_zap_end() frees the VMA's hugetlb_vma_lock inside the read-locked phase.

walk_hugetlb_range() can therefore load vma->vm_private_data, have the lock freed underneath it, and then down_read() a freed rw_semaphore. The load happens before the freeing side clears the pointer, so this is a use-after-free and not a NULL dereference. Any unprivileged user can reach it with no huge pages configured, as hugetlb_reserve_pages() allocates the lock before the VM_NORESERVE early return.

Pin mm_users across the scan, the way the other consumers do. mmput() from the exiting task can then no longer reach exit_mmap() while a walk is in progress.

[[email protected]: remove unneeded & undesirable test for !mm]
Fixes 52526ca7fdb9 ("fs/proc/task_mmu: implement IOCTL to get and optionally clear info about PTEs")
Assisted-by Claude:claude-opus-5
Cc Liam R. Howlett <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Jann Horn <[email protected]>
Cc Pedro Falcato <[email protected]>
Cc Muhammad Usama Anjum <[email protected]>
---
 fs/proc/task_mmu.c |    9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
fs/proc/task_mmu.c +7 -2
@@ -3231,15 +3231,18 @@ static long do_pagemap_scan(struct mm_st
 	size_t n_ranges_out = 0;
 	int ret;
 
+	if (!mmget_not_zero(mm))
+		return -ESRCH;
+
 	ret = pagemap_scan_get_args(&p.arg, uarg);
 	if (ret)
-		return ret;
+		goto out_mmput;
 
 	p.masks_of_interest = p.arg.category_mask | p.arg.category_anyof_mask |
 			      p.arg.return_mask;
 	ret = pagemap_scan_init_bounce_buffer(&p);
 	if (ret)
-		return ret;
+		goto out_mmput;
 
 	for (walk_start = p.arg.start; walk_start < p.arg.end;
 			walk_start = p.arg.walk_end) {
@@ -3294,6 +3297,8 @@ static long do_pagemap_scan(struct mm_st
 		ret = -EFAULT;
 
 	kfree(p.vec_buf);
+out_mmput:
+	mmput(mm);
 	return ret;
 }
 
author maintainer
#215 lore raw

PATCH 215/547 fsverity: Set S_VERITY only after rollback is no longer possible

In reply to Greg Kroah-Hartman

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

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

From: Eric Biggers <[email protected]>

commit c349b233d6ab0fc3517401a1e2d36f5f90eb8c9b upstream.

Commit f77f281b6118 ("fsverity: use a hashtable to find the fsverity_info") changed the implementation of FS_IOC_ENABLE_VERITY to make concurrent reads start going through fsverity verification slightly earlier than they did before.

Instead of it happening when enable_verity() calls fsverity_set_info(), it now happens when ->end_enable_verity() sets S_VERITY.

However, ext4 and btrfs can roll back verity after they set S_VERITY, causing a use-after-free.

Fix that by making ext4 and btrfs set S_VERITY only after rollback is no longer possible. On failure, don't roll back S_VERITY, but do roll back the filesystem-specific verity flag.

Also update enable_verity() to handle any future instances of this bug more safely by warning and *not* freeing the fsverity_info.

Finally, tweak some comments. Clarify one, and move information from another to its proper place in the comment for ->end_enable_verity().

Fixes f77f281b6118 ("fsverity: use a hashtable to find the fsverity_info")
---
 fs/btrfs/verity.c        |    7 ++++---
 fs/ext4/verity.c         |    4 +++-
 fs/verity/enable.c       |   12 +++++-------
 include/linux/fsverity.h |   12 +++++++-----
 4 files changed, 19 insertions(+), 16 deletions(-)
fs/btrfs/verity.c +4 -3
@@ -489,8 +489,6 @@ static int rollback_verity(struct btrfs_
 			inode->vfs_inode.i_ino);
 		goto out;
 	}
-	inode->ro_flags &= ~BTRFS_INODE_RO_VERITY;
-	btrfs_sync_inode_flags_to_i_flags(inode);
 	ret = btrfs_update_inode(trans, inode);
 	if (unlikely(ret)) {
 		btrfs_abort_transaction(trans, ret);
@@ -555,16 +553,19 @@ static int finish_verity(struct btrfs_in
 	if (IS_ERR(trans))
 		return PTR_ERR(trans);
 	inode->ro_flags |= BTRFS_INODE_RO_VERITY;
-	btrfs_sync_inode_flags_to_i_flags(inode);
 	ret = btrfs_update_inode(trans, inode);
 	if (ret)
 		goto end_trans;
 	ret = del_orphan(trans, inode);
 	if (ret)
 		goto end_trans;
+	/* Now that rollback is no longer possible, set S_VERITY. */
+	btrfs_sync_inode_flags_to_i_flags(inode);
 	clear_bit(BTRFS_INODE_VERITY_IN_PROGRESS, &inode->runtime_flags);
 	btrfs_set_fs_compat_ro(root->fs_info, VERITY);
 end_trans:
+	if (ret)
+		inode->ro_flags &= ~BTRFS_INODE_RO_VERITY;
 	btrfs_end_transaction(trans);
 	return ret;
 
fs/ext4/verity.c +3 -1
@@ -242,17 +242,19 @@ static int ext4_end_enable_verity(struct
 		goto stop_and_cleanup;
 
 	ext4_set_inode_flag(inode, EXT4_INODE_VERITY);
-	ext4_set_inode_flags(inode, false);
 	err = ext4_mark_iloc_dirty(handle, inode, &iloc);
 	if (err)
 		goto stop_and_cleanup;
 
 	ext4_journal_stop(handle);
 
+	/* Now that rollback is no longer possible, set S_VERITY. */
+	ext4_set_inode_flags(inode, false);
 	ext4_clear_inode_state(inode, EXT4_STATE_VERITY_IN_PROGRESS);
 	return 0;
 
 stop_and_cleanup:
+	ext4_clear_inode_flag(inode, EXT4_INODE_VERITY);
 	ext4_journal_stop(handle);
 cleanup:
 	/*
fs/verity/enable.c +5 -7
@@ -274,8 +274,8 @@ static int enable_verity(struct file *fi
 	 * initialization so that we don't have to undo the enabling when memory
 	 * allocation for the hash table fails.  This is safe because looking up
 	 * the fsverity_info always first checks the S_VERITY flag on the inode,
-	 * which will only be set at the very end of the ->end_enable_verity
-	 * method.
+	 * which will only be set at the very end of a successful call to
+	 * ->end_enable_verity().
 	 */
 	err = fsverity_set_info(vi);
 	if (err) {
@@ -285,10 +285,7 @@ static int enable_verity(struct file *fi
 
 	/*
 	 * Tell the filesystem to finish enabling verity on the file.
-	 * Serialized with ->begin_enable_verity() by the inode lock.  The file
-	 * system needs to set the S_VERITY flag on the inode at the very end of
-	 * the method, at which point the fsverity information can be accessed
-	 * by other threads.
+	 * Serialized with ->begin_enable_verity() by the inode lock.
 	 */
 	inode_lock(inode);
 	err = vops->end_enable_verity(filp, desc, desc_size, params.tree_size);
@@ -296,7 +293,8 @@ static int enable_verity(struct file *fi
 	if (err) {
 		fsverity_err(inode, "%ps() failed with err %d",
 			     vops->end_enable_verity, err);
-		fsverity_remove_info(vi);
+		if (!WARN_ON_ONCE(IS_VERITY(inode)))
+			fsverity_remove_info(vi);
 	} else if (WARN_ON_ONCE(!IS_VERITY(inode))) {
 		fsverity_remove_info(vi);
 		err = -EINVAL;
include/linux/fsverity.h +7 -5
@@ -54,11 +54,13 @@ struct fsverity_operations {
 	 * @merkle_tree_size: total bytes the Merkle tree took up
 	 *
 	 * If desc == NULL, then enabling verity failed and the filesystem only
-	 * must do any necessary cleanups.  Else, it must also store the given
-	 * verity descriptor to a fs-specific location associated with the inode
-	 * and do any fs-specific actions needed to mark the inode as a verity
-	 * inode, e.g. setting a bit in the on-disk inode.  The filesystem is
-	 * also responsible for setting the S_VERITY flag in the VFS inode.
+	 * must do any necessary cleanups.
+	 *
+	 * Else, the filesystem must store the given verity descriptor to a
+	 * fs-specific location associated with the inode and do any fs-specific
+	 * actions needed to mark the inode as a verity inode, e.g. set a bit in
+	 * the on-disk inode.  Finally, on success (only when rollback is no
+	 * longer possible!) it must set S_VERITY in the VFS inode.
 	 *
 	 * i_rwsem is held for write, but it may have been dropped between
 	 * ->begin_enable_verity() and ->end_enable_verity().
author maintainer
#216 lore raw

PATCH 216/547 genirq: Defer kfree(irqaction) until irq_thread_dtor() finishes

In reply to Greg Kroah-Hartman

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

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

From: Richard Patel <[email protected]>

commit d04adff6860587e843948b0c31174f8ae11b8dfe upstream.

When an interrupt thread exits abnormally via do_exit() (e.g. the interrupt handler oopses) without returning from irq_thread(), a concurrent call to free_irq() could free the irqaction before the irq_thread_dtor() exit task work runs.

irq thread (oopsed) free_irq()
------------------- ----------
do_exit()

    exit_mm()
      complete_vfork_done()  -------> kthread_stop() returns
    exit_files() ...                  kfree(action)
    exit_task_work()
      irq_thread_dtor()
        action->...                   <- use-after-free

Track the pending exit work with the IRQTF_EXIT_WORK thread flag, and have __free_irq() wait for the bit to clear before kfree().

irq_thread_dtor() only runs on irq_thread abnormal exit. If that dtor also faults, free_irq() will hang indefinitely, but double IRQ thread faults require a reboot anyways.

[ tglx: Add missing include ]

Fixes ed3e694d78cc ("move exit_task_work() past exit_files() et.al.")
---
 kernel/irq/internals.h |    2 ++
 kernel/irq/manage.c    |   26 ++++++++++++++++++++------
 2 files changed, 22 insertions(+), 6 deletions(-)
kernel/irq/internals.h +2 -0
@@ -36,6 +36,7 @@ extern struct irqaction chained_action;
  * IRQTF_AFFINITY  - irq thread is requested to adjust affinity
  * IRQTF_FORCED_THREAD  - irq action is force threaded
  * IRQTF_READY     - signals that irq thread is ready
+ * IRQTF_EXIT_WORK - irq thread exit task_work is pending
  */
 enum {
 	IRQTF_RUNTHREAD,
@@ -43,6 +44,7 @@ enum {
 	IRQTF_AFFINITY,
 	IRQTF_FORCED_THREAD,
 	IRQTF_READY,
+	IRQTF_EXIT_WORK,
 };
 
 /*
kernel/irq/manage.c +20 -6
@@ -21,6 +21,7 @@
 #include <linux/sched/isolation.h>
 #include <uapi/linux/sched/types.h>
 #include <linux/task_work.h>
+#include <linux/wait_bit.h>
 
 #include "internals.h"
 
@@ -1176,17 +1177,14 @@ void wake_threads_waitq(struct irq_desc
 		wake_up(&desc->wait_for_threads);
 }
 
-static void irq_thread_dtor(struct callback_head *unused)
+static void __irq_thread_dtor(struct irqaction *action)
 {
 	struct task_struct *tsk = current;
 	struct irq_desc *desc;
-	struct irqaction *action;
 
 	if (WARN_ON_ONCE(!(current->flags & PF_EXITING)))
 		return;
 
-	action = kthread_data(tsk);
-
 	pr_err("exiting task \"%s\" (%d) is an active IRQ thread (irq %d)\n",
 	       tsk->comm, tsk->pid, action->irq);
 
@@ -1203,6 +1201,14 @@ static void irq_thread_dtor(struct callb
 	irq_finalize_oneshot(desc, action);
 }
 
+static void irq_thread_dtor(struct callback_head *unused)
+{
+	struct irqaction *action = kthread_data(current);
+
+	__irq_thread_dtor(action);
+	clear_and_wake_up_bit(IRQTF_EXIT_WORK, &action->thread_flags);
+}
+
 static void irq_wake_secondary(struct irq_desc *desc, struct irqaction *action)
 {
 	struct irqaction *secondary = action->secondary;
@@ -1263,6 +1269,7 @@ static int irq_thread(void *data)
 	else
 		handler_fn = irq_thread_fn;
 
+	set_bit(IRQTF_EXIT_WORK, &action->thread_flags);
 	init_task_work(&on_exit_work, irq_thread_dtor);
 	task_work_add(current, &on_exit_work, TWA_NONE);
 
@@ -1283,6 +1290,7 @@ static int irq_thread(void *data)
 	 * oneshot mask bit can be set.
 	 */
 	task_work_cancel_func(current, irq_thread_dtor);
+	clear_and_wake_up_bit(IRQTF_EXIT_WORK, &action->thread_flags);
 	return 0;
 }
 
@@ -1853,6 +1861,12 @@ out_mput:
 	return ret;
 }
 
+static void irq_stop_thread(struct irqaction *action)
+{
+	kthread_stop_put(action->thread);
+	wait_on_bit(&action->thread_flags, IRQTF_EXIT_WORK, TASK_UNINTERRUPTIBLE);
+}
+
 /*
  * Internal function to unregister an irqaction - used to free
  * regular and special interrupts that are part of the architecture.
@@ -1958,9 +1972,9 @@ static struct irqaction *__free_irq(stru
 	 * the same bit to a newly requested action.
 	 */
 	if (action->thread) {
-		kthread_stop_put(action->thread);
+		irq_stop_thread(action);
 		if (action->secondary && action->secondary->thread)
-			kthread_stop_put(action->secondary->thread);
+			irq_stop_thread(action->secondary);
 	}
 
 	/* Last action releases resources */
author maintainer
#217 lore raw

PATCH 217/547 genirq: Move interrupt thread exit_work object to irqaction

In reply to Greg Kroah-Hartman

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

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

From: Richard Patel <[email protected]>

commit 89a9e003a2ef73f67dff03dfd59e0a5474b56b0b upstream.

irq_thread() registers irq_thread_dtor() as exit task_work using a stack-allocated callback_head. On normal interrupt thread exit, this work gets cancelled and never runs.

On x86, an abnormal interrupt thread exit (e.g. handler oops) discards the stack, including the callback_head, while that callback_head is still pending. By the time exit_task_work() runs, the stack memory formerly backing callback_head is already clobbered.

irq_thread() <-- on_exit_work allocated
** IRQ handler faults **
oops_end()
rewind_stack_and_make_dead() <-- on_exit_work freed
make_task_dead()

    do_exit(SIGSEGV)
      ...
      exit_shm()                    <-- on_exit_work clobbered
      ...
      exit_task_work()              <-- stack use-after-free
        exit_shm()+0x30             <-- wild jump to return addr

Thus, a benign threaded IRQ oops (e.g. a NULL pointer deref) is turned into a wild jump. This is caught by kernel IBT:

** first fault **

  Oops: general protection fault, kernel NULL pointer dereference 0x3c0: 0000 [#1] SMP NOPTI
  ...
  ** second fault **
  Missing ENDBR: exit_shm+0x30/0x1c0
  kernel BUG at arch/x86/kernel/cet.c:133!
  ...
   ? task_work_run+0x5c/0x90
   ? do_exit+0x209/0x460
   ? rewind_stack_and_make_dead+0x16/0x20
  ...
  note: irq/165-AudioDS[1427] exited with irqs disabled
  Fixing recursive fault but reboot is needed!

Fix this by storing the callback_head in struct irqaction. The irqaction is only freed once irq_thread_dtor() finishes.

Fixes 2deb4be28077 ("x86/dumpstack: When OOPSing, rewind the stack before do_exit()")
---
 include/linux/interrupt.h |    2 ++
 kernel/irq/manage.c       |    9 ++++-----
 2 files changed, 6 insertions(+), 5 deletions(-)
include/linux/interrupt.h +2 -0
@@ -119,6 +119,7 @@ typedef irqreturn_t (*irq_handler_t)(int
  * @thread_flags:	flags related to @thread
  * @thread_mask:	bitmask for keeping track of @thread activity
  * @dir:	pointer to the proc/irq/NN/name entry
+ * @thread_dtor:	task_work for @thread irregular exit cleanup
  */
 struct irqaction {
 	irq_handler_t		handler;
@@ -137,6 +138,7 @@ struct irqaction {
 	unsigned long		thread_mask;
 	const char		*name;
 	struct proc_dir_entry	*dir;
+	struct callback_head	thread_dtor;
 } ____cacheline_internodealigned_in_smp;
 
 extern irqreturn_t no_action(int cpl, void *dev_id);
kernel/irq/manage.c +4 -5
@@ -1201,9 +1201,9 @@ static void __irq_thread_dtor(struct irq
 	irq_finalize_oneshot(desc, action);
 }
 
-static void irq_thread_dtor(struct callback_head *unused)
+static void irq_thread_dtor(struct callback_head *work)
 {
-	struct irqaction *action = kthread_data(current);
+	struct irqaction *action = container_of(work, struct irqaction, thread_dtor);
 
 	__irq_thread_dtor(action);
 	clear_and_wake_up_bit(IRQTF_EXIT_WORK, &action->thread_flags);
@@ -1250,7 +1250,6 @@ static void wake_up_and_wait_for_irq_thr
  */
 static int irq_thread(void *data)
 {
-	struct callback_head on_exit_work;
 	struct irqaction *action = data;
 	struct irq_desc *desc = irq_to_desc(action->irq);
 	irqreturn_t (*handler_fn)(struct irq_desc *desc,
@@ -1270,8 +1269,8 @@ static int irq_thread(void *data)
 		handler_fn = irq_thread_fn;
 
 	set_bit(IRQTF_EXIT_WORK, &action->thread_flags);
-	init_task_work(&on_exit_work, irq_thread_dtor);
-	task_work_add(current, &on_exit_work, TWA_NONE);
+	init_task_work(&action->thread_dtor, irq_thread_dtor);
+	task_work_add(current, &action->thread_dtor, TWA_NONE);
 
 	while (!irq_wait_for_interrupt(desc, action)) {
 		irqreturn_t action_ret;
author maintainer
#218 lore raw

PATCH 218/547 HID: hiddev: keep state alive through disconnect unlock

In reply to Greg Kroah-Hartman

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

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

From: Yousef Alhouseen <[email protected]>

commit 03f449b5de36a25fc5eba7dabf2b4494389bdb91 upstream.

mutex_unlock() clears the mutex owner before taking its wait lock. A thread spinning in the final hiddev file release can acquire existancelock after hiddev_disconnect() clears the owner, then free hiddev before the disconnecting thread reaches the mutex wait lock. This causes a use-after-free in the mutex slow unlock path.

Give the connection and each open file an explicit reference. Drop each reference only after its existancelock critical section has completed, so neither unlock path can free the mutex while the other is still using it.

---
 drivers/hid/usbhid/hiddev.c |   37 +++++++++++++++++++------------------
 include/linux/hiddev.h      |    2 ++
 2 files changed, 21 insertions(+), 18 deletions(-)
drivers/hid/usbhid/hiddev.c +19 -18
@@ -46,6 +46,12 @@ struct hiddev_list {
 	struct mutex thread_lock;
 };
 
+static void hiddev_put(struct hiddev *hiddev)
+{
+	if (refcount_dec_and_test(&hiddev->refcount))
+		kfree(hiddev);
+}
+
 /*
  * Find a report, given the report's type and ID.  The ID can be specified
  * indirectly by REPORT_ID_FIRST (which returns the first report of the given
@@ -216,26 +222,21 @@ static int hiddev_fasync(int fd, struct
 static int hiddev_release(struct inode * inode, struct file * file)
 {
 	struct hiddev_list *list = file->private_data;
+	struct hiddev *hiddev = list->hiddev;
 	unsigned long flags;
 
-	spin_lock_irqsave(&list->hiddev->list_lock, flags);
+	spin_lock_irqsave(&hiddev->list_lock, flags);
 	list_del(&list->node);
-	spin_unlock_irqrestore(&list->hiddev->list_lock, flags);
+	spin_unlock_irqrestore(&hiddev->list_lock, flags);
 
-	mutex_lock(&list->hiddev->existancelock);
-	if (!--list->hiddev->open) {
-		if (list->hiddev->exist) {
-			hid_hw_close(list->hiddev->hid);
-			hid_hw_power(list->hiddev->hid, PM_HINT_NORMAL);
-		} else {
-			mutex_unlock(&list->hiddev->existancelock);
-			kfree(list->hiddev);
-			vfree(list);
-			return 0;
-		}
+	mutex_lock(&hiddev->existancelock);
+	if (!--hiddev->open && hiddev->exist) {
+		hid_hw_close(hiddev->hid);
+		hid_hw_power(hiddev->hid, PM_HINT_NORMAL);
 	}
 
-	mutex_unlock(&list->hiddev->existancelock);
+	mutex_unlock(&hiddev->existancelock);
+	hiddev_put(hiddev);
 	vfree(list);
 
 	return 0;
@@ -270,6 +271,7 @@ static int __hiddev_open(struct hiddev *
 	spin_unlock_irq(&hiddev->list_lock);
 
 	file->private_data = list;
+	refcount_inc(&hiddev->refcount);
 
 	return 0;
 
@@ -897,6 +899,7 @@ int hiddev_connect(struct hid_device *hi
 	INIT_LIST_HEAD(&hiddev->list);
 	spin_lock_init(&hiddev->list_lock);
 	mutex_init(&hiddev->existancelock);
+	refcount_set(&hiddev->refcount, 1);
 	hid->hiddev = hiddev;
 	hiddev->hid = hid;
 	hiddev->exist = 1;
@@ -937,9 +940,7 @@ void hiddev_disconnect(struct hid_device
 	if (hiddev->open) {
 		hid_hw_close(hiddev->hid);
 		wake_up_interruptible(&hiddev->wait);
-		mutex_unlock(&hiddev->existancelock);
-	} else {
-		mutex_unlock(&hiddev->existancelock);
-		kfree(hiddev);
 	}
+	mutex_unlock(&hiddev->existancelock);
+	hiddev_put(hiddev);
 }
include/linux/hiddev.h +2 -0
@@ -13,6 +13,7 @@
 #ifndef _HIDDEV_H
 #define _HIDDEV_H
 
+#include <linux/refcount.h>
 #include <uapi/linux/hiddev.h>
 
 
@@ -24,6 +25,7 @@ struct hiddev {
 	int minor;
 	int exist;
 	int open;
+	refcount_t refcount;
 	struct mutex existancelock;
 	wait_queue_head_t wait;
 	struct hid_device *hid;
author maintainer
#219 lore raw

PATCH 219/547 io_uring/io-wq: save worker type before dropping its reference

In reply to Greg Kroah-Hartman

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

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

From: Kyle Zeng <[email protected]>

commit 37e425460b7c41687e51e3254b1eb1d799da9614 upstream.

io_wq_cancel_tw_create() inspects cb->func after calling io_worker_cancel_cb(). For an existing worker, that call can drop the last worker reference and wake io_worker_exit(). If the canceling task is preempted, the worker can be unlinked and freed by kfree_rcu() before the callback function is inspected. KASAN reports a slab-use-after-free read in this path.

Save whether the callback belongs to an unpublished continuation worker while its reference is still held, then use the saved result for the conditional free. This preserves the existing accounting and frees only the worker allocated for the canceled continuation.

Fixes e6db6f9398da ("io_uring/io-wq: only free worker if it was allocated for creation")
---
 io_uring/io-wq.c |    8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
io_uring/io-wq.c +5 -3
@@ -1424,14 +1424,16 @@ static void io_wq_cancel_tw_create(struc
 
 	while ((cb = task_work_cancel_match(wq->task, io_task_work_match, wq)) != NULL) {
 		struct io_worker *worker;
+		bool free_worker;
 
 		worker = container_of(cb, struct io_worker, create_work);
-		io_worker_cancel_cb(worker);
 		/*
 		 * Only the worker continuation helper has worker allocated and
-		 * hence needs freeing.
+		 * hence needs freeing. Save this before dropping its reference.
 		 */
-		if (cb->func == create_worker_cont)
+		free_worker = cb->func == create_worker_cont;
+		io_worker_cancel_cb(worker);
+		if (free_worker)
 			kfree(worker);
 	}
 }
author maintainer
#220 lore raw

PATCH 220/547 iomap: dont resubmit an ioend after ->writeback_submit() failed

In reply to Greg Kroah-Hartman

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

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

From: Andrea Parri <[email protected]>

commit 3f517370076f1fedaa38cd8c78ceb73616b79336 upstream.

iomap_add_to_ioend() submits the pending ioend through ->writeback_submit() before allocating a new one for the current range. When the submission fails the helper completes the ioend with an error, but iomap_add_to_ioend() returns the error without clearing wpc->wb_ctx. iomap_writepages() then submits whatever wpc->wb_ctx points to, so the already completed ioend is submitted a second time.

For XFS the second bio_endio() lands in xfs_end_bio(), which list_add_tail()s the already linked ioend into ip->i_ioend_list. This corrupts the list and leaves a use-after-free/double-free window against the ioend completion worker. Reproduced with a fault-injected ->writeback_submit() failure on a reflinked XFS file with several CoW writeback ranges in flight: the unfixed kernel hits repeated "list_add double add" warnings from __list_add_valid_or_report(), the fixed kernel fails writeback cleanly.

Clear wpc->wb_ctx when ->writeback_submit() fails. The old iomap_submit_ioend() cleared the context unconditionally; that clear was lost when submission moved to iomap_ioend_writeback_submit(). The final ->writeback_submit() call in iomap_writepages() needs no equivalent fix:
it is the last thing the function does before returning, and every caller allocates its iomap_writepage_ctx on the stack for a single call, so wpc->wb_ctx is never read again afterwards.

---
 fs/iomap/ioend.c |   10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
fs/iomap/ioend.c +9 -1
@@ -246,8 +246,16 @@ ssize_t iomap_add_to_ioend(struct iomap_
 new_ioend:
 		if (ioend) {
 			error = wpc->ops->writeback_submit(wpc, 0);
-			if (error)
+			if (error) {
+				/*
+				 * ->writeback_submit() completed the ioend
+				 * with an error, so drop the stale context;
+				 * iomap_writepages() would otherwise submit
+				 * it a second time.
+				 */
+				wpc->wb_ctx = NULL;
 				return error;
+			}
 		}
 		wpc->wb_ctx = ioend = iomap_alloc_ioend(wpc, pos, ioend_flags);
 	}
author maintainer
#221 lore raw

PATCH 221/547 iommu/arm-smmu-v3: Disable the impl before disabling the SMMU on shutdown

In reply to Greg Kroah-Hartman

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

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

From: Nicolin Chen <[email protected]>

commit ab0dbf411aced59c04ce86fd8443faf13bdc9936 upstream.

arm_smmu_device_shutdown() only calls arm_smmu_device_disable(), and never the impl_ops->device_disable() hook. On tegra241-cmdqv, that hook quiesces every VINTF through tegra241_vintf_hw_deinit(), which issues a CMD_SYNC on the shared CMDQ while it is still enabled.

arm_smmu_disable_action() already runs this hook before disabling the SMMU, to cover an unbind or a probe failure, and no devres release ever follows a reboot or a kexec to run it again. Have arm_smmu_device_shutdown() call it directly, instead of reimplementing part of what it already does.

Fixes 9ff145a25c5c ("iommu/tegra241-cmdqv: Fix CMD_SYNC use-after-free on teardown")
Assisted-by LLM
---
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +1 -1
@@ -5633,7 +5633,7 @@ static void arm_smmu_device_shutdown(str
 {
 	struct arm_smmu_device *smmu = platform_get_drvdata(pdev);
 
-	arm_smmu_device_disable(smmu);
+	arm_smmu_disable_action(smmu);
 }
 
 static const struct of_device_id arm_smmu_of_match[] = {
author maintainer
#222 lore raw

PATCH 222/547 KVM: guest_memfd: Gracefully handle xarray errors when binding a memslot

In reply to Greg Kroah-Hartman

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

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

From: Sean Christopherson <[email protected]>

commit e6ecb88711d93b9e014532f17d3d29b57e80932c upstream.

If inserting a memslot into a guest_memfd's bindings xarray fails, propagate the error back to the caller, i.e. fail memslot creation as well. Signalling success and continuing on with memslot creation results in use-after-free, as the guest_memfd instance will remain reachable via the memslot after the file is freed (kvm_gmem_release() won't nullify the file pointer due to lack of a valid binding).

Opportunistically WARN and reject binding if KVM_MEMSLOT_GMEM_ONLY is already set, partly to guard against goofs elsewhere, but mostly so that KVM doesn't need to worry about clobbering flags when unwinding on failure.

Regarding the unwind, the slot must be fully prepared before inserting it into the bindings, at which point the slot becomes reachable. I.e. waiting to update the slot in order to avoid the ugly unwind isn't an option. And as part of the unwind, explicitly nullify the relevant bindings, as xarray can store a subset of entries when populating a range.

---
 virt/kvm/guest_memfd.c |   12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
virt/kvm/guest_memfd.c +10 -2
@@ -616,6 +616,9 @@ int kvm_gmem_bind(struct kvm *kvm, struc
 	BUILD_BUG_ON(sizeof(gpa_t) != sizeof(offset));
 	BUILD_BUG_ON(sizeof(gfn_t) != sizeof(slot->gmem.pgoff));
 
+	if (WARN_ON_ONCE(slot->flags & KVM_MEMSLOT_GMEM_ONLY))
+		return -EINVAL;
+
 	file = fget(fd);
 	if (!file)
 		return -EBADF;
@@ -654,7 +657,13 @@ int kvm_gmem_bind(struct kvm *kvm, struc
 	if (kvm_gmem_supports_mmap(inode))
 		slot->flags |= KVM_MEMSLOT_GMEM_ONLY;
 
-	xa_store_range(&f->bindings, start, end - 1, slot, GFP_KERNEL);
+	r = xa_err(xa_store_range(&f->bindings, start, end - 1, slot, GFP_KERNEL));
+	if (r) {
+		xa_store_range(&f->bindings, start, end - 1, NULL, GFP_KERNEL);
+		slot->gmem.file = NULL;
+		slot->gmem.pgoff = 0;
+		slot->flags &= ~KVM_MEMSLOT_GMEM_ONLY;
+	}
 	filemap_invalidate_unlock(inode->i_mapping);
 
 	/*
@@ -662,7 +671,6 @@ int kvm_gmem_bind(struct kvm *kvm, struc
 	 * not the other way 'round.  Active bindings are invalidated if the
 	 * file is closed before memslots are destroyed.
 	 */
-	r = 0;
 err:
 	fput(file);
 	return r;
author maintainer
#223 lore raw

PATCH 223/547 KVM: pfncache: use a dedicated invalidation sequence for cache refresh

In reply to Greg Kroah-Hartman

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

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

From: David Woodhouse <[email protected]>

commit da260bcb56feeb6489a83f310308453a0a7de25e upstream.

The gfn_to_pfn_cache refresh path guards against mmu notifier invalidations which complete while it has dropped gpc->lock for the HVA->PFN lookup: hva_to_pfn_retry() samples kvm->mmu_invalidate_seq and retries if it changed, or if mn_active_invalidate_count is still elevated.

That is insufficient for HVA-based caches. mmu_invalidate_seq is only advanced by kvm_mmu_invalidate_end() when the invalidated range overlaps a memslot, and an HVA-based cache (e.g. the Xen shared_info page mapped with KVM_XEN_ATTR_TYPE_SHARED_INFO_HVA) need not be backed by any memslot at all. An invalidation of the cached HVA which starts and ends entirely within the lookup window is thus invisible to the retry check: mn_active_invalidate_count is back to zero and the sequence never moved. The refresh then publishes a mapping of a page which has already been freed, and the next reader dereferences it:

  BUG: KASAN: use-after-free in kvm_xen_shared_info_init+0x3c6/0x440
  Read of size 4 at addr ffff8880599c2900 by task syz.2.383/7257

Since gfn_to_pfn_cache_invalidate_start() deliberately skips caches which are not currently valid (including one whose refresh is in progress, as the refresh clears the valid flag before dropping the lock), the retry check is the only line of defence, and it must fire for *any* invalidation, not just those hitting a memslot.

Add a dedicated kvm->gpc_invalidate_seq, incremented by every kvm_mmu_notifier_invalidate_range_end() under mn_invalidate_lock before mn_active_invalidate_count is decremented, and check it in hva_to_pfn_retry() instead of mmu_invalidate_seq. Incrementing in range_end() in the same critical section as the in-progress count also closes the variant where the cache is activated with the contested HVA only after invalidate_range_start() has run.

The same bug is also reachable through the per-vCPU vcpu_info cache (KVM_XEN_VCPU_ATTR_TYPE_VCPU_INFO_HVA), where the stale mapping is then dereferenced by kvm_setup_guest_pvclock() on the next KVM_RUN:

  BUG: KASAN: use-after-free in kvm_setup_guest_pvclock+0x5bf/0x660

This intentionally makes refresh retry on *unrelated* mmu notifier events; restoring precision (and reworking the GPC locking more generally) is left for a subsequent series.

Reproducers: https://david.woodhou.se/xen_shinfo_race.c
https://david.woodhou.se/vcpu_info_race.c

---
 include/linux/kvm_host.h |    2 ++
 virt/kvm/kvm_main.c      |   10 ++++++++++
 virt/kvm/pfncache.c      |   18 +++++++++---------
 3 files changed, 21 insertions(+), 9 deletions(-)
include/linux/kvm_host.h +2 -0
@@ -854,6 +854,8 @@ struct kvm {
 	gfn_t mmu_invalidate_range_start;
 	gfn_t mmu_invalidate_range_end;
 
+	unsigned long gpc_invalidate_seq;
+
 	struct list_head devices;
 	u64 manual_dirty_log_protect;
 	struct dentry *debugfs_dentry;
virt/kvm/kvm_main.c +10 -0
@@ -813,6 +813,16 @@ static void kvm_mmu_notifier_invalidate_
 
 	/* Pairs with the increment in range_start(). */
 	spin_lock(&kvm->mn_invalidate_lock);
+	kvm->gpc_invalidate_seq++;
+
+	/*
+	 * As with the MMU sequence counter and mmu_invalidate_in_progress, the
+	 * GPC sequence increase must be visible before the invalidate count
+	 * goes to zero.  Pairs with the smp_rmb() in
+	 * mmu_notifier_retry_cache().
+	 */
+	smp_wmb();
+
 	if (!WARN_ON_ONCE(!kvm->mn_active_invalidate_count))
 		--kvm->mn_active_invalidate_count;
 	wake = !kvm->mn_active_invalidate_count;
virt/kvm/pfncache.c +9 -9
@@ -124,7 +124,7 @@ static void gpc_unmap(kvm_pfn_t pfn, voi
 #endif
 }
 
-static inline bool mmu_notifier_retry_cache(struct kvm *kvm, unsigned long mmu_seq)
+static inline bool mmu_notifier_retry_cache(struct kvm *kvm, unsigned long gpc_seq)
 {
 	/*
 	 * mn_active_invalidate_count acts for all intents and purposes
@@ -136,20 +136,20 @@ static inline bool mmu_notifier_retry_ca
 	 * Note, it does not matter that mn_active_invalidate_count
 	 * is not protected by gpc->lock.  It is guaranteed to
 	 * be elevated before the mmu_notifier acquires gpc->lock, and
-	 * isn't dropped until after mmu_invalidate_seq is updated.
+	 * isn't dropped until after gpc_invalidate_seq is updated.
 	 */
 	if (kvm->mn_active_invalidate_count)
 		return true;
 
 	/*
 	 * Ensure mn_active_invalidate_count is read before
-	 * mmu_invalidate_seq.  This pairs with the smp_wmb() in
-	 * mmu_notifier_invalidate_range_end() to guarantee either the
+	 * gpc_invalidate_seq.  This pairs with the smp_wmb() in
+	 * kvm_mmu_notifier_invalidate_range_end() to guarantee either the
 	 * old (non-zero) value of mn_active_invalidate_count or the
-	 * new (incremented) value of mmu_invalidate_seq is observed.
+	 * new (incremented) value of gpc_invalidate_seq is observed.
 	 */
 	smp_rmb();
-	return kvm->mmu_invalidate_seq != mmu_seq;
+	return kvm->gpc_invalidate_seq != gpc_seq;
 }
 
 static kvm_pfn_t hva_to_pfn_retry(struct gfn_to_pfn_cache *gpc)
@@ -158,7 +158,7 @@ static kvm_pfn_t hva_to_pfn_retry(struct
 	void *old_khva = (void *)PAGE_ALIGN_DOWN((uintptr_t)gpc->khva);
 	kvm_pfn_t new_pfn = KVM_PFN_ERR_FAULT;
 	void *new_khva = NULL;
-	unsigned long mmu_seq;
+	unsigned long gpc_seq;
 	struct page *page;
 
 	struct kvm_follow_pfn kfp = {
@@ -181,7 +181,7 @@ static kvm_pfn_t hva_to_pfn_retry(struct
 	gpc->valid = false;
 
 	do {
-		mmu_seq = gpc->kvm->mmu_invalidate_seq;
+		gpc_seq = gpc->kvm->gpc_invalidate_seq;
 		smp_rmb();
 
 		write_unlock_irq(&gpc->lock);
@@ -232,7 +232,7 @@ static kvm_pfn_t hva_to_pfn_retry(struct
 		 * attempting to refresh.
 		 */
 		WARN_ON_ONCE(gpc->valid);
-	} while (mmu_notifier_retry_cache(gpc->kvm, mmu_seq));
+	} while (mmu_notifier_retry_cache(gpc->kvm, gpc_seq));
 
 	gpc->valid = true;
 	gpc->pfn = new_pfn;
author maintainer
#224 lore raw

PATCH 224/547 KVM: PPC: Book3S HV: Add SRCU protection for virtual-mode HPT hcalls

In reply to Greg Kroah-Hartman

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

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

From: Amit Machhiwal <[email protected]>

commit 61a39797bb136243c48b46e2586d8a9e2cea6a89 upstream.

The virtual-mode HPT hcall handlers (H_ENTER, H_REMOVE, H_BULK_REMOVE, H_CLEAR_REF, H_CLEAR_MOD) call into book3s_hv_rm_mmu.c, which accesses memslots via kvm_memslots_raw(). kvm_memslots_raw() uses rcu_dereference_raw_check() to bypass SRCU lockdep annotation checking. This is safe in real mode because the entire guest entry/exit is wrapped in srcu_read_lock/unlock inside kvmppc_run_core() and kvmhv_run_single_vcpu().

However, since commit 6165d5dd99db ("KVM: PPC: Book3S HV: add virtual mode handlers for HPT hcalls and page faults"), these same handlers are also executed in virtual mode via kvmppc_pseries_do_hcall(), which runs after SRCU has already been released on guest exit.

A concurrent KVM_SET_USER_MEMORY_REGION deletion or move can therefore call synchronize_srcu_expedited() — which does not wait for this thread — and then kfree(slot) and vfree(slot->arch.rmap) while the hcall handler still holds a raw pointer to the memslot. lock_rmap() then writes to freed vmalloc memory, leading to use-after-free and memory corruption. Because kvm_memslots_raw() suppresses lockdep checks, this race is entirely silent.

Fix this by factoring out the 7 HPT hcall handlers (H_REMOVE, H_ENTER, H_READ, H_CLEAR_MOD, H_CLEAR_REF, H_PROTECT, H_BULK_REMOVE) into a helper function, kvmppc_pseries_do_hpt_hcall(), and wrapping its call site in srcu_read_lock(&kvm->srcu) / srcu_read_unlock(&kvm->srcu, idx). Targeting only the HPT hcalls avoids wrapping non-HPT hcalls that sleep (such as H_CONFER, H_REGISTER_VPA, H_PAGE_INIT) or handlers that already acquire SRCU internally (such as H_RTAS).

Fixes 6165d5dd99db ("KVM: PPC: Book3S HV: add virtual mode handlers for HPT hcalls and page faults")
Cc [email protected] # v5.14+
---
 arch/powerpc/kvm/book3s_hv.c |   70 +++++++++++++++++++++----------------------
 1 file changed, 35 insertions(+), 35 deletions(-)
arch/powerpc/kvm/book3s_hv.c +35 -35
@@ -1159,6 +1159,38 @@ static long kvmppc_h_rpt_invalidate(stru
 	return H_SUCCESS;
 }
 
+static long kvmppc_pseries_do_hpt_hcall(struct kvm_vcpu *vcpu, unsigned long req)
+{
+	switch (req) {
+	case H_REMOVE:
+		return kvmppc_h_remove(vcpu, kvmppc_get_gpr(vcpu, 4),
+				       kvmppc_get_gpr(vcpu, 5),
+				       kvmppc_get_gpr(vcpu, 6));
+	case H_ENTER:
+		return kvmppc_h_enter(vcpu, kvmppc_get_gpr(vcpu, 4),
+				      kvmppc_get_gpr(vcpu, 5),
+				      kvmppc_get_gpr(vcpu, 6),
+				      kvmppc_get_gpr(vcpu, 7));
+	case H_READ:
+		return kvmppc_h_read(vcpu, kvmppc_get_gpr(vcpu, 4),
+				     kvmppc_get_gpr(vcpu, 5));
+	case H_CLEAR_MOD:
+		return kvmppc_h_clear_mod(vcpu, kvmppc_get_gpr(vcpu, 4),
+					  kvmppc_get_gpr(vcpu, 5));
+	case H_CLEAR_REF:
+		return kvmppc_h_clear_ref(vcpu, kvmppc_get_gpr(vcpu, 4),
+					  kvmppc_get_gpr(vcpu, 5));
+	case H_PROTECT:
+		return kvmppc_h_protect(vcpu, kvmppc_get_gpr(vcpu, 4),
+					kvmppc_get_gpr(vcpu, 5),
+					kvmppc_get_gpr(vcpu, 6));
+	case H_BULK_REMOVE:
+		return kvmppc_h_bulk_remove(vcpu);
+	}
+
+	return H_FUNCTION;
+}
+
 int kvmppc_pseries_do_hcall(struct kvm_vcpu *vcpu)
 {
 	struct kvm *kvm = vcpu->kvm;
@@ -1174,47 +1206,15 @@ int kvmppc_pseries_do_hcall(struct kvm_v
 
 	switch (req) {
 	case H_REMOVE:
-		ret = kvmppc_h_remove(vcpu, kvmppc_get_gpr(vcpu, 4),
-					kvmppc_get_gpr(vcpu, 5),
-					kvmppc_get_gpr(vcpu, 6));
-		if (ret == H_TOO_HARD)
-			return RESUME_HOST;
-		break;
 	case H_ENTER:
-		ret = kvmppc_h_enter(vcpu, kvmppc_get_gpr(vcpu, 4),
-					kvmppc_get_gpr(vcpu, 5),
-					kvmppc_get_gpr(vcpu, 6),
-					kvmppc_get_gpr(vcpu, 7));
-		if (ret == H_TOO_HARD)
-			return RESUME_HOST;
-		break;
 	case H_READ:
-		ret = kvmppc_h_read(vcpu, kvmppc_get_gpr(vcpu, 4),
-					kvmppc_get_gpr(vcpu, 5));
-		if (ret == H_TOO_HARD)
-			return RESUME_HOST;
-		break;
 	case H_CLEAR_MOD:
-		ret = kvmppc_h_clear_mod(vcpu, kvmppc_get_gpr(vcpu, 4),
-					kvmppc_get_gpr(vcpu, 5));
-		if (ret == H_TOO_HARD)
-			return RESUME_HOST;
-		break;
 	case H_CLEAR_REF:
-		ret = kvmppc_h_clear_ref(vcpu, kvmppc_get_gpr(vcpu, 4),
-					kvmppc_get_gpr(vcpu, 5));
-		if (ret == H_TOO_HARD)
-			return RESUME_HOST;
-		break;
 	case H_PROTECT:
-		ret = kvmppc_h_protect(vcpu, kvmppc_get_gpr(vcpu, 4),
-					kvmppc_get_gpr(vcpu, 5),
-					kvmppc_get_gpr(vcpu, 6));
-		if (ret == H_TOO_HARD)
-			return RESUME_HOST;
-		break;
 	case H_BULK_REMOVE:
-		ret = kvmppc_h_bulk_remove(vcpu);
+		idx = srcu_read_lock(&kvm->srcu);
+		ret = kvmppc_pseries_do_hpt_hcall(vcpu, req);
+		srcu_read_unlock(&kvm->srcu, idx);
 		if (ret == H_TOO_HARD)
 			return RESUME_HOST;
 		break;
author maintainer
#225 lore raw

PATCH 225/547 media: cx23885: unregister DVB bus when SP2 CI setup fails

In reply to Greg Kroah-Hartman

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

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

From: Myeonghun Pak <[email protected]>

commit 22f552ff726a82a086be4ef02ce5099a0e8624b6 upstream.

The DVBSKY S950C, DVBSKY T980C and TechnoTrend CT2-4500 CI paths register the DVB bus before attaching their SP2 CI client. If that client cannot be created, bound, or pinned, the current error path removes the I2C frontend components and only deallocates the frontend list, leaving the registered DVB adapter behind. Removing an I2C demod before unregistering the DVB bus can also expose the use-after-free ordering fixed for the normal remove path.

Unregister the DVB bus immediately when SP2 CI setup fails, before the existing I2C client cleanup. The bus helper empties the frontend list, so the later frontend deallocation has nothing left to release. Keep failures from vb2_dvb_register_bus() on the existing cleanup path. Also release an unbound SP2 client and propagate the actual I2C creation or CI registration error.

This issue was identified during our ongoing static-analysis research while reviewing kernel code.

Fixes 2b0aac3011bc ("[media] cx23885: move CI/MAC registration to a separate function")
Assisted-by OpenAI:GPT-5.6
---
 drivers/media/pci/cx23885/cx23885-dvb.c |   14 ++++++++++----
 1 file changed, 10 insertions(+), 4 deletions(-)
drivers/media/pci/cx23885/cx23885-dvb.c +10 -4
@@ -1158,8 +1158,12 @@ static int dvb_register_ci_mac(struct cx
 		info.platform_data = &sp2_config;
 		request_module(info.type);
 		client_ci = i2c_new_client_device(&i2c_bus->i2c_adap, &info);
-		if (!i2c_client_has_driver(client_ci))
+		if (IS_ERR(client_ci))
+			return PTR_ERR(client_ci);
+		if (!client_ci->dev.driver) {
+			i2c_unregister_device(client_ci);
 			return -ENODEV;
+		}
 		if (!try_module_get(client_ci->dev.driver->owner)) {
 			i2c_unregister_device(client_ci);
 			return -ENODEV;
@@ -1202,7 +1206,7 @@ static int dvb_register(struct cx23885_t
 	int (*p_set_voltage)(struct dvb_frontend *fe,
 			     enum fe_sec_voltage voltage) = NULL;
 	int mfe_shared = 0; /* bus not shared by default */
-	int ret;
+	int ret = -EINVAL;
 
 	/* Get the first frontend */
 	fe0 = vb2_dvb_get_frontend(&port->frontends, 1);
@@ -2586,8 +2590,10 @@ static int dvb_register(struct cx23885_t
 		goto frontend_detach;
 
 	ret = dvb_register_ci_mac(port);
-	if (ret)
+	if (ret) {
+		vb2_dvb_unregister_bus(&port->frontends);
 		goto frontend_detach;
+	}
 
 	return 0;
 
@@ -2618,7 +2624,7 @@ frontend_detach:
 
 	port->gate_ctrl = NULL;
 	vb2_dvb_dealloc_frontends(&port->frontends);
-	return -EINVAL;
+	return ret;
 }
 
 int cx23885_dvb_register(struct cx23885_tsport *port)
author maintainer
#226 lore raw

PATCH 226/547 media: gspca: use vb2_video_unregister_device() on disconnect

In reply to Greg Kroah-Hartman

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

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

From: Shuangpeng Bai <[email protected]>

commit 3dbbbc3cafa2de377d9b97af4e35b8b6b5282047 upstream.

gspca uses vb2_fop_release(), but gspca_disconnect() only unregisters the video device. If the queue owner closes the device after USB disconnect, vb2_fop_release() releases the queue and invokes gspca_stop_streaming() at that point.

gspca_stream_off() calls subdriver stop callbacks and usb_set_interface() through gspca_dev->dev. By the time the late close runs, the USB core can have freed the usb_device, resulting in a use-after-free. This was observed as a KASAN use-after-free in sd_stopN().

Use vb2_video_unregister_device() so the queue is released and streaming is stopped synchronously during disconnect, while the usb_device is still valid. Since the helper takes the queue lock, which is usb_lock, call it after dropping that lock.

Fixes f729ef5796d8 ("media: videobuf2-v4l2.c: add vb2_video_unregister_device helper function")
Cc [email protected] # 5.10.x
---
 drivers/media/usb/gspca/gspca.c |    3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
drivers/media/usb/gspca/gspca.c +1 -2
@@ -1636,9 +1636,8 @@ void gspca_disconnect(struct usb_interfa
 #endif
 
 	v4l2_device_disconnect(&gspca_dev->v4l2_dev);
-	video_unregister_device(&gspca_dev->vdev);
-
 	mutex_unlock(&gspca_dev->usb_lock);
+	vb2_video_unregister_device(&gspca_dev->vdev);
 
 	/* (this will call gspca_release() immediately or on last close) */
 	v4l2_device_put(&gspca_dev->v4l2_dev);
author maintainer
#227 lore raw

PATCH 227/547 media: imx-jpeg: cancel timeout worker when streaming stops

In reply to Greg Kroah-Hartman

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

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

From: Fan Wu <[email protected]>

commit 78fdfbf117c409273eecbfa7a528ef42358a0e38 upstream.

Each per-fd context ctx owns a delayed_work (ctx->task_timer, callback mxc_jpeg_device_run_timeout) armed via schedule_delayed_work() at the end of mxc_jpeg_device_run() to recover a stalled encode/decode job. The only existing cancellation is cancel_delayed_work() in the frame-done IRQ handler, which de-queues a pending work item but does not wait for a callback that has already started, and it only runs when a frame completes.

When the fd is closed while a job is in flight (the frame-done IRQ has not fired yet), nothing syncs the worker before mxc_jpeg_release() frees ctx with kfree() after v4l2_m2m_ctx_release(). A queued or executing mxc_jpeg_device_run_timeout() can then recover ctx through container_of(&ctx->task_timer) and dereference it (ctx->mxc_jpeg, slot_data, dev_warn) after ctx has been freed.

Cancel the worker from mxc_jpeg_stop_streaming(). The cancel cannot live in mxc_jpeg_release(): mxc_jpeg_device_run() arms the timer while holding only hw_lock, not the mxc_jpeg->lock mutex that release holds, so a cancel in release could still race a concurrent mxc_jpeg_device_run() that re-arms the timer afterwards. mxc_jpeg_stop_streaming() instead runs inside v4l2_m2m_ctx_release() -> vb2_queue_release(), i.e. after v4l2_m2m_cancel_job() has set TRANS_ABORT and waited for any in-flight job to finish (so __v4l2_m2m_try_queue() will not queue and v4l2_m2m_try_run() will not run any further job for this context, which prevents mxc_jpeg_device_run() from re-arming the timer) and before the m2m context is freed. cancel_delayed_work_sync() removes a pending work item and waits for a running callback, so the worker can no longer race with the subsequent kfree(). The cancel is placed before the buffer-release loop so a concurrently running timeout callback cannot race with it over the same buffers. If the frame-done IRQ canceled a still-pending timer, this cancel is a no-op; if the timeout callback has already started, it waits for the callback to finish. The same mxc_jpeg_stop_streaming() call is also reached from VIDIOC_STREAMOFF, which drains the worker early, although STREAMOFF itself does not free ctx -- the use-after-free arises only when the fd is later closed.

This bug was found by static analysis.

Fixes cfed9632ca8e ("media: imx-jpeg: Add a timeout mechanism for each frame")
---
 drivers/media/platform/nxp/imx-jpeg/mxc-jpeg.c |    2 ++
 1 file changed, 2 insertions(+)
drivers/media/platform/nxp/imx-jpeg/mxc-jpeg.c +2 -0
@@ -1798,6 +1798,8 @@ static void mxc_jpeg_stop_streaming(stru
 
 	dev_dbg(ctx->mxc_jpeg->dev, "Stop streaming ctx=%p", ctx);
 
+	cancel_delayed_work_sync(&ctx->task_timer);
+
 	/* Release all active buffers */
 	for (;;) {
 		if (V4L2_TYPE_IS_OUTPUT(q->type))
author maintainer
#228 lore raw

PATCH 228/547 media: marvell: mcam: stop DMA and cancel s_bh_work before freeing DMA buffers

In reply to Greg Kroah-Hartman

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

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

From: Fan Wu <[email protected]>

commit 0f29f84317c1e35f6a9265277be33e60d3fc8c1c upstream.

In vmalloc mode the frame-completion IRQ queues mcam_frame_work() on cam->s_bh_work, which memcpy()s from the dma_bufs[] that mcam_free_dma_bufs() frees with dma_free_coherent(). mccic_shutdown() frees those buffers without stopping the controller, so while streaming a late frame IRQ can re-arm the work after the buffers are gone, causing a use-after-free.

Stop the controller in mccic_shutdown() when streaming is still active (gated on an open fd, which holds a runtime-PM reference, so the device is powered), cancel s_bh_work in mcam_free_dma_bufs(), and move INIT_WORK() into mccic_register() before the device can be published.

Fixes 67a8dbbc4e04 ("[media] marvell-cam: Basic working MMP camera driver")
---
 drivers/media/platform/marvell/mcam-core.c |   14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)
drivers/media/platform/marvell/mcam-core.c +13 -1
@@ -406,6 +406,8 @@ static void mcam_free_dma_bufs(struct mc
 {
 	int i;
 
+	cancel_work_sync(&cam->s_bh_work);
+
 	for (i = 0; i < cam->nbufs; i++) {
 		dma_free_coherent(cam->dev, cam->dma_buf_size,
 				cam->dma_bufs[i], cam->dma_handles[i]);
@@ -1306,7 +1308,6 @@ static int mcam_setup_vb2(struct mcam_ca
 		break;
 	case B_vmalloc:
 #ifdef MCAM_MODE_VMALLOC
-		INIT_WORK(&cam->s_bh_work, mcam_frame_work);
 		vq->ops = &mcam_vb2_ops;
 		vq->mem_ops = &vb2_vmalloc_memops;
 		cam->dma_setup = mcam_ctlr_dma_vmalloc;
@@ -1864,6 +1865,12 @@ int mccic_register(struct mcam_camera *c
 		goto out;
 	}
 
+#ifdef MCAM_MODE_VMALLOC
+	/* Init before sensor bind: armed by IRQ, cancelled on probe-error paths. */
+	if (cam->buffer_mode == B_vmalloc)
+		INIT_WORK(&cam->s_bh_work, mcam_frame_work);
+#endif
+
 	mutex_init(&cam->s_mutex);
 	cam->state = S_NOTREADY;
 	mcam_set_config_needed(cam, 1);
@@ -1922,10 +1929,15 @@ void mccic_shutdown(struct mcam_camera *
 	 * take it down again will wedge the machine, which is frowned
 	 * upon.
 	 */
+	mutex_lock(&cam->s_mutex);
 	if (!list_empty(&cam->vdev.fh_list)) {
 		cam_warn(cam, "Removing a device with users!\n");
+		/* Stop so the IRQ can't re-arm s_bh_work after the buffers are freed. */
+		if (cam->state == S_STREAMING)
+			mcam_ctlr_stop_dma(cam);
 		sensor_call(cam, core, s_power, 0);
 	}
+	mutex_unlock(&cam->s_mutex);
 	if (cam->buffer_mode == B_vmalloc)
 		mcam_free_dma_bufs(cam);
 	v4l2_ctrl_handler_free(&cam->ctrl_handler);
author maintainer
#229 lore raw

PATCH 229/547 media: microchip-csi2dc: fix async notifier leak on probe error path

In reply to Greg Kroah-Hartman

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

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

From: Cong Nguyen <[email protected]>

commit c7528789244ce7329ca883170fb9315d739ae985 upstream.

csi2dc_of_parse() ends up calling csi2dc_prepare_notifier(), which registers the V4L2 async notifier with v4l2_async_nf_register(). The probe error label csi2dc_probe_cleanup_notifier is reached after csi2dc_of_parse() has already succeeded (e.g. when media entity init, csi2dc_power() or v4l2_async_register_subdev() fail), but it calls only v4l2_async_nf_cleanup() and never v4l2_async_nf_unregister().

The notifier therefore stays chained in the global notifier_list while the enclosing struct csi2dc_device is freed, leading to list corruption and a use-after-free when the list is next walked.

Unregister the notifier before cleaning it up on the error path, matching the teardown already done in csi2dc_remove().

Fixes 2de0b3c0f678 ("media: atmel: introduce microchip csi2dc driver")
Assisted-by Claude:claude-opus-4
---
 drivers/media/platform/microchip/microchip-csi2dc.c |    1 +
 1 file changed, 1 insertion(+)
drivers/media/platform/microchip/microchip-csi2dc.c +1 -0
@@ -735,6 +735,7 @@ static int csi2dc_probe(struct platform_
 	return 0;
 
 csi2dc_probe_cleanup_notifier:
+	v4l2_async_nf_unregister(&csi2dc->notifier);
 	v4l2_async_nf_cleanup(&csi2dc->notifier);
 csi2dc_probe_cleanup_entity:
 	media_entity_cleanup(&csi2dc->csi2dc_sd.entity);
author maintainer
#230 lore raw

PATCH 230/547 media: microchip-isc: take a reference on the parsed endpoints

In reply to Greg Kroah-Hartman

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

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

From: Balakrishnan Sambath <[email protected]>

commit f2eb2fd388bf3f1959556a326e797cacca341c86 upstream.

for_each_endpoint_of_node() drops the reference on the current node as it advances. xisc_parse_dt() and isc_parse_dt() store the node in subdev_entity->epn and release it later with of_node_put(), but never took their own reference, so the stored pointer refers to an already-released node. This underflows the refcount and can use-after-free, reachable through the camera device tree overlay.

Take a reference with of_node_get() when storing the node, and drop it in microchip_isc_subdev_cleanup() so the entities the bind loop never reaches on an early exit do not leak it.

Fixes c9aa973884a1 ("media: atmel: atmel-isc: add microchip-xisc driver")
Fixes d6701f13bd07 ("media: atmel: Use v4l2_async_notifier_add_fwnode_remote_subdev")
---
 drivers/media/platform/microchip/microchip-isc-base.c    |    6 +++++
 drivers/media/platform/microchip/microchip-sama5d2-isc.c |   17 ++++++++++-----
 drivers/media/platform/microchip/microchip-sama7g5-isc.c |   17 ++++++++++-----
 3 files changed, 30 insertions(+), 10 deletions(-)
drivers/media/platform/microchip/microchip-isc-base.c +6 -0
@@ -1860,6 +1860,12 @@ void microchip_isc_subdev_cleanup(struct
 	list_for_each_entry(subdev_entity, &isc->subdev_entities, list) {
 		v4l2_async_nf_unregister(&subdev_entity->notifier);
 		v4l2_async_nf_cleanup(&subdev_entity->notifier);
+		/*
+		 * Release the endpoint reference taken while parsing. It is
+		 * NULL for entities the bind loop already consumed, so this
+		 * only drops the ones left over on an early exit.
+		 */
+		of_node_put(subdev_entity->epn);
 	}
 
 	INIT_LIST_HEAD(&isc->subdev_entities);
drivers/media/platform/microchip/microchip-sama5d2-isc.c +12 -5
@@ -356,28 +356,30 @@ static int isc_parse_dt(struct device *d
 	struct device_node *epn;
 	struct isc_subdev_entity *subdev_entity;
 	unsigned int flags;
+	int ret;
 
 	INIT_LIST_HEAD(&isc->subdev_entities);
 
 	for_each_endpoint_of_node(np, epn) {
 		struct v4l2_fwnode_endpoint v4l2_epn = { .bus_type = 0 };
-		int ret;
 
 		ret = v4l2_fwnode_endpoint_parse(of_fwnode_handle(epn),
 						 &v4l2_epn);
 		if (ret) {
-			of_node_put(epn);
 			dev_err(dev, "Could not parse the endpoint\n");
-			return -EINVAL;
+			of_node_put(epn);
+			ret = -EINVAL;
+			goto err_cleanup;
 		}
 
 		subdev_entity = devm_kzalloc(dev, sizeof(*subdev_entity),
 					     GFP_KERNEL);
 		if (!subdev_entity) {
 			of_node_put(epn);
-			return -ENOMEM;
+			ret = -ENOMEM;
+			goto err_cleanup;
 		}
-		subdev_entity->epn = epn;
+		subdev_entity->epn = of_node_get(epn);
 
 		flags = v4l2_epn.bus.parallel.flags;
 
@@ -398,6 +400,11 @@ static int isc_parse_dt(struct device *d
 	}
 
 	return 0;
+
+err_cleanup:
+	list_for_each_entry(subdev_entity, &isc->subdev_entities, list)
+		of_node_put(subdev_entity->epn);
+	return ret;
 }
 
 static int microchip_isc_probe(struct platform_device *pdev)
drivers/media/platform/microchip/microchip-sama7g5-isc.c +12 -5
@@ -340,6 +340,7 @@ static int xisc_parse_dt(struct device *
 	struct isc_subdev_entity *subdev_entity;
 	unsigned int flags;
 	bool mipi_mode;
+	int ret;
 
 	INIT_LIST_HEAD(&isc->subdev_entities);
 
@@ -347,23 +348,24 @@ static int xisc_parse_dt(struct device *
 
 	for_each_endpoint_of_node(np, epn) {
 		struct v4l2_fwnode_endpoint v4l2_epn = { .bus_type = 0 };
-		int ret;
 
 		ret = v4l2_fwnode_endpoint_parse(of_fwnode_handle(epn),
 						 &v4l2_epn);
 		if (ret) {
-			of_node_put(epn);
 			dev_err(dev, "Could not parse the endpoint\n");
-			return -EINVAL;
+			of_node_put(epn);
+			ret = -EINVAL;
+			goto err_cleanup;
 		}
 
 		subdev_entity = devm_kzalloc(dev, sizeof(*subdev_entity),
 					     GFP_KERNEL);
 		if (!subdev_entity) {
 			of_node_put(epn);
-			return -ENOMEM;
+			ret = -ENOMEM;
+			goto err_cleanup;
 		}
-		subdev_entity->epn = epn;
+		subdev_entity->epn = of_node_get(epn);
 
 		flags = v4l2_epn.bus.parallel.flags;
 
@@ -387,6 +389,11 @@ static int xisc_parse_dt(struct device *
 	}
 
 	return 0;
+
+err_cleanup:
+	list_for_each_entry(subdev_entity, &isc->subdev_entities, list)
+		of_node_put(subdev_entity->epn);
+	return ret;
 }
 
 static int microchip_xisc_probe(struct platform_device *pdev)
author maintainer
#231 lore raw

PATCH 231/547 media: redrat3: fix UAF in probe error path leaving rc device registered

In reply to Greg Kroah-Hartman

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

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

From: Rik van Riel <[email protected]>

commit af452b9e01331b5338a1e5141624f17607239207 upstream.

redrat3 stores its device name and phys path inside the main rr3 structure, and the rc device's device_name and input_phys point into rr3. When the RC device is registered, it keeps those pointers.

  KASAN: slab-use-after-free in string_nocheck lib/vsprintf.c:648
  Read of size 1 at addr ffff888051fda758 by task udevd/7464
  Call Trace:
   string_nocheck lib/vsprintf.c:648 [inline]
   string+0x216/0x2d0 lib/vsprintf.c:730
   vsnprintf+0x74a/0xef0 lib/vsprintf.c:2945
   vscnprintf+0x41/0x90 lib/vsprintf.c:3014
   sysfs_emit+0x10e/0x180 fs/sysfs/file.c:761
   input_dev_show_name+0x58/0x70 drivers/input/input.c:1282

  Allocated by task 10:
   redrat3_dev_probe+0x477/0x2570 drivers/media/rc/redrat3.c:1023
  Freed by task 10:
   redrat3_delete drivers/media/rc/redrat3.c:466 [inline]
   redrat3_dev_probe+0x1bf4/0x2570 drivers/media/rc/redrat3.c:1124

Syzkaller triggers this via usb probing. It probes the RedRat3 USB interface, which calls redrat3_dev_probe() in redrat3.c. That function allocates rr3, then builds an rc device whose name points into rr3 via redrat3_init_rc_dev() in redrat3.c, and registers it with rc_register_device().

When the detector enable fails after the RC device is registered, the probe jumps to the led_free path. That path unregisters the LED but does not unregister the RC device before freeing rr3 via redrat3_delete() in redrat3.c. The RC device still holds device_name = rr3->name which is now freed.

Later udevd reads /sys/.../input device name via sysfs_emit() in file.c, which calls input_dev_show_name() in input.c, which emits dev->name which is the freed rr3->name.

When the detector enable fails after the RC device is registered, the error path must not leave the RC device registered. Make the probe error path clean up the same way redrat3_dev_disconnect() does.

This change should be safe because the RC device is fully registered at this point and its teardown via rc_unregister_device() is protected by the input device mutex, and rr3 is still alive during unregister so device_name remains valid until after unregister. The URBs are killed before rc_free, so no completion can run after rc is freed. No new lock ordering is introduced.

Reported-by [email protected]
Fixes 2154be651b90 ("[media] redrat3: new rc-core IR transceiver device driver")
Assisted-by Hermes:muse-spark-1.2 syzkaller
---
 drivers/media/rc/redrat3.c |    4 ++++
 1 file changed, 4 insertions(+)
drivers/media/rc/redrat3.c +4 -0
@@ -975,6 +975,7 @@ static int redrat3_dev_probe(struct usb_
 	struct device *dev = &intf->dev;
 	struct usb_host_interface *uhi;
 	struct redrat3_dev *rr3;
+	struct rc_dev *rc;
 	struct usb_endpoint_descriptor *ep;
 	struct usb_endpoint_descriptor *ep_narrow = NULL;
 	struct usb_endpoint_descriptor *ep_wide = NULL;
@@ -1119,9 +1120,12 @@ static int redrat3_dev_probe(struct usb_
 	return 0;
 
 led_free:
+	rc_unregister_device(rr3->rc);
 	led_classdev_unregister(&rr3->led);
 redrat_free:
+	rc = rr3->rc;
 	redrat3_delete(rr3, rr3->udev);
+	rc_free_device(rc);
 
 no_endpoints:
 	return retval;
author maintainer
#232 lore raw

PATCH 232/547 media: s5p-mfc: use timer_shutdown_sync() for the self-rearming watchdog

In reply to Greg Kroah-Hartman

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

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

From: Fan Wu <[email protected]>

commit 63069b5917cba2e15b1a78b3f4ff99e45102c56f upstream.

The MFC watchdog timer (s5p_mfc_watchdog) is self-rearming: every callback re-arms itself with add_timer() and, on a timeout, schedules watchdog_work. s5p_mfc_remove() tears this down with timer_delete_sync() followed by flush_work().

timer_delete_sync() dequeues the timer and waits for a callback that is already running, but it does not prevent a subsequent re-arm. Because the watchdog callback re-arms via add_timer(), this is the wrong shutdown
primitive: once the wait returns nothing guarantees a just-queued re-arm will not fire later, dereferencing dev (clock on/off, deinit_hw, load_firmware, init_hw) after video_unregister_device(), DMA teardown and s5p_mfc_final_pm() have run, a potential use-after-free.

Use timer_shutdown_sync(), which puts the timer into a shutdown state so that any add_timer()/mod_timer() from the callback becomes a no-op and no later firing is possible. Switch flush_work() to cancel_work_sync() so any watchdog_work that was already queued before the timer was stopped is cancelled rather than allowed to run to completion against the torn-down device.

This issue was found by an in-house static analysis tool. No runtime reproducer is available.

Fixes af9357467810 ("[media] MFC: Add MFC 5.1 V4L2 driver")
Cc Andrzej Hajda <[email protected]>
Assisted-by Codex:gpt-5.6
---
 drivers/media/platform/samsung/s5p-mfc/s5p_mfc.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/media/platform/samsung/s5p-mfc/s5p_mfc.c +2 -2
@@ -1474,8 +1474,8 @@ static void s5p_mfc_remove(struct platfo
 	}
 	mutex_unlock(&dev->mfc_mutex);
 
-	timer_delete_sync(&dev->watchdog_timer);
-	flush_work(&dev->watchdog_work);
+	timer_shutdown_sync(&dev->watchdog_timer);
+	cancel_work_sync(&dev->watchdog_work);
 
 	video_unregister_device(dev->vfd_enc);
 	video_unregister_device(dev->vfd_dec);
author maintainer
#233 lore raw

PATCH 233/547 mm/rmap: dont discard lazyfree THPs at PMD level

In reply to Greg Kroah-Hartman

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

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

From: Zi Yan <[email protected]>

commit 984c0700854e35779a2bcce6b02783e709b6efa2 upstream.

__discard_anon_folio_pmd_locked() clears a lazyfree THP's PMD before it determines whether the folio can be discarded, and restores it if the folio is dirty or has extra references. It is done under only the PMD lock and the anon_vma read lock inside try_to_unmap_one() and no mmap lock is held. The temporarily none PMD causes UAF.

A parallel munmap() or mremap() is supposed to serialize with it on the PMD lock, but zap_pmd_range() (called by munmap()) and move_page_tables() (called by mremap()) do not take the lock when they see the temporarily none PMD and skip the PMD. There is no more page table walk after the none PMD is restored:

- munmap(): free_pgtables() waits in unlink_anon_vmas() for the anon_vma lock, then free_pmd_range() drops the restored PMD as bad without removing the rmap, so the folio keeps a stale mapcount.

- whole-VMA MREMAP_DONTUNMAP: dontunmap_complete() unlinks the source VMA from its anon_vma while the restored PMD still maps the folio.

- plain mremap(): the THP is not moved but unmapped, so the THP's data is lost.

In the first two cases, the folio stays mapped, but no VMA that maps it is linked to its anon_vma. When the anon_vma is freed, it is still reachable when one rmap walks the folio. Racing lazyfree reclaim against MREMAP_DONTUNMAP as an unprivileged user reproduces a KASAN use-after-free in folio_lock_anon_vma_read() as reported in the Closes link.

One solution is to use an invalidated PMD instead of a cleared one until the discard is committed, but it needs arch fixes first.
1. GUP-fast still follows an invalidated PMD on riscv, LoongArch and s390.
2. sparc64 miscounts thp_pte_count when an invalidated PMD is set again or cleared.

To keep the fix simple for backport, stop discarding lazyfree THPs at PMD level instead. try_to_unmap_one() splits the PMD and discards the folio at PTE level.

unmap_huge_pmd_locked() and __discard_anon_folio_pmd_locked() are left in place, unused, to minimize this fix for backport and the invalidated PMD approach is planned as a follow-up series to use them again.

---
 mm/rmap.c |   11 -----------
 1 file changed, 11 deletions(-)
mm/rmap.c +0 -11
@@ -2275,17 +2275,6 @@ static bool try_to_unmap_one(struct foli
 		}
 
 		if (!pvmw.pte) {
-			if (folio_test_lazyfree(folio)) {
-				if (unmap_huge_pmd_locked(vma, pvmw.address, pvmw.pmd, folio))
-					goto walk_done;
-				/*
-				 * unmap_huge_pmd_locked has either already marked
-				 * the folio as swap-backed or decided to retain it
-				 * due to GUP or speculative references.
-				 */
-				goto walk_abort;
-			}
-
 			if (flags & TTU_SPLIT_HUGE_PMD) {
 				/*
 				 * We temporarily have to drop the PTL and
author maintainer
#234 lore raw

PATCH 234/547 mm/slab: sample slab_state once in kmem_cache_destroy()

In reply to Greg Kroah-Hartman

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

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

From: Imre Kaloz <[email protected]>

commit 088bfdc0d7947d623f4899b9011c866e4445074d upstream.

kmem_cache_release() tests slab_state >= FULL after kmem_cache_destroy() has dropped slab_mutex and unlinked the cache, and for a SLAB_TYPESAFE_BY_RCU cache after rcu_barrier(). If slab_late_init() runs before that test it sets slab_state to FULL but skips the unlinked cache, which never got a sysfs entry, so sysfs_slab_release() calls kobject_put() on a kobject that was never initialized:

  WARNING: lib/kobject.c:734 at kobject_put+0x64/0x2c0, CPU#1: kworker/u8:3/55
  kobject: '(null)' ((____ptrval____)): is not initialized, yet kobject_put() is being called.
  refcount_t: underflow; use-after-free.
  kobject_put+0x64/0x2c0
  sysfs_slab_release+0xc/0x20
  kmem_cache_destroy+0x104/0x1e0
  bioset_exit+0x13c/0x1e0
  disk_release+0x54/0x140
  put_disk+0x18/0x40
  floppy_async_init+0xbec/0xd10

slab_state >= FULL asks whether the cache has a kobject, which cache creation skips while slab_state <= UP. UP is the state just below FULL, so a false sample cannot skip a kobject_put() that was owed.

Seen on sparc64 at boot, where the asynchronous floppy init tears down its bio slab while the late initcalls are running.

Sample slab_state once, under slab_mutex which slab_late_init() holds when it sets FULL, and use the result for both the unlink and the release.

The history of this problem dates back to v3.2:

Commit 69cb8e6b7c29 ("slub: free slabs without holding locks") in v3.2 moved sysfs_slab_remove() outside slub_lock and introduced a race condition between kmem_cache_destroy() and slab_sysfs_init().

Commit 945cf2b6199be ("mm/sl[aou]b: Extract a common function for kmem_cache_destroy") in v3.7 accidentally closed the race while extracting a common implementation for kmem_cache_destroy().

Commit 5413dfba88d6 ("slub: drop mutex before deleting sysfs entry") in v3.8 re-opened the race by dropping slab_mutex around sysfs_slab_remove() in __kmem_cache_shutdown(), to avoid a lockdep splat between slab_mutex and the sysfs lock.

Commit 657dc2f97220 ("slab: remove synchronous rcu_barrier() call in memcg cache release path") in v4.11 shifted from synchronous rcu_barrier() to asynchronous RCU work for SLAB_TYPESAFE_BY_RCU caches. That commit, again, accidentally closed the race by moving sysfs_slab_release() to shutdown_cache(), but only for !SLAB_TYPESAFE_BY_RCU caches because destruction of SLAB_TYPESAFE_BY_RCU caches is done in an RCU work.

Commit 0495e337b703 ("mm/slab_common: Deleting kobject in kmem_cache_destroy() without holding slab_mutex/cpu_hotplug_lock") in v6.0 re-introduced the race for !SLAB_TYPESAFE_BY_RCU caches.

Fixes 69cb8e6b7c29 ("slub: free slabs without holding locks")
Fixes 5413dfba88d6 ("slub: drop mutex before deleting sysfs entry")
Fixes 0495e337b703 ("mm/slab_common: Deleting kobject in kmem_cache_destroy() without holding slab_mutex/cpu_hotplug_lock")
---
 mm/slab_common.c |   17 +++++++++++++----
 1 file changed, 13 insertions(+), 4 deletions(-)
mm/slab_common.c +13 -4
@@ -515,10 +515,10 @@ EXPORT_SYMBOL(kmem_buckets_create);
  * and release of the kobject does not need slab_mutex or cpu_hotplug_lock
  * protection. So they are now done without holding those locks.
  */
-static void kmem_cache_release(struct kmem_cache *s)
+static void kmem_cache_release(struct kmem_cache *s, bool sysfs_ready)
 {
 	kfence_shutdown_cache(s);
-	if (__is_defined(SLAB_SUPPORTS_SYSFS) && slab_state >= FULL)
+	if (__is_defined(SLAB_SUPPORTS_SYSFS) && sysfs_ready)
 		sysfs_slab_release(s);
 	else
 		slab_kmem_cache_release(s);
@@ -533,6 +533,7 @@ void slab_kmem_cache_release(struct kmem
 
 void kmem_cache_destroy(struct kmem_cache *s)
 {
+	bool sysfs_ready;
 	int err;
 
 	if (unlikely(!s) || !kasan_check_byte(s))
@@ -580,10 +581,18 @@ void kmem_cache_destroy(struct kmem_cach
 
 	list_del(&s->list);
 
+	/*
+	 * slab_late_init() sets slab_state to FULL under slab_mutex and adds
+	 * sysfs entries only for caches still on the list. Sample the state
+	 * here, so that a cache unlinked before that point is not handed to
+	 * sysfs_slab_release() with an uninitialized kobject.
+	 */
+	sysfs_ready = slab_state >= FULL;
+
 	mutex_unlock(&slab_mutex);
 	cpus_read_unlock();
 
-	if (slab_state >= FULL)
+	if (sysfs_ready)
 		sysfs_slab_unlink(s);
 	debugfs_slab_release(s);
 
@@ -593,7 +602,7 @@ void kmem_cache_destroy(struct kmem_cach
 	if (s->flags & SLAB_TYPESAFE_BY_RCU)
 		rcu_barrier();
 
-	kmem_cache_release(s);
+	kmem_cache_release(s, sysfs_ready);
 }
 EXPORT_SYMBOL(kmem_cache_destroy);
 
author maintainer
#235 lore raw

PATCH 235/547 mm/truncate: look up the end-edge straddler by index

In reply to Greg Kroah-Hartman

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

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

From: Zhang Yi <[email protected]>

commit f47dee903b9f0f1e4e7181e8a398a7678cabf0a5 upstream.

In truncate_inode_partial_folio(), after the first split at the start edge, folio_split() unlocks and drops the refcount of the after-split sub-folios. The sub-folio straddling the end of the truncation range is therefore unlocked and only transiently ref'd in the page cache while the code still derives it from a page pointer inside the original folio.

Between the first split finishing and page_folio() resolving split_at2, that tail page can be reclaimed, freed and reallocated as a new large folio in the same mapping at a different file offset. folio2 then points at a folio that does not cover the end boundary, yet folio2->mapping == folio->mapping still holds, so the stale pointer passes the mapping check and folio_split_or_unmap() splits a folio at a wrong position (or, with a transient refcount, a use-after-free window opens between try_get and the split). __folio_split()'s own folio != page_folio(split_at) check cannot catch this either since split_at2 has been reallocated as part of the new folio, so page_folio(split_at2) resolves back to folio2.

Look the straddler up by its page index instead. __filemap_get_folio() returns the folio currently covering the boundary, ref'd and locked, with the mapping validated under the lock, so the split target is always the real folio at the end edge.

---
 mm/truncate.c |   30 ++++++++++++++++--------------
 1 file changed, 16 insertions(+), 14 deletions(-)
mm/truncate.c +16 -14
@@ -259,30 +259,32 @@ bool truncate_inode_partial_folio(struct
 		 * for shmem truncate
 		 */
 		struct folio *folio2;
+		pgoff_t end_idx;
 
 		if (offset + length == size)
 			goto no_split;
 
-		split_at2 = folio_page(folio,
-				PAGE_ALIGN_DOWN(offset + length) / PAGE_SIZE);
-		folio2 = page_folio(split_at2);
-
-		if (!folio_try_get(folio2))
+		/*
+		 * After the first split at the start edge, the folio at the
+		 * end edge may be freed and reused concurrently.
+		 * __filemap_get_folio() looks up the straddler at end_idx
+		 * and returns it locked and ref'd with the mapping
+		 * validated.
+		 */
+		end_idx = (pos + offset + length) >> PAGE_SHIFT;
+		folio2 = __filemap_get_folio(folio->mapping, end_idx,
+					     FGP_LOCK | FGP_NOWAIT, 0);
+		if (IS_ERR(folio2))
 			goto no_split;
 
+		/* make sure folio2 is large */
 		if (!folio_test_large(folio2))
 			goto out;
 
-		if (!folio_trylock(folio2))
-			goto out;
-
-		/* make sure folio2 is large and does not change its mapping */
-		if (folio_test_large(folio2) &&
-		    folio2->mapping == folio->mapping)
-			folio_split_or_unmap(folio2, split_at2, min_order);
-
-		folio_unlock(folio2);
+		split_at2 = folio_page(folio2, (end_idx - folio2->index));
+		folio_split_or_unmap(folio2, split_at2, min_order);
 out:
+		folio_unlock(folio2);
 		folio_put(folio2);
 no_split:
 		return true;
author maintainer
#236 lore raw

PATCH 236/547 mm: khugepaged: fix folio is used after folio_put/unlock()

In reply to Greg Kroah-Hartman

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

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

From: Vernon Yang <[email protected]>

commit 9010383e71e6ce75fcd3c8f87133c8ce6c0e6ab4 upstream.

On the rollback path, folio_put() has already dropped the last reference of new_folio. On the success path, new_folio is already unlocked and can be freed concurrently. The trace_mm_khugepaged_collapse_file() is left with a dangling folio pointer.

So using the folio_pfn() before dropping the reference, closing use-after-free window.

---
 include/trace/events/huge_memory.h |    6 +++---
 mm/khugepaged.c                    |    4 +++-
 2 files changed, 6 insertions(+), 4 deletions(-)
include/trace/events/huge_memory.h +3 -3
@@ -211,10 +211,10 @@ TRACE_EVENT(mm_khugepaged_scan_file,
 );
 
 TRACE_EVENT(mm_khugepaged_collapse_file,
-	TP_PROTO(struct mm_struct *mm, struct folio *new_folio, pgoff_t index,
+	TP_PROTO(struct mm_struct *mm, unsigned long new_pfn, pgoff_t index,
 			unsigned long addr, bool is_shmem, struct file *file,
 			int nr, int result),
-	TP_ARGS(mm, new_folio, index, addr, is_shmem, file, nr, result),
+	TP_ARGS(mm, new_pfn, index, addr, is_shmem, file, nr, result),
 	TP_STRUCT__entry(
 		__field(struct mm_struct *, mm)
 		__field(unsigned long, hpfn)
@@ -228,7 +228,7 @@ TRACE_EVENT(mm_khugepaged_collapse_file,
 
 	TP_fast_assign(
 		__entry->mm = mm;
-		__entry->hpfn = new_folio ? folio_pfn(new_folio) : -1;
+		__entry->hpfn = new_pfn;
 		__entry->index = index;
 		__entry->addr = addr;
 		__entry->is_shmem = is_shmem;
mm/khugepaged.c +3 -1
@@ -2245,6 +2245,7 @@ static enum scan_result collapse_file(st
 	struct address_space *mapping = file->f_mapping;
 	struct page *dst;
 	struct folio *folio, *tmp, *new_folio;
+	unsigned long new_pfn = -1;
 	pgoff_t index = 0, end = start + HPAGE_PMD_NR;
 	LIST_HEAD(pagelist);
 	XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER);
@@ -2264,6 +2265,7 @@ static enum scan_result collapse_file(st
 	result = alloc_charge_folio(&new_folio, mm, cc, HPAGE_PMD_ORDER);
 	if (result != SCAN_SUCCEED)
 		goto out;
+	new_pfn = folio_pfn(new_folio);
 
 	mapping_set_update(&xas, mapping);
 
@@ -2667,7 +2669,7 @@ rollback:
 	folio_put(new_folio);
 out:
 	VM_BUG_ON(!list_empty(&pagelist));
-	trace_mm_khugepaged_collapse_file(mm, new_folio, index, addr, is_shmem, file, HPAGE_PMD_NR, result);
+	trace_mm_khugepaged_collapse_file(mm, new_pfn, index, addr, is_shmem, file, HPAGE_PMD_NR, result);
 	return result;
 }