Skip to contentSkip to conversation

7.3.7-rc1 review

PATCH In review Greg Kroah-Hartman 5 participants 1,010 messages Nov 25 Page 8 of 9

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

PATCH 831/1005 ovl: follow lower to lowerdata redirects from any lower layer

In reply to Greg Kroah-Hartman

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

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

From: Giuseppe Scrivano <[email protected]>

commit cbf4ccabcbfdda3da70c10b37e21e99cd2ee0946 upstream.

Commit 5ef7bcdeecc9 ("ovl: relax redirect/metacopy requirements for lower -> data redirect") allowed following redirects from a lower layer to a data-only layer without redirect_dir=follow and metacopy=on, so that data-only layers can be used with userxattr.

That fix was incomplete. Without metacopy=on, a metacopy file with an absolute redirect into a data-only layer is followed only from the lowest lower layer. From any other lower layer, the lookup fails with EPERM.

That commit also changed the behavior of redirect_dir=nofollow without making it visible to users. With data-only layers, some redirects are followed, although the mount options show redirect_dir=nofollow, or show nothing when that is the default.

Add redirect_dir=followdata, which follows only redirects from lower to lowerdata, and select it when there are data-only layers, unless redirect_dir=follow or redirect_dir=on is in effect, so the redirect follow mode in effect is shown in /proc/self/mountinfo.

Without metacopy=on, the absolute redirect of a lower metacopy file stops the lookup in the lower layers and the data is looked up in the data-only layers. Data-only layers cannot be used without following redirects, so reject an explicit redirect_dir=nofollow with data-only layers.

Fixes 5ef7bcdeecc9 ("ovl: relax redirect/metacopy requirements for lower -> data redirect")
---
 Documentation/filesystems/overlayfs.rst |   24 ++++++++++-------
 fs/overlayfs/namei.c                    |   24 ++++++++++++++---
 fs/overlayfs/overlayfs.h                |   15 +++++++++-
 fs/overlayfs/params.c                   |   45 +++++++++++++++++++++++++-------
 fs/overlayfs/params.h                   |    2 +
 fs/overlayfs/super.c                    |   17 +++++++-----
 6 files changed, 97 insertions(+), 30 deletions(-)
Documentation/filesystems/overlayfs.rst +15 -9
@@ -236,14 +236,19 @@ Module options (can also be changed thro
 Mount options:
 
 - "redirect_dir=on":
-    Redirects are enabled.
+    Redirects are created and followed.
 - "redirect_dir=follow":
     Redirects are not created, but followed.
+- "redirect_dir=followdata":
+    Redirects are not created.
+    Only redirects from lower to lowerdata are followed.
 - "redirect_dir=nofollow":
     Redirects are not created and not followed.
 - "redirect_dir=off":
-    If "redirect_always_follow" is enabled in the kernel/module config,
-    this "off" translates to "follow", otherwise it translates to "nofollow".
+    Redirects are not created.
+    Which redirects are followed depends on "redirect_always_follow" in the
+    kernel/module config, on data-only lower layers and on the "userxattr"
+    mount option.
 
 When the NFS export feature is enabled, every copied up directory is
 indexed by the file handle of the lower inode and a file handle of the
@@ -418,8 +423,8 @@ pointed by REDIRECT. This should not be
 "trusted." xattrs will require CAP_SYS_ADMIN. But it should be possible
 for untrusted layers like from a pen drive.
 
-Note: redirect_dir={off|nofollow|follow[*]} and nfs_export=on mount options
-conflict with metacopy=on, and will result in an error.
+Note: redirect_dir={off|nofollow|followdata|follow[*]} and nfs_export=on
+mount options conflict with metacopy=on, and will result in an error.
 
 [*] redirect_dir=follow only conflicts with metacopy=on if upperdir=... is
 given.
@@ -460,10 +465,11 @@ to the absolute path of the "lower data"
 
 Instead of explicitly enabling "metacopy=on" it is sufficient to specify at
 least one data-only layer to enable redirection of data to a data-only layer.
-In this case other forms of metacopy are rejected.  Note: this way, data-only
-layers may be used together with "userxattr", in which case careful attention
-must be given to privileges needed to change the "user.overlay.redirect" xattr
-to prevent misuse.
+In this case other forms of metacopy are rejected.  A data-only layer selects
+"redirect_dir=followdata", unless "redirect_dir=follow" or "redirect_dir=on" is
+in effect.  Note: this way, data-only layers may be used together with
+"userxattr", in which case careful attention must be given to privileges needed
+to change the "user.overlay.redirect" xattr to prevent misuse.
 
 Since kernel version v6.8, "data-only" lower layers can also be added using
 the "datadir+" mount options and the fsconfig syscall from new mount api.
fs/overlayfs/namei.c +21 -3
@@ -1087,7 +1087,8 @@ static bool ovl_check_follow_redirect(st
 		pr_warn_ratelimited("refusing to follow metacopy origin for (%pd2)\n", d->dentry);
 		return false;
 	}
-	if ((d->redirect || d->upperredirect) && !ovl_redirect_follow(ofs)) {
+	/* Check follow to lower layer, redirects to lowerdata are not checked here */
+	if ((d->redirect || d->upperredirect) && !ovl_redirect_follow_lower(ofs)) {
 		pr_warn_ratelimited("refusing to follow redirect for (%pd2)\n", d->dentry);
 		return false;
 	}
@@ -1105,13 +1106,26 @@ struct ovl_lookup_ctx {
 	unsigned int ctr;
 };
 
+/*
+ * Without metacopy=on, the absolute redirect of a lower metacopy file is
+ * followed only into the data-only layers.
+ */
+static bool ovl_is_lowerdata_redirect(struct ovl_lookup_ctx *ctx,
+				      struct ovl_lookup_data *d)
+{
+	struct ovl_fs *ofs = OVL_FS(d->sb);
+
+	return ofs->numdatalayer && !ofs->config.metacopy && ctx->ctr &&
+	       d->metacopy && d->absolute_redirect;
+}
+
 static int ovl_lookup_layers(struct ovl_lookup_ctx *ctx, struct ovl_lookup_data *d)
 {
 	struct dentry *dentry = ctx->dentry;
 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
 	struct ovl_entry *poe = OVL_E(dentry->d_parent);
 	struct ovl_entry *roe = OVL_E(dentry->d_sb->s_root);
-	bool check_redirect = (ovl_redirect_follow(ofs) || ofs->numdatalayer);
+	bool check_redirect = ovl_redirect_follow(ofs);
 	struct dentry *upperdir;
 	struct dentry *this;
 	struct dentry *origin = NULL;
@@ -1242,6 +1256,10 @@ static int ovl_lookup_layers(struct ovl_
 			ctx->ctr++;
 		}
 
+		/* Lookup of lowerdata in the data-only layers only */
+		if (ovl_is_lowerdata_redirect(ctx, d))
+			d->stop = true;
+
 		if (d->stop)
 			break;
 
@@ -1412,7 +1430,7 @@ struct dentry *ovl_lookup(struct inode *
 {
 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
 	struct ovl_entry *poe = OVL_E(dentry->d_parent);
-	bool check_redirect = (ovl_redirect_follow(ofs) || ofs->numdatalayer);
+	bool check_redirect = ovl_redirect_follow(ofs);
 	int err;
 	struct ovl_lookup_ctx ctx = {
 		.dentry = dentry,
fs/overlayfs/overlayfs.h +13 -2
@@ -75,11 +75,13 @@ enum ovl_entry_flag {
 
 enum {
 	/*
-	 * "off" mode is never used after mount options are verified. In effect
-	 * it translates to either "follow" or "nofollow".
+	 * "off" mode is never used after mount options are verified.
+	 * In effect it translates to either "follow", "nofollow" or
+	 * "followdata" (with data-only layers).
 	 */
 	OVL_REDIRECT_OFF,
 	OVL_REDIRECT_FOLLOW,
+	OVL_REDIRECT_FOLLOWDATA,
 	OVL_REDIRECT_NOFOLLOW,
 	OVL_REDIRECT_ON,
 };
@@ -635,11 +637,20 @@ static inline char ovl_get_opaquedir_val
 	return ovl_get_dir_xattr_val(ofs, path, OVL_XATTR_OPAQUE);
 }
 
+/* Are redirects followed into lower layers? */
+static inline bool ovl_redirect_follow_lower(struct ovl_fs *ofs)
+{
+	return ofs->config.redirect_mode == OVL_REDIRECT_FOLLOW ||
+	       ofs->config.redirect_mode == OVL_REDIRECT_ON;
+}
+
+/* Are redirects followed into lower or lowerdata layers? */
 static inline bool ovl_redirect_follow(struct ovl_fs *ofs)
 {
 	return ofs->config.redirect_mode != OVL_REDIRECT_NOFOLLOW;
 }
 
+/* Are redirects created in upper dir? */
 static inline bool ovl_redirect_dir(struct ovl_fs *ofs)
 {
 	return ofs->config.redirect_mode == OVL_REDIRECT_ON;
fs/overlayfs/params.c +36 -9

95 lines not on this page · raw message

fs/overlayfs/params.h +2 -0
@@ -42,3 +42,5 @@ int ovl_fs_params_verify(const struct ov
 			 struct ovl_config *config);
 int ovl_show_options(struct seq_file *m, struct dentry *dentry);
 const char *ovl_xino_mode(struct ovl_config *config);
+const char *ovl_redirect_mode(struct ovl_config *config);
+int ovl_redirect_follow_mode(bool follow_lower, size_t nr_data);
fs/overlayfs/super.c +10 -7
@@ -680,7 +680,7 @@ static int ovl_create_volatile_dirty(str
 }
 
 static int ovl_make_workdir(struct super_block *sb, struct ovl_fs *ofs,
-			    const struct path *workpath)
+			    const struct path *workpath, size_t nr_data)
 {
 	struct vfsmount *mnt = ovl_upper_mnt(ofs);
 	struct dentry *workdir;
@@ -744,9 +744,11 @@ static int ovl_make_workdir(struct super
 	if (err) {
 		pr_warn("failed to set xattr on upper\n");
 		ofs->noxattr = true;
-		if (ovl_redirect_follow(ofs)) {
-			ofs->config.redirect_mode = OVL_REDIRECT_NOFOLLOW;
-			pr_warn("...falling back to redirect_dir=nofollow.\n");
+		if (ovl_redirect_follow_lower(ofs)) {
+			ofs->config.redirect_mode =
+				ovl_redirect_follow_mode(false, nr_data);
+			pr_warn("...falling back to redirect_dir=%s.\n",
+				ovl_redirect_mode(&ofs->config));
 		}
 		if (ofs->config.metacopy) {
 			ofs->config.metacopy = false;
@@ -823,7 +825,7 @@ out:
 
 static int ovl_get_workdir(struct super_block *sb, struct ovl_fs *ofs,
 			   const struct path *upperpath,
-			   const struct path *workpath)
+			   const struct path *workpath, size_t nr_data)
 {
 	int err;
 
@@ -852,7 +854,7 @@ static int ovl_get_workdir(struct super_
 	if (err)
 		return err;
 
-	return ovl_make_workdir(sb, ofs, workpath);
+	return ovl_make_workdir(sb, ofs, workpath, nr_data);
 }
 
 static int ovl_get_indexdir(struct super_block *sb, struct ovl_fs *ofs,
@@ -1487,7 +1489,8 @@ static int ovl_fill_super_creds(struct f
 			}
 		}
 
-		err = ovl_get_workdir(sb, ofs, &ctx->upper, &ctx->work);
+		err = ovl_get_workdir(sb, ofs, &ctx->upper, &ctx->work,
+				      ctx->nr_data);
 		if (err)
 			return err;
 
author maintainer
#833 lore raw

PATCH 832/1005 smb: client: bound invalid NTLMSSP signature diagnostic

In reply to Greg Kroah-Hartman

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

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

From: Yifan Zhang <[email protected]>

commit 0584b02669c3e76188097174b4f25ed13723e94c upstream.

The NTLMSSP Signature field is an eight-byte binary value and need not be NUL-terminated. decode_ntlmssp_challenge() prints it with %s on the signature-mismatch path, so the diagnostic can continue beyond the received blob until it encounters a zero byte.

KASAN reports:

  BUG: KASAN: slab-out-of-bounds in string
  Read of size 1
  string
  vsnprintf
  _printk
  decode_ntlmssp_challenge

Print the fixed-width field with the bounded hexadecimal format.

The patched kernel reaches the invalid-signature path and returns -EINVAL without a KASAN report.

Fixes 0b3cc858003b ("[CIFS] NTLMSSP reenabled after move from connect.c to sess.c")
---
 fs/smb/client/sess.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/smb/client/sess.c +2 -2
@@ -666,8 +666,8 @@ int decode_ntlmssp_challenge(char *bcc_p
 	}
 
 	if (memcmp(pblob->Signature, "NTLMSSP", 8)) {
-		cifs_dbg(VFS, "blob signature incorrect %s\n",
-			 pblob->Signature);
+		cifs_dbg(VFS, "%s: blob signature incorrect: %8phN\n",
+			 __func__, pblob->Signature);
 		return -EINVAL;
 	}
 	if (pblob->MessageType != NtLmChallenge) {
author maintainer
#834 lore raw

PATCH 833/1005 smb: client: compare owner and group SIDs using their encoded lengths

In reply to Greg Kroah-Hartman

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

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

From: liuyong <[email protected]>

commit a2dabe73ea05ad3b3f8e1cc08fb2e7c2ddc5564b upstream.

populate_new_aces() compares owner and group SIDs over sizeof(struct smb_sid), including storage for all 15 possible subauthorities. Received SIDs contain only their encoded subauthorities. The comparison can read past the security descriptor, as shown by the supplied KASAN report for a 44-byte descriptor during chmod.

The input SIDs have already been checked by sid_from_sd(). Require equal subauthority counts, then compare only the fixed SID header and the encoded subauthorities with memcmp(). The count check ensures that both validated SIDs contain the number of bytes being compared.

These issues were discovered and fixed by Qihoo 360's Tulongfeng multi-agent system.

Fixes 0f22053e811c ("cifs: Fix unix perm bits to cifsacl conversion for "other" bits.")
---
 fs/smb/client/cifsacl.c |    5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
fs/smb/client/cifsacl.c +4 -1
@@ -1134,7 +1134,10 @@ static void populate_new_aces(char *nacl
 	 * updated in the inode.
 	 */
 
-	if (!memcmp(pownersid, pgrpsid, sizeof(struct smb_sid))) {
+	if (pownersid->num_subauth == pgrpsid->num_subauth &&
+	    !memcmp(pownersid, pgrpsid,
+		    CIFS_SID_BASE_SIZE +
+		    pownersid->num_subauth * sizeof(__le32))) {
 		/*
 		 * Case when owner and group SIDs are the same.
 		 * Set the more restrictive of the two modes.
author maintainer
#835 lore raw

PATCH 834/1005 smb: client: dont block dying tasks waiting for writeback on close

In reply to Greg Kroah-Hartman

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

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

From: Paulo Alcantara <[email protected]>

commit 15ea186abbcd04157c62e0901701870b812bb2bd upstream.

cifs_flush() waits uninterruptibly for the writeback it starts. A task that gets killed while closing a file on a hard mount with an unresponsive server is stuck in D state until the server comes back. It also consumes any writeback error for a caller that is about to exit, hiding it from everyone else.

Wait killably instead. If the closer gets killed, stop waiting and leave the error bits in the mapping for others to see; writeback already in flight completes on its own. Don't wait at all, nor check for errors, if it is already dying.

This is also needed before letting dying tasks issue their writes from a worker, which would otherwise make them wait for every one of them.

Fixes d3f1322af8f8 ("cifs: wait for writeback to complete in cifs_flush")
---
 fs/smb/client/file.c |   33 ++++++++++++++++++++++++++++++---
 1 file changed, 30 insertions(+), 3 deletions(-)
fs/smb/client/file.c +30 -3
@@ -2955,17 +2955,44 @@ fsync_exit:
 	return rc;
 }
 
+static int cifs_wait_writeback_killable(struct address_space *mapping)
+{
+	struct folio_batch fbatch;
+	pgoff_t index = 0;
+	int rc = 0;
+
+	folio_batch_init(&fbatch);
+	while (!rc &&
+	       filemap_get_folios_tag(mapping, &index, (pgoff_t)-1,
+				      PAGECACHE_TAG_WRITEBACK, &fbatch)) {
+		for (unsigned int i = 0;
+		     !rc && i < folio_batch_count(&fbatch); i++)
+			rc = folio_wait_writeback_killable(fbatch.folios[i]);
+		folio_batch_release(&fbatch);
+		cond_resched();
+	}
+	return rc;
+}
+
 /*
  * As file closes, flush all cached write data for this inode checking
  * for write behind errors.
  */
 int cifs_flush(struct file *file, fl_owner_t id)
 {
+	struct address_space *mapping = file->f_mapping;
 	struct inode *inode = file_inode(file);
-	int rc = 0;
+	int rc = 0, rc2;
 
-	if (file->f_mode & FMODE_WRITE)
-		rc = filemap_write_and_wait(inode->i_mapping);
+	if (file->f_mode & FMODE_WRITE) {
+		rc = filemap_fdatawrite(mapping);
+		if (fatal_signal_pending(current) ||
+		    cifs_wait_writeback_killable(mapping))
+			return 0;
+		rc2 = filemap_check_errors(mapping);
+		if (!rc)
+			rc = rc2;
+	}
 
 	cifs_dbg(FYI, "Flush inode %p file %p rc %d\n", inode, file, rc);
 	if (rc) {
author maintainer
#836 lore raw

PATCH 835/1005 smb: client: dont block dying tasks waiting for writeback on fsync

In reply to Greg Kroah-Hartman

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

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

From: Paulo Alcantara <[email protected]>

commit 0df0f24803061b6c2bef0d24de7c63c9cce46a49 upstream.

cifs_fsync() and cifs_strict_fsync() wait uninterruptibly for writeback through file_write_and_wait_range(). As with close, a task killed in fsync(2) on a hard mount with an unresponsive server is stuck in D state until the server comes back.

Wait killably instead, using the same helper as cifs_flush(). The writeback keeps going and its errors stay in the mapping; only the dying caller stops waiting for it.

---
 fs/smb/client/file.c |   64 +++++++++++++++++++++++++++++++++------------------
 1 file changed, 42 insertions(+), 22 deletions(-)
fs/smb/client/file.c +42 -22
@@ -2877,6 +2877,45 @@ cifs_get_readable_path(struct cifs_tcon
 	return -ENOENT;
 }
 
+static int cifs_wait_writeback_killable(struct address_space *mapping,
+					loff_t start, loff_t end)
+{
+	pgoff_t end_index = end >> PAGE_SHIFT;
+	pgoff_t index = start >> PAGE_SHIFT;
+	struct folio_batch fbatch;
+	int rc = 0;
+
+	folio_batch_init(&fbatch);
+	while (!rc &&
+	       filemap_get_folios_tag(mapping, &index, end_index,
+				      PAGECACHE_TAG_WRITEBACK, &fbatch)) {
+		for (unsigned int i = 0;
+		     !rc && i < folio_batch_count(&fbatch); i++)
+			rc = folio_wait_writeback_killable(fbatch.folios[i]);
+		folio_batch_release(&fbatch);
+		cond_resched();
+	}
+	return rc;
+}
+
+static int cifs_file_write_and_wait_killable(struct file *file,
+					     loff_t start, loff_t end)
+{
+	struct address_space *mapping = file->f_mapping;
+	int rc, rc2;
+
+	if (end < start)
+		return 0;
+
+	rc = filemap_fdatawrite_range(mapping, start, end);
+	if (cifs_wait_writeback_killable(mapping, start, end))
+		return -EINTR;
+	rc2 = file_check_and_advance_wb_err(file);
+	if (!rc)
+		rc = rc2;
+	return rc;
+}
+
 /*
  * Flush data on a strict file.
  */
@@ -2888,7 +2927,7 @@ int cifs_strict_fsync(struct file *file,
 	unsigned int xid;
 	int rc;
 
-	rc = file_write_and_wait_range(file, start, end);
+	rc = cifs_file_write_and_wait_killable(file, start, end);
 	if (rc) {
 		trace_cifs_fsync_err(inode->i_ino, rc);
 		return rc;
@@ -2920,7 +2959,7 @@ int cifs_fsync(struct file *file, loff_t
 	struct inode *inode = file_inode(file);
 	struct cifs_sb_info *cifs_sb = CIFS_SB(file);
 
-	rc = file_write_and_wait_range(file, start, end);
+	rc = cifs_file_write_and_wait_killable(file, start, end);
 	if (rc) {
 		trace_cifs_fsync_err(file_inode(file)->i_ino, rc);
 		return rc;
@@ -2955,25 +2994,6 @@ fsync_exit:
 	return rc;
 }
 
-static int cifs_wait_writeback_killable(struct address_space *mapping)
-{
-	struct folio_batch fbatch;
-	pgoff_t index = 0;
-	int rc = 0;
-
-	folio_batch_init(&fbatch);
-	while (!rc &&
-	       filemap_get_folios_tag(mapping, &index, (pgoff_t)-1,
-				      PAGECACHE_TAG_WRITEBACK, &fbatch)) {
-		for (unsigned int i = 0;
-		     !rc && i < folio_batch_count(&fbatch); i++)
-			rc = folio_wait_writeback_killable(fbatch.folios[i]);
-		folio_batch_release(&fbatch);
-		cond_resched();
-	}
-	return rc;
-}
-
 /*
  * As file closes, flush all cached write data for this inode checking
  * for write behind errors.
@@ -2987,7 +3007,7 @@ int cifs_flush(struct file *file, fl_own
 	if (file->f_mode & FMODE_WRITE) {
 		rc = filemap_fdatawrite(mapping);
 		if (fatal_signal_pending(current) ||
-		    cifs_wait_writeback_killable(mapping))
+		    cifs_wait_writeback_killable(mapping, 0, LLONG_MAX))
 			return 0;
 		rc2 = filemap_check_errors(mapping);
 		if (!rc)
author maintainer
#837 lore raw

PATCH 836/1005 smb: client: fix double conversion of DFS path in setup_dfs_ref()

In reply to Greg Kroah-Hartman

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

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

From: Fredric Cover <[email protected]>

commit 92509ce64ffff02d05fe9f3c82b889e1cc500076 upstream.

setup_dfs_ref() converts the path from the mount charset to the DFS cache charset (utf8) via dfs_get_path(), and then passes that already converted string to dfs_get_referral(). dfs_cache_find() converts its input again, assuming it is still in the mount charset.

When the mount charset is not utf8 (iocharset=iso8859-1, or a kernel built with a non-utf8 CONFIG_NLS_DEFAULT) and the DFS path contains non-ASCII characters, the utf8 bytes are interpreted as mount-charset characters and encoded a second time. For example, "é" is sent as c3 83 c2 a9 instead of c3 a9. The server then fails the second-level referral with STATUS_OBJECT_PATH_NOT_FOUND and the mount fails with -ENOENT, even though the path exists.

Pass the unconverted path to dfs_get_referral() so that it is converted exactly once.

Such mounts now get past the second-level referral and reach dfs_parse_target_referral(), which is why this change depends on "smb: client: fix out-of-bounds read in dfs_parse_target_referral()".

Tested with a Samba DFS root containing a link named "café", mounted with iocharset=iso8859-1 and the single Latin-1 byte 0xe9 in the path:
before, the mount failed with -ENOENT; with both patches applied, it succeeds.

---
 fs/smb/client/dfs.c |   10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
fs/smb/client/dfs.c +5 -5
@@ -103,6 +103,7 @@ static int setup_dfs_ref(struct dfs_info
 	struct cifs_sb_info *cifs_sb = rw->mnt_ctx->cifs_sb;
 	struct smb3_fs_context *ctx = rw->mnt_ctx->fs_ctx;
 	char *ref_path, *full_path;
+	const char *raw_path;
 	int rc;
 
 	set_root_smb_session(rw->mnt_ctx);
@@ -114,9 +115,10 @@ static int setup_dfs_ref(struct dfs_info
 
 	if (!tgt || (tgt->server_type == DFS_TYPE_LINK &&
 		     DFS_INTERLINK(tgt->flags)))
-		ref_path = dfs_get_path(cifs_sb, ctx->UNC);
+		raw_path = ctx->UNC;
 	else
-		ref_path = dfs_get_path(cifs_sb, full_path);
+		raw_path = full_path;
+	ref_path = dfs_get_path(cifs_sb, raw_path);
 	if (IS_ERR(ref_path)) {
 		rc = PTR_ERR(ref_path);
 		kfree(full_path);
@@ -125,9 +127,7 @@ static int setup_dfs_ref(struct dfs_info
 	ref_walk_path(rw) = ref_path;
 	ref_walk_fpath(rw) = full_path;
 
-	return dfs_get_referral(rw->mnt_ctx,
-				ref_walk_path(rw) + 1,
-				ref_walk_tl(rw));
+	return dfs_get_referral(rw->mnt_ctx, raw_path + 1, ref_walk_tl(rw));
 }
 
 static int __dfs_referral_walk(struct dfs_ref_walk *rw)
author maintainer
#838 lore raw

PATCH 837/1005 smb: client: fix OOB write when compounding SMB2_IOCTL with encryption

In reply to Greg Kroah-Hartman

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

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

From: Andrey Misiurov <[email protected]>

commit 73a0060cb22a1d2bd8bff364c18a4259ec0cb528 upstream.

On an encrypted ("seal") mount, SMB2_ioctl_init() keeps the IOCTL input in a separate iov (iov[1]); iov[0] is a 448-byte buffer from cifs_small_buf_get(). When such an IOCTL is not the last request of a compound, smb2_set_next_command() pads it for alignment by copying the whole request into iov[0]. A large enough input overflows that 448-byte buffer and corrupts the slab; the copy also sets rq_nvec to 1, so the input buffer is leaked too.

An unprivileged user can trigger it by creating a symlink with a long target on such a mount: the native symlink is sent as FSCTL_SET_REPARSE_POINT + QUERY_INFO + CLOSE in one compound, so the IOCTL is not the last request.

With slub_debug red zones on the cifs_small_rq cache, the overflow is caught on the next allocation from that cache in the same compound (the 0x61 bytes are the 'a' characters of the symlink target):

BUG cifs_small_rq (Not tainted): Object corrupt
[Left Redzone overwritten] 0xffff8a59c7790500-0xffff8a59c779053f First byte 0x61 instead of 0xbb

  Call Trace:
   check_object+0x1a8/0x350
   alloc_debug_processing+0xab/0x110
   ___slab_alloc+0x7e/0x2f0
   kmem_cache_alloc_noprof+0x28d/0x4b0
   mempool_alloc_slab+0x16/0x30
   cifs_small_buf_get+0x1a/0x30 [cifs]
   SMB2_close_init+0x8a/0x100 [cifs]
   smb2_compound_op+0x2571/0x2b50 [cifs]
   smb2_create_reparse_inode+0x27e/0x490 [cifs]
   mknod_nfs+0x1ce/0x2e0 [cifs]
   create_reparse_symlink+0x119/0x180 [cifs]
   cifs_symlink+0x19f/0x8e0 [cifs]
   vfs_symlink+0xa3/0x1b0
   __x64_sys_symlink+0x41/0x70

Pad the input to a multiple of 8 bytes when encryption is required. The request is then already aligned and smb2_set_next_command() no longer copies it; InputCount still carries the real length.

Fixes 90f7c100d2dd ("smb: client: fix compound alignment with encryption")
---
 fs/smb/client/smb2pdu.c |   12 ++++++++----
 1 file changed, 8 insertions(+), 4 deletions(-)
fs/smb/client/smb2pdu.c +8 -4
@@ -3453,11 +3453,12 @@ SMB2_ioctl_init(struct cifs_tcon *tcon,
 		char *in_data, u32 indatalen,
 		__u32 max_response_size)
 {
-	struct smb2_ioctl_req *req;
 	struct kvec *iov = rqst->rq_iov;
+	struct smb2_ioctl_req *req;
+	u32 in_buf_len = indatalen;
 	unsigned int total_len;
-	int rc;
 	char *in_data_buf;
+	int rc;
 
 	rc = smb2_ioctl_req_init(opcode, tcon, server,
 				 (void **) &req, &total_len);
@@ -3465,15 +3466,18 @@ SMB2_ioctl_init(struct cifs_tcon *tcon,
 		return rc;
 
 	if (indatalen) {
+		if (smb3_encryption_required(tcon))
+			in_buf_len = ALIGN(indatalen, 8);
 		/*
 		 * indatalen is usually small at a couple of bytes max, so
 		 * just allocate through generic pool
 		 */
-		in_data_buf = kmemdup(in_data, indatalen, GFP_NOFS);
+		in_data_buf = kzalloc(in_buf_len, GFP_NOFS);
 		if (!in_data_buf) {
 			cifs_small_buf_release(req);
 			return -ENOMEM;
 		}
+		memcpy(in_data_buf, in_data, indatalen);
 	}
 
 	req->CtlCode = cpu_to_le32(opcode);
@@ -3497,7 +3501,7 @@ SMB2_ioctl_init(struct cifs_tcon *tcon,
 		rqst->rq_nvec = 2;
 		iov[0].iov_len = total_len - 1;
 		iov[1].iov_base = in_data_buf;
-		iov[1].iov_len = indatalen;
+		iov[1].iov_len = in_buf_len;
 	} else {
 		rqst->rq_nvec = 1;
 		iov[0].iov_len = total_len;
author maintainer
#839 lore raw

PATCH 838/1005 smb: client: fix out-of-bounds read in dfs_parse_target_referral()

In reply to Greg Kroah-Hartman

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

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

From: Fredric Cover <[email protected]>

commit 86aacc2f3f6ba18e1d87feee24f37c94b3ce863a upstream.

dfs_parse_target_referral() decides whether a prefix path remains after the consumed part of full_path with:

	if (strlen(full_path) - ref->path_consumed)

strlen() returns size_t, so if path_consumed is larger than the length of full_path, the subtraction wraps around to a huge non-zero value. The branch is then taken, prepath is set to a pointer past the terminating NUL of full_path, and *prepath reads out of bounds.

path_consumed can exceed strlen(full_path) when the mount charset is not utf8. The referral code derives path_consumed from the canonical path, which is in the DFS cache charset (utf8), but it is applied here to full_path, which is in the mount charset. Each non-ASCII character in the consumed part of the path that is longer in utf8 than in the mount charset makes the count too large by the difference.

This was reproduced with iocharset=iso8859-1 against a Samba DFS root containing a link named "café", mounting with the single Latin-1 byte 0xe9 in the path. On an unmodified tree such a mount fails earlier with -ENOENT because the path is converted to utf8 twice in setup_dfs_ref(); with that fixed ("smb: client: fix double conversion of DFS path in setup_dfs_ref()"), the mount reaches this code. full_path was 29 bytes while path_consumed was 30:

  BUG: KASAN: slab-out-of-bounds in dfs_parse_target_referral+0x26a/0x270
  Read of size 1 at addr ffff88810db89d5f by task mount/1743
  ...
  The buggy address is located 0 bytes to the right of
   allocated 31-byte region [ffff88810db89d40, ffff88810db89d5f)

Compare path_consumed against the string length instead of subtracting, so that no prefix path is used when the consumed count covers the whole string. With the bounds check in place the same mount succeeds and no KASAN report is produced.

This only prevents the out-of-bounds access. path_consumed is still in the wrong units, so a non-ASCII link followed by a path component can still produce a wrong prefix path. That needs a separate fix.

---
 fs/smb/client/dfs.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/smb/client/dfs.c +1 -1
@@ -33,7 +33,7 @@ int dfs_parse_target_referral(const char
 	if (WARN_ON_ONCE(!ref->node_name || ref->path_consumed < 0))
 		return -EINVAL;
 
-	if (strlen(full_path) - ref->path_consumed) {
+	if ((size_t)ref->path_consumed < strlen(full_path)) {
 		prepath = full_path + ref->path_consumed;
 		/* skip initial delimiter */
 		if (*prepath == '/' || *prepath == '\\')
author maintainer
#840 lore raw

PATCH 839/1005 smb: client: flush deferred handles of other names before a hard link open

In reply to Greg Kroah-Hartman

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

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

From: Paulo Alcantara <[email protected]>

commit 25912ed3b75dcf5ff623dcb549b925dd0d0948f7 upstream.

Opening a hard link of a file whose other name still holds a deferred, leased handle fails with EINVAL over SMB3. The client caches lease keys per inode, but the server ties a lease to the file name it was granted under, so reusing the inode's lease key to open a different name of the same inode is rejected with STATUS_INVALID_PARAMETER (MS-SMB2 3.3.5.9.11).

Commit 262b73ef442e ("smb3 client: fix open hardlink on deferred close file error") already closes the inode's deferred handles before such an open so the new name can take a fresh lease, but cifs_get_hardlink_path() only triggered that flush when a cached handle had the same open flags as the new open, so a differently accessed name - written then read, say - slipped through and still failed.

Match on the name instead: flush when a cached handle for another name of the inode is open, regardless of access mode.

---
 fs/smb/client/file.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/smb/client/file.c +1 -1
@@ -2232,7 +2232,7 @@ cifs_get_hardlink_path(struct cifs_tcon
 	spin_lock(&cinode->open_file_lock);
 
 	list_for_each_entry(open_file, &cinode->openFileList, flist) {
-		if (file->f_flags == open_file->f_flags) {
+		if (open_file->dentry != file_dentry(file)) {
 			rc = -EINVAL;
 			break;
 		}
author maintainer
#841 lore raw

PATCH 840/1005 smb: client: hold server ref while queueing reconnect work

In reply to Greg Kroah-Hartman

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

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

From: Joseph Qi <[email protected]>

commit f02d249e9756b78990aaaa1635e47e06deb2cb51 upstream.

When query_server_interfaces() returns -EOPNOTSUPP on a secondary channel, smb2_reconnect() calls smb3_update_ses_channels() which for a channel runs cifs_chan_skip_or_disable(). That clears the channel's slot in the session and calls cifs_put_tcp_session(), which can drop the last reference of the channel and tear it down.

smb2_reconnect() then falls through to skip_add_channels and queues reconnect work on that server, using a server that may already be freed. The send path obtained the channel from cifs_pick_channel(), which does not take a reference, so the session's channel reference is the only one.

Take our own reference on the channel before calling smb3_update_ses_channels() and drop it after the reconnect work has been queued, so the channel cannot be freed while it is still used.

Fixes f591062bdbf4 ("cifs: handle servers that still advertise multichannel after disabling")
---
 fs/smb/client/smb2pdu.c |   19 ++++++++++++++++++-
 1 file changed, 18 insertions(+), 1 deletion(-)
fs/smb/client/smb2pdu.c +18 -1
@@ -250,9 +250,10 @@ static int
 smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon,
 	       struct TCP_Server_Info *server, bool from_reconnect)
 {
+	bool hold_server_ref = false;
 	struct cifs_ses *ses;
-	int xid;
 	int rc = 0;
+	int xid;
 
 	/*
 	 * SMB2s NegProt, SessSetup, Logoff do not have tcon yet so
@@ -470,6 +471,20 @@ skip_sess_setup:
 			 * treat this as server not supporting multichannel
 			 */
 
+			/*
+			 * If server is a secondary channel,
+			 * cifs_chan_skip_or_disable() called below may
+			 * drop its last reference, so hold our own
+			 * reference until the reconnect work below has
+			 * been queued.
+			 */
+			spin_lock(&cifs_tcp_ses_lock);
+			if (server->srv_count) {
+				server->srv_count++;
+				hold_server_ref = true;
+			}
+			spin_unlock(&cifs_tcp_ses_lock);
+
 			rc = smb3_update_ses_channels(ses, server,
 						       from_reconnect,
 						       true /* disable_mchan */);
@@ -498,6 +513,8 @@ skip_add_channels:
 
 	if (smb2_command != SMB2_INTERNAL_CMD)
 		cifs_queue_server_reconn(server);
+	if (hold_server_ref)
+		cifs_put_tcp_session(server, from_reconnect);
 
 	atomic_inc(&tconInfoReconnectCount);
 out:
author maintainer
#842 lore raw

PATCH 841/1005 smb: client: hold the inode across cifs_oplock_break()

In reply to Greg Kroah-Hartman

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

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

From: Joseph Qi <[email protected]>

commit fce78321f1b59531cf6fc94860550db1db8dec55 upstream.

cifs_oplock_break() drops the handle reference in the middle of the handler and keeps using cinode afterwards, to send the break acknowledgment and again in cifs_done_oplock_break(). The reference cifs_queue_oplock_break() takes is the only pin: the handle holds the dentry and the dentry is what keeps the inode alive.

When that put is the last reference, the dput() in cifsFileInfo_put_final() kills an unhashed dentry, drops the last i_count and evicts the inode, so the rest of the handler runs on an object whose free is only RCU-deferred. An unhashed dentry that a handle still references is an ordinary state: unlinking an open file leaves the dentry that way, and so does the dcache teardown at unmount.

Take a reference on the inode for the lifetime of the handler and drop it once the break has been reported. This also covers the cifs_get_tlink() failure path, where the put is followed directly by the out label.

Fixes b98749cac4a6 ("CIFS: keep FileInfo handle live during oplock break")
Fixes 23b26f4408ac ("smb: client: avoid leaking refcount when cifs_sb_tlink() fails")
---
 fs/smb/client/file.c |    9 +++++++++
 1 file changed, 9 insertions(+)
fs/smb/client/file.c +9 -0
@@ -3401,6 +3401,14 @@ void cifs_oplock_break(struct work_struc
 	__u64 persistent_fid, volatile_fid;
 	__u16 net_fid;
 
+	/*
+	 * Dropping the handle reference below also drops the dentry
+	 * reference that pins this inode, and cinode is still needed to
+	 * acknowledge the break and to report it as complete.  Hold the inode
+	 * until that is done.
+	 */
+	ihold(inode);
+
 	wait_on_bit(&cinode->flags, CIFS_INODE_PENDING_WRITERS,
 			TASK_UNINTERRUPTIBLE);
 
@@ -3488,6 +3496,7 @@ oplock_break_ack:
 	cifs_put_tlink(tlink);
 out:
 	cifs_done_oplock_break(cinode);
+	iput(inode);
 }
 
 #ifdef CONFIG_SWAP
author maintainer
#843 lore raw

PATCH 842/1005 smb: client: issue writes from a worker if the task is dying

In reply to Greg Kroah-Hartman

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

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

From: Paulo Alcantara <[email protected]>

commit 1a747bacf250959703c68fed1bb643f888dd3ad2 upstream.

A task with a fatal signal pending can't send on the socket:
__smb_send_rqst() refuses it upfront with -ERESTARTSYS, as SIGKILL can't be blocked and a send interrupted halfway forces a reconnect. Writeback, however, runs in the context of whoever starts it, so when a dying task flushes dirty pages - close() racing with SIGKILL, or fd teardown during exit_group() - every write subrequest gets refused:

smb3_write_err: ... offset=0x1400000 len=0x400000 rc=-512
cifs_flush_err: ino=... rc=-512

Since the switch to netfslib, a failed upload ends writeback with the folios clean, so the data is silently lost: the server ends up with 20MiB of a 64MiB file while stat(2) reports the full size.

Issue writeback subrequests of dying tasks from a new cifswritebackd workqueue instead, like afs does for all of its writes, so they get sent from a context with no signals. Leave direct and unbuffered writes alone, as their callers get the error. Use a dedicated WQ_UNBOUND workqueue as the writes may block for long on credits, sends or reopens, e.g. on hard mounts with an unresponsive server, and must not hold up other cifs work such as reconnects, nor starve the WQ_MEM_RECLAIM rescuer of cifsiod_wq.

Fixes 3ee1a1fc3981 ("cifs: Cut over to using netfslib")
---
 fs/smb/client/cifsfs.c   |   13 ++++++++++++-
 fs/smb/client/cifsglob.h |    1 +
 fs/smb/client/file.c     |   26 +++++++++++++++++++++++++-
 3 files changed, 38 insertions(+), 2 deletions(-)
fs/smb/client/cifsfs.c +12 -1
@@ -165,6 +165,7 @@ struct workqueue_struct	*cifsoplockd_wq;
 struct workqueue_struct	*deferredclose_wq;
 struct workqueue_struct	*serverclose_wq;
 struct workqueue_struct	*cfid_put_wq;
+struct workqueue_struct	*cifs_writeback_wq;
 __u32 cifs_lock_secret;
 
 /*
@@ -2125,9 +2126,16 @@ init_cifs(void)
 		goto out_destroy_serverclose_wq;
 	}
 
+	cifs_writeback_wq = alloc_workqueue("cifswritebackd",
+					    WQ_UNBOUND | WQ_MEM_RECLAIM, 0);
+	if (!cifs_writeback_wq) {
+		rc = -ENOMEM;
+		goto out_destroy_cfid_put_wq;
+	}
+
 	rc = cifs_init_inodecache();
 	if (rc)
-		goto out_destroy_cfid_put_wq;
+		goto out_destroy_writeback_wq;
 
 	rc = cifs_init_netfs();
 	if (rc)
@@ -2198,6 +2206,8 @@ out_destroy_netfs:
 	cifs_destroy_netfs();
 out_destroy_inodecache:
 	cifs_destroy_inodecache();
+out_destroy_writeback_wq:
+	destroy_workqueue(cifs_writeback_wq);
 out_destroy_cfid_put_wq:
 	destroy_workqueue(cfid_put_wq);
 out_destroy_serverclose_wq:
@@ -2243,6 +2253,7 @@ exit_cifs(void)
 	destroy_workqueue(fileinfo_put_wq);
 	destroy_workqueue(serverclose_wq);
 	destroy_workqueue(cfid_put_wq);
+	destroy_workqueue(cifs_writeback_wq);
 	destroy_workqueue(cifsiod_wq);
 }
 
fs/smb/client/cifsglob.h +1 -0
@@ -2145,6 +2145,7 @@ extern struct workqueue_struct *cifsoplo
 extern struct workqueue_struct *deferredclose_wq;
 extern struct workqueue_struct *serverclose_wq;
 extern struct workqueue_struct *cfid_put_wq;
+extern struct workqueue_struct *cifs_writeback_wq;
 extern __u32 cifs_lock_secret;
 
 extern mempool_t *cifs_sm_req_poolp;
fs/smb/client/file.c +25 -1
@@ -105,10 +105,16 @@ retry:
 #endif
 }
 
+static bool cifs_writeback_dying(struct netfs_io_subrequest *subreq)
+{
+	return subreq->rreq->origin == NETFS_WRITEBACK &&
+		fatal_signal_pending(current);
+}
+
 /*
  * Issue a subrequest to upload to the server.
  */
-static void cifs_issue_write(struct netfs_io_subrequest *subreq)
+static void __cifs_issue_write(struct netfs_io_subrequest *subreq)
 {
 	struct cifs_io_subrequest *wdata =
 		container_of(subreq, struct cifs_io_subrequest, subreq);
@@ -142,6 +148,24 @@ fail:
 	goto out;
 }
 
+static void cifs_issue_write_worker(struct work_struct *work)
+{
+	struct netfs_io_subrequest *subreq;
+
+	subreq = container_of(work, struct netfs_io_subrequest, work);
+	__cifs_issue_write(subreq);
+}
+
+static void cifs_issue_write(struct netfs_io_subrequest *subreq)
+{
+	if (unlikely(cifs_writeback_dying(subreq))) {
+		subreq->work.func = cifs_issue_write_worker;
+		WARN_ON_ONCE(!queue_work(cifs_writeback_wq, &subreq->work));
+		return;
+	}
+	__cifs_issue_write(subreq);
+}
+
 static void cifs_netfs_invalidate_cache(struct netfs_io_request *wreq)
 {
 	cifs_invalidate_cache(wreq->inode, 0);
author maintainer
#844 lore raw

PATCH 843/1005 smb: client: let umount -f abort retried reads and writes

In reply to Greg Kroah-Hartman

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

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

From: Paulo Alcantara <[email protected]>

commit adeb82ac455582eac1894d1ca1b0aba110a65cc3 upstream.

umount -f only wakes up tasks waiting on the server's queues. Reads and writes being retried - forever on hard mounts - keep going, so with the server gone the unmount still hangs in sync_filesystem() waiting for their writeback. NFS kills outstanding RPCs on umount -f instead.

Count umount -f attempts per superblock and have each read and write request remember the count it started with. Fail with -EIO, rather than retry, reissue, issue or wait for credits, any subrequest of a request that predates a umount -f once it is a retry or the server or share is disconnected; a kworker doing writeback can't be signalled out of the credit wait otherwise. First attempts on a connected server still go ahead, and requests started later aren't aborted (but see below), so I/O on a healthy server keeps working if the unmount then fails with -EBUSY or only detaches one of several mounts.

retry_count is not bumped yet when netfs_retry_write_stream() calls prepare_write() for the first retry, so don't rely on it alone to tell a reissue from a first attempt: treat a subrequest as a retry when it already carries an xid (it has been prepared before) in prepare_write()/prepare_read(), or when its replay flag is set in cifs_io_aborted(), and abort it when the mount is going away even if the connection still looks healthy.

Requests created after umount -f - writeback kicked off by the background flusher, an oplock break or sync_filesystem() during the final teardown - snapshot the already bumped count and would otherwise retry forever on a hard mount, hanging cifs_kill_sb(). Once a superblock that saw a umount -f reaches cifs_kill_sb() the mount is going away for good, so flag it and stop retrying I/O on it too; one that never saw a umount -f still flushes as before.

A sync(2) or syncfs() waiting under s_umount for writeback started after umount -f would still keep the unmount from reaching cifs_kill_sb(), so also stop retrying such I/O while s_umount is contended. After a failed umount -f, that also stops reads and writes retrying while a remount, freeze or new mount of the same superblock waits on s_umount.

Fixes 2c1238a7477a ("cifs: make retry logic in read/write path consistent with other paths")
---
 fs/smb/client/cifs_fs_sb.h |    2 +
 fs/smb/client/cifsfs.c     |   10 ++++++++
 fs/smb/client/cifsglob.h   |    1 
 fs/smb/client/cifsproto.h  |    2 +
 fs/smb/client/file.c       |   55 +++++++++++++++++++++++++++++++++++++++++++++
 fs/smb/client/smb2pdu.c    |   16 +++----------
 6 files changed, 74 insertions(+), 12 deletions(-)
fs/smb/client/cifs_fs_sb.h +2 -0
@@ -57,6 +57,7 @@ struct cifs_sb_info {
 	atomic_t active;
 	atomic_t mnt_cifs_flags;
 	atomic_t outstanding_rreq;	/* nr of rreqs not yet fully deinitialized */
+	atomic_t umount_aborts;		/* nr of umount -f attempts */
 	struct delayed_work prune_tlinks;
 	struct rcu_head rcu;
 
@@ -68,6 +69,7 @@ struct cifs_sb_info {
 	 * (cifs_autodisable_serverino) in order to match new mounts.
 	 */
 	bool mnt_cifs_serverino_autodisabled;
+	bool exiting;			/* umount -f committed: stop retries */
 	/*
 	 * Available once the mount has completed.
 	 */
fs/smb/client/cifsfs.c +10 -0
@@ -300,6 +300,15 @@ static void cifs_kill_sb(struct super_bl
 	struct cifs_sb_info *cifs_sb = CIFS_SB(sb);
 
 	/*
+	 * Reaching here after a umount -f means the mount is going away for
+	 * good, so stop retrying I/O that can no longer complete (e.g.
+	 * writeback to a server that is gone) rather than looping forever on
+	 * a hard mount and hanging the teardown below.
+	 */
+	if (atomic_read(&cifs_sb->umount_aborts))
+		WRITE_ONCE(cifs_sb->exiting, true);
+
+	/*
 	 * We need to release all dentries for the cached directories
 	 * and close all deferred file handles before we kill the sb.
 	 */
@@ -838,6 +847,7 @@ static void cifs_umount_begin(struct sup
 	if (cifs_sb == NULL)
 		return;
 
+	atomic_inc(&cifs_sb->umount_aborts);
 	tcon = cifs_sb_master_tcon(cifs_sb);
 
 	spin_lock(&cifs_tcp_ses_lock);
fs/smb/client/cifsglob.h +1 -0
@@ -1486,6 +1486,7 @@ struct cifs_io_request {
 	struct netfs_io_request		rreq;
 	struct cifsFileInfo		*cfile;
 	pid_t				pid;
+	int				umount_aborts;
 };
 
 /* asynchronous read support */
fs/smb/client/cifsproto.h +2 -0
@@ -137,6 +137,8 @@ bool is_size_safe_to_change(struct cifsI
 			    bool from_readdir);
 void cifs_write_subrequest_terminated(struct cifs_io_subrequest *wdata,
 				      ssize_t result);
+bool cifs_io_stopped(struct cifs_io_subrequest *subreq);
+bool cifs_io_should_replay(struct cifs_io_subrequest *subreq);
 struct cifsFileInfo *find_writable_file(struct cifsInodeInfo *cifs_inode,
 					int flags);
 int __cifs_get_writable_file(struct cifsInodeInfo *cifs_inode,
fs/smb/client/file.c +55 -0

103 lines not on this page · raw message

fs/smb/client/smb2pdu.c +4 -12
@@ -4850,9 +4850,7 @@ do_retry:
 
 	/* see if we need to retry */
 	if (is_replayable_error(rdata->result) &&
-	    smb2_should_replay(tcon,
-			       &rdata->retries,
-			       &rdata->cur_sleep))
+	    cifs_io_should_replay(rdata))
 		rdata->replay = true;
 
 	trace_smb3_rw_credits(rreq_debug_id, subreq_debug_index, rdata->credits.value,
@@ -4961,9 +4959,7 @@ async_readv_out:
 out:
 	/* if the send error is retryable, let netfs know about it */
 	if (is_replayable_error(rc) &&
-	    smb2_should_replay(tcon,
-			       &rdata->retries,
-			       &rdata->cur_sleep)) {
+	    cifs_io_should_replay(rdata)) {
 		rdata->replay = true;
 		trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_retry_needed);
 		__set_bit(NETFS_SREQ_NEED_RETRY, &rdata->subreq.flags);
@@ -5200,9 +5196,7 @@ smb2_writev_callback(struct TCP_Server_I
 
 	/* see if we need to retry */
 	if (is_replayable_error(wdata->result) &&
-	    smb2_should_replay(tcon,
-			       &wdata->retries,
-			       &wdata->cur_sleep))
+	    cifs_io_should_replay(wdata))
 		wdata->replay = true;
 
 	cifs_write_subrequest_terminated(wdata, result ?: written);
@@ -5374,9 +5368,7 @@ async_writev_out:
 out:
 	/* if the send error is retryable, let netfs know about it */
 	if (is_replayable_error(rc) &&
-	    smb2_should_replay(tcon,
-			       &wdata->retries,
-			       &wdata->cur_sleep)) {
+	    cifs_io_should_replay(wdata)) {
 		wdata->replay = true;
 		trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_retry_needed);
 		__set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags);
author maintainer
#845 lore raw

PATCH 844/1005 smb: client: retry writeback on interrupts and allocation failures

In reply to Greg Kroah-Hartman

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

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

From: Paulo Alcantara <[email protected]>

commit fb39fbd782bcd2dccd05f633bc6ac348209dc272 upstream.

Issuing writes from a worker only helps when the task is already dying at issue time. A fatal signal can still arrive after that check and before __smb_send_rqst() checks again, or while waiting for a credit in cifs_call_async(), or in the middle of a send. The write then fails with -ERESTARTSYS, which isn't a replayable error, so netfs marks the subrequest failed and drops its folios clean:

netfs_sreq: R=000041f6[2] UPLD SUBMT ... s=400000 0/400000
smb3_write_err: R=000041f6[2] ... offset=0x400000 len=0x400000 rc=-512
netfs_failure: R=000041f6[2] UPLD ... upload e=-512

losing 4MiB of a 64MiB file closed by a task killed meanwhile. A failed memory allocation while building or sending a write drops its data the same way.

No server status maps to an interrupt error or to -ENOMEM, so for writeback such errors always mean the client gave up locally. Mark the subrequest for retry, with backoff and giving up on umount -f, as cifs did with is_retryable_error() before switching to netfslib and as NFS does for these errors. netfs collects writeback from a workqueue, so the retry gets prepared and issued with no signals pending.

Only the SMB2 read and write paths sleep before replaying, so SMB1 would resend such writes right away. Move the sleep to cifs_issue_read() and __cifs_issue_write().

Fixes 3ee1a1fc3981 ("cifs: Cut over to using netfslib")
---
 fs/smb/client/file.c    |   14 ++++++++++++++
 fs/smb/client/smb2pdu.c |   12 ++----------
 2 files changed, 16 insertions(+), 10 deletions(-)
fs/smb/client/file.c +14 -0
@@ -179,6 +179,9 @@ static void __cifs_issue_write(struct ne
 	if (wdata->req->cfile->invalidHandle)
 		goto fail;
 
+	if (wdata->replay && wdata->cur_sleep)
+		msleep(wdata->cur_sleep);
+
 	wdata->server->ops->async_writev(wdata);
 out:
 	return;
@@ -312,6 +315,9 @@ static void cifs_issue_read(struct netfs
 	    subreq->rreq->origin != NETFS_DIO_READ)
 		__set_bit(NETFS_SREQ_CLEAR_TAIL, &subreq->flags);
 
+	if (rdata->replay && rdata->cur_sleep)
+		msleep(rdata->cur_sleep);
+
 	trace_netfs_sreq(subreq, netfs_sreq_trace_submit);
 	rc = rdata->server->ops->async_readv(rdata);
 	if (rc)
@@ -2705,6 +2711,14 @@ void cifs_write_subrequest_terminated(st
 		spin_unlock(&inode->i_lock);
 	}
 
+	if ((is_interrupt_error(result) || result == -ENOMEM) &&
+	    wreq->origin == NETFS_WRITEBACK && cifs_io_should_replay(wdata)) {
+		wdata->replay = true;
+		trace_netfs_sreq(&wdata->subreq,
+				 netfs_sreq_trace_io_retry_needed);
+		__set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags);
+	}
+
 	netfs_write_subrequest_terminated(&wdata->subreq, result);
 }
 
fs/smb/client/smb2pdu.c +2 -10
@@ -4913,12 +4913,8 @@ smb2_async_readv(struct cifs_io_subreque
 
 	shdr = (struct smb2_hdr *)buf;
 
-	if (rdata->replay) {
-		/* Back-off before retry */
-		if (rdata->cur_sleep)
-			msleep(rdata->cur_sleep);
+	if (rdata->replay)
 		smb2_set_replay(server, &rqst);
-	}
 
 	if (rdata->credits.value > 0) {
 		shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(io_parms.length,
@@ -5315,12 +5311,8 @@ smb2_async_writev(struct cifs_io_subrequ
 	}
 #endif
 
-	if (wdata->replay) {
-		/* Back-off before retry */
-		if (wdata->cur_sleep)
-			msleep(wdata->cur_sleep);
+	if (wdata->replay)
 		smb2_set_replay(server, &rqst);
-	}
 
 	cifs_dbg(FYI, "async write at %llu %u bytes iter=%zx\n",
 		 io_parms->offset, io_parms->length, iov_iter_count(&wdata->subreq.io_iter));
author maintainer
#846 lore raw

PATCH 845/1005 smb: client: retry writes that couldnt be issued due to a reconnect

In reply to Greg Kroah-Hartman

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

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

From: Paulo Alcantara <[email protected]>

commit 64db0dc1f3e689145e698bc1b20ee70b1724b945 upstream.

__cifs_issue_write() fails a subrequest with -EAGAIN when its handle got invalidated or its credits belong to a session from before a reconnect, both before sending anything. netfs used to retry any -EAGAIN by itself, but now only retries subrequests marked for it, so these writes fail and their folios end writeback clean, losing the data.

Mark them for retry instead. The retry gets the handle reopened and fresh credits in cifs_prepare_write().

Fixes 82e8885bd763 ("netfs: when subreq is marked for retry, do not check if it faced an error")
---
 fs/smb/client/file.c |    6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
fs/smb/client/file.c +4 -2
@@ -187,10 +187,12 @@ out:
 	return;
 
 fail:
-	if (rc == -EAGAIN)
+	if (rc == -EAGAIN) {
 		trace_netfs_sreq(subreq, netfs_sreq_trace_retry);
-	else
+		__set_bit(NETFS_SREQ_NEED_RETRY, &subreq->flags);
+	} else {
 		trace_netfs_sreq(subreq, netfs_sreq_trace_fail);
+	}
 	add_credits_and_wake_if(wdata->server, &wdata->credits, 0);
 	cifs_write_subrequest_terminated(wdata, rc);
 	goto out;
author maintainer
#847 lore raw

PATCH 846/1005 smb: client: skip NULL channel in __cifs_put_smb_ses()

In reply to Greg Kroah-Hartman

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

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

From: Joseph Qi <[email protected]>

commit 8deaf64a59a263161dfc5128f8398fb3dcba4fac upstream.

cifs_chan_skip_or_disable() clears a secondary channel's slot in the session (ses->chans[chan_index].server = NULL) without lowering chan_count when the server stops supporting multichannel. When the session is later released, __cifs_put_smb_ses() walks every slot up to chan_count and calls cifs_put_tcp_session() on it, which dereferences the server pointer immediately, so a slot left NULL by the skip path makes the release crash with a NULL pointer dereference.

Clearing a slot without lowering chan_count is older than cifs_chan_skip_or_disable(): cifs_chan_update_iface() could already do the same since commit b54034a73baf9 ("cifs: during reconnect, update interface if necessary"), and the release loop has been unguarded since then. Commit 12d1e301bdfd1 ("cifs: do not let cifs_chan_update_iface deallocate channels") later removed that trigger, but the crash is reachable through it on older kernels.

cifs_decrease_secondary_channels() already guards the same put with if (server). Add the same guard to the release loop so a skipped channel slot is left alone.

Fixes b54034a73baf9 ("cifs: during reconnect, update interface if necessary")
---
 fs/smb/client/connect.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
fs/smb/client/connect.c +2 -1
@@ -2179,7 +2179,8 @@ void __cifs_put_smb_ses(struct cifs_ses
 			kref_put(&ses->chans[i].iface->refcount, release_iface);
 			ses->chans[i].iface = NULL;
 		}
-		cifs_put_tcp_session(ses->chans[i].server, 0);
+		if (ses->chans[i].server)
+			cifs_put_tcp_session(ses->chans[i].server, 0);
 		ses->chans[i].server = NULL;
 	}
 
author maintainer
#848 lore raw

PATCH 847/1005 smb: client: validate descriptor headers before query result allocation

In reply to Greg Kroah-Hartman

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

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

From: liuyong <[email protected]>

commit ffb59029c0d52bf76fdd2678f5d6fd13e26220dd upstream.

query_info() uses the server's returned length instead of the caller's minimum when a dynamic result is requested. A zero-length ACL response can therefore return ZERO_SIZE_PTR to id_mode_to_cifs_acl(), whose ownership-change path reads dacloffset before checking the header size. A KASAN-enabled test shows a read at address 0x20 and a kernel Oops.

Validate the returned range and the caller's minimum before allocating the dynamic result. Keep the reported length zero if validation fails.

Use the security descriptor header size as the minimum in SMB2_query_acl(). DACL-only and SACL-only xattr queries do not require owner and group SIDs, so enforcing MIN_SEC_DESC_LEN would reject short descriptors that these queries could previously return. The rewrite paths validate the required owner/group SIDs and DACL separately before using their contents.

These issues were discovered and fixed by Qihoo 360's Tulongfeng multi-agent system.

Fixes 9ee2afe5207b ("cifs: prevent copying past input buffer boundaries")
---
 fs/smb/client/cifsacl.h |   14 --------------
 fs/smb/client/smb2pdu.c |   11 ++++++++++-
 2 files changed, 10 insertions(+), 15 deletions(-)
fs/smb/client/cifsacl.h +0 -14
@@ -93,18 +93,4 @@ struct owner_group_sids {
 	struct owner_sid group;
 } __packed;
 
-/*
- * Minimum security identifier can be one for system defined Users
- * and Groups such as NULL SID and World or Built-in accounts such
- * as Administrator and Guest and consists of
- * Revision + Num (Sub)Auths + Authority + Domain (one Subauthority)
- */
-#define MIN_SID_LEN  (1 + 1 + 6 + 4) /* in bytes */
-
-/*
- * Minimum security descriptor can be one without any SACL and DACL and can
- * consist of revision, type, and two sids of minimum size for owner and group
- */
-#define MIN_SEC_DESC_LEN  (sizeof(struct smb_ntsd) + (2 * MIN_SID_LEN))
-
 #endif /* _CIFSACL_H */
fs/smb/client/smb2pdu.c +10 -1
@@ -4058,6 +4058,14 @@ replay_again:
 				ses->Suid, info_class, (__u32)info_type);
 
 	if (dlen) {
+		rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset),
+				       le32_to_cpu(rsp->OutputBufferLength),
+				       &rsp_iov, min_len);
+		if (rc) {
+			*dlen = 0;
+			goto qinf_exit;
+		}
+
 		*dlen = le32_to_cpu(rsp->OutputBufferLength);
 		if (!*data) {
 			*data = kmalloc(*dlen, GFP_KERNEL);
@@ -4112,7 +4120,8 @@ SMB2_query_acl(const unsigned int xid, s
 
 	return query_info(xid, tcon, persistent_fid, volatile_fid,
 			  0, SMB2_O_INFO_SECURITY, extra_info,
-			  SMB2_MAX_BUFFER_SIZE, MIN_SEC_DESC_LEN, data, plen);
+			  SMB2_MAX_BUFFER_SIZE, sizeof(struct smb_ntsd),
+			  data, plen);
 }
 
 int
author maintainer
#849 lore raw

PATCH 848/1005 smb: client: dont give up writeback on the first replayable error

In reply to Greg Kroah-Hartman

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

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

From: Paulo Alcantara <[email protected]>

commit 274dec866f0882ee5a0f3d58d4d5c31af0c02417 upstream.

Read and write retries follow the hard and retrans mount options, and mounts are soft with no retrans by default. For writeback this means that a single replayable error, e.g. a reconnect while sending, fails the subrequest and netfs ends writeback with its folios clean: the data is gone, possibly long after write(2) succeeded, with only fsync(2) left to notice. NFS soft mounts, by comparison, wait minutes for a server to answer before failing a request.

Keep retrying writeback on replayable errors, with exponential backoff:
forever on hard mounts, and on soft mounts for max(3, retrans) echo intervals from the first failure - 3 minutes by default, the time after which a silent server is considered unresponsive. The window applies to each write sent to the server, not to the whole writeback. umount -f or a shutdown still stops it right away. Direct and unbuffered writes, whose callers get the error, keep following the mount options.

Fixes 2c1238a7477a ("cifs: make retry logic in read/write path consistent with other paths")
---
 fs/smb/client/cifsglob.h  |    1 +
 fs/smb/client/file.c      |   21 +++++++++++++++++++++
 fs/smb/client/smb2ops.c   |    9 +--------
 fs/smb/client/smb2proto.h |    9 +++++++++
 4 files changed, 32 insertions(+), 8 deletions(-)
fs/smb/client/cifsglob.h +1 -0
@@ -1503,6 +1503,7 @@ struct cifs_io_subrequest {
 	bool				replay;
 	unsigned int			retries;	/* number of retries so far */
 	unsigned int			cur_sleep;	/* time to sleep before replay */
+	unsigned long			retry_deadline;
 	struct kvec			iov[2];
 	struct TCP_Server_Info		*server;
 #ifdef CONFIG_CIFS_SMB_DIRECT
fs/smb/client/file.c +21 -0
@@ -53,12 +53,33 @@ bool cifs_io_stopped(struct cifs_io_subr
 	return aborts && rwsem_is_contended(&sb->s_umount);
 }
 
+static bool cifs_writeback_retry_expired(struct cifs_io_subrequest *subreq,
+					 struct cifs_tcon *tcon)
+{
+	struct TCP_Server_Info *server = tcon->ses->server;
+	unsigned long window;
+
+	if (tcon->retry)
+		return false;
+	if (!subreq->retry_deadline) {
+		window = max(3U, server->retrans) * server->echo_interval;
+		subreq->retry_deadline = (jiffies + window) | 1;
+	}
+	return time_after(jiffies, subreq->retry_deadline);
+}
+
 bool cifs_io_should_replay(struct cifs_io_subrequest *subreq)
 {
 	struct cifs_tcon *tcon = tlink_tcon(subreq->req->cfile->tlink);
 
 	if (cifs_io_stopped(subreq))
 		return false;
+	if (subreq->rreq->origin == NETFS_WRITEBACK) {
+		if (cifs_writeback_retry_expired(subreq, tcon))
+			return false;
+		smb2_replay_backoff(&subreq->cur_sleep);
+		return true;
+	}
 	return smb2_should_replay(tcon, &subreq->retries, &subreq->cur_sleep);
 }
 
fs/smb/client/smb2ops.c +1 -8
@@ -2935,14 +2935,7 @@ bool smb2_should_replay(struct cifs_tcon
 		return false;
 
 	if (tcon->retry || (*pretries)++ < tcon->ses->server->retrans) {
-		/* Update sleep time for exponential backoff */
-		if (!(*pcur_sleep))
-			(*pcur_sleep) = 1;
-		else {
-			(*pcur_sleep) = ((*pcur_sleep) << 1);
-			if ((*pcur_sleep) > CIFS_MAX_SLEEP)
-				(*pcur_sleep) = CIFS_MAX_SLEEP;
-		}
+		smb2_replay_backoff(pcur_sleep);
 		return true;
 	}
 
fs/smb/client/smb2proto.h +9 -0
@@ -119,6 +119,15 @@ unsigned long smb_rqst_len(struct TCP_Se
 void smb2_set_next_command(struct cifs_tcon *tcon, struct smb_rqst *rqst);
 void smb2_set_related(struct smb_rqst *rqst);
 void smb2_set_replay(struct TCP_Server_Info *server, struct smb_rqst *rqst);
+
+static inline void smb2_replay_backoff(int *pcur_sleep)
+{
+	if (!*pcur_sleep)
+		*pcur_sleep = 1;
+	else
+		*pcur_sleep = min(*pcur_sleep << 1, CIFS_MAX_SLEEP);
+}
+
 bool smb2_should_replay(struct cifs_tcon *tcon, int *pretries,
 			int *pcur_sleep);
 
author maintainer
#850 lore raw

PATCH 849/1005 smb: client: dont retry failed writes forever regardless of mount options

In reply to Greg Kroah-Hartman

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

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

From: Paulo Alcantara <[email protected]>

commit bb203c9af62adb59d82e8ecb715e778329e3b771 upstream.

smb2_writev_callback() marks a write for retry whenever the server fails it with a replayable status, ignoring smb2_should_replay() and so the hard and retrans mount options. The latter is only used to decide on a backoff, so on a soft mount with no retrans, a server that keeps failing a write with e.g. STATUS_INSUFFICIENT_RESOURCES gets it resent forever, thousands of times per second, hanging anything waiting on its writeback:

smb3_write_err: R=005c359e[2] ... offset=0x27000 len=0xfdf0 rc=-11 (569410 times in 255 seconds, same subrequest, no growing delay)

Only retry such writes when cifs_io_should_replay() allows it, as already done for send errors in smb2_async_writev(), otherwise let them fail. Writeback thus keeps retrying them with backoff, within its retry window. Base the decision on the result of this attempt rather than on wdata->result, which is never reset on success and may hold the error of a previous attempt.

Writes cut short by a reconnect get retried regardless too. Have writeback ones go through cifs_io_should_replay() as well, so that they back off and soft mounts give up on them after the retry window, as on other replayable errors. Other writes cut short keep being retried, without spending the mount's retries, but as replays, since they may have reached the server, unless umount -f stopped them, which fails them with -EIO.

Fixes 2c1238a7477a ("cifs: make retry logic in read/write path consistent with other paths")
---
 fs/smb/client/smb2pdu.c |   25 ++++++++++++++-----------
 1 file changed, 14 insertions(+), 11 deletions(-)
fs/smb/client/smb2pdu.c +14 -11
@@ -5096,6 +5096,7 @@ smb2_writev_callback(struct TCP_Server_I
 	};
 	unsigned int rreq_debug_id = wdata->rreq->debug_id;
 	unsigned int subreq_debug_index = wdata->subreq.debug_index;
+	bool cut_short = false;
 	ssize_t result = 0;
 	size_t written = 0;
 
@@ -5109,10 +5110,7 @@ smb2_writev_callback(struct TCP_Server_I
 		credits.instance = server->reconnect_instance;
 		result = smb2_check_receive(mid, server, 0);
 		if (result != 0) {
-			if (is_replayable_error(result)) {
-				trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_retry_needed);
-				__set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags);
-			} else {
+			if (!is_replayable_error(result)) {
 				wdata->subreq.error = result;
 				trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_bad);
 			}
@@ -5141,12 +5139,9 @@ smb2_writev_callback(struct TCP_Server_I
 		break;
 	case MID_REQUEST_SUBMITTED:
 		trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_req_submitted);
-		__set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags);
-		result = -EAGAIN;
-		break;
+		fallthrough;
 	case MID_RETRY_NEEDED:
-		trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_retry_needed);
-		__set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags);
+		cut_short = true;
 		result = -EAGAIN;
 		break;
 	case MID_RESPONSE_MALFORMED:
@@ -5200,9 +5195,17 @@ smb2_writev_callback(struct TCP_Server_I
 	wdata->credits.value = 0;
 
 	/* see if we need to retry */
-	if (is_replayable_error(wdata->result) &&
-	    cifs_io_should_replay(wdata))
+	if (is_replayable_error(result) &&
+	    ((cut_short && wdata->rreq->origin != NETFS_WRITEBACK &&
+	      !cifs_io_stopped(wdata)) ||
+	     cifs_io_should_replay(wdata))) {
 		wdata->replay = true;
+		trace_netfs_sreq(&wdata->subreq,
+				 netfs_sreq_trace_io_retry_needed);
+		__set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags);
+	} else if (cut_short && cifs_io_stopped(wdata)) {
+		result = -EIO;
+	}
 
 	cifs_write_subrequest_terminated(wdata, result ?: written);
 	release_mid(server, mid);
author maintainer
#851 lore raw

PATCH 850/1005 smb: client: dont spend read retries on reads cut short by a reconnect

In reply to Greg Kroah-Hartman

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

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

From: Paulo Alcantara <[email protected]>

commit 1d4fcbfad120ddc30b81651f12096bfc84052f9a upstream.

smb2_readv_callback() always retries a read cut short by a reconnect, but still asks cifs_io_should_replay() whether to mark it as a replay. On a soft mount that spends one of the mount's retransmissions and grows the backoff, so a later replayable error on the reissued read can fail it early.

Mark such reads as replays without consulting the mount's retries, as already done for writes.

Fixes 2c1238a7477a ("cifs: make retry logic in read/write path consistent with other paths")
---
 fs/smb/client/smb2pdu.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
fs/smb/client/smb2pdu.c +3 -1
@@ -4739,6 +4739,7 @@ smb2_readv_callback(struct TCP_Server_In
 	struct smb_rqst rqst = { .rq_iov = &rdata->iov[0], .rq_nvec = 1 };
 	unsigned int rreq_debug_id = rdata->rreq->debug_id;
 	unsigned int subreq_debug_index = rdata->subreq.debug_index;
+	bool cut_short = false;
 
 	if (rdata->got_bytes) {
 		rqst.rq_iter	  = rdata->subreq.io_iter;
@@ -4787,6 +4788,7 @@ smb2_readv_callback(struct TCP_Server_In
 		trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_retry_needed);
 do_retry:
 		__set_bit(NETFS_SREQ_NEED_RETRY, &rdata->subreq.flags);
+		cut_short = true;
 		rdata->result = -EAGAIN;
 		if (server->sign && rdata->got_bytes)
 			/* reset bytes number since we can not check a sign */
@@ -4859,7 +4861,7 @@ do_retry:
 
 	/* see if we need to retry */
 	if (is_replayable_error(rdata->result) &&
-	    cifs_io_should_replay(rdata))
+	    (cut_short || cifs_io_should_replay(rdata)))
 		rdata->replay = true;
 
 	trace_smb3_rw_credits(rreq_debug_id, subreq_debug_index, rdata->credits.value,
author maintainer
#852 lore raw

PATCH 851/1005 smb: client: dont write back through O_DIRECT handles

In reply to Greg Kroah-Hartman

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

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

From: Paulo Alcantara <[email protected]>

commit 0e85145af984f7cae2aadaa694cb8612009027ac upstream.

Writeback uses the first writable handle of the inode, which may have been opened with O_DIRECT. Such handles are opened with FILE_NO_INTERMEDIATE_BUFFERING, for which Windows rejects any unaligned I/O with STATUS_INVALID_PARAMETER. Writeback of partly dirty pages and of the unaligned tail of a file through one of them fails, so netfs ends it with the folios clean and the data never reaches the server.

xfstests generic/051, where fsstress mixes both kinds of opens, loses about 1% of its writes this way:

smb3_write_err: ... offset=0xde90d7 len=0xbd0b rc=-22

All the rejected writes in a network capture were unaligned writes on a no-buffering handle; none of the aligned ones, and none of the unaligned ones on regular handles, were.

Prefer a handle that was not opened with O_DIRECT, and use one that was only if there is no other.

Fixes 1013e760d10e ("SMB3: Don't ignore O_SYNC/O_DSYNC and O_DIRECT flags")
---
 fs/smb/client/cifsglob.h |    1 +
 fs/smb/client/file.c     |   15 ++++++++++++---
 2 files changed, 13 insertions(+), 3 deletions(-)
fs/smb/client/cifsglob.h +1 -0
@@ -1897,6 +1897,7 @@ enum cifs_find_flags {
 	FIND_WITH_DELETE	= (1U << 1),
 	FIND_NO_PENDING_DELETE	= (1U << 2),
 	FIND_OPEN_FLAGS		= (1U << 3),
+	FIND_NO_DIRECT		= (1U << 4),
 };
 
 #define   MID_FREE 0
fs/smb/client/file.c +12 -3
@@ -362,9 +362,15 @@ static void cifs_begin_writeback(struct
 	struct cifs_io_request *req = container_of(wreq, struct cifs_io_request, rreq);
 	int ret;
 
-	ret = cifs_get_writable_file(CIFS_I(wreq->inode), FIND_ANY, &req->cfile);
+	ret = cifs_get_writable_file(CIFS_I(wreq->inode), FIND_NO_DIRECT,
+				     &req->cfile);
 	if (ret) {
-		cifs_dbg(VFS, "No writable handle in writepages ret=%d\n", ret);
+		ret = cifs_get_writable_file(CIFS_I(wreq->inode), FIND_ANY,
+					     &req->cfile);
+	}
+	if (ret) {
+		cifs_dbg(VFS, "%s: couldn't find writable handle: %d\n",
+			 __func__, ret);
 		return;
 	}
 
@@ -2835,7 +2841,7 @@ int __cifs_get_writable_file(struct cifs
 	}
 
 	if (test_bit(CIFS_INO_TMPFILE, &cifs_inode->flags))
-		find_flags = FIND_ANY;
+		find_flags &= FIND_NO_DIRECT;
 
 	cifs_sb = CIFS_SB(cifs_inode);
 
@@ -2865,6 +2871,9 @@ refind_writable:
 		    !open_flags_match(cifs_inode, open_flags,
 				      open_file->f_flags))
 			continue;
+		if ((find_flags & FIND_NO_DIRECT) &&
+		    (open_file->f_flags & O_DIRECT))
+			continue;
 		if (OPEN_FMODE(open_file->f_flags) & FMODE_WRITE) {
 			if (!open_file->invalidHandle) {
 				/* found a good writable file */
author maintainer
#853 lore raw

PATCH 852/1005 dm log userspace: drop the device reference on error

In reply to Greg Kroah-Hartman

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

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

From: [email protected] <[email protected]>

commit 0550d3b14e008b033b02cfce668008ec6addffe4 upstream.

userspace_ctr() takes a reference on the log device with dm_get_device(). When the integrated-flush workqueue allocation fails it jumps to the shared error path, which frees the log context without dropping that reference, so the device stays busy and cannot be removed.

userspace_dtr() drops the reference correctly; do the same here.

Fixes 5066a4df1f42 ("dm log userspace: allow mark requests to piggyback on flush requests")
---
 drivers/md/dm-log-userspace-base.c |    6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/md/dm-log-userspace-base.c +5 -1
@@ -294,9 +294,11 @@ static int userspace_ctr(struct dm_dirty
 		}
 		r = dm_get_device(ti, devices_rdata,
 				  dm_table_get_mode(ti->table), &lc->log_dev);
-		if (r)
+		if (r) {
 			DMERR("Failed to register %s with device-mapper",
 			      devices_rdata);
+			goto out;
+		}
 	}
 
 	if (lc->integrated_flush) {
@@ -315,6 +317,8 @@ static int userspace_ctr(struct dm_dirty
 out:
 	kfree(devices_rdata);
 	if (r) {
+		if (lc->log_dev)
+			dm_put_device(lc->ti, lc->log_dev);
 		mempool_exit(&lc->flush_entry_pool);
 		kfree(lc);
 		kfree(ctr_str);
author maintainer
#854 lore raw

PATCH 853/1005 dm: avoid double-dropping the zone reset submission reference

In reply to Greg Kroah-Hartman

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

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

From: Yaohan Li <[email protected]>

commit c4965effbe15f837a8089e79c0fc17ab19363cce upstream.

On an error in __send_zone_reset_all(), the submission reference held by the dm_io can be decremented there and again by the caller's error path. If another clone is still outstanding, the second drop can release the dm_io before that clone completes.

Only drop the submission reference in __send_zone_reset_all() on success. On failure, leave the reference for the caller's existing error handling to release once.

The error path was reproduced under KASAN with an injected GFP_NOIO allocation failure while another zone-reset clone remained in flight. With the change, the same failure was reported normally, without the observed use-after-free, and ordinary zone resets continued to work.

Fixes 81e7706345f06 ("dm: handle REQ_OP_ZONE_RESET_ALL")
Assisted-by ZCode:GLM-4
---
 drivers/md/dm.c |    9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
drivers/md/dm.c +7 -2
@@ -1929,8 +1929,13 @@ static blk_status_t __send_zone_reset_al
 			break;
 	}
 
-	/* Release the reference that alloc_io() took for submission. */
-	atomic_sub(1, &ci->io->io_count);
+	/*
+	 * Release the reference that alloc_io() took for submission. On error,
+	 * that reference was not consumed: dm_split_and_process_bio() releases
+	 * it on the error path, so do not release it here a second time.
+	 */
+	if (sts == BLK_STS_OK)
+		atomic_dec(&ci->io->io_count);
 
 	return sts;
 }
author maintainer
#855 lore raw

PATCH 854/1005 dm: fail a REQ_PREFLUSH bio with data when its preflush fails

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 e92cd41e8e5ee5616c6c7cd4378661d942f0a7c0 upstream.

For a bio with REQ_PREFLUSH and data, dm core may send an empty flush first. If the flush fails, __dm_io_complete() still reissues the bio without REQ_PREFLUSH and drops the error. When that write succeeds, the XFS log keeps running and fsync() can return 0.

End the bio with the flush error instead of writing the data, as blk-mq does.

Fixes 6a8736d10cb4 ("dm: relax ordering of bio-based flush implementation")
---
 drivers/md/dm.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/md/dm.c +2 -2
@@ -983,7 +983,7 @@ static void __dm_io_complete(struct dm_i
 	if (requeued)
 		return;
 
-	if (unlikely(requeue_flush_with_data)) {
+	if (unlikely(requeue_flush_with_data) && !io_error) {
 		/*
 		 * Preflush done for flush with data, reissue
 		 * without REQ_PREFLUSH.
@@ -991,7 +991,7 @@ static void __dm_io_complete(struct dm_i
 		bio->bi_opf &= ~REQ_PREFLUSH;
 		queue_io(md, bio);
 	} else {
-		/* done with normal IO or empty flush */
+		/* done with normal IO, empty flush or failed preflush */
 		if (io_error)
 			bio->bi_status = io_error;
 		bio_endio(bio);
author maintainer
#856 lore raw

PATCH 855/1005 dm: fix infinite loop in dm_blk_do_report_zones()

In reply to Greg Kroah-Hartman

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

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

From: Mark Bundschuh <[email protected]>

commit 648320de920b30ae1730bbf0e8b86c0df0fb490a upstream.

If the device underlying a zoned target is removed, its capacity is set to 0 and blkdev_report_zones() returns 0 without reporting any zones. The mapped device keeps its old capacity, so args->zone_idx and args->next_sector never advance and dm_blk_do_report_zones() loops forever. On non-preemptible kernels this causes soft lockups and RCU stalls.

The following sequence of commands triggers the hang:

modprobe scsi_debug zbc=managed dev_size_mb=1024 zone_size_mb=64 udevadm settle
echo '0 2097152 linear /dev/sda 0' | dmsetup create lin echo 1 > /sys/block/sda/device/delete
blkzone report -o 0 -c 1 /dev/mapper/lin

Fix this by returning -EIO when a target reports no zones. The target always maps args->next_sector, so a zero return means the underlying device no longer covers that sector.

---
 drivers/md/dm-zone.c |    2 ++
 1 file changed, 2 insertions(+)
drivers/md/dm-zone.c +2 -0
@@ -33,6 +33,8 @@ static int dm_blk_do_report_zones(struct
 					      nr_zones - args->zone_idx);
 		if (ret < 0)
 			return ret;
+		if (!ret)
+			return -EIO;
 	} while (args->zone_idx < nr_zones &&
 		 args->next_sector < get_capacity(md->disk));
 
author maintainer
#857 lore raw

PATCH 856/1005 dm: fix use-after-free when dm_get_device() widens the open mode

In reply to Greg Kroah-Hartman

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

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

From: Ming-Hung Tsai <[email protected]>

commit c834161ded1a141a58d5f03b24f6894291222c96 upstream.

There's an UAF bug in dm_get_device(): when a table construction calls dm_get_device() on the same device twice with widen access mode (e.g., read-only first then read-write), the second dm_get_device() calls upgrade_mode(), which reopens the device in upgraded mode, making previously returned dm_dev* a stale pointer.

Fixing approaches:
- Add per-mode views (dm_dev_ref) from a per-device dm_dev_internal to multiple table_devices.
- Keep reusing the dm_dev_ref when the requested mode is included, i.e., a read-only reference can reuse the read-write opened device within a table.
- Maintain a canonical block_device pointer in dm_dev_internal for handling the DM_TABLE_DEPS ioctl.

Also tweak the way of mode sharing check in find_ref() to "(x & mask) == mask". The result stays the same to the previous upgrade_mode() guard "(x | mask) == x".

Pros: keep the relationship between dm_dev_internal and table_device:
one dm_dev_internal per device, regardless the mode, so the output of DMM_TABLE_DEPS ioctl unchanged.

Cons: extra dm_dev_ref allocation.

Note that now the table_device's count not necessarily mean the number tables referecing this <dev, mode> pair, since we're allowing multiple references within a table.

Fixes 86f1152b117a ("dm: allow active and inactive tables to share dm_devs")
---
 drivers/md/dm-ioctl.c |    2 
 drivers/md/dm-table.c |  140 +++++++++++++++++++++++++++-----------------------
 drivers/md/dm.c       |    2 
 drivers/md/dm.h       |   18 ++++++
 4 files changed, 97 insertions(+), 65 deletions(-)
drivers/md/dm-ioctl.c +1 -1
@@ -1794,7 +1794,7 @@ static void retrieve_deps(struct dm_tabl
 	deps->count = count;
 	count = 0;
 	list_for_each_entry(dd, dm_table_get_devices(table), list)
-		deps->dev[count++] = huge_encode_dev(dd->dm_dev->bdev->bd_dev);
+		deps->dev[count++] = huge_encode_dev(dd->bdev->bd_dev);
 
 	param->data_size = param->data_start + needed;
 }
drivers/md/dm-table.c +78 -62

202 lines not on this page · raw message

drivers/md/dm.c +1 -1
@@ -1588,7 +1588,7 @@ static void __send_empty_flush(struct cl
 			 */
 			clone = alloc_tio(ci, NULL, 0, &len, GFP_NOIO);
 			atomic_add(1, &ci->io->io_count);
-			bio_set_dev(clone, dd->dm_dev->bdev);
+			bio_set_dev(clone, dd->bdev);
 			clone->bi_end_io = clone_endio;
 			dm_submit_bio_remap(clone, NULL);
 		}
drivers/md/dm.h +17 -1
@@ -37,10 +37,26 @@
 
 /*
  * List of devices that a metadevice uses and should open/close.
+ * There is one dm_dev_internal per device. It holds one dm_dev_ref
+ * for each mode that the targets opened the device with.
  */
 struct dm_dev_internal {
 	struct list_head list;
-	refcount_t count;
+	struct block_device *bdev;
+	struct list_head refs;
+};
+
+/*
+ * One open of a device with one mode, shared by the targets of a table.
+ * dm_get_device() reuses a dm_dev_ref whose mode covers the requested
+ * mode, and adds a new one only when none does. So the dm_dev_refs of
+ * a device have different modes, and a table holds each table_device
+ * at most once. table_device->count is still the number of tables that
+ * use the table_device.
+ */
+struct dm_dev_ref {
+	struct list_head list;
+	refcount_t count;	/* dm_get_device() calls that returned dm_dev */
 	struct dm_dev *dm_dev;
 };
 
author maintainer
#858 lore raw

PATCH 857/1005 dm: Reject table setup after queue or disk teardown

In reply to Greg Kroah-Hartman

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

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

From: Kirtikumar Anandrao Ramchandani <[email protected]>

commit ae310e4ad872a42f4707a596e66417f2aaa52826 upstream.

A failed table load can leave a mapped device in a state where its queue has already been initialized or its disk has been removed, while md->type is still DM_TYPE_NONE. A later table load then calls blk_mq_init_allocated_queue() on the same queue. If del_gendisk() exited the old hardware contexts, blk_mq_exit_hctx() dereferences their cleared flush queue pointer.

Reject setup attempts after queue initialization or disk removal. A failed request queue initialization still leaves md->tag_set NULL and can be retried. Set the request-based disk operations only after that initialization succeeds, so an unsuccessful attempt cannot leave a bio-based retry with request-based operations.

---
 drivers/md/dm.c |    6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/md/dm.c +5 -1
@@ -2611,13 +2611,17 @@ int dm_setup_md_queue(struct mapped_devi
 
 	WARN_ON_ONCE(type == DM_TYPE_NONE);
 
+	/* A failed setup may have left the queue initialized or the disk dead. */
+	if (md->tag_set || test_bit(GD_DEAD, &md->disk->state))
+		return -ENODEV;
+
 	if (type == DM_TYPE_REQUEST_BASED) {
-		md->disk->fops = &dm_rq_blk_dops;
 		r = dm_mq_init_request_queue(md, t);
 		if (r) {
 			DMERR("Cannot initialize queue for request-based dm mapped device");
 			return r;
 		}
+		md->disk->fops = &dm_rq_blk_dops;
 	}
 
 	r = dm_calculate_queue_limits(t, &limits);
author maintainer
#859 lore raw

PATCH 858/1005 dm cache: reject kcopyd client destory if it setup failed

In reply to Greg Kroah-Hartman

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

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

From: Edward Adam Davis <[email protected]>

commit 8b97b168eb4d3affcf23d2980a0c3f35ed9262e2 upstream.

The value of cache->copier is -EINTR when failed to create a rescuer kthread for wq kcopyd, in cache_create(), the code jumps directly to __destroy(cache), it merely performs a simple check to see whether copier is NULL, potentially hitting:

BUG: KASAN: null-ptr-deref in dm_kcopyd_client_destroy+0xae/0x480 drivers/md/dm-kcopyd.c:980
Read of size 4 at addr 0000000000000174 by task syz.2.19/6560
Call Trace:
 dm_kcopyd_client_destroy+0xae/0x480 drivers/md/dm-kcopyd.c:980
 __destroy+0x172/0x2f0 drivers/md/dm-cache-target.c:1973
 cache_create drivers/md/dm-cache-target.c:2604 [inline]
 cache_ctr+0x1674/0x2bf0 drivers/md/dm-cache-target.c:2649
 dm_table_add_target+0x58d/0xc70 drivers/md/dm-table.c:749
 populate_table drivers/md/dm-ioctl.c:1602 [inline]
 table_load+0x325/0x8a0 drivers/md/dm-ioctl.c:1645
 ctl_ioctl drivers/md/dm-ioctl.c:2221 [inline]

Set copier to NULL to avoid destroying a invalid kcopy client.

---
 drivers/md/dm-cache-target.c |    1 +
 1 file changed, 1 insertion(+)
drivers/md/dm-cache-target.c +1 -0
@@ -2544,6 +2544,7 @@ static int cache_create(struct cache_arg
 	if (IS_ERR(cache->copier)) {
 		*error = "could not create kcopyd client";
 		r = PTR_ERR(cache->copier);
+		cache->copier = NULL;
 		goto bad;
 	}
 
author maintainer
#860 lore raw

PATCH 859/1005 dm cache: validate the discard block size before narrowing

In reply to Greg Kroah-Hartman

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

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

From: Kirtikumar Anandrao Ramchandani <[email protected]>

commit df8daa4d916c88ef7888c738e0eb3b6f11714a6f upstream.

The discard block size doubles until the origin fits within the discard bitset limit. too_many_discard_blocks() passes this sector_t size to sector_div(), whose divisor is only 32 bits. Once the size exceeds that range, the division uses a truncated divisor, which can become zero.

Use a 64-bit divisor when checking the block count. The selected size is stored in a u32, so reject sizes that cannot be represented before the assignment and before calculating the bitset size. This prevents a truncated zero size from reaching dm_sector_div_up().

An earlier proposal checks whether the mapped length exceeds the origin device. This fix also covers an origin device whose valid size requires a discard block size beyond the field's range.

Reported-by [email protected]
Fixes 08b184514f65 ("dm cache: revert 'prevent corruption caused by discard_block_size > cache_block_size'")
---
 drivers/md/dm-cache-target.c |   14 ++++++++++----
 1 file changed, 10 insertions(+), 4 deletions(-)
drivers/md/dm-cache-target.c +10 -4
@@ -17,6 +17,7 @@
 #include <linux/jiffies.h>
 #include <linux/init.h>
 #include <linux/kstrtox.h>
+#include <linux/math64.h>
 #include <linux/mempool.h>
 #include <linux/module.h>
 #include <linux/rwsem.h>
@@ -2383,9 +2384,7 @@ static int create_cache_policy(struct ca
 static bool too_many_discard_blocks(sector_t discard_block_size,
 				    sector_t origin_size)
 {
-	(void) sector_div(origin_size, discard_block_size);
-
-	return origin_size > MAX_DISCARD_BLOCKS;
+	return div64_u64(origin_size, discard_block_size) > MAX_DISCARD_BLOCKS;
 }
 
 static sector_t calculate_discard_block_size(sector_t cache_block_size,
@@ -2422,6 +2421,7 @@ static int cache_create(struct cache_arg
 	struct cache *cache;
 	struct dm_target *ti = ca->ti;
 	dm_block_t origin_blocks;
+	sector_t discard_block_size;
 	struct dm_cache_metadata *cmd;
 	bool may_format = ca->features.mode == CM_WRITE;
 
@@ -2521,9 +2521,15 @@ static int cache_create(struct cache_arg
 	}
 	clear_bitset(cache->dirty_bitset, from_cblock(cache->cache_size));
 
-	cache->discard_block_size =
+	discard_block_size =
 		calculate_discard_block_size(cache->sectors_per_block,
 					     cache->origin_sectors);
+	if (discard_block_size > U32_MAX) {
+		*error = "Discard block size exceeds 32 bits";
+		r = -EOVERFLOW;
+		goto bad;
+	}
+	cache->discard_block_size = discard_block_size;
 	cache->discard_nr_blocks = to_dblock(dm_sector_div_up(cache->origin_sectors,
 							      cache->discard_block_size));
 	cache->discard_bitset = alloc_bitset(from_dblock(cache->discard_nr_blocks));
author maintainer
#861 lore raw

PATCH 860/1005 dm crypt: fix use of uninitialized percpu_counter in ctr error path

In reply to Greg Kroah-Hartman

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

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

From: Zhao Feng <[email protected]>

commit 8ba1ade3e6b595b9091040feaa3341d7e45ba95d upstream.

If percpu_counter_init() fails in crypt_ctr() (e.g. when the underlying percpu allocation fails under memory pressure or fault injection), the error path jumps to "bad", which calls crypt_dtr(). crypt_dtr() then evaluates WARN_ON(percpu_counter_sum(&cc->n_allocated_pages) != 0) and calls percpu_counter_destroy() on a counter that was never initialized, because __percpu_counter_init_many() returns -ENOMEM before calling raw_spin_lock_init() on fbc->lock.

With lockdep enabled this triggers "INFO: trying to register non-static key" in __percpu_counter_sum(), as reported by syzbot. The console additionally shows "crypt: Unknown error (-ENOMEM)" because this failure path sets no ti->error.

Move percpu_counter_init() to right after the allocation of cc, before ti->private is set and before any "goto bad" can happen. On failure, set ti->error and free cc directly, so that crypt_dtr() is only ever called with an initialized counter.

Reported-by [email protected]
Fixes 5059353df86e ("dm crypt: limit the number of allocated pages")
---
 drivers/md/dm-crypt.c |   12 ++++++++----
 1 file changed, 8 insertions(+), 4 deletions(-)
drivers/md/dm-crypt.c +8 -4
@@ -3208,6 +3208,14 @@ static int crypt_ctr(struct dm_target *t
 		ti->error = "Cannot allocate encryption context";
 		return -ENOMEM;
 	}
+
+	ret = percpu_counter_init(&cc->n_allocated_pages, 0, GFP_KERNEL);
+	if (ret < 0) {
+		ti->error = "Cannot initialize page counter";
+		kfree_sensitive(cc);
+		return ret;
+	}
+
 	cc->key_size = key_size;
 	cc->sector_size = (1 << SECTOR_SHIFT);
 	cc->sector_shift = 0;
@@ -3219,10 +3227,6 @@ static int crypt_ctr(struct dm_target *t
 	crypt_calculate_pages_per_client();
 	spin_unlock(&dm_crypt_clients_lock);
 
-	ret = percpu_counter_init(&cc->n_allocated_pages, 0, GFP_KERNEL);
-	if (ret < 0)
-		goto bad;
-
 	/* Optional parameters need to be read before cipher constructor */
 	if (argc > 5) {
 		ret = crypt_ctr_optional(ti, argc - 5, &argv[5]);
author maintainer
#862 lore raw

PATCH 861/1005 dm mpath: fix buffer overflow in parse_hw_handler()

In reply to Greg Kroah-Hartman

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

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

From: [email protected] <[email protected]>

commit 8f611fe94a781c6fb658488cc7eab4e4923e6df6 upstream.

parse_hw_handler() builds the hw_handler parameter string in a buffer sized with

	len = 4;

plus one byte per argument. Those four bytes were meant for the decimal form of the parameter count, three digits plus the terminating NUL. dm_read_arg_group() accepts up to 1024 arguments and the count written is 'hw_argc - 1', so a count of 1000 or more needs four digits plus the NUL and sprintf() writes one byte past the allocation.

Size the buffer from the actual string length instead.

Fixes 2bfd2e1337f0 ("[SCSI] scsi_dh: Use scsi_dh_set_params() in multipath.")
---
 drivers/md/dm-mpath.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/md/dm-mpath.c +2 -1
@@ -1085,8 +1085,9 @@ static int parse_hw_handler(struct dm_ar
 
 	if (hw_argc > 1) {
 		char *p;
-		int i, j, len = 4;
+		int i, j, len;
 
+		len = snprintf(NULL, 0, "%d", hw_argc - 1) + 1;
 		for (i = 0; i <= hw_argc - 2; i++)
 			len += strlen(as->argv[i]) + 1;
 		p = m->hw_handler_params = kzalloc(len, GFP_KERNEL);
author maintainer
#863 lore raw

PATCH 862/1005 dm mpath: cap queue_if_no_path_timeout_secs

In reply to Greg Kroah-Hartman

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

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

From: Yingjie Wang <[email protected]>

commit ae5b40accbc06f93e6a513e0e9a07fd32b197e49 upstream.

enable_nopath_timeout() arms the no-path timer with
jiffies + queue_if_no_path_timeout_secs * HZ. The module parameter is an unbounded unsigned long, so the delay can exceed what mod_timer()
handles: a delay above LONG_MAX is treated as already expired, and values above ULONG_MAX / HZ also wrap in the multiplication. The timer then clears queue_if_no_path right away, and I/O queued after the last path fails gets -EIO instead of waiting for the configured time.

On x86-64 with HZ=1000, 9223372036854776 seconds failed a write after 124 ms while one second less remained queued throughout a 4.2-second observation window. A value of 18446744073709552 seconds wrapped to 384 jiffies and failed the write after 455 ms. On 32-bit kernels with HZ=1000 the delay passes LONG_MAX above 2147483 seconds, a little under 25 days.

Cap the seconds value at the largest whole-second delay not exceeding MAX_JIFFY_OFFSET before multiplying by HZ. This prevents signed-delta overflow and multiplication wrap. The timer wheel's existing handling of very long delays is unchanged.

Fixes be240ff5e402 ("dm mpath: Add timeout mechanism for queue_if_no_path")
---
 drivers/md/dm-mpath.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/md/dm-mpath.c +2 -1
@@ -797,7 +797,8 @@ static void queue_if_no_path_timeout_wor
 static void enable_nopath_timeout(struct multipath *m)
 {
 	unsigned long queue_if_no_path_timeout =
-		READ_ONCE(queue_if_no_path_timeout_secs) * HZ;
+		min_t(unsigned long, READ_ONCE(queue_if_no_path_timeout_secs),
+		      MAX_JIFFY_OFFSET / HZ) * HZ;
 
 	lockdep_assert_held(&m->lock);
 
author maintainer
#864 lore raw

PATCH 863/1005 dm thin: avoid wrapping no_space_timeout

In reply to Greg Kroah-Hartman

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

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

From: Yingjie Wang <[email protected]>

commit bcb78d49620f666b4a9d62997691e8d031fd4ebc upstream.

set_pool_mode() converts the no_space_timeout module parameter with READ_ONCE(no_space_timeout_secs) * HZ. The usual arithmetic conversions evaluate the product as unsigned int, so it can wrap before being stored in the unsigned long delay. With HZ=1000, 4294968 seconds becomes 704
jiffies: a pool that runs out of data space switches to error_if_no_space and fails queued writes with -ENOSPC after about 0.7 seconds.

Widen the value before the multiplication and cap it at MAX_JIFFY_OFFSET / HZ, so large timeouts no longer wrap into short delays. On 32-bit kernels, values beyond the supported jiffies range saturate at the largest whole-second delay not exceeding MAX_JIFFY_OFFSET. The timer wheel's existing handling of very long delays is unchanged.

Fixes 80c578930ce7 ("dm thin: add 'no_space_timeout' dm-thin-pool module param")
---
 drivers/md/dm-thin.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/md/dm-thin.c +3 -1
@@ -2542,7 +2542,9 @@ static void set_pool_mode(struct pool *p
 	struct pool_c *pt = pool->ti->private;
 	bool needs_check = dm_pool_metadata_needs_check(pool->pmd);
 	enum pool_mode old_mode = get_pool_mode(pool);
-	unsigned long no_space_timeout = READ_ONCE(no_space_timeout_secs) * HZ;
+	unsigned long no_space_timeout =
+		min_t(unsigned long, READ_ONCE(no_space_timeout_secs),
+		      MAX_JIFFY_OFFSET / HZ) * HZ;
 
 	/*
 	 * Never allow the pool to transition to PM_WRITE mode if user
author maintainer
#865 lore raw

PATCH 864/1005 dm-pcache: do not advance dirty_tail after backing flush failure

In reply to Greg Kroah-Hartman

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

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

From: guolingxing <[email protected]>

commit b1310cb291935c788f34ed6eb1e7e9b42cfac045 upstream.

After all writeback bios for a kset complete, writeback_ctx_end() flushes the backing device and then advances the persistent dirty_tail. However, backing_dev_flush() discards the error returned by blkdev_issue_flush(), so dirty_tail is advanced even when the written data is not known to be durable.

dirty_tail points to the first kset that still requires writeback. Advancing it causes recovery to treat the preceding kset as clean and allows its cache copy to eventually be reclaimed by garbage collection. If the backing device flush failed, a subsequent power failure may therefore result in data loss.

Make backing_dev_flush() return the flush status and handle a flush failure like a writeback I/O failure. Leave dirty_tail unchanged so that the same kset will be retried.

Fixes 1d57628ff95b ("dm-pcache: add persistent cache target in device-mapper")
---
 drivers/md/dm-pcache/backing_dev.c     |    4 ++--
 drivers/md/dm-pcache/backing_dev.h     |    2 +-
 drivers/md/dm-pcache/cache_writeback.c |   28 +++++++++++++++++++++-------
 3 files changed, 24 insertions(+), 10 deletions(-)
drivers/md/dm-pcache/backing_dev.c +2 -2
@@ -336,9 +336,9 @@ struct pcache_backing_dev_req *backing_d
 	return backing_req;
 }
 
-void backing_dev_flush(struct pcache_backing_dev *backing_dev)
+int backing_dev_flush(struct pcache_backing_dev *backing_dev)
 {
-	blkdev_issue_flush(backing_dev->dm_dev->bdev);
+	return blkdev_issue_flush(backing_dev->dm_dev->bdev);
 }
 
 int pcache_backing_init(void)
drivers/md/dm-pcache/backing_dev.h +1 -1
@@ -120,7 +120,7 @@ struct pcache_backing_dev_req *backing_d
 						struct pcache_backing_dev_req_opts *opts);
 void backing_dev_req_init(struct pcache_backing_dev_req *backing_req,
 			struct pcache_backing_dev_req_opts *opts);
-void backing_dev_flush(struct pcache_backing_dev *backing_dev);
+int backing_dev_flush(struct pcache_backing_dev *backing_dev);
 
 int pcache_backing_init(void);
 void pcache_backing_exit(void);
drivers/md/dm-pcache/cache_writeback.c +21 -7
@@ -18,12 +18,18 @@ static void writeback_ctx_end(struct pca
 		return;
 
 	if (!cache->writeback_ctx.ret) {
-		backing_dev_flush(cache->backing_dev);
-
-		mutex_lock(&cache->dirty_tail_lock);
-		cache_pos_advance(&cache->dirty_tail, cache->writeback_ctx.advance);
-		cache_encode_dirty_tail(cache);
-		mutex_unlock(&cache->dirty_tail_lock);
+		ret = backing_dev_flush(cache->backing_dev);
+		if (ret) {
+			pcache_dev_err(CACHE_TO_PCACHE(cache),
+				       "failed to flush backing device: %d", ret);
+			cache->writeback_ctx.ret = ret;
+		} else {
+			mutex_lock(&cache->dirty_tail_lock);
+			cache_pos_advance(&cache->dirty_tail,
+					  cache->writeback_ctx.advance);
+			cache_encode_dirty_tail(cache);
+			mutex_unlock(&cache->dirty_tail_lock);
+		}
 	}
 	queue_delayed_work(cache_get_wq(cache), &cache->writeback_work, 0);
 }
@@ -76,8 +82,16 @@ static inline bool is_cache_clean(struct
 
 void cache_writeback_exit(struct pcache_cache *cache)
 {
+	int ret;
+
 	cancel_delayed_work_sync(&cache->writeback_work);
-	backing_dev_flush(cache->backing_dev);
+
+	ret = backing_dev_flush(cache->backing_dev);
+	if (ret)
+		pcache_dev_err(CACHE_TO_PCACHE(cache),
+			       "failed to flush backing device during exit: %d",
+			       ret);
+
 	cache_tree_exit(&cache->writeback_key_tree);
 }
 
author maintainer
#866 lore raw

PATCH 865/1005 dm-sysfs: fix misbehavior if kobject_init_and_add fails

In reply to Greg Kroah-Hartman

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

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

From: Mikulas Patocka <[email protected]>

commit 406d576cc457203cf86eac7f17839b2efec81db4 upstream.

If kobject_init_and_add fails, we must call kobject_put (see the comment at kobject_init_and_add).

Before calling kobject_init_and_add, we must zero the kobject (see
https://lwn.net/Articles/52085/). If the first call to dm_sysfs_init failed, it may be called again, and that second call would see an uninitialized kobject.

Fixes 784aae735d9b ("dm: add name and uuid to sysfs")
---
 drivers/md/dm-sysfs.c |   17 ++++++++++++++---
 1 file changed, 14 insertions(+), 3 deletions(-)
drivers/md/dm-sysfs.c +14 -3
@@ -128,9 +128,20 @@ static const struct kobj_type dm_ktype =
  */
 int dm_sysfs_init(struct mapped_device *md)
 {
-	return kobject_init_and_add(dm_kobject(md), &dm_ktype,
-				    &disk_to_dev(dm_disk(md))->kobj,
-				    "%s", "dm");
+	struct kobject *kobj = dm_kobject(md);
+	int r;
+
+	/* The kobject must be zeroed before calling kobject_init */
+	memset(kobj, 0, sizeof(struct kobject));
+	r = kobject_init_and_add(kobj, &dm_ktype,
+				 &disk_to_dev(dm_disk(md))->kobj,
+				 "%s", "dm");
+	if (unlikely(r)) {
+		/* Weird semantics - we must call kobject_put on failure */
+		dm_sysfs_exit(md);
+		return r;
+	}
+	return 0;
 }
 
 /*
author maintainer
#867 lore raw

PATCH 866/1005 dm-verity: dont restart or panic on errors during system shutdown

In reply to Greg Kroah-Hartman

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

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

From: Weijiang Zhou <[email protected]>

commit 47930d1236d2988cdc580c10d3af21b6b02d7ece upstream.

Commit 252bd1256396 ("dm verity: skip verity work if I/O error when system is shutting down") stopped I/O errors during shutdown from triggering a restart, since devices may legitimately be gone by then. Errors that reach verity_handle_err(), e.g. through a failed hash block read followed by a failed FEC attempt, are not covered and still call kernel_restart() or panic().

During a reboot that is both wrong (nothing is corrupt) and harmful: it races with the reboot already in progress and replaces its reason with "dm-verity device corrupted", which bootloaders such as Android's treat as a verity failure and switch the device to EIO mode.

Apply the same shutdown check in verity_handle_err(). Corruption is still logged, recorded in hash_failed and reported via uevent, and the I/O still fails.

Fixes 252bd1256396 ("dm verity: skip verity work if I/O error when system is shutting down")
---
 drivers/md/dm-verity-target.c |   27 ++++++++++++++++++---------
 1 file changed, 18 insertions(+), 9 deletions(-)
drivers/md/dm-verity-target.c +18 -9
@@ -171,6 +171,15 @@ static void verity_hash_at_level(struct
 }
 
 /*
+ * Skip verity work in response to I/O error when system is shutting down.
+ */
+static inline bool verity_is_system_shutting_down(void)
+{
+	return system_state == SYSTEM_HALT || system_state == SYSTEM_POWER_OFF
+		|| system_state == SYSTEM_RESTART;
+}
+
+/*
  * Handle verification errors.
  */
 static int verity_handle_err(struct dm_verity *v, enum verity_block_type type,
@@ -219,6 +228,15 @@ out:
 	if (v->mode == DM_VERITY_MODE_LOGGING)
 		return 0;
 
+	/*
+	 * Devices may already be quiesced (e.g. UFS set offline by its
+	 * shutdown hook), so a failure here does not imply corruption.  Fail
+	 * the I/O but do not restart or panic, which would also override the
+	 * reboot reason of the shutdown already in progress.
+	 */
+	if (verity_is_system_shutting_down())
+		return 1;
+
 	if (v->mode == DM_VERITY_MODE_RESTART)
 		kernel_restart("dm-verity device corrupted");
 
@@ -593,15 +611,6 @@ error:
 	return r;
 }
 
-/*
- * Skip verity work in response to I/O error when system is shutting down.
- */
-static inline bool verity_is_system_shutting_down(void)
-{
-	return system_state == SYSTEM_HALT || system_state == SYSTEM_POWER_OFF
-		|| system_state == SYSTEM_RESTART;
-}
-
 static void restart_io_error(struct work_struct *w)
 {
 	kernel_restart("dm-verity device has I/O error");
author maintainer
#868 lore raw

PATCH 867/1005 dm persistent data: test return value of node_copy

In reply to Greg Kroah-Hartman

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

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

From: Mikulas Patocka <[email protected]>

commit 624d146d97c5fbe7200ef4b2dd5350ecf57d6b79 upstream.

There were 3 places where the return value of node_copy was not tested.

Assisted-by Claude:claude-opus-5
Fixes c671ffa55d8b ("dm btree remove: change a bunch of BUG_ON() calls to proper errors")
---
 drivers/md/persistent-data/dm-btree-remove.c |   13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)
drivers/md/persistent-data/dm-btree-remove.c +10 -3
@@ -253,7 +253,9 @@ static int __rebalance2(struct dm_btree_
 		/*
 		 * Merge
 		 */
-		node_copy(left, right, -nr_right);
+		ret = node_copy(left, right, -nr_right);
+		if (unlikely(ret))
+			return ret;
 		left->header.nr_entries = cpu_to_le32(nr_left + nr_right);
 		delete_at(parent, r->index);
 
@@ -315,13 +317,16 @@ static int delete_center_node(struct dm_
 {
 	uint32_t max_entries = le32_to_cpu(left->header.max_entries);
 	unsigned int shift = min(max_entries - nr_left, nr_center);
+	int ret;
 
 	if (nr_left + shift > max_entries) {
 		DMERR("node shift out of bounds");
 		return -EINVAL;
 	}
 
-	node_copy(left, center, -shift);
+	ret = node_copy(left, center, -shift);
+	if (unlikely(ret))
+		return ret;
 	left->header.nr_entries = cpu_to_le32(nr_left + shift);
 
 	if (shift != nr_center) {
@@ -333,7 +338,9 @@ static int delete_center_node(struct dm_
 		}
 
 		node_shift(right, shift);
-		node_copy(center, right, shift);
+		ret = node_copy(center, right, shift);
+		if (unlikely(ret))
+			return ret;
 		right->header.nr_entries = cpu_to_le32(nr_right + shift);
 	}
 	*key_ptr(parent, r->index) = right->keys[0];
author maintainer
#869 lore raw

PATCH 868/1005 dm persistent data: dont ignore writeback errors

In reply to Greg Kroah-Hartman

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

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

From: Mikulas Patocka <[email protected]>

commit fa887f2ebee7aff97eb87b3365939616ade09774 upstream.

An error returned by ie_cache_writeback could be silently overwritten by another successful ie_cache_writeback. This commit fixes disk_ll_commit, so that it doesn't ignore the error and returns it immediatelly.

Assisted-by Claude:claude-opus-5
Fixes 6b06dd5a9722 ("dm space map disk: cache a small number of index entries")
---
 drivers/md/persistent-data/dm-space-map-common.c |    9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
drivers/md/persistent-data/dm-space-map-common.c +6 -3
@@ -1190,17 +1190,20 @@ static dm_block_t disk_ll_max_entries(st
 
 static int disk_ll_commit(struct ll_disk *ll)
 {
-	int r = 0;
+	int r;
 	unsigned int i;
 
 	for (i = 0; i < IE_CACHE_SIZE; i++) {
 		struct ie_cache *iec = ll->ie_cache + i;
 
-		if (iec->valid && iec->dirty)
+		if (iec->valid && iec->dirty) {
 			r = ie_cache_writeback(ll, iec);
+			if (unlikely(r))
+				return r;
+		}
 	}
 
-	return r;
+	return 0;
 }
 
 int sm_ll_new_disk(struct ll_disk *ll, struct dm_transaction_manager *tm)
author maintainer
#870 lore raw

PATCH 869/1005 dm persistent data: dont leak bufio buffer if find_leaf fails

In reply to Greg Kroah-Hartman

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

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

From: Mikulas Patocka <[email protected]>

commit b27523a0781aae0b51ac13f29dc65373d14b8434 upstream.

If find_leaf fails, the function dm_btree_cursor_begin would return an error, but it would keep the dm-bufio buffers held. This would result in a memory leak and a warning when releasing the dm-bufio cache.

This commit fixes it, so that dm_btree_cursor_begin releases the buffers on error.

Assisted-by Claude:claude-opus-5
Fixes 7d111c81fa29 ("dm btree: introduce cursor api")
---
 drivers/md/persistent-data/dm-btree.c |    8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
drivers/md/persistent-data/dm-btree.c +7 -1
@@ -1582,7 +1582,13 @@ int dm_btree_cursor_begin(struct dm_btre
 	if (r)
 		return r;
 
-	return find_leaf(c);
+	r = find_leaf(c);
+	if (unlikely(r)) {
+		dm_btree_cursor_end(c);
+		return r;
+	}
+
+	return 0;
 }
 EXPORT_SYMBOL_GPL(dm_btree_cursor_begin);
 
author maintainer
#871 lore raw

PATCH 870/1005 dm snapshot: fix discard_granularity unit in snapshot_io_hints

In reply to Greg Kroah-Hartman

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

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

From: wuyuehong <[email protected]>

commit d7216d7be2bbfdf3312695b6e41a4fc7c5e22902 upstream.

snapshot_io_hints() copies the snapshot store's chunk_size, which is in 512-byte sectors, into queue_limits.discard_granularity, which, like all other members of struct queue_limits, is in bytes.

For snapshots with a chunk size smaller than 512 sectors, e.g. the 16 KiB (32-sector) chunks created by the syzkaller reproducer, the resulting granularity is smaller than a single sector. When dm_calculate_queue_limits() then stacks the target limits into the table limits:

blk_stack_limits(limits, &ti_limits, 0)

queue_limit_discard_alignment() truncates that granularity to zero sectors and sector_div() divides by zero:

  Oops: divide error: 0000 [#1] SMP KASAN NOPTI
  RIP: 0010:queue_limit_discard_alignment block/blk-settings.c:645 [inline]
  RIP: 0010:blk_stack_limits+0x1105/0x2d00 block/blk-settings.c:916
  Call Trace:
   dm_calculate_queue_limits+0x70c/0x1510 drivers/md/dm-table.c:1823
   dm_setup_md_queue+0x199/0x4f0 drivers/md/dm.c:2618
   table_load+0x4fd/0x8a0 drivers/md/dm-ioctl.c:1661

The divide fault itself only became reachable when commit e924da7d6622 ("block: Drop granularity check in queue_limit_discard_alignment()") removed the check for a sub-sector granularity in v6.13. Kernels before that returned a zero discard alignment instead of faulting, but they still advertised a granularity 512 times too small.

Use the same chunk_size << SECTOR_SHIFT conversion that io_overlaps_chunk() already applies to turn chunk_size into bytes.

Fixes 2e6023850e17 ("dm snapshot: add optional discard support features")
Reported-by [email protected]
---
 drivers/md/dm-snap.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/md/dm-snap.c +1 -1
@@ -2414,7 +2414,7 @@ static void snapshot_io_hints(struct dm_
 			snap = snap_src;
 
 		/* All discards are split on chunk_size boundary */
-		limits->discard_granularity = snap->store->chunk_size;
+		limits->discard_granularity = snap->store->chunk_size << SECTOR_SHIFT;
 		limits->max_hw_discard_sectors = snap->store->chunk_size;
 
 		up_read(&_origins_lock);
author maintainer
#872 lore raw

PATCH 871/1005 dm snapshot: split discards on chunk boundaries

In reply to Greg Kroah-Hartman

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

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

From: Chen Cheng <[email protected]>

commit 4fe2c2baad01da64d47f1a0c8fc093df994bcef5 upstream.

dm-snapshot did not set ti->max_discard_granularity when it allows discards, so a discard could reach the target unaligned, or spanning several chunks. Set the flag, so dm splits discards on chunk boundaries.

Fixes 2e6023850e17 ("dm snapshot: add optional discard support features")
---
 drivers/md/dm-snap.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/md/dm-snap.c +3 -1
@@ -1358,8 +1358,10 @@ static int snapshot_ctr(struct dm_target
 
 	ti->private = s;
 	ti->num_flush_bios = num_flush_bios;
-	if (s->discard_zeroes_cow)
+	if (s->discard_zeroes_cow) {
 		ti->num_discard_bios = (s->discard_passdown_origin ? 2 : 1);
+		ti->max_discard_granularity = true;
+	}
 	ti->per_io_data_size = sizeof(struct dm_snap_tracked_chunk);
 
 	/* Add snapshot to the list of snapshots for this origin */
author maintainer
#873 lore raw

PATCH 872/1005 dm snapshot: fix discard writing into the next COW chunk

In reply to Greg Kroah-Hartman

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

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

From: Chen Cheng <[email protected]>

commit 73174b4bb6fcd0e6cf973c9402a0fae2e567ad9f upstream.

zero_exception() zeroes one chunk of the COW device and takes the start sector from bio->bi_iter.bi_sector. remap_exception() has already set that to the COW chunk start plus the offset inside the chunk. That offset is needed for reads and writes, but for a discard it is wrong:
the zeroing window is shifted, so the head of the target chunk keeps its old data and the tail lands in the next COW chunk, which holds a different exception.

io_overlaps_chunk() should have caught this, but it only compares the length. "maps to entire chunks" in snapshot.rst also means the discard has to start on a chunk boundary.

A discard that is not a full chunk has a second problem: after remap_exception() it is sent to the COW device, where it hits a chunk that still backs a live exception. After a discard the contents are undefined, but the exception stays in the table and keeps pointing at that chunk, so a later read returns whatever the discard left instead of the snapshot's data.

Reproducer:

	truncate -s 4M o.img c.img
	o=$(losetup -f --show o.img)
	c=$(losetup -f --show c.img)
	dmsetup create snap --table \
		"0 8192 snapshot $o $c P 512 1 discard_zeroes_cow"

	# write two chunks, this creates two exceptions
	head -c 256K /dev/zero | tr '\000' '\252' > pat
	dd if=pat of=/dev/mapper/snap bs=256K seek=1 count=1 conv=notrunc
	dd if=pat of=/dev/mapper/snap bs=256K seek=2 count=1 conv=notrunc

	# shift the snapshot by 8 sectors, so a discard that is aligned on
	# top is unaligned inside the snapshot
	dmsetup create top --table "0 8184 linear /dev/mapper/snap 8"
	blkdiscard -o 262144 -l 262144 /dev/mapper/top
	sync
	echo 3 > /proc/sys/vm/drop_caches

	# chunk 1
	dd if=/dev/mapper/snap bs=512 skip=512 count=8 | od -An -tx1 -N1
	# chunk 2
	dd if=/dev/mapper/snap bs=512 skip=1024 count=8 | od -An -tx1 -N1
Before: aa 00  <- chunk 2 was zeroed although it was not discarded
After:  aa aa  <- nothing written, a discard is only a hint

Fix it by requiring the discard to start on a chunk boundary in io_overlaps_chunk(), and by finishing a discard that is not a full chunk with bio_endio() instead of passing it down to the COW device.

Fixes 2e6023850e17 ("dm snapshot: add optional discard support features")
---
 drivers/md/dm-snap.c |   12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)
drivers/md/dm-snap.c +7 -5
@@ -1948,8 +1948,8 @@ static void zero_exception(struct dm_sna
 
 static bool io_overlaps_chunk(struct dm_snapshot *s, struct bio *bio)
 {
-	return bio->bi_iter.bi_size ==
-		(s->store->chunk_size << SECTOR_SHIFT);
+	return bio->bi_iter.bi_size == (s->store->chunk_size << SECTOR_SHIFT) &&
+	       !(bio->bi_iter.bi_sector & s->store->chunk_mask);
 }
 
 static int snapshot_map(struct dm_target *ti, struct bio *bio)
@@ -2009,11 +2009,13 @@ static int snapshot_map(struct dm_target
 	e = dm_lookup_exception(&s->complete, chunk);
 	if (e) {
 		remap_exception(s, e, bio, chunk);
-		if (unlikely(bio_op(bio) == REQ_OP_DISCARD) &&
-		    io_overlaps_chunk(s, bio)) {
+		if (unlikely(bio_op(bio) == REQ_OP_DISCARD)) {
 			dm_exception_table_unlock(&lock);
 			up_read(&s->lock);
-			zero_exception(s, e, bio, chunk);
+			if (io_overlaps_chunk(s, bio))
+				zero_exception(s, e, bio, chunk);
+			else
+				bio_endio(bio);
 			r = DM_MAPIO_SUBMITTED; /* discard is not issued */
 			goto out;
 		}
author maintainer
#874 lore raw

PATCH 873/1005 dm zoned: back off when reclaim cannot make progress

In reply to Greg Kroah-Hartman

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

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

From: Kyrylo Biryuk <[email protected]>

commit 9bb1d14877f4929be17f7fdbeb4cfdf5025d464b upstream.

When a reclaim pass cannot make progress, dmz_reclaim_work() still ends with dmz_schedule_reclaim(). If the target is idle, dmz_should_reclaim() keeps returning true, the work is queued again with no delay and the worker spins on the same failing pass. This patch handles two such cases:

- dmz_do_reclaim() fails with -ENOSPC because no free zone is available to copy the data into, for example on a target without cache zones that has no free sequential zone left. The next patch also makes this the expected result when an idle target with cache zones has random zones but no free sequential zone.
- dmz_do_reclaim() finds no zone it can lock for reclaim and returns -EBUSY. Since commit 90a9b8693f1b ("dm zoned: reclaim random zones when idle"), dmz_should_reclaim() returns true on an idle target whenever the total number of random (and cache) zones is non-zero, whether or not any of them holds data. Each pass then also runs dmz_check_dev(), which checks every device for media events (a TEST UNIT READY on SCSI disks).

The -EBUSY loop lasts as long as the target stays idle; it ends when a pass finishes while the target is busy and has enough free zones. On three 27 TB host-managed SATA drives used as md RAID5 members (7.2.10 with the module built out of tree, all random zones free, target idle for 300 seconds, kprobes attached, two other drives on the controller being zero-filled), each member's SCSI device counted about 108,000 requests per second with the stock module and the system used about 915 s of CPU time, against about 46 s with this series. libata completes TEST UNIT READY in software, so these counters do not measure commands sent to the drives; the cost is CPU time.

When a pass fails with -ENOSPC or -EBUSY, retrying at once is unlikely to make progress: re-arm the idle poll instead, so that reclaim is retried after DMZ_IDLE_PERIOD unless a zone allocation or a "reclaim" message queues it earlier. On a busy target, zone allocations can restart reclaim immediately when free space is low enough to require reclaim. Re-arming also keeps the poll running after a complete idle drain. The poll can still stop after a pass that ends while reclaim is not needed; that is unchanged.

Skip the device check for these two results: they normally mean that there is no zone to copy into or no zone to reclaim, not that a device failed, and the I/O paths check the devices themselves. Use queue_delayed_work() so that work an allocation has already queued is not postponed.

A pass that fails with an I/O error, for example on an unreadable block of a device that stays online, is still retried at once while the target is idle; this patch does not change that.

Tested on 7.4-rc1 with this patch and the next one, on three emulated host-managed drives (scsi_debug, 1 GiB, 32 MiB zones) each under dm-zoned as md RAID5 members, all random zones free and the target idle for 300 seconds. With the stock module each member's SCSI device counted about 70.2 million requests and the reclaim workers used 726 s of CPU. With this series: 75 requests per member, 30 passes per worker (one per DMZ_IDLE_PERIOD) and 0.08 s of CPU. Data written during the tests read back with matching checksums, and no kernel warnings were logged.

Fixes 3b1a94c88b79 ("dm zoned: drive-managed zoned block device target")
Fixes 90a9b8693f1b ("dm zoned: reclaim random zones when idle")
---
 drivers/md/dm-zoned-reclaim.c |   10 ++++++++++
 1 file changed, 10 insertions(+)
drivers/md/dm-zoned-reclaim.c +10 -0
@@ -537,6 +537,16 @@ static void dmz_reclaim_work(struct work
 		dmz_nr_rnd_zones(zmd, zrc->dev_idx));
 
 	ret = dmz_do_reclaim(zrc);
+	if (ret == -ENOSPC || ret == -EBUSY) {
+		/*
+		 * No zone to copy into (-ENOSPC) or no zone to reclaim
+		 * (-EBUSY): retrying at once cannot make progress and would
+		 * spin. Poll again after the idle period instead, without
+		 * postponing work that an allocation has already queued.
+		 */
+		queue_delayed_work(zrc->wq, &zrc->work, DMZ_IDLE_PERIOD);
+		return;
+	}
 	if (ret && ret != -EINTR) {
 		if (!dmz_check_dev(zmd))
 			return;
author maintainer
#875 lore raw

PATCH 874/1005 dm zoned: do not reclaim a random zone into another random zone

In reply to Greg Kroah-Hartman

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

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

From: Kyrylo Biryuk <[email protected]>

commit dab527d83462a618d99bfc96370ce45ae3428706 upstream.

dmz_reclaim_rnd_data() falls back to a random destination zone when no free sequential zone is available and the target has cache zones. When the target is idle and the cache zone list is empty, dmz_get_rnd_zone_for_reclaim() selects random zones of the zoned device as well, so a random zone is then copied into another random zone. That frees nothing: the next pass picks the next random zone and copies it again, for as long as the target stays idle.

Seen on a two-device target (256 GiB regular cache device plus a 27 TB host-managed drive) used as an md RAID5 member: after a full rebuild every chunk was mapped and no sequential zone was free, and the idle drive kept reading and writing while the free zone counters in "dmsetup status" did not change.

Only switch to a random destination zone when the zone being reclaimed is a cache zone: moving it to the zoned device still frees cache space.

This depends on "dm zoned: back off when reclaim cannot make progress":
without it, dmz_reclaim_work() would retry the resulting -ENOSPC at once, and run dmz_check_dev(), for as long as the target stays idle.

Tested on 7.4-rc1 together with the previous patch, on a two-device target (a 512 MiB RAM-backed regular cache device plus a 1 GiB scsi_debug host-managed drive) filled until no sequential zone was free, then idle for 60 seconds: the stock module made 877 random-to-random copies; with this series it made none, and each pass failed with -ENOSPC once per DMZ_IDLE_PERIOD without a device check.

Fixes c5c788595292 ("dm zoned: start reclaim with sequential zones")
---
 drivers/md/dm-zoned-reclaim.c |    8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
drivers/md/dm-zoned-reclaim.c +7 -1
@@ -288,7 +288,13 @@ static int dmz_reclaim_rnd_data(struct d
 again:
 	szone = dmz_alloc_zone(zmd, zrc->dev_idx,
 			       alloc_flags | DMZ_ALLOC_RECLAIM);
-	if (!szone && alloc_flags == DMZ_ALLOC_SEQ && dmz_nr_cache_zones(zmd)) {
+	/*
+	 * If no free sequential zone is available, a cache zone can still be
+	 * moved into a free random zone of the zoned device, which frees cache
+	 * space. Do not do this for a random zone: moving it into another
+	 * random zone frees nothing and, on an idle target, repeats forever.
+	 */
+	if (!szone && alloc_flags == DMZ_ALLOC_SEQ && dmz_is_cache(dzone)) {
 		alloc_flags = DMZ_ALLOC_RND;
 		goto again;
 	}
author maintainer
#876 lore raw

PATCH 875/1005 dm-cache: fix NULL pointer dereference on open failure

In reply to Greg Kroah-Hartman

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

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

From: Mikulas Patocka <[email protected]>

commit d12afc2f9ed6e14019fed9c02a74ad699915dc85 upstream.

When __begin_transaction_flags in metadata_open fails, dm_cache_metadata_close is called. dm_cache_metadata_close attempts to execute list_del(&cmd->list);, but the "cmd" object is not on any list yet, thus it crashes with NULL pointer dereference.

Fix this by initializing cmd->list after cmd is allocated.

Assisted-by Claude:claude-opus-5
Fixes 9b1cc9f251af ("dm cache: share cache-metadata object across inactive and active DM tables")
---
 drivers/md/dm-cache-metadata.c |    1 +
 1 file changed, 1 insertion(+)
drivers/md/dm-cache-metadata.c +1 -0
@@ -766,6 +766,7 @@ static struct dm_cache_metadata *metadat
 		return ERR_PTR(-ENOMEM);
 	}
 
+	INIT_LIST_HEAD(&cmd->list);
 	cmd->version = metadata_version;
 	refcount_set(&cmd->ref_count, 1);
 	init_rwsem(&cmd->root_lock);
author maintainer
#877 lore raw

PATCH 876/1005 dm-cache: fix ending a cursor that never began

In reply to Greg Kroah-Hartman

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

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

From: Mikulas Patocka <[email protected]>

commit 421420758be348cb90715bfaa26e1211a12ff1d0 upstream.

If dm_bitset_cursor_begin fails, dm_array_cursor_end(&cmd->hint_cursor) is called. However, cmd->hint_cursor was only initialized if the variable hints_valid is true. Thus, we must also destroy hint_cursor only if hints_valid is true.

Assisted-by Claude:claude-opus-5
Fixes 629d0a8a1a10 ("dm cache metadata: add "metadata2" feature")
---
 drivers/md/dm-cache-metadata.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/md/dm-cache-metadata.c +2 -1
@@ -1433,7 +1433,8 @@ static int __load_mappings(struct dm_cac
 					   from_cblock(cmd->cache_blocks),
 					   &cmd->dirty_cursor);
 		if (r) {
-			dm_array_cursor_end(&cmd->hint_cursor);
+			if (hints_valid)
+				dm_array_cursor_end(&cmd->hint_cursor);
 			dm_array_cursor_end(&cmd->mapping_cursor);
 			return r;
 		}
author maintainer
#878 lore raw

PATCH 877/1005 dm-crypt: reject integrity_key_size with non-authenc AEAD ciphers

In reply to Greg Kroah-Hartman

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

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

From: xietangxin <[email protected]>

commit bd93c4e59c5132282c01f142806e307c7380e7ea upstream.

When integrity_key_size parameter is paired with a pure AEAD cipher that is not an authenc composite, crypt_ctr_auth_cipher() returns 0 early without allocating cc->authenc_key, but cc->key_mac_size remains non-zero because CRYPT_KEY_MAC_SIZE_SET was set during option parsing. As a result crypt_copy_authenckey() dereferences NULL crashes the kernel.

Reject the contradictory configuration explicitly instead of silently returning 0, so userspace gets a clear -EINVAL.

Fixes 4441686b24a1 ("dm-crypt: Allow to specify the integrity key size as option")
Reported-by [email protected]
Assisted-by LLM
---
 drivers/md/dm-crypt.c |    5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/md/dm-crypt.c +4 -1
@@ -2826,8 +2826,11 @@ static int crypt_ctr_auth_cipher(struct
 	char *start, *end, *mac_alg = NULL;
 	struct crypto_ahash *mac;
 
-	if (!strstarts(cipher_api, "authenc("))
+	if (!strstarts(cipher_api, "authenc(")) {
+		if (test_bit(CRYPT_KEY_MAC_SIZE_SET, &cc->cipher_flags))
+			return -EINVAL;
 		return 0;
+	}
 
 	start = strchr(cipher_api, '(');
 	end = strchr(cipher_api, ',');
author maintainer
#879 lore raw

PATCH 878/1005 dm-crypt: defer async write submission to write thread

In reply to Greg Kroah-Hartman

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

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

From: Josef Schlehofer <[email protected]>

commit 6fed9e26810f0b466dbcebe35a73d1fd48793ff5 upstream.

With no_write_workqueue, kcryptd_crypt_write_io_submit() submits the bio directly, even when called from kcryptd_async_done(). An async cipher may run this callback in softirq or with BH disabled, where submit_bio_noacct() must not be called because it can sleep.

Submit inline only when async is false. Async completions are sent to the write thread, as is already done for submit_from_crypt_cpus. Use the async flag rather than in_interrupt(), since callback context depends on the cipher driver. Sync ciphers still submit inline.

Tested with cryptd in QEMU (x86_64 and arm64) with CONFIG_DEBUG_ATOMIC_SLEEP, and on a P2020 running 6.18.55 without it.

In QEMU:

- 4k writes logging "sleeping function called from invalid context":
100/100 unpatched, 0/155 patched.
- nr_requests=4 on a loop device: 0/6 unpatched runs completed, 4/4 patched runs completed.

On the P2020, a warning in blk_mq_run_hw_queue() appeared in the 6th unpatched run and did not appear in 30 patched runs.

Fixes 39d42fa96ba1 ("dm crypt: add flags to optionally bypass kcryptd workqueues")
---
 drivers/md/dm-crypt.c |    5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/md/dm-crypt.c +3 -2
@@ -1964,8 +1964,9 @@ static void kcryptd_crypt_write_io_submi
 	/* crypt_convert should have filled the clone bio */
 	BUG_ON(io->ctx.iter_out.bi_size);
 
-	if ((likely(!async) && test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags)) ||
-	    test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags)) {
+	if (likely(!async) &&
+	    (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags) ||
+	     test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags))) {
 		dm_submit_bio_remap(io->base_bio, clone);
 		return;
 	}
author maintainer
#880 lore raw

PATCH 879/1005 dm-integrity: dont recalculate with HMAC because of a dirty bitmap

In reply to Greg Kroah-Hartman

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

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

From: Sinan Polat <[email protected]>

commit 875a7161fe1574205293c36f7bbd0815023e48a1 upstream.

Commit 5c02406428d5 ("dm integrity: conditionally disable "recalculate" feature") refuses a superblock with SB_FLAG_RECALCULATING if a keyed hash is used without "legacy_recalculate". Otherwise someone who can write to the device, but does not know the key, could modify data and have the kernel compute valid tags for it.

dm_integrity_resume() can still start the same recalculation in J or D
mode: if SB_FLAG_DIRTY_BITMAP is set and the bitmap is not clear, or log2_blocks_per_bitmap_bit does not match, it sets SB_FLAG_RECALCULATING and recalc_sector = 0. The superblock is not authenticated unless fix_hmac and journal_mac are both used, so the flag can be set offline. Resume also runs on the first activation.

Apply the constructor's policy there. If recalculation is not allowed, log an error and keep the existing tags, so modified blocks fail verification. This also avoids queueing recalc_work on a NULL recalc_wq when internal_hash is not used.

Fixes 5c02406428d5 ("dm integrity: conditionally disable "recalculate" feature")
Assisted-by Claude:claude-opus-5-5
---
 drivers/md/dm-integrity.c |   24 ++++++++++++++++++++++--
 1 file changed, 22 insertions(+), 2 deletions(-)
drivers/md/dm-integrity.c +22 -2
@@ -3888,6 +3888,24 @@ static bool superblock_changed(struct dm
 	       memcmp(ic->sb->salt, ic->sb_copy->salt, SALT_SIZE) != 0;
 }
 
+/*
+ * The superblock is authenticated only if fix_hmac and journal_mac are used,
+ * so SB_FLAG_DIRTY_BITMAP may have been set by someone who doesn't know the
+ * key. Apply the policy that the constructor applies to SB_FLAG_RECALCULATING.
+ */
+static bool dm_integrity_may_recalc_dirty_bitmap(struct dm_integrity_c *ic)
+{
+	if (!ic->internal_hash) {
+		DMERR("Dirty bitmap found, but internal_hash is not used");
+		return false;
+	}
+	if (dm_integrity_disable_recalculate(ic)) {
+		DMERR("Dirty bitmap found, but HMAC recalculation requires \"legacy_recalculate\"");
+		return false;
+	}
+	return true;
+}
+
 static void dm_integrity_resume(struct dm_target *ti)
 {
 	struct dm_integrity_c *ic = ti->private;
@@ -3977,8 +3995,10 @@ static void dm_integrity_resume(struct d
 			if (!(ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit &&
 			      block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_TEST_ALL_CLEAR)) ||
 			    ic->reset_recalculate_flag) {
-				ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
-				ic->sb->recalc_sector = cpu_to_le64(0);
+				if (dm_integrity_may_recalc_dirty_bitmap(ic)) {
+					ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING);
+					ic->sb->recalc_sector = cpu_to_le64(0);
+				}
 			}
 			init_journal(ic, 0, ic->journal_sections, 0);
 			replay_journal(ic);
author maintainer
#881 lore raw

PATCH 880/1005 dm-integrity: dont attempt to commit journal on disabled device

In reply to Greg Kroah-Hartman

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

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

From: Mikulas Patocka <[email protected]>

commit e5e03918fbec31f0c896f4f43c2bd2aadf35d43d upstream.

If the device is disabled due to an error, we shouldn't attempt to flush the journal. We jump straight to the label release_flush_bios, that will call do_endio on all queued bios. do_endio will terminate the bios with the error.

This fixes WARN_ON in the function pad_uncommitted reported by syzkaller.

---
 drivers/md/dm-integrity.c |    6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/md/dm-integrity.c +5 -1
@@ -2908,6 +2908,11 @@ static void integrity_commit(struct work
 
 	spin_lock_irq(&ic->endio_wait.lock);
 	flushes = bio_list_get(&ic->flush_bio_list);
+	if (unlikely(dm_integrity_failed(ic))) {
+		wake_up_locked(&ic->endio_wait);
+		spin_unlock_irq(&ic->endio_wait.lock);
+		goto release_flush_bios;
+	}
 	if (unlikely(ic->mode != 'J')) {
 		spin_unlock_irq(&ic->endio_wait.lock);
 		dm_integrity_flush_buffers(ic, true);
@@ -5429,7 +5434,6 @@ try_smaller_buffer:
 		r = create_journal(ic, &ti->error);
 		if (r)
 			goto bad;
-
 	}
 
 	if (ic->mode == 'B') {
author maintainer
#882 lore raw

PATCH 881/1005 dm-raid: bound array_position before indexing failed_devices

In reply to Greg Kroah-Hartman

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

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

From: Jay Vadayath <[email protected]>

commit 11b5cd14c0eecae458cecbe53d21a3dbc10190f5 upstream.

super_init_validation() reads role = le32_to_cpu(sb2->array_position) out of an on-disk dm_raid_superblock and then uses it as a bit index into the failed_devices bitmap via test_bit(role, (void *)failed_devices). failed_devices is a uint64_t[DISKS_ARRAY_ELEMS] (DISKS_ARRAY_ELEMS == 4, i.e. 256 bits) living on the stack. The only guard is role < 0, so any on-disk array_position >= 256 makes test_bit() read past the end of the stack array (array_position == 256 reads failed_devices[4], 8 bytes past the object). For a raid1 set the role != raid_disk reorder branch falls through to the same test_bit().

A crafted dm-raid superblock therefore causes a stack out-of-bounds read during table load. Reachable by anyone able to issue a dmsetup create with attacker-controlled metadata (CAP_SYS_ADMIN in the target namespace); the crash fires in the constructor / analyse_superblocks path, before any md_run or array sizing.

  BUG: KASAN: stack-out-of-bounds in super_validate+0x1cd0/0x3390
  Read of size 8 at addr ffff888007b17828 by task poc/152
  Call Trace:
   dump_stack_lvl+0x64/0x80
   print_report+0xd0/0x630
   kasan_report+0xe5/0x120
   kasan_check_range+0x105/0x1b0
   super_validate+0x1cd0/0x3390        (super_init_validation, inlined)
   raid_ctr+0x2c4b/0xa0f0
   dm_table_add_target+0x66f/0xf80
   table_load+0x2ee/0x780
   ctl_ioctl+0x362/0x9f0
   dm_ctl_ioctl+0x9/0x10
   __x64_sys_ioctl+0x134/0x1c0
   do_syscall_64+0xe2/0x4b0
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

role is a device position that must refer to an actual member of the array, so reject anything outside [0, rs->raid_disks) instead of only the negative case. rs->raid_disks is always <= the 256-bit capacity of failed_devices, so this both closes the out-of-bounds access and matches the intended semantics.

This bug was discovered by Artiphishell's vTriage pipeline, which generated a crafted raid1 superblock (magic "DmRd", compat_features=1, num_devices=2, array_position=256, level=1) and a dmsetup-create reproducer that reliably triggers the KASAN report on an unpatched kernel (the precursor DMINFO "raid device #256 now at position #0" is visible in the serial log just before the splat). The fix below was drafted with the Claude coding assistant; a userspace reproducer is available on request.

---
 drivers/md/dm-raid.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/md/dm-raid.c +2 -1
@@ -2420,7 +2420,8 @@ static int super_init_validation(struct
 		 */
 		if (!test_bit(FirstUse, &r->flags) && (r->raid_disk >= 0)) {
 			role = le32_to_cpu(sb2->array_position);
-			if (role < 0)
+			/* Bound @role before it indexes the failed_devices stack bitmap. */
+			if (role < 0 || role >= rs->raid_disks)
 				continue;
 
 			if (role != r->raid_disk) {
author maintainer
#883 lore raw

PATCH 882/1005 dm-raid: fix use-after-free in raid_dtr()

In reply to Greg Kroah-Hartman

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

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

From: Li Youhong <[email protected]>

commit 46af2c975958119290ddcd984a98491966123a7b upstream.

raid_dtr() currently flushes event_work only if work_pending() is true. This is insufficient because once a worker has dequeued the work, the PENDING bit is cleared while do_table_event() is still running. In that window raid_set_free() can free the raid_set, leading to a use-after-free when do_table_event() accesses rs->ti->table.

Flush event_work whenever it has been initialized, so raid_set is not freed while the event handler is still running. The .func guard skips the flush for mddev instances where INIT_WORK has not run yet.

Fixes db29d79b34d9 ("dm-raid: delay flushing event_work() after reconfig_mutex is released")
---
 drivers/md/dm-raid.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/md/dm-raid.c +1 -1
@@ -3334,7 +3334,7 @@ static void raid_dtr(struct dm_target *t
 	rs->md.dm_gendisk = NULL;
 	mddev_unlock(&rs->md);
 
-	if (work_pending(&rs->md.event_work))
+	if (rs->md.event_work.func)
 		flush_work(&rs->md.event_work);
 	raid_set_free(rs);
 }
author maintainer
#884 lore raw

PATCH 883/1005 dm-thin: fix data corruption if discard races with regular I/O

In reply to Greg Kroah-Hartman

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

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

From: Mikulas Patocka <[email protected]>

commit 62ee9c09366cad69410330087d990e469dd92314 upstream.

In the function break_up_discard_bio, if a discard hits the same block as regular I/O, it was intended to skip the discard for the affected range. However, the skip code only advances "data_begin", it doesn't advance "virt_begin". So, the data_begin and virt_begin variables become unsynchronized.

process_prepared_discard_passdown_pt1 calculates "data_end = m->data_block + (m->virt_end - m->virt_begin);" - if m->data_block is incremented and m->virt_begin isn't, it will overshoot the intended discard range.

Fixes e2dd8aca2d76 ("dm bio prison v1: improve concurrent IO performance")
Assisted-by Claude:claude-opus-5
---
 drivers/md/dm-thin.c |    1 +
 1 file changed, 1 insertion(+)
drivers/md/dm-thin.c +1 -0
@@ -1703,6 +1703,7 @@ static void break_up_discard_bio(struct
 			(void) build_key(tc->td, PHYSICAL, data_begin, data_begin + len, &data_key);
 			if (bio_detain(tc->pool, &data_key, NULL, &data_cell)) {
 				/* contention, we'll give up with this range */
+				virt_begin += len;
 				data_begin += len;
 				continue;
 			}
author maintainer
#885 lore raw

PATCH 884/1005 dm-thin: fix leak if __set_snapshot_details fails

In reply to Greg Kroah-Hartman

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

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

From: Mikulas Patocka <[email protected]>

commit dfb95816cf6f2f2660af2ec64c65dc204c60b5e7 upstream.

If __set_snapshot_details fails, the variable td is leaked - this prevents any other snapshot with the same id from being created.

Fix this by removing it from the list and freeing it.

Assisted-by Claude:claude-opus-5
Fixes 991d9fa02da0 ("dm: add thin provisioning target")
---
 drivers/md/dm-thin-metadata.c |    5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/md/dm-thin-metadata.c +4 -1
@@ -1225,10 +1225,13 @@ static int __create_snap(struct dm_pool_
 	__close_device(td);
 
 	if (r)
-		goto bad;
+		goto bad2;
 
 	return 0;
 
+bad2:
+	list_del(&td->list);
+	kfree(td);
 bad:
 	dm_btree_remove(&pmd->tl_info, pmd->root, &key, &pmd->root);
 	dm_btree_remove(&pmd->details_info, pmd->details_root,
author maintainer
#886 lore raw

PATCH 885/1005 dm-thin: fix parsing of feature arguments

In reply to Greg Kroah-Hartman

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

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

From: Mikulas Patocka <[email protected]>

commit c557fa19a83efad1e20eb733df821b745a4589ff upstream.

"struct dm_arg _args" limits the number of arguments to 4, but there are 5 possible arguments that can be specified.

Assisted-by Claude:claude-opus-5
Fixes 787a996cb251 ("dm thin: add error_if_no_space feature")
---
 drivers/md/dm-thin.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/md/dm-thin.c +1 -1
@@ -3149,7 +3149,7 @@ static int parse_pool_features(struct dm
 	const char *arg_name;
 
 	static const struct dm_arg _args[] = {
-		{0, 4, "Invalid number of pool feature arguments"},
+		{0, 5, "Invalid number of pool feature arguments"},
 	};
 
 	/*
author maintainer
#887 lore raw

PATCH 886/1005 vt: serialise the producers of the flip buffer

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

commit 5d1d814408c1c8e797031eac8ddd40de1a9e8e93 upstream.

Typing on a virtual console while the console replies to an escape sequence can make the kernel write past the end of a buffer. A user who can write to the foreground console can cause this on purpose if they can also inject key events, through /dev/uinput or by writing to the /dev/input/event* node of a keyboard.

Input for a tty goes through the flip buffer of its port. A driver inserts the data with tty_insert_flip_*() and then calls tty_flip_buffer_push() to pass it on to the line discipline. The insert functions take no lock: they check that the current struct tty_buffer has room, copy the data to offset ->used, and then advance ->used. So a flip buffer supports only one producer at a time, and a driver that has several must serialise them.

Four functions feed the flip buffer of a virtual console:

- put_queue(), puts_queue() and fn_send_intr() insert typed characters and breaks for the keyboard handler. They run under kbd_event_lock.
- respond_string() inserts the reply when a program writes an escape sequence that requests one, such as a cursor position report. It runs under the console lock.

The keyboard handler gets its events from the input layer and feeds the foreground console. Key events that a program writes to /dev/uinput or to an event node reach it in the same way as typed keys.

The keyboard handler and respond_string() share no lock, so they can interleave:

keyboard handler respond_string()
================ ================
room check passes
room check passes
memcpy() to offset used
used += len
memcpy() to offset used used += len
/* used > size of the buffer */

The room check subtracts ->used from the size, and both are unsigned. Once ->used exceeds the size, the result wraps, so the check always passes, and each later insert lands further past the buffer.

Reproduced as root, with keys from a uinput keyboard and cursor position reports on the same console: KFENCE reported an out-of-bounds write 1,024 bytes past the buffer in under 10 s.

Fix this by taking port->lock, with interrupts disabled, around the insert and the push in these four functions. kbd_keycode() already takes port->lock under kbd_event_lock, so this lock ordering is not new.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
Cc stable <[email protected]>
Cc Jiri Slaby <[email protected]>
Cc Nicolas Pitre <[email protected]>
Cc Kees Cook <[email protected]>
Cc Joshua Rogers <[email protected]>
Cc Chris Mason <[email protected]>
Cc Helge Deller <[email protected]>
Cc Thomas Zimmermann <[email protected]>
Cc Mingyu Wang <[email protected]>
Cc Randy Dunlap <[email protected]>
Cc Ronan Pigott <[email protected]>
Cc Liav Mordouch <[email protected]>
---
 drivers/tty/vt/keyboard.c |    6 ++++++
 drivers/tty/vt/vt.c       |    2 ++
 2 files changed, 8 insertions(+)
drivers/tty/vt/keyboard.c +6 -0
@@ -322,15 +322,20 @@ int kbd_rate(struct kbd_repeat *rpt)
 
 /*
  * Helper Functions.
+ *
+ * A flip buffer allows one producer at a time, and respond_string() in vt.c
+ * feeds the same one under the console lock. So take the lock of the port.
  */
 static void put_queue(struct vc_data *vc, int ch)
 {
+	guard(spinlock_irqsave)(&vc->port.lock);
 	tty_insert_flip_char(&vc->port, ch, 0);
 	tty_flip_buffer_push(&vc->port);
 }
 
 static void puts_queue(struct vc_data *vc, const char *cp)
 {
+	guard(spinlock_irqsave)(&vc->port.lock);
 	tty_insert_flip_string(&vc->port, cp, strlen(cp));
 	tty_flip_buffer_push(&vc->port);
 }
@@ -587,6 +592,7 @@ static void fn_inc_console(struct vc_dat
 
 static void fn_send_intr(struct vc_data *vc)
 {
+	guard(spinlock_irqsave)(&vc->port.lock);
 	tty_insert_flip_char(&vc->port, 0, TTY_BREAK);
 	tty_flip_buffer_push(&vc->port);
 }
drivers/tty/vt/vt.c +2 -0
@@ -1857,6 +1857,8 @@ static void csi_m(struct vc_data *vc)
 
 static void respond_string(const char *p, size_t len, struct tty_port *port)
 {
+	/* The keyboard handler feeds the same flip buffer. */
+	guard(spinlock_irqsave)(&port->lock);
 	tty_insert_flip_string(port, p, len);
 	tty_flip_buffer_push(port);
 }
author maintainer
#888 lore raw

PATCH 887/1005 comedi: addi_apci_1500: fix clearing of the gate enable

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 ade85ceef46892425a08f3ee52ca06729ee4922e upstream.

INSN_CONFIG_SET_GATE_SRC reads the mode register of the counter/timer, is meant to clear the External Gate Enable bit, sets it again if the external gate was asked for, and writes the register back. The mask lacks its '~': all the bits but EGE are cleared instead. So

- the external gate can be enabled but never be disabled again, and
- the instruction wipes the mode (continuous or single cycle, external output, count and trigger enables, retrigger, duty cycle) which INSN_CONFIG_SET_COUNTER_MODE has programmed: the timer silently falls back to a single cycle pulse.

With the right mask, the instruction only changes the gate bit. An application which sets the gate source after the counter mode now keeps the mode it has asked for.

Fixes a8c66b684efa ("staging: comedi: addi_apci_1500: rewrite the subdevice support functions")
Cc stable <[email protected]>
---
 drivers/comedi/drivers/addi_apci_1500.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/comedi/drivers/addi_apci_1500.c +1 -1
@@ -696,7 +696,7 @@ static int apci1500_timer_insn_config(st
 			return -EINVAL;
 
 		val = z8536_read(dev, Z8536_CT_MODE_REG(chan));
-		val &= Z8536_CT_MODE_EGE;
+		val &= ~Z8536_CT_MODE_EGE;
 		if (data[1] == 1)
 			val |= Z8536_CT_MODE_EGE;
 		else if (data[1] > 1)
author maintainer
#889 lore raw

PATCH 888/1005 comedi: fix endless recursion in comedi_event()

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 d432e5d3dbd98589029905e898bfe7005be69b68 upstream.

When comedi_event() was split into a wrapper which takes a reference on the running command and _comedi_event(), which does the work, the wrapper ended up calling itself:

	if (comedi_get_is_subdevice_running(s)) {
		comedi_event(dev, s);
		comedi_put_is_subdevice_running(s);
	}

As long as the command is running every level takes another reference and recurses, until the stack is used up.

Most drivers go through comedi_handle_events(), which calls _comedi_event(). usbdux, usbduxfast and usbduxsigma cannot use that and call comedi_event() from their URB completion handlers, i.e. for every completed URB of a running acquisition.

---
 drivers/comedi/comedi_fops.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/comedi/comedi_fops.c +1 -1
@@ -3494,7 +3494,7 @@ void _comedi_event(struct comedi_device
 void comedi_event(struct comedi_device *dev, struct comedi_subdevice *s)
 {
 	if (comedi_get_is_subdevice_running(s)) {
-		comedi_event(dev, s);
+		_comedi_event(dev, s);
 		comedi_put_is_subdevice_running(s);
 	}
 }
author maintainer
#890 lore raw

PATCH 889/1005 comedi: ni_660x: dont poll without a DMA channel

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 5a0c88567a5ebbe24ecb7828e200f63ed972718f upstream.

A counter command owns a MITE DMA channel from ni_660x_cmd() to ni_660x_cancel(). A command does not only end by COMEDI_CANCEL: when the reader is too slow mite_sync_input_dma() sets COMEDI_CB_OVERFLOW, and counter errors set COMEDI_CB_ERROR, and comedi_handle_events() then calls ->cancel() from the interrupt handler. That releases the channel and clears counter->mite_chan, but s->busy stays set until the owner has read the rest of the data and seen the end of the acquisition.

do_poll_ioctl() only looks at s->busy, so a COMEDI_POLL in that state ends in mite_sync_dma(NULL, s), which dereferences the channel.

Test the channel like ni_pcidio_poll() and ni_sync_ai_dma() do. The pointer only changes under dev->mutex, which the ioctl holds, or in the interrupt handler under interrupt_lock, which is taken here.

---
 drivers/comedi/drivers/ni_660x.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/comedi/drivers/ni_660x.c +2 -1
@@ -459,7 +459,8 @@ static int ni_660x_input_poll(struct com
 
 	/* lock to avoid race with comedi_poll */
 	spin_lock_irqsave(&devpriv->interrupt_lock, flags);
-	mite_sync_dma(counter->mite_chan, s);
+	if (counter->mite_chan)
+		mite_sync_dma(counter->mite_chan, s);
 	spin_unlock_irqrestore(&devpriv->interrupt_lock, flags);
 	return comedi_buf_read_n_available(s);
 }
author maintainer
#891 lore raw

PATCH 890/1005 comedi: ni_tio: Fix overflow of the clock period

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 ec214735bb113be747454812035b83010892e0d2 upstream.

ni_tio_set_clock_src() stores the period of the clock source, which the user passes in nanoseconds, in picoseconds:

	counter->clock_period_ps = period_ns * 1000;

period_ns is an unsigned int, so that the product is computed in 32 bits, although clock_period_ps is a u64. It wraps for periods above 4294967 ns, that is for external clocks slower than 233 Hz. INSN_CONFIG_GET_CLOCK_SRC then reports a wrong period, and ni_tio_set_sync_mode() decides on a wrong one: 4294968 ns become 704 ps, which is below the limit of 25 ns under which the alternate synchronization mode for fast clocks is switched on.

The multiplication was done in 64 bits until the constant pico_per_nano, a uint64_t, was replaced by a literal. Widen again.

---
 drivers/comedi/drivers/ni_tio.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/comedi/drivers/ni_tio.c +1 -1
@@ -800,7 +800,7 @@ static int ni_tio_set_clock_src(struct n
 				GI_PRESCALE_X2(counter_dev->variant) |
 				GI_PRESCALE_X8(counter_dev->variant), bits);
 	}
-	counter->clock_period_ps = period_ns * 1000;
+	counter->clock_period_ps = (u64)period_ns * 1000;
 	ni_tio_set_sync_mode(counter);
 	return 0;
 }
author maintainer
#892 lore raw

PATCH 891/1005 comedi: vmk80xx: report failed transfers of the K8061

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 92fa93505576188acc22c5de1999db9a1c70c09b upstream.

For the K8061 board vmk80xx_read_packet() and vmk80xx_write_packet() call vmk80xx_do_bulk_msg(), which ignores the result of its two bulk transfers, and return 0. After a timeout, a stall or an unplug the instruction handlers therefore go on and hand the old content of usb_rx_buf to user space as a fresh sample (analog and digital inputs, counters, PWM and output read-back), and writes to the outputs are reported as done.

All callers check the result already, because the K8055 branch of the two functions returns that of usb_interrupt_msg(). Return the error of the bulk transfers as well, and don't wait for an answer to a command that could not be sent.

---
 drivers/comedi/drivers/vmk80xx.c |   25 ++++++++++++-------------
 1 file changed, 12 insertions(+), 13 deletions(-)
drivers/comedi/drivers/vmk80xx.c +12 -13
@@ -151,7 +151,7 @@ struct vmk80xx_private {
 	enum vmk80xx_model model;
 };
 
-static void vmk80xx_do_bulk_msg(struct comedi_device *dev)
+static int vmk80xx_do_bulk_msg(struct comedi_device *dev)
 {
 	struct vmk80xx_private *devpriv = dev->private;
 	struct usb_device *usb = comedi_to_usb_dev(dev);
@@ -161,6 +161,7 @@ static void vmk80xx_do_bulk_msg(struct c
 	unsigned int rx_pipe;
 	size_t tx_size;
 	size_t rx_size;
+	int ret;
 
 	tx_addr = devpriv->ep_tx->bEndpointAddress;
 	rx_addr = devpriv->ep_rx->bEndpointAddress;
@@ -169,11 +170,13 @@ static void vmk80xx_do_bulk_msg(struct c
 	tx_size = usb_endpoint_maxp(devpriv->ep_tx);
 	rx_size = usb_endpoint_maxp(devpriv->ep_rx);
 
-	usb_bulk_msg(usb, tx_pipe, devpriv->usb_tx_buf, tx_size, NULL,
-		     PACKET_TIMEOUT);
+	ret = usb_bulk_msg(usb, tx_pipe, devpriv->usb_tx_buf, tx_size, NULL,
+			   PACKET_TIMEOUT);
+	if (ret)
+		return ret;
 
-	usb_bulk_msg(usb, rx_pipe, devpriv->usb_rx_buf, rx_size, NULL,
-		     PACKET_TIMEOUT);
+	return usb_bulk_msg(usb, rx_pipe, devpriv->usb_rx_buf, rx_size, NULL,
+			    PACKET_TIMEOUT);
 }
 
 static int vmk80xx_read_packet(struct comedi_device *dev)
@@ -183,10 +186,8 @@ static int vmk80xx_read_packet(struct co
 	struct usb_endpoint_descriptor *ep;
 	unsigned int pipe;
 
-	if (devpriv->model == VMK8061_MODEL) {
-		vmk80xx_do_bulk_msg(dev);
-		return 0;
-	}
+	if (devpriv->model == VMK8061_MODEL)
+		return vmk80xx_do_bulk_msg(dev);
 
 	ep = devpriv->ep_rx;
 	pipe = usb_rcvintpipe(usb, ep->bEndpointAddress);
@@ -204,10 +205,8 @@ static int vmk80xx_write_packet(struct c
 
 	devpriv->usb_tx_buf[0] = cmd;
 
-	if (devpriv->model == VMK8061_MODEL) {
-		vmk80xx_do_bulk_msg(dev);
-		return 0;
-	}
+	if (devpriv->model == VMK8061_MODEL)
+		return vmk80xx_do_bulk_msg(dev);
 
 	ep = devpriv->ep_tx;
 	pipe = usb_sndintpipe(usb, ep->bEndpointAddress);
author maintainer
#893 lore raw

PATCH 892/1005 iio: accel: adxl380: dont stay in standby on -EINVAL

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 4c56180167ea4d419a0578545bf62110494b563d upstream.

adxl380_set_act_inact_threshold() puts the sensor into standby, writes the threshold and switches the measurement on again. A threshold above 8191 is refused in between, and the sensor stays in standby: no samples and no events until the next write that succeeds.

adxl380_set_range() has the same problem and a worse one. It rescales both thresholds for the new range. If one no longer fits it returns -EINVAL with the sensor in standby, the new range in the chip, the old one in st->range and rescaled thresholds in the driver's state: from the next successful write on the samples are reported with the wrong scale.

Switch the measurement on again if the threshold is refused. In adxl380_set_range() see whether the thresholds fit before anything is changed.

Fixes df36de13677a ("iio: accel: add ADXL380 driver")
Cc stable <[email protected]>
---
 drivers/iio/accel/adxl380.c |   11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)
drivers/iio/accel/adxl380.c +10 -1
@@ -334,8 +334,11 @@ static int adxl380_set_act_inact_thresho
 		return ret;
 
 	ret = adxl380_write_act_inact_threshold(st, act, th);
-	if (ret)
+	if (ret) {
+		/* Leave standby also if the value was refused */
+		adxl380_set_measure_en(st, true);
 		return ret;
+	}
 
 	return adxl380_set_measure_en(st, true);
 }
@@ -698,6 +701,12 @@ static int adxl380_set_range(struct adxl
 
 	guard(mutex)(&st->lock);
 
+	/* The thresholds are rescaled: see that they fit before any change */
+	if (mult_frac(max(st->act_threshold, st->inact_threshold),
+		      adxl380_range_scale_factor_tbl[st->range],
+		      adxl380_range_scale_factor_tbl[range]) > ADXL380_THRESH_MAX)
+		return -EINVAL;
+
 	ret = adxl380_set_measure_en(st, false);
 	if (ret)
 		return ret;
author maintainer
#894 lore raw

PATCH 893/1005 iio: adc: ad7923: add the AD7927 to the SPI ID table

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 594157b4f3f64db5833dee679194c33a5968f92e upstream.

The binding describes the AD7927 as

  compatible = "adi,ad7927", "adi,ad7928";

The OF match takes the second string. The modalias of the SPI device is made from the first one, "ad7927", which is not in the spi_device_id table:
spi_get_device_id() returns NULL and ad7923_probe() dereferences it for the chip information. The module is not loaded automatically either, as the uevent of an SPI device says "spi:ad7927".

Add the name, with the data of the AD7928.

Fixes 1140f96cd4af ("dt-bindings: iio: adc: ad7923: adjust documentation")
Cc stable <[email protected]>
---
 drivers/iio/adc/ad7923.c |    1 +
 1 file changed, 1 insertion(+)
drivers/iio/adc/ad7923.c +1 -0
@@ -366,6 +366,7 @@ static const struct spi_device_id ad7923
 	{ .name = "ad7924", .driver_data = AD7924 },
 	{ .name = "ad7908", .driver_data = AD7908 },
 	{ .name = "ad7918", .driver_data = AD7918 },
+	{ .name = "ad7927", .driver_data = AD7928 },
 	{ .name = "ad7928", .driver_data = AD7928 },
 	{ }
 };
author maintainer
#895 lore raw

PATCH 894/1005 iio: adc: check the result of ad_sd_init()

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 905b5d93b795b0e2311a8c855c1cdd97c9cc2989 upstream.

ad_sd_init() asks for the optional "rdy" GPIO and returns the error if that fails, for instance -EPROBE_DEFER. The binding of the AD7780 describes such a GPIO.

ad7780, ad7791, ad7793 and max11205 ignore the result. The function has then returned before it set the driver data of the IIO device, which devm_ad_sd_setup_buffer_and_trigger() dereferences a few lines further down in these probe functions, and sigma_delta->rdy_gpiod holds an ERR_PTR() which ad_sigma_delta_clear_pending_event() takes for a GPIO.

Return the error, as the other users of the library do.

Fixes a87ef09b1fdf ("iio: adc: ad_sigma_delta: Add support for reading irq status using a GPIO")
Cc stable <[email protected]>
---
 drivers/iio/adc/ad7780.c   |    4 +++-
 drivers/iio/adc/ad7791.c   |    4 +++-
 drivers/iio/adc/ad7793.c   |    4 +++-
 drivers/iio/adc/max11205.c |    4 +++-
 4 files changed, 12 insertions(+), 4 deletions(-)
drivers/iio/adc/ad7780.c +3 -1
@@ -311,7 +311,9 @@ static int ad7780_probe(struct spi_devic
 	st = iio_priv(indio_dev);
 	st->gain = 1;
 
-	ad_sd_init(&st->sd, indio_dev, spi, &ad7780_sigma_delta_info);
+	ret = ad_sd_init(&st->sd, indio_dev, spi, &ad7780_sigma_delta_info);
+	if (ret)
+		return ret;
 
 	st->chip_info =
 		&ad7780_chip_info_tbl[spi_get_device_id(spi)->driver_data];
drivers/iio/adc/ad7791.c +3 -1
@@ -435,7 +435,9 @@ static int ad7791_probe(struct spi_devic
 		return ret;
 
 	st->info = &ad7791_chip_infos[spi_get_device_id(spi)->driver_data];
-	ad_sd_init(&st->sd, indio_dev, spi, &ad7791_sigma_delta_info);
+	ret = ad_sd_init(&st->sd, indio_dev, spi, &ad7791_sigma_delta_info);
+	if (ret)
+		return ret;
 
 	indio_dev->name = spi_get_device_id(spi)->name;
 	indio_dev->modes = INDIO_DIRECT_MODE;
drivers/iio/adc/ad7793.c +3 -1
@@ -796,7 +796,9 @@ static int ad7793_probe(struct spi_devic
 
 	st = iio_priv(indio_dev);
 
-	ad_sd_init(&st->sd, indio_dev, spi, &ad7793_sigma_delta_info);
+	ret = ad_sd_init(&st->sd, indio_dev, spi, &ad7793_sigma_delta_info);
+	if (ret)
+		return ret;
 
 	if (pdata->refsel != AD7793_REFSEL_INTERNAL) {
 		ret = devm_regulator_get_enable_read_voltage(dev, "refin");
drivers/iio/adc/max11205.c +3 -1
@@ -114,7 +114,9 @@ static int max11205_probe(struct spi_dev
 
 	st = iio_priv(indio_dev);
 
-	ad_sd_init(&st->sd, indio_dev, spi, &max11205_sigma_delta_info);
+	ret = ad_sd_init(&st->sd, indio_dev, spi, &max11205_sigma_delta_info);
+	if (ret)
+		return ret;
 
 	st->chip_info = spi_get_device_match_data(spi);
 	if (!st->chip_info)
author maintainer
#896 lore raw

PATCH 895/1005 iio: addac: ad74413r: fix the values of set_multiple

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 e6dfbd84b833ed595a5236b027357e917de28260 upstream.

ad74413r_gpio_set_multiple() walks over the lines in the mask and looks up the new value of each with

if (*bits & offset)

offset is the number of the line, not a bit mask. Line 0 is always driven low, line 1 gets the value meant for line 0, line 2 the one meant for line 1, and line 3 is driven high if either of these two is.

Test the bit which belongs to the line.

Fixes fea251b6a5db ("iio: addac: add AD74413R driver")
Cc stable <[email protected]>
---
 drivers/iio/addac/ad74413r.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/iio/addac/ad74413r.c +1 -1
@@ -312,7 +312,7 @@ static int ad74413r_gpio_set_multiple(st
 			return ret;
 
 		real_mask |= BIT(real_offset);
-		if (*bits & offset)
+		if (test_bit(offset, bits))
 			real_bits |= BIT(real_offset);
 	}
 
author maintainer
#897 lore raw

PATCH 896/1005 iio: hid-sensors: fix a division by zero

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 fd4c92bbd3a64556e81042ff8d30545b15a3b93a upstream.

convert_to_vtf_format() divides the micro part of a value by 10^(6 + exp). The unit exponent of a HID field is a nibble and goes down to -8. For -7 and -8 the argument of int_pow() is negative, which the unsigned parameter turns into a huge power of ten: 0 modulo 2^64. The division by it is a divide error. The exponent comes from the report descriptor of the sensor hub, the value from a write to the hysteresis attribute of the IIO device.

Multiply by 10^(-exp - 6) in these two cases.

Fixes 73c6768b710a ("iio: hid-sensors: Common attribute and trigger")
Cc stable <[email protected]>
---
 drivers/iio/common/hid-sensors/hid-sensor-attributes.c |    5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/iio/common/hid-sensors/hid-sensor-attributes.c +4 -1
@@ -140,7 +140,10 @@ static u32 convert_to_vtf_format(int siz
 	if (val1 < 0 || val2 < 0)
 		sign = -1;
 	exp = hid_sensor_convert_exponent(exp);
-	if (exp < 0) {
+	if (exp < -6) {
+		value = abs(val1) * int_pow(10, -exp);
+		value += abs(val2) * int_pow(10, -exp - 6);
+	} else if (exp < 0) {
 		divisor = int_pow(10, 6 + exp);
 		value = abs(val1) * int_pow(10, -exp);
 		value += abs(val2) / divisor;
author maintainer
#898 lore raw

PATCH 897/1005 iio: sx9310: use the data of the I2C table

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 f3fc8718af9189aad13a2ad7f5b256475bb14b21 upstream.

sx9310_check_whoami() takes the chip information from device_get_match_data(), which only looks at the OF and ACPI tables, and dereferences it. For a client which was bound through the i2c_device_id table, for instance one created with

echo sx9310 0x28 > /sys/bus/i2c/devices/i2c-1/new_device

it returns NULL, and the kernel oopses as soon as something at that address answers the read of the WHOAMI register.

The I2C table has the same pointers. Use i2c_get_match_data(), which falls back to it.

Fixes 21fd3b1373f6 ("iio: proximity: sx9310: Convert enum->pointer for match data table")
Cc stable <[email protected]>
---
 drivers/iio/proximity/sx9310.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/iio/proximity/sx9310.c +1 -1
@@ -891,7 +891,7 @@ static int sx9310_check_whoami(struct de
 	if (ret)
 		return ret;
 
-	ddata = device_get_match_data(dev);
+	ddata = i2c_get_match_data(data->client);
 	if (ddata->whoami != whoami)
 		return -ENODEV;
 
author maintainer
#899 lore raw

PATCH 898/1005 mei: lb: read the MTU once

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 1115120f89f5c22bf49f7423cf158a04a474dd93 upstream.

mei_cldev_mtu() returns 0 if the client is not connected. A link reset disconnects all clients at any time, from the reset work.

mei_lb_push_payload_v2() asks for the MTU to allocate the request buffer and asks again for every chunk. If the reset comes in between,

	chunk_size = min(payload_size - sent_data, 0 - sizeof(*req));

makes the chunk the whole rest of the payload, and the memcpy() behind it writes over the end of the buffer. If the reset comes before the first call, kzalloc(0) returns ZERO_SIZE_PTR, which passes the NULL check and is dereferenced. An MTU not bigger than the request header has the same effect as 0.

Read the MTU once and refuse one which leaves no room for payload. If the client has gone, sending the chunk fails.

---
 drivers/misc/mei/mei_lb.c |   12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
drivers/misc/mei/mei_lb.c +10 -2
@@ -312,16 +312,24 @@ static int mei_lb_push_payload_v2(struct
 	size_t chunk_size;
 	size_t req_size;
 	ssize_t bytes;
+	size_t mtu;
 	int ret;
 
-	struct mei_lb2_req *req __free(kfree) = kzalloc(mei_cldev_mtu(cldev), GFP_KERNEL);
+	/* The MTU turns into 0 when a link reset disconnects the client */
+	mtu = mei_cldev_mtu(cldev);
+	if (mtu <= sizeof(struct mei_lb2_req)) {
+		dev_err(dev, "MTU is too small: %zu\n", mtu);
+		return -EMSGSIZE;
+	}
+
+	struct mei_lb2_req *req __free(kfree) = kzalloc(mtu, GFP_KERNEL);
 	if (!req)
 		return -ENOMEM;
 
 	first_chunk = MEI_LB2_FLAG_FST_CHUNK;
 	last_chunk = 0;
 	do {
-		chunk_size = min(payload_size - sent_data, mei_cldev_mtu(cldev) - sizeof(*req));
+		chunk_size = min(payload_size - sent_data, mtu - sizeof(*req));
 
 		req_size = struct_size(req, payload, chunk_size);
 		if (sent_data + chunk_size == payload_size)
author maintainer
#900 lore raw

PATCH 899/1005 mei: me: add ice lake point LP iTouch DID

In reply to Greg Kroah-Hartman

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

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

From: Antonio Vázquez Blanco <[email protected]>

commit 73383d06da9a1ded4c85845407cb4029aeecca39 upstream.

Add the device ID for the Intel Precise Touch & Stylus (iTouch) function on Ice Lake Point LP. It appears as PCI device 8086:34e4, next to the regular MEI function at 8086:34e0, on Microsoft Surface Pro 7 and Surface Laptop 3.

Without this entry mei_me does not bind, the touch controller is unreachable, and neither the touchscreen nor the pen work. Users currently work around this by binding the device by hand at boot:

  echo "8086 34e4 ffffffff ffffffff 0 0 9" > \
          /sys/bus/pci/drivers/mei_me/new_id

where the trailing 9 is the mei_me_cfgs[] index of MEI_ME_PCH12_CFG. That is fragile by construction, since the index is positional and any reordering of the config array silently changes which config the device gets.

This ID was first reported in June 2020, together with Sunrise Point's 0x9d3e, in "mei: me: Add itouch device IDs for SPT / ICP" [1]. That submission was declined over the server platform ID conflict, and the Sunrise Point half was subsequently added in commit 372a829862e5 ("mei:
me: add MEI device for SPT with ITPS capability"). Ice Lake Point was never added.

Use MEI_ME_PCH12_SPS_ITOUCH_CFG, so that the device is reported with the correct kind and the SPS firmware exclusion applies. Note this is not the config the manual new_id workaround above selects: it reports kind "itouch" rather than "mei", and it does not set up a DMA ring.

---
 drivers/misc/mei/hw-me-regs.h |    1 +
 drivers/misc/mei/pci-me.c     |    1 +
 2 files changed, 2 insertions(+)
drivers/misc/mei/hw-me-regs.h +1 -0
@@ -94,6 +94,7 @@
 #define PCI_DEVICE_ID_INTEL_MEI_CDF        0x18D3  /* Cedar Fork */
 
 #define PCI_DEVICE_ID_INTEL_MEI_ICP_LP     0x34E0  /* Ice Lake Point LP */
+#define PCI_DEVICE_ID_INTEL_MEI_ICP_LP_3   0x34E4  /* Ice Lake Point LP 3 (iTouch) */
 #define PCI_DEVICE_ID_INTEL_MEI_ICP_N      0x38E0  /* Ice Lake Point N */
 
 #define PCI_DEVICE_ID_INTEL_MEI_JSP_N      0x4DE0  /* Jasper Lake Point N */
drivers/misc/mei/pci-me.c +1 -0
@@ -98,6 +98,7 @@ static const struct pci_device_id mei_me
 	{ PCI_DEVICE_DATA(INTEL, MEI_CMP_H_3, MEI_ME_PCH8_ITOUCH_CFG) },
 
 	{ PCI_DEVICE_DATA(INTEL, MEI_ICP_LP, MEI_ME_PCH12_CFG) },
+	{ PCI_DEVICE_DATA(INTEL, MEI_ICP_LP_3, MEI_ME_PCH12_SPS_ITOUCH_CFG) },
 	{ PCI_DEVICE_DATA(INTEL, MEI_ICP_N, MEI_ME_PCH12_CFG) },
 
 	{ PCI_DEVICE_DATA(INTEL, MEI_TGP_LP, MEI_ME_PCH15_CFG) },
author maintainer
#901 lore raw

PATCH 900/1005 misc: bcm-vk: fix DMA allocation memory leak

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 a36b3db60466d44eefcc5c252ce927c043429922 upstream.

bcm_vk_dma_alloc() leaks dma->pages and pinned user-page references when page pinning or coherent SG allocation fails. DMA mapping failures can also leave the SG list and earlier mappings unreleased, as bcm_vk_sg_alloc() skips the partially initialized slot.

This issue was found by our static analysis tool under development.

---
 drivers/misc/bcm-vk/bcm_vk_sg.c |   43 +++++++++++++++++++++++++++++++++-------
 1 file changed, 36 insertions(+), 7 deletions(-)
drivers/misc/bcm-vk/bcm_vk_sg.c +36 -7
@@ -78,7 +78,8 @@ static int bcm_vk_dma_alloc(struct devic
 		dma->nr_pages = (err >= 0) ? err : 0;
 		dev_err(dev, "get_user_pages_fast, err=%d [%d]\n",
 			err, dma->nr_pages);
-		return err < 0 ? err : -EINVAL;
+		err = err < 0 ? err : -EINVAL;
+		goto err_pages;
 	}
 
 	/* Max size of sg list is 1 per mapped page + fields at start */
@@ -90,8 +91,10 @@ static int bcm_vk_dma_alloc(struct devic
 					 dma->sglen,
 					 &dma->handle,
 					 GFP_KERNEL);
-	if (!dma->sglist)
-		return -ENOMEM;
+	if (!dma->sglist) {
+		err = -ENOMEM;
+		goto err_pages;
+	}
 
 	dma->sglist[SGLIST_NUM_SG] = 0;
 	dma->sglist[SGLIST_TOTALSIZE] = vkdata->size;
@@ -108,8 +111,8 @@ static int bcm_vk_dma_alloc(struct devic
 			       dma->direction);
 	transfer_size = size;
 	if (unlikely(dma_mapping_error(dev, sg_addr))) {
-		__free_page(dma->pages[0]);
-		return -EIO;
+		err = -EIO;
+		goto err_sglist;
 	}
 
 	for (i = 1; i < dma->nr_pages; i++) {
@@ -121,8 +124,8 @@ static int bcm_vk_dma_alloc(struct devic
 				    size,
 				    dma->direction);
 		if (unlikely(dma_mapping_error(dev, addr))) {
-			__free_page(dma->pages[i]);
-			return -EIO;
+			err = -EIO;
+			goto err_unmap;
 		}
 
 		/*
@@ -167,6 +170,32 @@ static int bcm_vk_dma_alloc(struct devic
 #endif
 
 	return 0;
+
+err_unmap:
+	/*
+	 * Unmap completed SG entries and the in-progress DMA range,
+	 * which has not been written to the SG list yet.
+	 */
+	sgdata = (struct _vk_data *)&dma->sglist[SGLIST_VKDATA_START];
+	for (i = 0; i < dma->sglist[SGLIST_NUM_SG]; i++) {
+		size = sgdata[i].size;
+		addr = get_unaligned(&sgdata[i].address);
+		dma_unmap_page(dev, addr, size, dma->direction);
+	}
+	dma_unmap_page(dev, sg_addr, transfer_size, dma->direction);
+
+err_sglist:
+	dma_free_coherent(dev, dma->sglen, dma->sglist, dma->handle);
+
+err_pages:
+	for (i = 0; i < dma->nr_pages; i++)
+		put_page(dma->pages[i]);
+	kfree(dma->pages);
+	dma->pages = NULL;
+	dma->sglist = NULL;
+	dma->sglen = 0;
+	dma->nr_pages = 0;
+	return err;
 }
 
 int bcm_vk_sg_alloc(struct device *dev,
author maintainer
#902 lore raw

PATCH 901/1005 misc: ibmvmc: initialize HMC state before device registration

In reply to Greg Kroah-Hartman

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

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

From: Jiale Yao <[email protected]>

commit 2022f170e5655c40b93ed98629f7d0adb98cea49 upstream.

misc_register() exposes the IBM VMC device before the HMC state and spinlocks are initialized. A userspace operation racing module initialization can therefore access an HMC through an uninitialized spinlock.

Initialize all HMC state before registering the misc device.

Fixes 0eca353e7ae7 ("misc: IBM Virtual Management Channel Driver (VMC)")
Cc stable <[email protected]>
---
 drivers/misc/ibmvmc.c |   16 ++++++++--------
 1 file changed, 8 insertions(+), 8 deletions(-)
drivers/misc/ibmvmc.c +8 -8
@@ -2365,14 +2365,6 @@ static int __init ibmvmc_module_init(voi
 	ibmvmc.state = ibmvmc_state_initial;
 	pr_info("ibmvmc: version %s\n", IBMVMC_DRIVER_VERSION);
 
-	rc = misc_register(&ibmvmc_miscdev);
-	if (rc) {
-		pr_err("ibmvmc: misc registration failed\n");
-		goto misc_register_failed;
-	}
-	pr_info("ibmvmc: node %d:%d\n", MISC_MAJOR,
-		ibmvmc_miscdev.minor);
-
 	/* Initialize data structures */
 	memset(hmcs, 0, sizeof(struct ibmvmc_hmc) * MAX_HMCS);
 	for (i = 0; i < MAX_HMCS; i++) {
@@ -2382,6 +2374,14 @@ static int __init ibmvmc_module_init(voi
 			hmcs[i].queue_outbound_msgs[j] = VMC_INVALID_BUFFER_ID;
 	}
 
+	rc = misc_register(&ibmvmc_miscdev);
+	if (rc) {
+		pr_err("ibmvmc: misc registration failed\n");
+		goto misc_register_failed;
+	}
+	pr_info("ibmvmc: node %d:%d\n", MISC_MAJOR,
+		ibmvmc_miscdev.minor);
+
 	/* Sanity check module parms */
 	ibmvmc_scrub_module_parms();
 
author maintainer
#903 lore raw

PATCH 902/1005 misc: vmw_vmci: wait for callbacks in event unsubscribe

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 824a27d391cf934d3232e8e2dabee221fc4e18ae upstream.

event_deliver() calls the callbacks of the subscribers inside an RCU read side critical section. vmci_event_unsubscribe() used to call synchronize_rcu() before it freed the subscription. This did more than to protect the struct vmci_subscription: when the function returned, no callback was running any more, and its callers rely on that.

vmci_transport_free_resources() unsubscribes from VMCI_EVENT_QP_PEER_DETACH and frees the struct vmci_transport, which is the callback data, a few lines later:

CPU0 CPU1
event_deliver()

    rcu_read_lock()
    vmci_transport_peer_detach_cb()
                                      vmci_event_unsubscribe()
                                        list_del_rcu(&s->node)
                                        kvfree_rcu_mightsleep(s)
                                      kfree(transport)
      spin_lock_bh(&trans->lock)

The event is sent when the peer of the queue pair detaches, so the other end of a vsock connection chooses the time. vmci_transport_exit() and vmci_guest_remove_device() unsubscribe callbacks which are gone with their module.

kvfree_rcu_mightsleep() only waits for a grace period if it cannot allocate memory. Bring the synchronize_rcu() back. The cleanup work of the vmci transport now waits for one grace period per socket again.

Fixes 6da3f33770e0 ("misc: vmw_vmci: Switch to kvfree_rcu() API")
Cc stable <[email protected]>
Cc Bryan Tan <[email protected]>
Cc Vishnu Dasa <[email protected]>
Cc Broadcom internal kernel review list <[email protected]>
Cc Arnd Bergmann <[email protected]>
---
 drivers/misc/vmw_vmci/vmci_event.c |    7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
drivers/misc/vmw_vmci/vmci_event.c +6 -1
@@ -213,7 +213,12 @@ int vmci_event_unsubscribe(u32 sub_id)
 	if (!s)
 		return VMCI_ERROR_NOT_FOUND;
 
-	kvfree_rcu_mightsleep(s);
+	/*
+	 * Wait for event_deliver(): the caller is going to free what the
+	 * callback works on.
+	 */
+	synchronize_rcu();
+	kfree(s);
 
 	return VMCI_SUCCESS;
 }
author maintainer
#904 lore raw

PATCH 903/1005 serial: 8250_exar: check priv->gpio properly

In reply to Greg Kroah-Hartman

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

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

From: Jiri Slaby (SUSE) <[email protected]>

commit 0353b51965883cf70dad162908e07395f242000f upstream.

priv->gpio is set by platform_device_register_full(), which returns error-encoded pointers on failure, not NULL. Sashiko reported:

Quoted 7 lines

Does __xr17v35x_register_gpio() return an ERR_PTR if platform_device_register_full() fails?

If it does, we might be storing an error pointer directly into priv->gpio in xr17v35x_register_gpio() without validating it with IS_ERR(). Because the error is ignored, the device probe successfully continues.

Before commit 1145d1a0703f ("serial: 8250_exar: use platform_device_register_full()"), __xr17v35x_register_gpio() returned NULL on any failure (platform_device_alloc(), device_add_software_node() or platform_device_add() failing were all turned into a NULL return). The plain truthy check in xr17v35x_unregister_gpio() matched that convention. That commit switched registration to platform_device_register_full(), which reports failure as an ERR_PTR() instead of NULL, but the unregister check was never updated to match. As a result, a failed registration left an error pointer in priv->gpio, and unbind would tear it down as if it were a real platform_device, dereferencing the encoded error value in device_remove_software_node() and platform_device_unregister().

Use IS_ERR_OR_NULL() instead, so both the unset (non-EXAR vendor, priv->gpio never assigned) and failed-registration (ERR_PTR) cases are skipped.

---
 drivers/tty/serial/8250/8250_exar.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/tty/serial/8250/8250_exar.c +1 -1
@@ -1180,7 +1180,7 @@ static int xr17v35x_register_gpio(struct
 
 static void xr17v35x_unregister_gpio(struct exar8250 *priv)
 {
-	if (priv->gpio) {
+	if (!IS_ERR_OR_NULL(priv->gpio)) {
 		__xr17v35x_unregister_gpio(priv->gpio);
 		priv->gpio = NULL;
 	}
author maintainer
#905 lore raw

PATCH 904/1005 serial: 8250_lpss: dont divide by 0 above 6.25 Mbaud

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 08daebfd63e9054e097eb2653eff9381de43a422 upstream.

byt_set_termios() derives the clock of the UART from the baud rate in the termios, which nobody has looked at yet:

	fuart = baud * 16;
	...
	fuart *= rounddown_pow_of_two(fref / fuart);
	...
	p->uartclk = fuart;

fref is 100 MHz. For a baud rate above 6250000, which BOTHER allows, fref / fuart is 0, and rounddown_pow_of_two(0) shifts 1UL by -1. On x86 that is 1UL << 63, the product with a multiple of 16 is 0, and so is uartclk. serial8250_get_baud_rate() then passes 0 for both limits, uart_get_baud_rate() finds no rate which fits, WARNs and returns 0, and uart_get_divisor() or dw8250_get_divisor() divide by 16 * 0.

Everybody who may open the tty can oops the kernel with one TCSETS2.

Don't ask for more than fref. The limits are those of a 100 MHz clock then, and uart_get_baud_rate() falls back to the old rate as for any other rate that the port cannot do. 8250_mid, which has the same formula, treats this case separately.

Fixes 21947ba654a6 ("serial: 8250_pci: replace switch-case by formula")
Cc stable <[email protected]>
Cc "Ilpo Järvinen" <[email protected]>
Cc Andy Shevchenko <[email protected]>
Cc Jiri Slaby <[email protected]>
Cc Heikki Krogerus <[email protected]>
Cc Peter Hurley <[email protected]>
---
 drivers/tty/serial/8250/8250_lpss.c |    3 +++
 1 file changed, 3 insertions(+)
drivers/tty/serial/8250/8250_lpss.c +3 -0
@@ -82,6 +82,9 @@ static void byt_set_termios(struct uart_
 	/* Gracefully handle the B0 case: fall back to B9600 */
 	fuart = fuart ? fuart : 9600 * 16;
 
+	/* Fuart <= Fref: leave it to the core to refuse a higher baud rate */
+	fuart = min(fuart, fref);
+
 	/* Get Fuart closer to Fref */
 	fuart *= rounddown_pow_of_two(fref / fuart);
 
author maintainer
#906 lore raw

PATCH 905/1005 serial: 8250_mxpcie: handle hangup during break

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 899e3c6e30ff34cf7a260b806fdedb56749e36e9 upstream.

Ending a software break on a Moxa PCIe port in RS-485 2-wire mode dereferences a NULL tty pointer if the port was hung up while the break was being sent.

send_break() calls ->break_ctl(tty, -1), sleeps for the break duration and then calls ->break_ctl(tty, 0), without excluding a concurrent hangup. A hangup (a modem DCD drop, or the session leader exiting while another process of the session is in TCSBRK/TCSBRKP) runs uart_hangup(), which shuts the port down and clears port->state->port.tty. The second call still reaches mxpcie8250_software_break_ctl() through uart_break_ctl(), which then does:

    struct tty_struct *tty = port->state->port.tty;
    ...
    baud = tty_get_baud_rate(tty);

with tty == NULL.

The bug was found by code inspection and has not been reproduced.

Fix by taking a reference to the port's tty with tty_port_tty_get() and only restoring the divisor when a tty is still attached; a hung up port is shut down, and the next open programs the divisor again through set_termios().

Fixes ade78d3d253c ("serial: 8250_mxpcie: add break support for RS485 using MUEx50 features")
Cc stable <[email protected]>
Cc Jiri Slaby <[email protected]>
Cc Crescent Hsieh <[email protected]>
Cc Andy Shevchenko <[email protected]>
Cc Linmao Li <[email protected]>
---
 drivers/tty/serial/8250/8250_mxpcie.c |   13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)
drivers/tty/serial/8250/8250_mxpcie.c +9 -4
@@ -411,7 +411,7 @@ static int mxpcie8250_handle_irq(struct
 static void mxpcie8250_software_break_ctl(struct uart_port *port, int break_state)
 {
 	struct uart_8250_port *up = up_to_u8250p(port);
-	struct tty_struct *tty = port->state->port.tty;
+	struct tty_struct *tty;
 	unsigned int baud, quot;
 	u8 sfr, tx_byte = 0x01;
 
@@ -438,9 +438,14 @@ static void mxpcie8250_software_break_ct
 
 		serial_out(up, UART_FCR, UART_FCR_CLEAR_XMIT);
 
-		baud = tty_get_baud_rate(tty);
-		quot = uart_get_divisor(port, baud);
-		serial8250_do_set_divisor(port, baud, quot);
+		/* A hangup during the break detaches the tty */
+		tty = tty_port_tty_get(&port->state->port);
+		if (tty) {
+			baud = tty_get_baud_rate(tty);
+			quot = uart_get_divisor(port, baud);
+			serial8250_do_set_divisor(port, baud, quot);
+			tty_kref_put(tty);
+		}
 		serial_out(up, UART_LCR, up->lcr);
 	}
 }
author maintainer
#907 lore raw

PATCH 906/1005 serial: core: respect runtime PM when sending x_char

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 84da8238f7bd3025fc16da32c4cd9992c95a783b upstream.

__uart_start() calls the start_tx operation only if the port is runtime active. Otherwise it asks for a resume, and serial_port_runtime_resume() starts the transmitter.

uart_send_xchar() calls start_tx at once, under the port lock, whatever the state of the device. With 8250_omap, serial8250_start_tx() then calls pm_runtime_get_sync() for a suspended device: that sleeps, and omap8250_runtime_resume() takes the port lock again. A tcflow(TCIOFF) on an idle port is enough, if autosuspend has been enabled. It was allowed as long as that driver used pm_runtime_irq_safe().

Share the part of __uart_start() that deals with runtime PM. A stopped transmission still does not hold up an XON or XOFF character. Let a pending x_char count as work for serial_port_runtime_resume(), and keep the port from being suspended with it.

Fixes 8700a7ea5519 ("serial: 8250_omap: Drop pm_runtime_irq_safe()")
Cc stable <[email protected]>
Cc Jiri Slaby <[email protected]>
Cc Hugo Villeneuve <[email protected]>
Cc Johan Hovold <[email protected]>
Cc Karl Mehltretter <[email protected]>
Cc John Ogness <[email protected]>
Cc "Uwe Kleine-König (The Capable Hub)" <[email protected]>
Cc Tony Lindgren <[email protected]>
---
 drivers/tty/serial/serial_core.c |   25 +++++++++++++++----------
 drivers/tty/serial/serial_port.c |    4 ++--
 2 files changed, 17 insertions(+), 12 deletions(-)
drivers/tty/serial/serial_core.c +15 -10
@@ -135,17 +135,11 @@ static void uart_stop(struct tty_struct
 	uart_port_unlock_deref(port, flags);
 }
 
-static void __uart_start(struct uart_state *state)
+static void uart_port_start_tx(struct uart_port *port)
 {
-	struct uart_port *port = state->uart_port;
-	struct serial_port_device *port_dev;
+	struct serial_port_device *port_dev = port->port_dev;
 	int err;
 
-	if (!port || port->flags & UPF_DEAD || uart_tx_stopped(port))
-		return;
-
-	port_dev = port->port_dev;
-
 	/* Increment the runtime PM usage count for the active check below */
 	err = pm_runtime_get(&port_dev->dev);
 	if (err < 0 && err != -EINPROGRESS) {
@@ -164,6 +158,16 @@ static void __uart_start(struct uart_sta
 	pm_runtime_put_autosuspend(&port_dev->dev);
 }
 
+static void __uart_start(struct uart_state *state)
+{
+	struct uart_port *port = state->uart_port;
+
+	if (!port || port->flags & UPF_DEAD || uart_tx_stopped(port))
+		return;
+
+	uart_port_start_tx(port);
+}
+
 static void uart_start(struct tty_struct *tty)
 {
 	struct uart_state *state = tty->driver_data;
@@ -718,8 +722,9 @@ static void uart_send_xchar(struct tty_s
 	else {
 		guard(uart_port_lock_irqsave)(port);
 		port->x_char = ch;
-		if (ch)
-			port->ops->start_tx(port);
+		/* It goes out even if the transmission is stopped */
+		if (ch && !(port->flags & UPF_DEAD))
+			uart_port_start_tx(port);
 	}
 	uart_port_deref(port);
 }
drivers/tty/serial/serial_port.c +2 -2
@@ -23,8 +23,8 @@
 /* Only considers pending TX for now. Caller must take care of locking */
 static int __serial_port_busy(struct uart_port *port)
 {
-	return !uart_tx_stopped(port) &&
-		!kfifo_is_empty(&port->state->port.xmit_fifo);
+	return port->x_char || (!uart_tx_stopped(port) &&
+		!kfifo_is_empty(&port->state->port.xmit_fifo));
 }
 
 static int serial_port_runtime_resume(struct device *dev)
author maintainer
#908 lore raw

PATCH 907/1005 serial: fsl_lpuart: fix tty ref of wakeup event

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 0f0664a63efdfd70d1c555080781f4e8464445aa upstream.

To report a wakeup event, lpuart_resume_noirq() gets the tty with tty_port_tty_get() and never puts it: each wakeup by the UART leaks a reference, and the tty is not freed when it is closed.

With no_console_suspend, the function also gets there for a console which is not open. Then tty_port_tty_get() returns NULL, which is dereferenced.

Fixes 18bdfccf3c30 ("tty: serial: fsl_lpuart: Add missing wakeup event reporting")
Cc stable <[email protected]>
Cc Jiri Slaby <[email protected]>
Cc Frank Li <[email protected]>
Cc Peng Fan <[email protected]>
Cc Shitalkumar Gandhi <[email protected]>
Cc Sherry Sun <[email protected]>
---
 drivers/tty/serial/fsl_lpuart.c |   10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
drivers/tty/serial/fsl_lpuart.c +8 -2
@@ -3113,8 +3113,14 @@ static int lpuart_resume_noirq(struct de
 			/* check whether lpuart wakeup was triggered */
 			wake_active = stat & (UARTSTAT_RDRF | UARTSTAT_RXEDGIF);
 
-			if (wake_active && irqd_is_wakeup_set(irq_get_irq_data(sport->port.irq)))
-				pm_wakeup_event(tty_port_tty_get(port)->dev, 0);
+			if (wake_active && irqd_is_wakeup_set(irq_get_irq_data(sport->port.irq))) {
+				struct tty_struct *tty = tty_port_tty_get(port);
+
+				if (tty) {
+					pm_wakeup_event(tty->dev, 0);
+					tty_kref_put(tty);
+				}
+			}
 		}
 	}
 
author maintainer
#909 lore raw

PATCH 908/1005 serial: imx: fix the tty reference of the wakeup event

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 6d7fbd5a28d092ab61ec0092cf1e085d2bb9ed7e upstream.

To report a wakeup event, imx_uart_enable_wakeup() gets the tty with tty_port_tty_get() and never puts it: each wakeup by the UART leaks a reference, and the tty is not freed when it is closed.

Fixes 0cfadf4bcd28 ("tty: serial: imx: Add missing wakeup event reporting")
Cc stable <[email protected]>
Cc Jiri Slaby <[email protected]>
Cc Frank Li <[email protected]>
Cc Sascha Hauer <[email protected]>
Cc Pengutronix Kernel Team <[email protected]>
Cc Fabio Estevam <[email protected]>
Cc Robin Gong <[email protected]>
Cc Petr Mladek <[email protected]>
Cc John Ogness <[email protected]>
Cc Pan Chuang <[email protected]>
Cc Karl Mehltretter <[email protected]>
Cc Sherry Sun <[email protected]>
---
 drivers/tty/serial/imx.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
drivers/tty/serial/imx.c +8 -2
index 986fefb45c63..18892fc4a35b 100644
@@ -2742,8 +2742,14 @@ static void imx_uart_enable_wakeup(struct imx_port *sport, bool on)
 		imx_uart_writel(sport, ucr1, UCR1);
 	}
 
-	if (wake_active && irqd_is_wakeup_set(irq_get_irq_data(sport->port.irq)))
-		pm_wakeup_event(tty_port_tty_get(port)->dev, 0);
+	if (wake_active && irqd_is_wakeup_set(irq_get_irq_data(sport->port.irq))) {
+		struct tty_struct *tty = tty_port_tty_get(port);
+
+		if (tty) {
+			pm_wakeup_event(tty->dev, 0);
+			tty_kref_put(tty);
+		}
+	}
 
 	uart_port_unlock_irq(&sport->port);
 }
Signature · 1 line
2.56.1
author maintainer
#910 lore raw

PATCH 909/1005 serial: rda: free the interrupt on shutdown

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 859f7c56709b161a72b629b6f2f1384dcd374404 upstream.

rda_uart_startup() requests the interrupt, and nothing ever frees it. It is not shared, so once the port has been closed, the next startup fails with -EBUSY and the port cannot be opened any more.

Free it in rda_uart_shutdown().

Fixes c10b13325ced ("tty: serial: Add RDA8810PL UART driver")
Cc stable <[email protected]>
Cc Jiri Slaby <[email protected]>
Cc Arnd Bergmann <[email protected]>
Cc "Andreas Färber" <[email protected]>
Cc Olof Johansson <[email protected]>
---
 drivers/tty/serial/rda-uart.c |    2 ++
 1 file changed, 2 insertions(+)
drivers/tty/serial/rda-uart.c +2 -0
@@ -471,6 +471,8 @@ static void rda_uart_shutdown(struct uar
 	rda_uart_write(port, val, RDA_UART_CTRL);
 
 	uart_port_unlock_irqrestore(port, flags);
+
+	free_irq(port->irq, port);
 }
 
 static const char *rda_uart_type(struct uart_port *port)
author maintainer
#911 lore raw

PATCH 910/1005 serial: samsung: dont leak the tty on an RX IRQ

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 7ada442f5ef77f8d53f608a0141a5e88a888ca9f upstream.

s3c24xx_serial_rx_chars_dma() starts by taking a reference to the tty. If the interrupt is not a receive timeout, it switches the port from PIO back to DMA and leaves through the "finish" label, which does not drop the reference.

A port with RX DMA changes to PIO on every receive timeout, that is at the end of every burst of data, and comes back this way when the next burst starts. So each burst takes a reference which is never dropped, and the tty structure is not freed when the port is closed for the last time.

Drop the reference on both paths.

Fixes b543c301c2c5 ("serial: samsung: add DMA support for RX")
Cc stable <[email protected]>
Cc Krzysztof Kozlowski <[email protected]>
Cc Peter Griffin <[email protected]>
Cc Alim Akhtar <[email protected]>
Cc Jiri Slaby <[email protected]>
Cc Robert Baldyga <[email protected]>
---
 drivers/tty/serial/samsung_tty.c |    5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
drivers/tty/serial/samsung_tty.c +2 -3
@@ -736,14 +736,13 @@ static irqreturn_t s3c24xx_serial_rx_cha
 
 	s3c24xx_serial_rx_drain_fifo(ourport);
 
-	if (tty) {
+	if (tty)
 		tty_flip_buffer_push(t);
-		tty_kref_put(tty);
-	}
 
 	wr_regl(port, S3C2410_UTRSTAT, S3C2410_UTRSTAT_TIMEOUT);
 
 finish:
+	tty_kref_put(tty);
 	uart_port_unlock(port);
 
 	return IRQ_HANDLED;
author maintainer
#912 lore raw

PATCH 911/1005 serial: samsung: put the previous baud clock

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 eedf2cf3505c1562a2fb24f8b997056f023d242b upstream.

s3c24xx_serial_getclk() returns the best baud clock with the reference which clk_get() has taken. s3c24xx_serial_set_termios() stores it in ourport->baudclk and disables the clock which was there before, but does not put it.

clk_get() hands out a new handle on every call, so the new clock never equals the old one, and every call of ->set_termios() leaks a handle: a struct clk and a copy of the connection name. Whoever has the port open can repeat that at will with tcsetattr().

Put the old clock when it is replaced, and the new one in case it is not stored.

Fixes 5f5a7a5578c5 ("serial: samsung: switch to clkdev based clock lookup")
Cc stable <[email protected]>
Cc Krzysztof Kozlowski <[email protected]>
Cc Peter Griffin <[email protected]>
Cc Alim Akhtar <[email protected]>
Cc Jiri Slaby <[email protected]>
Cc Kukjin Kim <[email protected]>
Cc Thomas Abraham <[email protected]>
---
 drivers/tty/serial/samsung_tty.c |    3 +++
 1 file changed, 3 insertions(+)
drivers/tty/serial/samsung_tty.c +3 -0
@@ -1498,11 +1498,14 @@ static void s3c24xx_serial_set_termios(s
 
 		if (!IS_ERR(ourport->baudclk)) {
 			clk_disable_unprepare(ourport->baudclk);
+			clk_put(ourport->baudclk);
 			ourport->baudclk = ERR_PTR(-EINVAL);
 		}
 
 		ourport->baudclk = clk;
 		ourport->baudclk_rate = clk ? clk_get_rate(clk) : 0;
+	} else {
+		clk_put(clk);
 	}
 
 	if (ourport->info->has_divslot) {
author maintainer
#913 lore raw

PATCH 912/1005 thunderbolt: stream: Undo more if the start fails

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 03e3c33fe074ba57ae4457894fe5b6a90e3be6ee upstream.

If the receive buffers cannot be allocated or mapped, tbstream_dev_start() stops and frees the rings, but

- leaves the DMA paths through the XDomain connection enabled, with the hop IDs of rings which no longer exist;
- does not release the frame array and the pages which tbstream_dev_alloc_rx_buffers() had allocated and mapped before it failed.

Fixes 6db21d817b43 ("thunderbolt: Add support for USB4STREAM")
Cc stable <[email protected]>
Cc Andreas Noever <[email protected]>
Cc Mika Westerberg <[email protected]>
Cc Yehezkel Bernat <[email protected]>
Cc Alan Borzeszkowski <[email protected]>
---
 drivers/thunderbolt/stream.c |    6 ++++++
 1 file changed, 6 insertions(+)
drivers/thunderbolt/stream.c +6 -0
@@ -630,6 +630,12 @@ static int tbstream_dev_start(struct tbs
 err_stop:
 	tb_ring_stop(sdev->rx_ring.ring);
 	tb_ring_stop(sdev->tx_ring.ring);
+	tb_xdomain_disable_paths(xd, sdev->out_hopid,
+				 sdev->tx_ring.ring->hop,
+				 sdev->in_hopid,
+				 sdev->rx_ring.ring->hop);
+	if (sdev->rx_ring.frames)
+		tbstream_ring_free(&sdev->rx_ring);
 err_free_rx:
 	tb_ring_free(sdev->rx_ring.ring);
 err_free_tx_buffers:
author maintainer
#914 lore raw

PATCH 913/1005 tty: fix misapplied compat_ptr() in tty_compat_ioctl()

In reply to Greg Kroah-Hartman

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

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

From: Jiri Slaby (SUSE) <[email protected]>

commit 895dc0eaa2779ff46a0b2a20b5ce9eb0b1125cb2 upstream.

Since commit f0193d3ea73b below, cmd was converted with compat_ptr(), while arg was passed to ld->ops->ioctl() unmodified. Fix it so cmd stays cmd and arg gets converted through compat_ptr() as intended.

Notes:
2) compat_ptr() did nothing to cmd, provided it is uint,
1) compat_ptr() is no-op everywhere (was different on s390 before 8e0b986c59c6 ("s390: Remove compat support")),
3) arg might not have been chopped correctly until 8e0b986c59c6. But I am not sure why noone noticed all those (7) years (from f0193d3ea73b to 8e0b986c59c6)?

Fixes f0193d3ea73b ("change semantics of ldisc ->compat_ioctl()")
Cc [email protected] # applicable from 4.20 to 6.18 incl
Assisted-by LLM
---
 drivers/tty/tty_io.c |    3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
drivers/tty/tty_io.c +1 -2
@@ -2969,8 +2969,7 @@ static long tty_compat_ioctl(struct file
 	if (ld->ops->compat_ioctl)
 		retval = ld->ops->compat_ioctl(tty, cmd, arg);
 	if (retval == -ENOIOCTLCMD && ld->ops->ioctl)
-		retval = ld->ops->ioctl(tty, (unsigned long)compat_ptr(cmd),
-				arg);
+		retval = ld->ops->ioctl(tty, cmd, (unsigned long)compat_ptr(arg));
 	tty_ldisc_deref(ld);
 
 	return retval;
author maintainer
#915 lore raw

PATCH 914/1005 USB: cdc-acm: fix NULL-deref on hangup

In reply to Greg Kroah-Hartman

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

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

From: Johan Hovold <[email protected]>

commit bc9dd21ec61acd152d9e7c12cb07db37c63ad41a upstream.

Make sure to take a reference to the port tty when processing carrier detect changes to avoid dereferencing a NULL pointer when the port is being hung up.

---
 drivers/usb/class/cdc-acm.c |   18 ++++++++++++------
 1 file changed, 12 insertions(+), 6 deletions(-)
drivers/usb/class/cdc-acm.c +12 -6
@@ -294,6 +294,7 @@ static void acm_process_notification(str
 	unsigned long flags;
 	struct usb_cdc_notification *dr = (struct usb_cdc_notification *)buf;
 	unsigned char *data = buf + sizeof(struct usb_cdc_notification);
+	struct tty_struct *tty;
 
 	switch (dr->bNotificationType) {
 	case USB_CDC_NOTIFY_NETWORK_CONNECTION:
@@ -320,12 +321,17 @@ static void acm_process_notification(str
 
 		difference = acm->ctrlin ^ newctrl;
 
-		if ((difference & USB_CDC_SERIAL_STATE_DCD) && acm->port.tty) {
-			struct tty_ldisc *ld = tty_ldisc_ref(acm->port.tty);
-			if (ld) {
-				if (ld->ops->dcd_change)
-					ld->ops->dcd_change(acm->port.tty, newctrl & USB_CDC_SERIAL_STATE_DCD);
-				tty_ldisc_deref(ld);
+		if (difference & USB_CDC_SERIAL_STATE_DCD) {
+			tty = tty_port_tty_get(&acm->port);
+			if (tty) {
+				struct tty_ldisc *ld = tty_ldisc_ref(tty);
+
+				if (ld) {
+					if (ld->ops->dcd_change)
+						ld->ops->dcd_change(tty, newctrl & USB_CDC_SERIAL_STATE_DCD);
+					tty_ldisc_deref(ld);
+				}
+				tty_kref_put(tty);
 			}
 		}
 
author maintainer
#916 lore raw

PATCH 915/1005 usb: pci-quirks: always assert xHCI OS ownership

In reply to Greg Kroah-Hartman

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

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

From: Rishabh Jain <[email protected]>

commit 5550405351199fe78f4a3cd606c07f5ad7220e1b upstream.

The xHCI ownership protocol requires the OS driver to assert the HC OS Owned semaphore before using the host controller, then wait for HC BIOS Owned to clear if firmware owns it.

quirk_usb_handoff_xhci() currently asserts OS Owned only when BIOS Owned is already set. If firmware leaves BIOS Owned clear, Linux uses the xHC while both ownership semaphores remain clear.

The timeout fallback also clears BIOS Owned using the original register value, which can clear OS Owned at the same time.

On an AMD PROM21 xHCI controller (1022:43fc), this caused every S3 resume to terminate Controller Restore State with USBSTS 0x401. Linux then reset the host controller, both root hubs and the USB Bluetooth adapter.

The controller entered resume ready and halted with USBSTS 0x1. Endpoint state, 100 ms save/restore delays, scratchpads, the DCBAA, device contexts and command, event and transfer rings were verified not to cause the restore error.

Across four S3 cycles, asserting only HC OS Owned changed USBLEGSUP from 0x00000801 to 0x01000801 and eliminated the restore failure. Testing included the unmodified 7.1.8-ogc1.1.fc44.x86_64 distribution kernel using a test module that set the HC OS Owned semaphore. The same test was repeated after review with the same result. Clearing USBLEGCTLSTS was independently verified to be unnecessary.

Always assert OS Owned for controllers using the standard xHCI handoff, and leave the existing TI/Renesas forced handoff unchanged. Keep OS Owned asserted after the standard handoff, including when forcing BIOS Owned clear after a timeout, to prevent firmware from reclaiming the controller during subsequent suspends.

---
 drivers/usb/host/pci-quirks.c |   13 ++++++++-----
 1 file changed, 8 insertions(+), 5 deletions(-)
drivers/usb/host/pci-quirks.c +8 -5
@@ -1194,10 +1194,11 @@ static void quirk_usb_handoff_xhci(struc
 			 && pdev->device == 0x0014)) {
 		val = (val | XHCI_HC_OS_OWNED) & ~XHCI_HC_BIOS_OWNED;
 		writel(val, base + ext_cap_offset);
-	}
-
-	/* If the BIOS owns the HC, signal that the OS wants it, and wait */
-	if (val & XHCI_HC_BIOS_OWNED) {
+	} else {
+		/*
+		 * Perform the standard handoff and leave OS ownership set to
+		 * keep the BIOS at bay during subsequent suspends.
+		 */
 		writel(val | XHCI_HC_OS_OWNED, base + ext_cap_offset);
 
 		/* Wait for 1 second with 10 microsecond polling interval */
@@ -1209,7 +1210,9 @@ static void quirk_usb_handoff_xhci(struc
 			dev_warn(&pdev->dev,
 				 "xHCI BIOS handoff failed (BIOS bug ?) %08x\n",
 				 val);
-			writel(val & ~XHCI_HC_BIOS_OWNED, base + ext_cap_offset);
+			writel((val | XHCI_HC_OS_OWNED) &
+			       ~XHCI_HC_BIOS_OWNED,
+			       base + ext_cap_offset);
 		}
 	}
 
author maintainer
#917 lore raw

PATCH 916/1005 USB: serial: garmin_gps: fix deadlock on reset request

In reply to Greg Kroah-Hartman

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

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

From: Johan Hovold <[email protected]>

commit ab89a9dab02d9553eb0cc27fd3e4a4998acbc8e9 upstream.

The garmin_gps driver has a reset feature that is supposed to reset the device when writing a private reset request packet. The reset is however done synchronously from the write() callback (and without holding the required device lock) which leads to a deadlock in the line discipline when hanging up the port as part of disconnect.

Switch to using the asynchronous reset interface while dropping the redundant and synchronous stopping of the interrupt urb (write() callbacks are supposed to be atomic and USB core, USB serial core and the driver itself will unlink and kill all URBs during disconnect).

---
 drivers/usb/serial/garmin_gps.c |   12 +++---------
 1 file changed, 3 insertions(+), 9 deletions(-)
drivers/usb/serial/garmin_gps.c +3 -9
@@ -818,10 +818,9 @@ static void priv_status_resp(struct usb_
  * Garmin specific driver functions
  ******************************************************************************/
 
-static int process_resetdev_request(struct usb_serial_port *port)
+static void process_resetdev_request(struct usb_serial_port *port)
 {
 	unsigned long flags;
-	int status;
 	struct garmin_data *garmin_data_p = usb_get_serial_port_data(port);
 
 	spin_lock_irqsave(&garmin_data_p->lock, flags);
@@ -830,13 +829,8 @@ static int process_resetdev_request(stru
 	garmin_data_p->serial_num = 0;
 	spin_unlock_irqrestore(&garmin_data_p->lock, flags);
 
-	usb_kill_urb(port->interrupt_in_urb);
-	dev_dbg(&port->dev, "%s - usb_reset_device\n", __func__);
-	status = usb_reset_device(port->serial->dev);
-	if (status)
-		dev_dbg(&port->dev, "%s - usb_reset_device failed: %d\n",
-			__func__, status);
-	return status;
+	dev_dbg(&port->dev, "%s - usb_queue_reset_device\n", __func__);
+	usb_queue_reset_device(port->serial->interface);
 }
 
 
author maintainer
#918 lore raw

PATCH 917/1005 USB: serial: oti6858: fix the teardown order in close

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 f184ae84a5d19554d980a918a9c8baaef87ac301 upstream.

The driver passes a baton around: the completion handler of the interrupt urb either resubmits the urb, submits the read urb or schedules one of the two delayed works, and the works and the bulk completion handlers submit the interrupt urb again.

oti6858_close() cancels the works first and kills the urbs afterwards. An interrupt urb that completes in between schedules a work again:

	oti6858_close()
	  cancel_delayed_work_sync(setup)
	  cancel_delayed_work_sync(write)
				oti6858_read_int_callback()
				  schedule_delayed_work(setup)
	  usb_kill_urb(interrupt_in_urb)	/* not in flight */
				setup_line()
				  usb_submit_urb(interrupt_in_urb)

The port is now closed with the baton still going round. The next open fails because the interrupt urb is already submitted, and if the device is unplugged, oti6858_port_remove() frees the private data while a work may be pending or running.

Poison the interrupt urb first: that waits for the handler and makes all further submissions fail, so nothing schedules the works any more. Then cancel the works, after which only the bulk urbs are left, kill those, and make the interrupt urb usable again for the next open. Don't print an error for the submissions that fail with -EPERM in this window, as oti6858_read_bulk_callback() already does.

Fixes 49cdee0ed0fc ("USB: oti6858 usb-serial driver (in Nokia CA-42 cable)")
Cc stable <[email protected]>
Cc Johan Hovold <[email protected]>
---
 drivers/usb/serial/oti6858.c |   16 ++++++++++++----
 1 file changed, 12 insertions(+), 4 deletions(-)
drivers/usb/serial/oti6858.c +12 -4
@@ -248,7 +248,7 @@ static void setup_line(struct work_struc
 
 	dev_dbg(&port->dev, "%s(): submitting interrupt urb\n", __func__);
 	result = usb_submit_urb(port->interrupt_in_urb, GFP_KERNEL);
-	if (result != 0) {
+	if (result != 0 && result != -EPERM) {
 		dev_err(&port->dev, "%s(): usb_submit_urb() failed with error %d\n",
 			__func__, result);
 	}
@@ -300,7 +300,7 @@ static void send_data(struct work_struct
 
 		dev_dbg(&port->dev, "%s(): submitting interrupt urb\n", __func__);
 		result = usb_submit_urb(port->interrupt_in_urb, GFP_NOIO);
-		if (result != 0) {
+		if (result != 0 && result != -EPERM) {
 			dev_err(&port->dev, "%s(): usb_submit_urb() failed with error %d\n",
 				__func__, result);
 		}
@@ -561,6 +561,13 @@ static void oti6858_close(struct usb_ser
 
 	dev_dbg(&port->dev, "%s(): after buf_clear()\n", __func__);
 
+	/*
+	 * The interrupt urb schedules the works, and the works and the bulk
+	 * urbs resubmit the interrupt urb: keep it from being submitted until
+	 * all of them are gone.
+	 */
+	usb_poison_urb(port->interrupt_in_urb);
+
 	/* cancel scheduled setup */
 	cancel_delayed_work_sync(&priv->delayed_setup_work);
 	cancel_delayed_work_sync(&priv->delayed_write_work);
@@ -569,7 +576,8 @@ static void oti6858_close(struct usb_ser
 	dev_dbg(&port->dev, "%s(): shutting down urbs\n", __func__);
 	usb_kill_urb(port->write_urb);
 	usb_kill_urb(port->read_urb);
-	usb_kill_urb(port->interrupt_in_urb);
+
+	usb_unpoison_urb(port->interrupt_in_urb);
 }
 
 static int oti6858_tiocmset(struct tty_struct *tty,
@@ -826,7 +834,7 @@ static void oti6858_write_bulk_callback(
 	/* schedule the interrupt urb if we are still open */
 	dev_dbg(&port->dev, "%s(): submitting interrupt urb\n", __func__);
 	result = usb_submit_urb(port->interrupt_in_urb, GFP_ATOMIC);
-	if (result != 0) {
+	if (result != 0 && result != -EPERM) {
 		dev_err(&port->dev, "%s(): failed submitting int urb,"
 					" error %d\n", __func__, result);
 	}
author maintainer
#919 lore raw

PATCH 918/1005 usb: typec: mux: fsa4480: Keep the USB 2.0 switch on in DP-only modes

In reply to Greg Kroah-Hartman

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

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

From: Joonhoe Kim <[email protected]>

commit 89aaaa26f6985d55676fc5c90440f279733fa132 upstream.

DisplayPort pin assignments C and E give all four SuperSpeed lanes to DisplayPort, but the USB 2.0 D+/D- pair is not part of the pin assignment and stays available. The FSA4480 sits on that pair, and in these modes the driver turns its USB switch off, so a USB 2.0 hub or device behind a DisplayPort sink is disconnected as soon as the DisplayPort mode is set.

Configure the USB switch the same way in all DisplayPort modes.

Fixes c7054c31c1c9 ("usb: typec: fsa4480: rework mux & switch setup to handle more states")
Cc stable <[email protected]>
---
 drivers/usb/typec/mux/fsa4480.c |    9 +--------
 1 file changed, 1 insertion(+), 8 deletions(-)
drivers/usb/typec/mux/fsa4480.c +1 -8
@@ -93,16 +93,9 @@ static int fsa4480_set(struct fsa4480 *f
 		sel = FSA4480_SEL_USB;
 	} else if (fsa->svid) {
 		switch (fsa->mode) {
-		/* DP Only */
 		case TYPEC_DP_STATE_C:
-		case TYPEC_DP_STATE_E:
-			enable |= FSA4480_ENABLE_SBU;
-			if (reverse)
-				sel = FSA4480_SEL_SBU_REVERSE;
-			break;
-
-		/* DP + USB */
 		case TYPEC_DP_STATE_D:
+		case TYPEC_DP_STATE_E:
 		case TYPEC_DP_STATE_F:
 			enable |= FSA4480_ENABLE_USB | FSA4480_ENABLE_SBU;
 			sel = FSA4480_SEL_USB;
author maintainer
#920 lore raw

PATCH 919/1005 usb: typec: nb7vpq904m: Set client data in probe to avoid crash on remove

In reply to Greg Kroah-Hartman

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

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

From: Chaz Bailey <[email protected]>

commit 2022b10726be78849626ea3fa33038ee96a54e46 upstream.

nb7vpq904m_probe() allocates struct nb7vpq904m, but client data is not set during probe.

In nb7vpq904m_remove(), i2c_get_clientdata(client) returns NULL, leading to a NULL pointer dereference when accessing nb7->retimer or nb7->sw.

Set client data upon successful allocation in probe.

Fixes 88d8f3ac9c67 ("usb: typec: add support for the nb7vpq904m Type-C Linear Redriver")
Cc stable <[email protected]>
---
 drivers/usb/typec/mux/nb7vpq904m.c |    1 +
 1 file changed, 1 insertion(+)
drivers/usb/typec/mux/nb7vpq904m.c +1 -0
@@ -396,6 +396,7 @@ static int nb7vpq904m_probe(struct i2c_c
 		return -ENOMEM;
 
 	nb7->client = client;
+	i2c_set_clientdata(client, nb7);
 
 	nb7->regmap = devm_regmap_init_i2c(client, &nb7_regmap);
 	if (IS_ERR(nb7->regmap)) {
author maintainer
#921 lore raw

PATCH 920/1005 usb: uas: ignore UAS for ASMT135x bridges (174c:55aa)

In reply to Greg Kroah-Hartman

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

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

From: Olivier Kaloudoff <[email protected]>

commit fafd23d61494461256d374f67c121f2712e1af2f upstream.

The ASMedia chip detection in uas_use_uas_driver() assumes that every device with idVendor/idProduct 174c:5106 or 174c:55aa reporting a config.MaxPower of 0 is an ASM1153 with working UAS.

ASMT135x bridges (iProduct "ASMT135x") share the same 174c:55aa id and also report MaxPower == 0, so they take the "ASM1153, do nothing" path — but their UAS implementation is broken:

- The first READ(16) issued by sd probing times out after 30 s; enumeration only completes after a uas_eh_abort_handler plus a full uas_eh_host_reset_handler cycle:

scsi 3:0:0:0: Direct-Access ASMT ASMT135x 0 PQ: 0 ANSI: 6
sd 3:0:0:0: [sdb] tag#26 uas_eh_abort_handler 0 uas-tag 1 inflight: CMD IN sd 3:0:0:0: [sdb] tag#26 CDB: Read(16) 88 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 scsi host3: uas_eh_host_reset_handler start
usb 6-2: reset SuperSpeed USB device number 2 using xhci_hcd
scsi host3: uas_eh_host_reset_handler success

- Under concurrent load the bridge stalls: all inflight commands (20+ UAS tags in the captured incident, mixed READ(16)/WRITE(16)) hit the 30 s UAS timeout in the same event, forcing repeated abort/reset cycles and eventually a USB disconnect. Writes dropped mid-flight during these resets returned zeros to the filesystem (observed as XFS metadata corruption on the mounted volume).

- Sequential-write throughput is ~45 MiB/s under UAS versus ~136 MiB/s after disabling UAS (usb-storage BOT mode), which is fully stable:
several tens of GiB written without a single error.

- Bulk reads of healthy LBA ranges do work under UAS (~190 MiB/s, no errors); the failure pattern is command-timeout at enumeration and under queue depth / write load, not a broken transfer path.

Since 174c:55aa is shared across several ASMedia bridges and enclosure rebrandings, distinguish the ASMT135x by its product string — the same approach used for the HIKSEMI MD202 check a few lines below. The product strings of working bridges using the same id ("ASM1053E", "ASM1153", "ASM1153E", "ASM1351", vendor rebrands such as "YZWY_TECH") do not contain "ASMT135", so the match is safe.

Verified on an ORICO enclosure (iManufacturer "ASMT", iProduct "ASMT135x", bcdDevice 1.00) attached through an Alpine Ridge TB3 dock:
with the equivalent usb-storage quirks parameter (174c:55aa:u) the device is completely stable.

---
 drivers/usb/storage/uas-detect.h |    8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
drivers/usb/storage/uas-detect.h +7 -1
@@ -78,6 +78,8 @@ static int uas_use_uas_driver(struct usb
 	 * ASM1051 - with broken (*) uas support
 	 * ASM1053 - with working uas support, but problems with large xfers
 	 * ASM1153 - with working uas support
+	 * ASMT135x - broken uas support, shares the ASM1153 MaxPower == 0
+	 *            signature, identify it by its product string
 	 *
 	 * Devices with these chips re-use a number of device-ids over the
 	 * entire line, so the device-id is useless to determine if we're
@@ -99,7 +101,11 @@ static int uas_use_uas_driver(struct usb
 			(le16_to_cpu(udev->descriptor.idProduct) == 0x5106 ||
 			 le16_to_cpu(udev->descriptor.idProduct) == 0x55aa)) {
 		if (udev->actconfig->desc.bMaxPower == 0) {
-			/* ASM1153, do nothing */
+			if (udev->product && strstr(udev->product, "ASMT135")) {
+				/* ASMT135x, broken uas */
+				flags |= US_FL_IGNORE_UAS;
+			}
+			/* else ASM1153, do nothing */
 		} else if (udev->speed < USB_SPEED_SUPER) {
 			/* No streams info, assume ASM1051 */
 			flags |= US_FL_IGNORE_UAS;
author maintainer
#922 lore raw

PATCH 921/1005 usb: usbtest: prevent divide by zero in simple_io() with zero length

In reply to Greg Kroah-Hartman

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

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

From: YuanZhe Liu <[email protected]>

commit fdaca138694111153f96c7d76877734b9dbf0e01 upstream.

A divide error oops was observed in simple_io():

	usbtest 1-1:1.0: TEST 3:  write/1 0..0 bytes 16307 times
	Oops: divide error: 0000 [#1] SMP KASAN
	RIP: 0010:simple_io+0x2c4/0x540 drivers/usb/misc/usbtest.c:497

The variable-length tests (test 3 and test 4) compute the next URB size with "len %= max", where max is the original urb->transfer_buffer_length. However, when a zero-length transfer is requested (param->length == 0), simple_alloc_urb() still returns a valid URB with transfer_buffer_length set to 0. On the first vary update, "len %= max" divides by zero and the kernel oopses.

Commit 564e69893c63 ("USB: usbtest: prevent a divide by zero bug") added the equivalent zero check to alloc_sglist(), which covers the scatterlist tests (test 7/8), but the single-URB variable-length path in simple_io() was left unprotected.

Fix this by returning -EINVAL early from simple_io() when vary is requested but max is zero, so the divide by zero never occurs. Zero-length transfers without vary remain valid for the other callers of simple_io().

---
 drivers/usb/misc/usbtest.c |    3 +++
 1 file changed, 3 insertions(+)
drivers/usb/misc/usbtest.c +3 -0
@@ -466,6 +466,9 @@ static int simple_io(
 	int			retval = 0;
 	unsigned long		expire;
 
+	if (vary && !max)
+		return -EINVAL;
+
 	urb->context = &completion;
 	while (retval == 0 && iterations-- > 0) {
 		init_completion(&completion);
author maintainer
#923 lore raw

PATCH 922/1005 usb: typec: ucsi: acpi: Assume UCSI 1.0 on HP ZBook 8 G2i 14

In reply to Greg Kroah-Hartman

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

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

From: Ihor Urazov <[email protected]>

commit 3ee1e1c3fca6fb5d0abbe0fc91539951ffa60aa7 upstream.

The HP ZBook 8 G2i 14 (board 8ED9) exposes a working UCSI ACPI PPM, but its UCSI VERSION field reads zero until the first command completes. ucsi_register() rejects a zero version with -ENODEV, so no Type-C ports are registered.

The firmware's _DSM READ function (2) is a stub. The mailbox VERSION field is written only by the EC response handler, after a command completes, after which it reads 0x0100 (UCSI 1.0). The mailbox is 48 bytes with 16-byte MESSAGE_IN/MESSAGE_OUT fields, the UCSI 1.x layout, and _DSM function 5 is not implemented.

Add a DMI-specific read_version for this board that substitutes the version the firmware itself reports, UCSI 1.0, only when VERSION reads zero. A non-zero firmware version is used as is.

The same firmware defect on the HP ZBook Fury G1i 16 was discussed in "[RFC PATCH] usb: typec: ucsi: acpi: bootstrap PPM on HP systems with empty _DSM func 2" [1]. The defect was reported to HP as case 5166176673.

Tested on an HP ZBook 8 G2i 14 with BIOS Y70 01.02.08, from a fresh boot where VERSION reads zero: three connectors register, the PD contract and alternate modes of a Thunderbolt dock are reported, and its DisplayPort output stays up across the PPM reset in ucsi_init(). Dock unplug/replug and s2idle suspend/resume update the connector state without errors.

---
 drivers/usb/typec/ucsi/ucsi_acpi.c |   35 +++++++++++++++++++++++++++++++++++
 1 file changed, 35 insertions(+)
drivers/usb/typec/ucsi/ucsi_acpi.c +35 -0
@@ -148,6 +148,34 @@ static const struct ucsi_operations ucsi
 	.async_control = ucsi_acpi_async_control
 };
 
+static int ucsi_hp_read_version(struct ucsi *ucsi, u16 *version)
+{
+	struct ucsi_acpi *ua = ucsi_get_drvdata(ucsi);
+	int ret;
+
+	ret = ucsi_acpi_read_version(ucsi, version);
+	if (ret)
+		return ret;
+
+	/* Firmware fills in VERSION (1.0) only after the first command completes */
+	if (!*version) {
+		dev_warn(ua->dev, "UCSI version is zero, assuming 1.0\n");
+		*version = UCSI_VERSION_1_0;
+	}
+
+	return 0;
+}
+
+static const struct ucsi_operations ucsi_hp_ops = {
+	.read_version = ucsi_hp_read_version,
+	.read_cci = ucsi_acpi_read_cci,
+	.poll_cci = ucsi_acpi_poll_cci,
+	.read_message_in = ucsi_acpi_read_message_in,
+	.write_message_out = ucsi_acpi_write_message_out,
+	.sync_control = ucsi_sync_control_common,
+	.async_control = ucsi_acpi_async_control
+};
+
 static int ucsi_gram_sync_control(struct ucsi *ucsi, u64 command, u32 *cci,
 				  void *val, size_t len, void *msg_out,
 				  size_t msg_out_size)
@@ -198,6 +226,13 @@ static const struct dmi_system_id ucsi_a
 	},
 	{
 		.matches = {
+			DMI_MATCH(DMI_SYS_VENDOR, "HP"),
+			DMI_MATCH(DMI_BOARD_NAME, "8ED9"),
+		},
+		.driver_data = (void *)&ucsi_hp_ops,
+	},
+	{
+		.matches = {
 			DMI_MATCH(DMI_SYS_VENDOR, "LG Electronics"),
 			DMI_MATCH(DMI_PRODUCT_FAMILY, "LG gram PC"),
 			DMI_MATCH(DMI_PRODUCT_NAME, "90Q"),
author maintainer
#924 lore raw

PATCH 923/1005 usb: typec: ucsi: debugfs: Fix GET commands on UCSI < 2.0

In reply to Greg Kroah-Hartman

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

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

From: Ali Ahmet Memiş <[email protected]>

commit 7cfb037005c04b9dee5b0c4626e56e2eddeef157 upstream.

Since the debugfs response buffer grew to 24 bytes, every GET command fails with -EINVAL on UCSI < 2.0, where the data length is limited to 16 bytes. Clamp the length to UCSI_MAX_DATA_LENGTH().

Fixes d9dc19910321 ("usb: typec: ucsi: Fix debugfs response truncation beyond 16 bytes")
Cc stable <[email protected]>
---
 drivers/usb/typec/ucsi/debugfs.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/usb/typec/ucsi/debugfs.c +2 -1
index 77a0dd75edd3..3cffd3778c67 100644
@@ -60,7 +60,8 @@ static int ucsi_cmd(void *data, u64 val)
 	case UCSI_GET_LPM_PPM_INFO:
 		ret = ucsi_send_command(ucsi, val,
 					&ucsi->debugfs->response,
-					sizeof(ucsi->debugfs->response));
+					min(sizeof(ucsi->debugfs->response),
+					    UCSI_MAX_DATA_LENGTH(ucsi)));
 		break;
 	default:
 		ret = -EOPNOTSUPP;
Signature · 1 line
2.56.1
author maintainer
#925 lore raw

PATCH 924/1005 usb: typec: ucsi: Set ucsi->connector before enabling notifications

In reply to Greg Kroah-Hartman

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

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

From: Uttkarsh Aggarwal <[email protected]>

commit 5b4b83c2ffe8740f6f3e54ea4d4962a62c063ef1 upstream.

In ucsi_init(), ucsi->connector is assigned only after the UCSI_SET_NOTIFICATION_ENABLE command completes. But once that command is sent, the PPM is free to raise a connector change notification at any time, which is handled through:

    ucsi_notify_common() -> ucsi_connector_change()

ucsi_connector_change() indexes into ucsi->connector to get the connector and schedule its work item. If this notification arrives before ucsi_init() reaches the "ucsi->connector = connector;" line, ucsi->connector is still NULL and the driver crashes dereferencing it.

Fix this by setting ucsi->connector right after the connectors are registered, before notifications are enabled, so it is always valid by the time a connector change event can be delivered. Also clear ucsi->connector in the err_unregister path so it isn't left pointing at freed memory if a later step in ucsi_init() fails.

---
 drivers/usb/typec/ucsi/ucsi.c |   10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
drivers/usb/typec/ucsi/ucsi.c +9 -1
@@ -2134,6 +2134,14 @@ static int ucsi_init(struct ucsi *ucsi)
 			goto err_unregister;
 	}
 
+	/*
+	 * Set ucsi->connector before enabling notifications. A connector
+	 * change event can be handled as soon as the notifications are
+	 * enabled below, and ucsi_connector_change() indexes into
+	 * ucsi->connector, so it must not be NULL at that point.
+	 */
+	ucsi->connector = connector;
+
 	/* Enable all supported notifications */
 	ntfy = ucsi_get_supported_notifications(ucsi);
 	command = UCSI_SET_NOTIFICATION_ENABLE | ntfy;
@@ -2141,7 +2149,6 @@ static int ucsi_init(struct ucsi *ucsi)
 	if (ret < 0)
 		goto err_unregister;
 
-	ucsi->connector = connector;
 	ucsi->ntfy = ntfy;
 
 	mutex_lock(&ucsi->ppm_lock);
@@ -2155,6 +2162,7 @@ static int ucsi_init(struct ucsi *ucsi)
 	return 0;
 
 err_unregister:
+	ucsi->connector = NULL;
 	for (con = connector; con->port; con++)
 		ucsi_unregister_port(con);
 	for (i = 0; i < ucsi->cap.num_connectors; i++)
author maintainer
#926 lore raw

PATCH 925/1005 usb: xhci: disable the correct slot on alloc_dev failure

In reply to Greg Kroah-Hartman

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

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

From: Xu Rao <[email protected]>

commit 2f2fe3201029ffc215b46ac40a0a9587715bc43a upstream.

xhci_alloc_dev() stores the Slot ID returned by the Enable Slot command in the local slot_id variable. udev->slot_id is updated only after xhci_alloc_virt_device() succeeds.

If endpoint resource reservation or virtual device allocation fails before that update, the error path passes udev->slot_id to xhci_disable_and_free_slot(). During initial enumeration this is slot 0. When reallocating a device whose virtual device is missing or belongs to another usb_device, udev->slot_id may contain a stale Slot ID. The newly enabled slot can therefore remain active, or the wrong slot can be disabled.

Pass slot_id, which identifies the slot enabled by this invocation. xhci_disable_and_free_slot() already handles a missing xhci->devs entry.

---
 drivers/usb/host/xhci.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/usb/host/xhci.c +1 -1
@@ -4300,7 +4300,7 @@ int xhci_alloc_dev(struct usb_hcd *hcd,
 	return 1;
 
 disable_slot:
-	xhci_disable_and_free_slot(xhci, udev->slot_id);
+	xhci_disable_and_free_slot(xhci, slot_id);
 
 	return 0;
 }
author maintainer
#927 lore raw

PATCH 926/1005 usb: xhci: clear stale bandwidth data after hibernation

In reply to Greg Kroah-Hartman

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

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

From: Niklas Neronin <[email protected]>

commit d1ec1859f3b8641e3e5c5953cc7dd8e63b54339f upstream.

Controllers using software managed bandwidth accounting maintain periodic endpoint bandwidth information in struct 'xhci_interval_bw_table'.

Each root hub port owns a bandwidth table and a list of TT bandwidth domains, where each TT has its own bandwidth table. Virtual devices reference the bandwidth table of their current bandwidth domain through 'bw_table' or 'tt_info'.

Historically, resume from S4 reinitialized the entire xHCI driver state, which implicitly cleared all bandwidth accounting data. After the hibernation resume path was optimized to preserve parts of the driver state, virtual devices and TT bandwidth information were freed and recreated, but the root hub bandwidth tables were left intact.

As a result, stale bandwidth accounting data could remain in the root hub bandwidth tables across hibernation resume, leading to incorrect bandwidth calculations after devices were rediscovered.

Fix this by resetting all bandwidth accounting data in xhci_rh_bw_cleanup() so that resume starts with a clean bandwidth state, and resetting the total active endpoints count.

---
 drivers/usb/host/xhci-mem.c | 16 +++++++++++++++-
 drivers/usb/host/xhci.c     |  1 +
 2 files changed, 16 insertions(+), 1 deletion(-)
drivers/usb/host/xhci-mem.c +15 -1
index af8d4b74c4ba..75577f441cdd 100644
@@ -1903,24 +1903,38 @@ EXPORT_SYMBOL_GPL(xhci_remove_secondary_interrupter);
 void xhci_rh_bw_cleanup(struct xhci_hcd *xhci)
 {
 	struct xhci_root_port_bw_info *rh_bw;
+	struct xhci_interval_bw_table *bw_table;
+	struct xhci_interval_bw *interval_bw;
 	struct xhci_tt_bw_info *tt_info, *tt_next;
 	struct list_head *eps, *ep, *ep_next;
 
 	for (int i = 0; i < xhci->max_ports; i++) {
 		rh_bw = &xhci->rh_bw[i];
 
+		rh_bw->num_active_tts = 0;
 		/* Clear and free all TT bandwidth entries */
 		list_for_each_entry_safe(tt_info, tt_next, &rh_bw->tts, tt_list) {
 			list_del(&tt_info->tt_list);
 			kfree(tt_info);
 		}
 
+		bw_table = &rh_bw->bw_table;
+		bw_table->interval0_esit_payload = 0;
+		bw_table->bw_used = 0;
+		bw_table->ss_bw_in = 0;
+		bw_table->ss_bw_out = 0;
+
 		/* Clear per-interval endpoint lists */
 		for (int j = 0; j < XHCI_MAX_INTERVAL; j++) {
-			eps = &rh_bw->bw_table.interval_bw[j].endpoints;
+			interval_bw = &bw_table->interval_bw[j];
+			eps = &interval_bw->endpoints;
 
+			interval_bw->num_packets = 0;
 			list_for_each_safe(ep, ep_next, eps)
 				list_del_init(ep);
+			interval_bw->overhead[LS_OVERHEAD_TYPE] = 0;
+			interval_bw->overhead[FS_OVERHEAD_TYPE] = 0;
+			interval_bw->overhead[HS_OVERHEAD_TYPE] = 0;
 		}
 	}
 }
drivers/usb/host/xhci.c +1 -0
index 94da0268b7b3..a762dd010e8d 100644
@@ -1185,6 +1185,7 @@ int xhci_resume(struct xhci_hcd *xhci, bool power_lost, bool is_auto_resume)
 		for (int i = xhci->max_slots; i > 0; i--)
 			xhci_free_virt_devices_depth_first(xhci, i);
 
+		xhci->num_active_eps = 0;
 		xhci_rh_bw_cleanup(xhci);
 
 		xhci->cmd_ring_reserved_trbs = 0;
Signature · 1 line
2.56.1
author maintainer
#928 lore raw

PATCH 927/1005 usb: gadget: f_mass_storage: take filesem in nofua store to fix backing-file UAF

In reply to Greg Kroah-Hartman

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

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

From: Yu Zhang <[email protected]>

commit 450fa94d7ae9fc91c3df525f5d1322bf8fecf7b2 upstream.

fsg_store_nofua() syncs the LUN's backing file when switching from async to sync mode:

	if (!nofua && curlun->nofua)
		fsg_lun_fsync_sub(curlun);

fsg_lun_fsync_sub() dereferences curlun->filp (vfs_fsync(filp)). Unlike every other store that touches the backing file -- fsg_store_ro() and fsg_store_cdrom() (down_read), fsg_store_file() (down_write) -- fsg_store_nofua() holds no filesem while doing so.

A concurrent close of the backing file runs under down_write(filesem) and does fput(curlun->filp) in fsg_lun_close() (fsg_store_file() with an empty path, the SCSI START_STOP eject in do_start_stop(), or forced_eject), so it can free the file while fsg_store_nofua() is dereferencing it:

	BUG: KASAN: slab-use-after-free in vfs_fsync+0x20/0xe0
	 vfs_fsync+0x20/0xe0
	 fsg_lun_fsync_sub+0xa0/0xd0
	 fsg_store_nofua+0x138/0x160
	 configfs_write_iter+0x1a7/0x250
	 vfs_write+0x5df/0x940
	Allocated by task 3459:
	 fsg_store_file+0x150/0x1f0
	 configfs_write_iter+0x1a7/0x250
	Freed by task 3459:
	 __fput+0x456/0x6c0
	 __fput_deferred+0x10d/0x330
	 fsg_store_file+0x9e/0x1f0
	 configfs_write_iter+0x1a7/0x250

Hold filesem for read around the fsync in fsg_store_nofua() so the backing file cannot be closed underneath it. The lock is only needed when the fsync actually runs, so it is taken only in that branch.

Reproduced on a mass_storage gadget over dummy_hcd by writing lun.N/nofua (1 then 0) from one task while another task rewrites and clears lun.N/file.

---
 drivers/usb/gadget/function/f_mass_storage.c |    8 ++++++--
 drivers/usb/gadget/function/storage_common.c |    7 +++++--
 drivers/usb/gadget/function/storage_common.h |    3 ++-
 3 files changed, 13 insertions(+), 5 deletions(-)
drivers/usb/gadget/function/f_mass_storage.c +6 -2
@@ -2667,8 +2667,9 @@ static ssize_t nofua_store(struct device
 			   const char *buf, size_t count)
 {
 	struct fsg_lun		*curlun = fsg_lun_from_dev(dev);
+	struct rw_semaphore	*filesem = dev_get_drvdata(dev);
 
-	return fsg_store_nofua(curlun, buf, count);
+	return fsg_store_nofua(curlun, filesem, buf, count);
 }
 
 static ssize_t file_store(struct device *dev, struct device_attribute *attr,
@@ -3246,7 +3247,10 @@ static ssize_t fsg_lun_opts_nofua_show(s
 static ssize_t fsg_lun_opts_nofua_store(struct config_item *item,
 				       const char *page, size_t len)
 {
-	return fsg_store_nofua(to_fsg_lun_opts(item)->lun, page, len);
+	struct fsg_lun_opts *opts = to_fsg_lun_opts(item);
+	struct fsg_opts *fsg_opts = to_fsg_opts(opts->group.cg_item.ci_parent);
+
+	return fsg_store_nofua(opts->lun, &fsg_opts->common->filesem, page, len);
 }
 
 CONFIGFS_ATTR(fsg_lun_opts_, nofua);
drivers/usb/gadget/function/storage_common.c +5 -2
@@ -415,7 +415,8 @@ ssize_t fsg_store_ro(struct fsg_lun *cur
 }
 EXPORT_SYMBOL_GPL(fsg_store_ro);
 
-ssize_t fsg_store_nofua(struct fsg_lun *curlun, const char *buf, size_t count)
+ssize_t fsg_store_nofua(struct fsg_lun *curlun, struct rw_semaphore *filesem,
+			const char *buf, size_t count)
 {
 	bool		nofua;
 	int		ret;
@@ -425,8 +426,10 @@ ssize_t fsg_store_nofua(struct fsg_lun *
 		return ret;
 
 	/* Sync data when switching from async mode to sync */
-	if (!nofua && curlun->nofua)
+	if (!nofua && curlun->nofua) {
+		guard(rwsem_read)(filesem);
 		fsg_lun_fsync_sub(curlun);
+	}
 
 	curlun->nofua = nofua;
 
drivers/usb/gadget/function/storage_common.h +2 -1
@@ -210,7 +210,8 @@ ssize_t fsg_show_cdrom(struct fsg_lun *c
 ssize_t fsg_show_removable(struct fsg_lun *curlun, char *buf);
 ssize_t fsg_store_ro(struct fsg_lun *curlun, struct rw_semaphore *filesem,
 		     const char *buf, size_t count);
-ssize_t fsg_store_nofua(struct fsg_lun *curlun, const char *buf, size_t count);
+ssize_t fsg_store_nofua(struct fsg_lun *curlun, struct rw_semaphore *filesem,
+			const char *buf, size_t count);
 ssize_t fsg_store_file(struct fsg_lun *curlun, struct rw_semaphore *filesem,
 		       const char *buf, size_t count);
 ssize_t fsg_store_cdrom(struct fsg_lun *curlun, struct rw_semaphore *filesem,
author maintainer
#929 lore raw

PATCH 928/1005 usb: gadget: f_midi: fix UAF race during IN request handling

In reply to Greg Kroah-Hartman

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

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

From: Sonali Pradhan <[email protected]>

commit 78a8d6537f1de34770e460edee360b556ef40427 upstream.

f_midi_disable() drains and frees pre-allocated IN requests from in_req_fifo without holding midi->transmit_lock. If f_midi_transmit() runs concurrently on the workqueue, f_midi_do_transmit() can peek a request from in_req_fifo and write into its buffer while f_midi_disable() frees it, leading to a use-after-free.

Additionally, when usb_ep_queue() fails in f_midi_do_transmit() (such as with -ESHUTDOWN when the endpoint is disabled concurrently), it resets req->length = 0 and returns active instead of the error code, causing the do-while loop in f_midi_transmit() to keep spinning under midi->transmit_lock until the substream is drained.

Fix this by acquiring midi->transmit_lock in f_midi_disable() while releasing IN requests from in_req_fifo, and returning the error code from f_midi_do_transmit() when usb_ep_queue() fails so f_midi_transmit() aborts immediately and drops active substreams.

Fixes e1e3d7ec5da3 ("usb: gadget: f_midi: pre-allocate IN requests")
Cc stable <[email protected]>
---
 drivers/usb/gadget/function/f_midi.c |    4 ++++
 1 file changed, 4 insertions(+)
drivers/usb/gadget/function/f_midi.c +4 -0
@@ -420,6 +420,7 @@ static void f_midi_disable(struct usb_fu
 	struct f_midi *midi = func_to_midi(f);
 	struct usb_composite_dev *cdev = f->config->cdev;
 	struct usb_request *req = NULL;
+	unsigned long flags;
 
 	DBG(cdev, "disable\n");
 
@@ -431,8 +432,10 @@ static void f_midi_disable(struct usb_fu
 	usb_ep_disable(midi->out_ep);
 
 	/* release IN requests */
+	spin_lock_irqsave(&midi->transmit_lock, flags);
 	while (kfifo_get(&midi->in_req_fifo, &req))
 		free_ep_req(midi->in_ep, req);
+	spin_unlock_irqrestore(&midi->transmit_lock, flags);
 
 	f_midi_drop_out_substreams(midi);
 }
@@ -661,6 +664,7 @@ static int f_midi_do_transmit(struct f_m
 		ERROR(midi, "%s failed to queue req: %d\n",
 		      midi->in_ep->name, err);
 		req->length = 0; /* Re-use request next time. */
+		return err;
 	} else {
 		/* Upon success, put request at the back of the queue. */
 		kfifo_skip(&midi->in_req_fifo);
author maintainer
#930 lore raw

PATCH 929/1005 usb: gadget: f_ncm: restart the TX timer if the TX freelist is empty

In reply to Greg Kroah-Hartman

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

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

From: Cosmin Tanislav <[email protected]>

commit 78585f90feb3bbaf3b1c642294c8c47e451dc3cf upstream.

ncm_wrap_ntb() aggregates datagrams into a pending NTB, which is sent either when it becomes full, or after 300us since the NTB was started, using ndo_start_xmit() (eth_start_xmit()).

ndo_start_xmit() returns NETDEV_TX_BUSY when the TX freelist is empty.

For regular packets this is fine since the networking core will requeue them, but for timer-flushed packets there is no logic to handle this situation, and HRTIMER_NORESTART is returned from ncm_tx_timeout() without checking eth_start_xmit()'s return value.

Under sustained TX saturation the request freelist is empty most of the time. Since the timer is never restarted, small packets keep getting accumulated into the NTB, until either TX_MAX_NUM_DPE packets are stored or NTB_DEFAULT_IN_SIZE is reached, which is an unknown amount of time.

Check the return value of ndo_start_xmit() and restart the timer after another 300us.

---
 drivers/usb/gadget/function/f_ncm.c |    7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
drivers/usb/gadget/function/f_ncm.c +6 -1
@@ -1148,6 +1148,7 @@ static enum hrtimer_restart ncm_tx_timeo
 {
 	struct f_ncm *ncm = container_of(data, struct f_ncm, task_timer);
 	struct net_device *netdev = READ_ONCE(ncm->netdev);
+	netdev_tx_t ret;
 
 	if (netdev) {
 		/* XXX This allowance of a NULL skb argument to ndo_start_xmit
@@ -1158,7 +1159,11 @@ static enum hrtimer_restart ncm_tx_timeo
 		 *
 		 * This will call directly into u_ether's eth_start_xmit()
 		 */
-		netdev->netdev_ops->ndo_start_xmit(NULL, netdev);
+		ret = netdev->netdev_ops->ndo_start_xmit(NULL, netdev);
+		if (ret == NETDEV_TX_BUSY) {
+			hrtimer_forward_now(data, TX_TIMEOUT_NSECS);
+			return HRTIMER_RESTART;
+		}
 	}
 	return HRTIMER_NORESTART;
 }
author maintainer
#931 lore raw

PATCH 930/1005 usb: gadget: u_serial: fix NULL deref in gs_close() after failed open

In reply to Greg Kroah-Hartman

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

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

From: Brian Ellis <[email protected]>

commit ea6cf69ad03c8d85138830c0d2c3b946b5ae231d upstream.

gs_close() opens with

	struct gs_port *port = tty->driver_data;
	...
	spin_lock_irq(&port->port_lock);

and never checks port. gs_open() assigns tty->driver_data only on the port.count 0 -> 1 edge, so any failure earlier in gs_open() leaves it NULL, and tty_open() calls tty_release(), and hence ->close(), when ->open() fails.

syzbot hit exactly this on arm64. Fault injection failed the kfifo_alloc() of the write buffer in gs_open():

   __kfifo_alloc_node+0x10c/0x208 lib/kfifo.c:44
   gs_open+0x144/0x514 drivers/usb/gadget/function/u_serial.c:636
   tty_open+0x404/0x89c drivers/tty/tty_io.c:2137

and the tty core's close of the failed open then took port_lock through the NULL port:

  BUG: unable to handle kernel paging request in gs_close
  KASAN: null-ptr-deref in range [0x00000000000003a0-0x00000000000003a7]
  Call trace:
   spin_lock_irq include/linux/spinlock.h:372 [inline]
   gs_close+0xac/0x65c drivers/usb/gadget/function/u_serial.c:698
   tty_release+0x2c4/0xffc drivers/tty/tty_io.c:1745
   tty_open+0x46c/0x89c drivers/tty/tty_io.c:2146

Return early instead. There is nothing to release when the open never got far enough to claim the port.

Unlike the check reverted by commit f6c7bc4a6823 ("Revert "usb: gadget:
u_serial: Add null pointer check in gs_start_io""), this is not hiding a
race: the tty core calls ->close() for an ->open() that failed by design, so driver_data is legitimately unset on that path.

---
 drivers/usb/gadget/function/u_serial.c |    3 +++
 1 file changed, 3 insertions(+)
drivers/usb/gadget/function/u_serial.c +3 -0
@@ -695,6 +695,9 @@ static void gs_close(struct tty_struct *
 	struct gs_port *port = tty->driver_data;
 	struct gserial	*gser;
 
+	if (!port)
+		return;
+
 	spin_lock_irq(&port->port_lock);
 
 	if (port->port.count != 1) {
author maintainer
#932 lore raw

PATCH 931/1005 usb: gadget: u_serial: pin ports while TTYs are installed

In reply to Greg Kroah-Hartman

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

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

From: Krystian Kaniewski <[email protected]>

commit 1981b53c2b52a00f0f4b9eb87183c9aedc8dac5d upstream.

A slab-use-after-free can occur when gserial_free_line() frees struct gs_port while it is still reachable through an installed TTY. The port->port.count value tracks successful opens, but it is zero before gs_open() and again after gs_close(), before TTY cleanup has finished. Teardown can therefore free gs_port while tty_init_dev() or release_tty() still accesses its tty_port.

Manage gs_port lifetime with tty_port references. Take a reference in gs_install(), drop it in gs_cleanup(), and move the final free to gs_port_destruct(). Unregister the TTY device before dropping the owner reference.

Keep each minor reserved until the old port is destroyed so an installed TTY for one generation cannot overlap a replacement at the same minor. Publish the new port before device registration so the cdev and add uevent never expose a TTY before gs_install() can pin it. Since commit 8df07fe93573 ("tty: fix saved termios reset race"), u_serial registration no longer frees saved termios. On registration failure, unpublish the port before dropping its owner reference.

Check in gs_open() that the installed port is still the published generation. Track failures after a successful install so close callbacks issued by the TTY core do not decrement port->port.count for opens that never incremented it.

---
 drivers/usb/gadget/function/u_serial.c |  167 ++++++++++++++++++++++++++-------
 1 file changed, 134 insertions(+), 33 deletions(-)
drivers/usb/gadget/function/u_serial.c +134 -33
@@ -70,10 +70,28 @@
  *	gserial->ioport == usb_ep->driver_data ... gs_port
  *	gs_port->port_usb ... gserial
  *
- * gs_port <---> tty_struct ... links will be null when the TTY file
- * isn't opened; managed by gs_open()/gs_close()
- *	gserial->port_tty ... tty_struct
- *	tty_struct->driver_data ... gserial
+ * gs_port <---> tty_struct:
+ *	tty->driver_data refers to gs_port from install through cleanup,
+ *	pinning the port via tty_port reference counting.
+ *	gs_port->port.tty exists only while the port is open.
+ *
+ * Each entry in ports[] is guarded by ports[i].lock and models three states:
+ *   - Free:      !port && !reserved
+ *   - Published:  port &&  reserved
+ *   - Retiring:   !port &&  reserved
+ *
+ * A minor remains reserved until gs_port_destruct() runs upon final tty_port
+ * release, preventing minor reuse while cleanup of the installed TTY is still
+ * underway. The owner reference is retained through device unregister so the
+ * destructor releases the reservation only after device teardown is complete.
+ *
+ * open_close_failures tracks failed gs_open() calls where port->port.count
+ * was not incremented. The TTY core calls gs_close() on open failure to tear
+ * down the tty; tracking failures as aggregate credits allows gs_close() to
+ * consume a credit and exit without decrementing port->port.count. Credits
+ * are aggregate rather than paired with individual files (another gs_close()
+ * can consume a failed open's credit before that file's own close runs).
+ * It is protected by tty_lock.
  */
 
 /* RX and TX queues can buffer QUEUE_SIZE packets before they hit the
@@ -128,6 +146,7 @@ struct gs_port {
 	wait_queue_head_t	close_wait;
 	bool			suspended;	/* port suspended */
 	bool			start_delayed;	/* delay start when suspended */
+	unsigned int		open_close_failures; /* protected by tty_lock */
 	struct async_icount	icount;
 
 	/* REVISIT this state ... */
@@ -135,8 +154,9 @@ struct gs_port {
 };
 
 static struct portmaster {
-	struct mutex	lock;			/* protect open/close */
+	struct mutex	lock;			/* protect open/close and port slot */
 	struct gs_port	*port;
+	bool		reserved;
 } ports[MAX_U_SERIAL_PORTS];
 
 #define GS_CLOSE_TIMEOUT		15		/* seconds */
@@ -603,22 +623,60 @@ static int gserial_wakeup_host(struct gs
 
 /* TTY Driver */
 
+static int gs_install(struct tty_driver *driver, struct tty_struct *tty)
+{
+	struct gs_port *port;
+	struct tty_port *tport;
+	int ret;
+
+	mutex_lock(&ports[tty->index].lock);
+	port = ports[tty->index].port;
+	if (!port) {
+		mutex_unlock(&ports[tty->index].lock);
+		return -ENODEV;
+	}
+
+	tport = tty_port_get(&port->port);
+	if (!tport) {
+		mutex_unlock(&ports[tty->index].lock);
+		return -ENODEV;
+	}
+
+	ret = tty_port_install(tport, driver, tty);
+	if (ret) {
+		mutex_unlock(&ports[tty->index].lock);
+		tty_port_put(tport);
+		return ret;
+	}
+
+	tty->driver_data = port;
+	mutex_unlock(&ports[tty->index].lock);
+
+	return 0;
+}
+
+static void gs_cleanup(struct tty_struct *tty)
+{
+	tty_port_put(tty->port);
+}
+
 /*
- * gs_open sets up the link between a gs_port and its associated TTY.
- * That link is broken *only* by TTY close(), and all driver methods
- * know that.
+ * gs_open associates an open TTY with its gs_port.
+ *
+ * There are two TTY-to-port relationships: port->port.tty exists from the
+ * first successful open until final close, while tty->driver_data is assigned
+ * during gs_install() and remains valid through gs_cleanup().
  */
 static int gs_open(struct tty_struct *tty, struct file *file)
 {
 	int		port_num = tty->index;
-	struct gs_port	*port;
+	struct gs_port	*port = tty->driver_data;
 	int		status = 0;
 
 	mutex_lock(&ports[port_num].lock);
-	port = ports[port_num].port;
-	if (!port) {
+	if (ports[port_num].port != port) {
 		status = -ENODEV;
-		goto out;
+		goto fail_unlock;
 	}
 
 	spin_lock_irq(&port->port_lock);
@@ -638,7 +696,7 @@ static int gs_open(struct tty_struct *tt
 		if (status) {
 			pr_debug("gs_open: ttyGS%d (%p,%p) no buffer\n",
 				 port_num, tty, file);
-			goto out;
+			goto fail_unlock;
 		}
 
 		spin_lock_irq(&port->port_lock);
@@ -648,7 +706,6 @@ static int gs_open(struct tty_struct *tt
 	if (port->port.count++)
 		goto exit_unlock_port;
 
-	tty->driver_data = port;
 	port->port.tty = tty;
 
 	/* if connected, start the I/O stream */
@@ -672,7 +729,11 @@ static int gs_open(struct tty_struct *tt
 
 exit_unlock_port:
 	spin_unlock_irq(&port->port_lock);
-out:
+	mutex_unlock(&ports[port_num].lock);
+	return status;
+
+fail_unlock:
+	port->open_close_failures++;
 	mutex_unlock(&ports[port_num].lock);
 	return status;
 }
@@ -698,6 +759,11 @@ static void gs_close(struct tty_struct *
 	if (!port)
 		return;
 
+	if (port->open_close_failures > 0) {
+		port->open_close_failures--;
+		return;
+	}
+
 	spin_lock_irq(&port->port_lock);
 
 	if (port->port.count != 1) {
@@ -912,8 +978,10 @@ static int gs_get_icount(struct tty_stru
 }
 
 static const struct tty_operations gs_tty_ops = {
+	.install =		gs_install,
 	.open =			gs_open,
 	.close =		gs_close,
+	.cleanup =		gs_cleanup,
 	.write =		gs_write,
 	.put_char =		gs_put_char,
 	.flush_chars =		gs_flush_chars,
@@ -1206,14 +1274,41 @@ static void gs_console_exit(struct gs_po
 
 #endif
 
-static int
+static void gs_port_destruct(struct tty_port *tport)
+{
+	struct gs_port *port = container_of(tport, struct gs_port, port);
+	unsigned int port_num = port->port_num;
+
+	mutex_lock(&ports[port_num].lock);
+	if (WARN_ON(ports[port_num].port))
+		ports[port_num].port = NULL;
+	WARN_ON(!ports[port_num].reserved);
+	if (gs_tty_driver)
+		gs_tty_driver->ports[port_num] = NULL;
+	ports[port_num].reserved = false;
+	mutex_unlock(&ports[port_num].lock);
+
+	kfifo_free(&port->port_write_buf);
+	kfree(port);
+}
+
+static const struct tty_port_operations gs_port_ops = {
+	.destruct = gs_port_destruct,
+};
+
+static struct gs_port *
 gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding)
 {
 	struct gs_port	*port;
 	int		ret = 0;
 
 	mutex_lock(&ports[port_num].lock);
-	if (ports[port_num].port) {
+	if (WARN_ON_ONCE(ports[port_num].port && !ports[port_num].reserved)) {
+		ret = -EBUSY;
+		goto out;
+	}
+
+	if (ports[port_num].reserved) {
 		ret = -EBUSY;
 		goto out;
 	}
@@ -1225,6 +1320,7 @@ gs_port_alloc(unsigned port_num, struct
 	}
 
 	tty_port_init(&port->port);
+	port->port.ops = &gs_port_ops;
 	spin_lock_init(&port->port_lock);
 	init_waitqueue_head(&port->drain_wait);
 	init_waitqueue_head(&port->close_wait);
@@ -1238,10 +1334,14 @@ gs_port_alloc(unsigned port_num, struct
 	port->port_num = port_num;
 	port->port_line_coding = *coding;
 
+	ports[port_num].reserved = true;
 	ports[port_num].port = port;
+	mutex_unlock(&ports[port_num].lock);
+	return port;
+
 out:
 	mutex_unlock(&ports[port_num].lock);
-	return ret;
+	return ERR_PTR(ret);
 }
 
 static int gs_closed(struct gs_port *port)
@@ -1261,8 +1361,7 @@ static void gserial_free_port(struct gs_
 	/* wait for old opens to finish */
 	wait_event(port->close_wait, gs_closed(port));
 	WARN_ON(port->port_usb != NULL);
-	tty_port_destroy(&port->port);
-	kfree(port);
+	tty_port_put(&port->port);
 }
 
 void gserial_free_line(unsigned char port_num)
@@ -1279,15 +1378,15 @@ void gserial_free_line(unsigned char por
 	ports[port_num].port = NULL;
 	mutex_unlock(&ports[port_num].lock);
 
-	gserial_free_port(port);
 	tty_unregister_device(gs_tty_driver, port_num);
+	gserial_free_port(port);
 }
 EXPORT_SYMBOL_GPL(gserial_free_line);
 
 int gserial_alloc_line_no_console(unsigned char *line_num)
 {
 	struct usb_cdc_line_coding	coding;
-	struct gs_port			*port;
+	struct gs_port			*port = ERR_PTR(-EBUSY);
 	struct device			*tty_dev;
 	int				ret;
 	int				port_num;
@@ -1298,19 +1397,20 @@ int gserial_alloc_line_no_console(unsign
 	coding.bDataBits = USB_CDC_1_STOP_BITS;
 
 	for (port_num = 0; port_num < MAX_U_SERIAL_PORTS; port_num++) {
-		ret = gs_port_alloc(port_num, &coding);
-		if (ret == -EBUSY)
-			continue;
-		if (ret)
+		port = gs_port_alloc(port_num, &coding);
+		if (IS_ERR(port)) {
+			ret = PTR_ERR(port);
+			if (ret == -EBUSY)
+				continue;
 			return ret;
+		}
 		break;
 	}
-	if (ret)
-		return ret;
+	if (IS_ERR(port))
+		return PTR_ERR(port);
 
 	/* ... and sysfs class devices, so mdev/udev make /dev/ttyGS* */
 
-	port = ports[port_num].port;
 	tty_dev = tty_port_register_device(&port->port,
 			gs_tty_driver, port_num, NULL);
 	if (IS_ERR(tty_dev)) {
@@ -1319,14 +1419,15 @@ int gserial_alloc_line_no_console(unsign
 
 		ret = PTR_ERR(tty_dev);
 		mutex_lock(&ports[port_num].lock);
+		WARN_ON(ports[port_num].port != port);
 		ports[port_num].port = NULL;
 		mutex_unlock(&ports[port_num].lock);
-		gserial_free_port(port);
-		goto err;
+		tty_port_put(&port->port);
+		return ret;
 	}
+
 	*line_num = port_num;
-err:
-	return ret;
+	return 0;
 }
 EXPORT_SYMBOL_GPL(gserial_alloc_line_no_console);
 
author maintainer
#933 lore raw

PATCH 932/1005 usb: dwc3: trace: Restore request name assignment

In reply to Greg Kroah-Hartman

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

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

From: Thinh Nguyen <[email protected]>

commit d8090de52e0a8f1761ced4fc31d52a3e289e341c upstream.

The commit 0a06917432a7 ("usb: dwc3: Log dwc3 address in traces") removed the __assign_str(name) call from dwc3_log_request. The name field still exists in the trace event, but nothing fills it in, so the endpoint name printed for these events is leftover garbage from the ring buffer.

Put the __assign_str() call back so the endpoint name is logged again.

---
 drivers/usb/dwc3/trace.h | 1 +
 1 file changed, 1 insertion(+)
drivers/usb/dwc3/trace.h +1 -0
index 5253da23d8b0..0caaa0b396d1 100644
@@ -141,6 +141,7 @@ DECLARE_EVENT_CLASS(dwc3_log_request,
 	),
 	TP_fast_assign(
 		__entry->base_address = req->dep->dwc->xhci_resources[0].start;
+		__assign_str(name);
 		__entry->req = req;
 		__entry->actual = req->request.actual;
 		__entry->length = req->request.length;
Signature · 1 line
2.56.1
author maintainer
#934 lore raw

PATCH 933/1005 usb: dwc3: gadget: Clear delayed stop on End Transfer completion

In reply to Greg Kroah-Hartman

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

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

From: Thinh Nguyen <[email protected]>

commit f2bd20f92a7dc68980a6098397503067192ce63a upstream.

When an End Transfer command times out outside of the SETUP phase, the driver sets DWC3_EP_DELAY_STOP to retry it on the next SETUP phase. If the command completes in the meantime, the flag is left set. Requests queued to the endpoint are then deferred, and the retry may end a transfer that is started later.

Clear DWC3_EP_DELAY_STOP when the End Transfer command completes.

---
 drivers/usb/dwc3/gadget.c |    1 +
 1 file changed, 1 insertion(+)
drivers/usb/dwc3/gadget.c +1 -0
@@ -3872,6 +3872,7 @@ static void dwc3_gadget_endpoint_command
 	if (dep->stream_capable)
 		dep->flags |= DWC3_EP_IGNORE_NEXT_NOSTREAM;
 
+	dep->flags &= ~DWC3_EP_DELAY_STOP;
 	dep->flags &= ~DWC3_EP_END_TRANSFER_PENDING;
 	dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
 	dwc3_gadget_ep_cleanup_cancelled_requests(dep);
author maintainer
#935 lore raw

PATCH 934/1005 usb: dwc3: gadget: Issue no-op Start Transfer only for stream endpoints

In reply to Greg Kroah-Hartman

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

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

From: Thinh Nguyen <[email protected]>

commit e616d91e02881983e5dadf6980c4aa08123800b3 upstream.

The function driver may re-enable an endpoint before the End Transfer command issued on ep disable completes. The no-op Start Transfer issued on ep enable then fails with "No Resource".

Only stream endpoints need the no-op Start Transfer to initiate a stream. Other bulk and interrupt endpoints start their transfer when a request is queued. Skip it for those endpoints, and move it to a helper to be reused.

---
 drivers/usb/dwc3/gadget.c |   97 +++++++++++++++++++++++-----------------------
 1 file changed, 50 insertions(+), 47 deletions(-)
drivers/usb/dwc3/gadget.c +50 -47
@@ -906,6 +906,54 @@ static int dwc3_gadget_resize_tx_fifos(s
 	return 0;
 }
 
+static int dwc3_gadget_ep_start_noop_transfer(struct dwc3_ep *dep)
+{
+	struct dwc3_gadget_ep_cmd_params params;
+	struct dwc3		*dwc = dep->dwc;
+	struct dwc3_trb		*trb;
+	dma_addr_t		trb_dma;
+	u32			cmd;
+	int			ret;
+
+	memset(&params, 0, sizeof(params));
+	trb = &dep->trb_pool[0];
+	trb_dma = dwc3_trb_dma_offset(dep, trb);
+
+	params.param0 = upper_32_bits(trb_dma);
+	params.param1 = lower_32_bits(trb_dma);
+
+	cmd = DWC3_DEPCMD_STARTTRANSFER;
+
+	ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
+	if (ret < 0)
+		return ret;
+
+	/*
+	 * For streams, at start, there maybe a race where the host primes the
+	 * endpoint before the function driver queues a request to initiate a
+	 * stream. In that case, the controller will not see the prime to
+	 * generate the ERDY and start stream. To workaround this, issue a
+	 * no-op TRB as normal, but end it immediately. As a result, when the
+	 * function driver queues the request, the next START_TRANSFER command
+	 * will cause the controller to generate an ERDY to initiate the
+	 * stream.
+	 */
+	dwc3_stop_active_transfer(dep, false, true);
+
+	/*
+	 * All stream eps will reinitiate stream on NoStream rejection.
+	 *
+	 * However, if the controller is capable of TXF_FLUSH_BYPASS, then IN
+	 * direction endpoints will automatically restart the stream without
+	 * the driver initiation.
+	 */
+	if (!dep->direction ||
+	    !(dwc->hwparams.hwparams9 & DWC3_GHWPARAMS9_DEV_TXF_FLUSH_BYPASS))
+		dep->flags |= DWC3_EP_FORCE_RESTART_STREAM;
+
+	return 0;
+}
+
 /**
  * __dwc3_gadget_ep_enable - initializes a hw endpoint
  * @dep: endpoint to be initialized
@@ -971,55 +1019,10 @@ static int __dwc3_gadget_ep_enable(struc
 	 * Issue StartTransfer here with no-op TRB so we can always rely on No
 	 * Response Update Transfer command.
 	 */
-	if (usb_endpoint_xfer_bulk(desc) ||
-			usb_endpoint_xfer_int(desc)) {
-		struct dwc3_gadget_ep_cmd_params params;
-		struct dwc3_trb	*trb;
-		dma_addr_t trb_dma;
-		u32 cmd;
-
-		memset(&params, 0, sizeof(params));
-		trb = &dep->trb_pool[0];
-		trb_dma = dwc3_trb_dma_offset(dep, trb);
-
-		params.param0 = upper_32_bits(trb_dma);
-		params.param1 = lower_32_bits(trb_dma);
-
-		cmd = DWC3_DEPCMD_STARTTRANSFER;
-
-		ret = dwc3_send_gadget_ep_cmd(dep, cmd, &params);
+	if (dep->stream_capable) {
+		ret = dwc3_gadget_ep_start_noop_transfer(dep);
 		if (ret < 0)
 			return ret;
-
-		if (dep->stream_capable) {
-			/*
-			 * For streams, at start, there maybe a race where the
-			 * host primes the endpoint before the function driver
-			 * queues a request to initiate a stream. In that case,
-			 * the controller will not see the prime to generate the
-			 * ERDY and start stream. To workaround this, issue a
-			 * no-op TRB as normal, but end it immediately. As a
-			 * result, when the function driver queues the request,
-			 * the next START_TRANSFER command will cause the
-			 * controller to generate an ERDY to initiate the
-			 * stream.
-			 */
-			dwc3_stop_active_transfer(dep, false, true);
-
-			/*
-			 * All stream eps will reinitiate stream on NoStream
-			 * rejection.
-			 *
-			 * However, if the controller is capable of
-			 * TXF_FLUSH_BYPASS, then IN direction endpoints will
-			 * automatically restart the stream without the driver
-			 * initiation.
-			 */
-			if (!dep->direction ||
-			    !(dwc->hwparams.hwparams9 &
-			      DWC3_GHWPARAMS9_DEV_TXF_FLUSH_BYPASS))
-				dep->flags |= DWC3_EP_FORCE_RESTART_STREAM;
-		}
 	}
 
 out:
author maintainer
#936 lore raw

PATCH 935/1005 usb: dwc3: gadget: Recover from End Transfer timeout

In reply to Greg Kroah-Hartman

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

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

From: Thinh Nguyen <[email protected]>

commit 61575534fb05d52d36979f38976ece74649f091a upstream.

If the End Transfer command times out, the endpoint resource is never released and every subsequent Start Transfer to the endpoint fails with "No Resource". Schedule an error recovery to reset the controller.

---
 drivers/usb/dwc3/gadget.c |    5 +++++
 1 file changed, 5 insertions(+)
drivers/usb/dwc3/gadget.c +5 -0
@@ -1754,6 +1754,8 @@ static int __dwc3_gadget_get_frame(struc
 	return DWC3_DSTS_SOFFN(reg);
 }
 
+static void dwc3_schedule_err_recovery(struct dwc3 *dwc);
+
 /**
  * __dwc3_stop_active_transfer - stop the current active transfer
  * @dep: isoc endpoint
@@ -1797,6 +1799,9 @@ static int __dwc3_stop_active_transfer(s
 		dev_err_ratelimited(dep->dwc->dev,
 				"end transfer failed: %d\n", ret);
 
+	if (ret == -ETIMEDOUT && dep->dwc->err_state == DWC3_ERR_NONE)
+		dwc3_schedule_err_recovery(dep->dwc);
+
 	dep->resource_index = 0;
 
 	if (!interrupt)
author maintainer
#937 lore raw

PATCH 936/1005 usb: dwc3: gadget: Reject requests to a disabled endpoint

In reply to Greg Kroah-Hartman

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

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

From: Thinh Nguyen <[email protected]>

commit 5eb11b1647b0534b3a61a21473d77ebf4ffbed7c upstream.

__dwc3_gadget_ep_disable() releases the lock while giving back requests, and DWC3_EP_ENABLED is only cleared afterward. A function driver can queue a new request in this window, and the driver would start a transfer on an endpoint that is already disabled in hardware.

Clear DWC3_EP_ENABLED before giving back the requests, and reject requests queued to an endpoint that is not enabled.

---
 drivers/usb/dwc3/gadget.c |    5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/usb/dwc3/gadget.c +4 -1
@@ -1087,6 +1087,8 @@ static int __dwc3_gadget_ep_disable(stru
 	reg &= ~DWC3_DALEPENA_EP(dep->number);
 	dwc3_writel(dwc, DWC3_DALEPENA, reg);
 
+	dep->flags &= ~DWC3_EP_ENABLED;
+
 	dwc3_remove_requests(dwc, dep, -ESHUTDOWN);
 
 	dep->stream_capable = false;
@@ -1998,7 +2000,8 @@ static int __dwc3_gadget_ep_queue(struct
 {
 	struct dwc3		*dwc = dep->dwc;
 
-	if (!dep->endpoint.desc || !dwc->pullups_connected || !dwc->connected) {
+	if (!(dep->flags & DWC3_EP_ENABLED) || !dep->endpoint.desc ||
+	    !dwc->pullups_connected || !dwc->connected) {
 		dev_dbg(dwc->dev, "%s: can't queue to disabled endpoint\n",
 				dep->name);
 		return -ESHUTDOWN;
author maintainer
#938 lore raw

PATCH 937/1005 usb: dwc3: gadget: Reset endpoint flags on controller start

In reply to Greg Kroah-Hartman

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

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

From: Thinh Nguyen <[email protected]>

commit 7c9bc134e5b3315e0456cda9e8e59c752309ea78 upstream.

The flags of a disabled endpoint may be preserved while its End Transfer command is pending. If the command never completes, the stale flags persist across a soft disconnect or an error recovery, and the endpoint can't be used again.

Reset the flags of all non-control endpoints when starting the controller.

---
 drivers/usb/dwc3/gadget.c |   10 ++++++++++
 1 file changed, 10 insertions(+)
drivers/usb/dwc3/gadget.c +10 -0
@@ -2958,6 +2958,7 @@ static int __dwc3_gadget_start(struct dw
 {
 	struct dwc3_ep		*dep;
 	int			ret = 0;
+	u32			epnum;
 	u32			reg;
 
 	/*
@@ -3015,6 +3016,15 @@ static int __dwc3_gadget_start(struct dw
 		return ret;
 	}
 
+	for (epnum = 2; epnum < dwc->num_eps; epnum++) {
+		dep = dwc->eps[epnum];
+		if (!dep)
+			continue;
+
+		dep->flags &= (DWC3_EP_TXFIFO_RESIZED |
+			       DWC3_EP_RESOURCE_ALLOCATED);
+	}
+
 	dep = dwc->eps[0];
 	dep->flags = 0;
 	ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT);
author maintainer
#939 lore raw

PATCH 938/1005 usb: dwc3: gadget: Track a timed out End Transfer

In reply to Greg Kroah-Hartman

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

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

From: Thinh Nguyen <[email protected]>

commit af91c6322e633504aa45de278f5d520f39d127be upstream.

If an End Transfer command with CMDIOC times out, the driver clears the resource index but keeps DWC3_EP_TRANSFER_STARTED without setting DWC3_EP_END_TRANSFER_PENDING. The command is still outstanding, but a later stop issues another End Transfer with resource index 0, and the next Start Transfer fails with "No Resource".

Mark the timed out End Transfer as pending so that no other command is issued to the endpoint until it completes. For any other failure, there is no outstanding command, so clear DWC3_EP_TRANSFER_STARTED.

---
 drivers/usb/dwc3/gadget.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/usb/dwc3/gadget.c +2 -2
@@ -1806,9 +1806,9 @@ static int __dwc3_stop_active_transfer(s
 
 	dep->resource_index = 0;
 
-	if (!interrupt)
+	if (!interrupt || (ret && ret != -ETIMEDOUT))
 		dep->flags &= ~DWC3_EP_TRANSFER_STARTED;
-	else if (!ret)
+	else
 		dep->flags |= DWC3_EP_END_TRANSFER_PENDING;
 
 	dep->flags &= ~DWC3_EP_DELAY_STOP;
author maintainer
#940 lore raw

PATCH 939/1005 usb: dwc3: gadget: Wait for End Transfer completion on ep disable

In reply to Greg Kroah-Hartman

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

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

From: Thinh Nguyen <[email protected]>

commit 1338410c21a5710b7ba88057034d35367ba0f054 upstream.

The End Transfer command on ep disable is issued without interrupt, and the endpoint flags are cleared right after a fixed delay. The command may not have completed by then. If the function driver re-enables the endpoint and queues a request, the next Start Transfer fails with "No Resource".

Issue the End Transfer command with interrupt on ep disable, and keep DWC3_EP_END_TRANSFER_PENDING and DWC3_EP_TRANSFER_STARTED until the command completes. Defer the no-op Start Transfer of a stream endpoint re-enabled in the meantime to the command completion.

---
 drivers/usb/dwc3/core.h   |    4 +++-
 drivers/usb/dwc3/ep0.c    |    2 +-
 drivers/usb/dwc3/gadget.c |   42 +++++++++++++++++++++++++++++++++++-------
 3 files changed, 39 insertions(+), 9 deletions(-)
drivers/usb/dwc3/core.h +3 -1
@@ -771,6 +771,7 @@ struct dwc3_ep {
 #define DWC3_EP_TXFIFO_RESIZED		BIT(12)
 #define DWC3_EP_DELAY_STOP             BIT(13)
 #define DWC3_EP_RESOURCE_ALLOCATED	BIT(14)
+#define DWC3_EP_PENDING_NOOP_START	BIT(15)
 
 	/* This last one is specific to EP0 */
 #define DWC3_EP0_DIR_IN			BIT(31)
@@ -1695,7 +1696,8 @@ int dwc3_send_gadget_ep_cmd(struct dwc3_
 int dwc3_send_gadget_generic_command(struct dwc3 *dwc, unsigned int cmd,
 		u32 param);
 void dwc3_gadget_clear_tx_fifos(struct dwc3 *dwc);
-void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep, int status);
+void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep, int status,
+			  bool interrupt);
 #else
 static inline int dwc3_gadget_init(struct dwc3 *dwc)
 { return 0; }
drivers/usb/dwc3/ep0.c +1 -1
@@ -315,7 +315,7 @@ void dwc3_ep0_out_start(struct dwc3 *dwc
 		if (dwc->connected)
 			dwc3_stop_active_transfer(dwc3_ep, false, true);
 		else
-			dwc3_remove_requests(dwc, dwc3_ep, -ESHUTDOWN);
+			dwc3_remove_requests(dwc, dwc3_ep, -ESHUTDOWN, false);
 	}
 }
 
drivers/usb/dwc3/gadget.c +35 -7

87 lines not on this page · raw message

author maintainer
#941 lore raw

PATCH 940/1005 usb: dwc3: xilinx: fix system suspend and resume PHY handling

In reply to Greg Kroah-Hartman

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

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

From: Radhey Shyam Pandey <[email protected]>

commit 2fad8d241a6833d0c7aeafa0ab596e83c7b4ec9c upstream.

System suspend and resume error paths do not handle PHY and clock resources correctly. Suspend calls phy_exit() without first powering off the PHY and ignores failures, while resume can leave clocks enabled if PHY reinitialization fails.

Propagate errors to the PM core and unwind resources to ensure a consistent state on suspend and resume failures.

Fixes d6edcdc1ef06 ("usb: dwc3: xilinx: fix usb3 non-wakeup source resume failure")
Cc stable <[email protected]>
Assisted-by Claude:claude-opus-5
---
 drivers/usb/dwc3/dwc3-xilinx.c |   24 +++++++++++++++++++++---
 1 file changed, 21 insertions(+), 3 deletions(-)
drivers/usb/dwc3/dwc3-xilinx.c +21 -3
@@ -383,13 +383,26 @@ static int __maybe_unused dwc3_xlnx_runt
 static int __maybe_unused dwc3_xlnx_suspend(struct device *dev)
 {
 	struct dwc3_xlnx *priv_data = dev_get_drvdata(dev);
+	int ret;
+
+	ret = phy_power_off(priv_data->usb3_phy);
+	if (ret < 0)
+		return ret;
 
-	phy_exit(priv_data->usb3_phy);
+	ret = phy_exit(priv_data->usb3_phy);
+	if (ret < 0)
+		goto err_phy_power_on;
 
 	/* Disable the clocks */
 	clk_bulk_disable(priv_data->num_clocks, priv_data->clks);
 
 	return 0;
+
+err_phy_power_on:
+	if (phy_power_on(priv_data->usb3_phy))
+		dev_err(dev, "failed to restore PHY power after suspend error\n");
+
+	return ret;
 }
 
 static int __maybe_unused dwc3_xlnx_resume(struct device *dev)
@@ -403,15 +416,20 @@ static int __maybe_unused dwc3_xlnx_resu
 
 	ret = phy_init(priv_data->usb3_phy);
 	if (ret < 0)
-		return ret;
+		goto err_clk_disable;
 
 	ret = phy_power_on(priv_data->usb3_phy);
 	if (ret < 0) {
 		phy_exit(priv_data->usb3_phy);
-		return ret;
+		goto err_clk_disable;
 	}
 
 	return 0;
+
+err_clk_disable:
+	clk_bulk_disable(priv_data->num_clocks, priv_data->clks);
+
+	return ret;
 }
 
 static const struct dev_pm_ops dwc3_xlnx_dev_pm_ops = {
author maintainer
#942 lore raw

PATCH 941/1005 usb: dwc3: xilinx: re-assert resets on ZynqMP init error paths

In reply to Greg Kroah-Hartman

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

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

From: Radhey Shyam Pandey <[email protected]>

commit f33f0dd2eb014bffda02ecfd182de3ddab058596 upstream.

If reset deassert or PHY setup fails partway through dwc3_xlnx_init_zynqmp(), re-assert the resets that were already released before unwinding the PHY.

Only undo the reset cycle the function actually performed. The cycle is skipped when no usb3-phy is present, because asserting the core resets can break a USB3 configuration that is live but missing from the device tree, so the error path skips it for the same reason. Asserting an already asserted reset is harmless, so one block covers however far the deasserts progressed.

Save the ZynqMP reset handles in driver private data so later probe teardown can re-assert released resets.

Fixes 84770f028fab ("usb: dwc3: Add driver for Xilinx platforms")
Cc stable <[email protected]>
Assisted-by Claude:claude-opus-5
---
 drivers/usb/dwc3/dwc3-xilinx.c |   55 ++++++++++++++++++++++++++---------------
 1 file changed, 36 insertions(+), 19 deletions(-)
drivers/usb/dwc3/dwc3-xilinx.c +36 -19
@@ -48,6 +48,9 @@ struct dwc3_xlnx {
 	void __iomem			*regs;
 	int				(*pltfm_init)(struct dwc3_xlnx *data);
 	struct phy			*usb3_phy;
+	struct reset_control		*usb_crst;
+	struct reset_control		*usb_hibrst;
+	struct reset_control		*usb_apbrst;
 };
 
 static void dwc3_xlnx_mask_phy_rst(struct dwc3_xlnx *priv_data, bool mask)
@@ -112,7 +115,6 @@ static int dwc3_xlnx_init_versal(struct
 static int dwc3_xlnx_init_zynqmp(struct dwc3_xlnx *priv_data)
 {
 	struct device		*dev = priv_data->dev;
-	struct reset_control	*crst, *hibrst, *apbrst;
 	struct gpio_desc	*reset_gpio;
 	int			ret = 0;
 
@@ -124,25 +126,25 @@ static int dwc3_xlnx_init_zynqmp(struct
 		goto err;
 	}
 
-	crst = devm_reset_control_get_exclusive(dev, "usb_crst");
-	if (IS_ERR(crst)) {
-		ret = PTR_ERR(crst);
+	priv_data->usb_crst = devm_reset_control_get_exclusive(dev, "usb_crst");
+	if (IS_ERR(priv_data->usb_crst)) {
+		ret = PTR_ERR(priv_data->usb_crst);
 		dev_err_probe(dev, ret,
 			      "failed to get core reset signal\n");
 		goto err;
 	}
 
-	hibrst = devm_reset_control_get_exclusive(dev, "usb_hibrst");
-	if (IS_ERR(hibrst)) {
-		ret = PTR_ERR(hibrst);
+	priv_data->usb_hibrst = devm_reset_control_get_exclusive(dev, "usb_hibrst");
+	if (IS_ERR(priv_data->usb_hibrst)) {
+		ret = PTR_ERR(priv_data->usb_hibrst);
 		dev_err_probe(dev, ret,
 			      "failed to get hibernation reset signal\n");
 		goto err;
 	}
 
-	apbrst = devm_reset_control_get_exclusive(dev, "usb_apbrst");
-	if (IS_ERR(apbrst)) {
-		ret = PTR_ERR(apbrst);
+	priv_data->usb_apbrst = devm_reset_control_get_exclusive(dev, "usb_apbrst");
+	if (IS_ERR(priv_data->usb_apbrst)) {
+		ret = PTR_ERR(priv_data->usb_apbrst);
 		dev_err_probe(dev, ret,
 			      "failed to get APB reset signal\n");
 		goto err;
@@ -156,19 +158,19 @@ static int dwc3_xlnx_init_zynqmp(struct
 	 * absent.
 	 */
 	if (priv_data->usb3_phy) {
-		ret = reset_control_assert(crst);
+		ret = reset_control_assert(priv_data->usb_crst);
 		if (ret < 0) {
 			dev_err(dev, "Failed to assert core reset\n");
 			goto err;
 		}
 
-		ret = reset_control_assert(hibrst);
+		ret = reset_control_assert(priv_data->usb_hibrst);
 		if (ret < 0) {
 			dev_err(dev, "Failed to assert hibernation reset\n");
 			goto err;
 		}
 
-		ret = reset_control_assert(apbrst);
+		ret = reset_control_assert(priv_data->usb_apbrst);
 		if (ret < 0) {
 			dev_err(dev, "Failed to assert APB reset\n");
 			goto err;
@@ -179,7 +181,7 @@ static int dwc3_xlnx_init_zynqmp(struct
 	if (ret < 0)
 		goto err;
 
-	ret = reset_control_deassert(apbrst);
+	ret = reset_control_deassert(priv_data->usb_apbrst);
 	if (ret < 0) {
 		dev_err(dev, "Failed to release APB reset\n");
 		goto err_phy_exit;
@@ -195,21 +197,21 @@ static int dwc3_xlnx_init_zynqmp(struct
 		writel(PIPE_CLK_DESELECT, priv_data->regs + XLNX_USB_FPD_PIPE_CLK);
 	}
 
-	ret = reset_control_deassert(crst);
+	ret = reset_control_deassert(priv_data->usb_crst);
 	if (ret < 0) {
 		dev_err(dev, "Failed to release core reset\n");
-		goto err_phy_exit;
+		goto err_reset_assert;
 	}
 
-	ret = reset_control_deassert(hibrst);
+	ret = reset_control_deassert(priv_data->usb_hibrst);
 	if (ret < 0) {
 		dev_err(dev, "Failed to release hibernation reset\n");
-		goto err_phy_exit;
+		goto err_reset_assert;
 	}
 
 	ret = phy_power_on(priv_data->usb3_phy);
 	if (ret < 0)
-		goto err_phy_exit;
+		goto err_reset_assert;
 
 	/* ulpi reset via gpio-modepin or gpio-framework driver */
 	reset_gpio = devm_gpiod_get_optional(dev, "reset", GPIOD_OUT_HIGH);
@@ -230,6 +232,21 @@ static int dwc3_xlnx_init_zynqmp(struct
 
 err_phy_power_off:
 	phy_power_off(priv_data->usb3_phy);
+err_reset_assert:
+	/*
+	 * Undo only the reset cycle performed above.  That cycle is skipped
+	 * when there is no usb3-phy.  The deasserts stay unconditional so a
+	 * core the bootloader left in reset still comes up, but they are
+	 * deliberately not paired with an assert here: resetting a USB3
+	 * configuration that is live but missing from the device tree could
+	 * break it.  Asserting an already asserted reset is harmless, so one
+	 * block covers however far the cycle's deasserts got.
+	 */
+	if (priv_data->usb3_phy) {
+		reset_control_assert(priv_data->usb_hibrst);
+		reset_control_assert(priv_data->usb_crst);
+		reset_control_assert(priv_data->usb_apbrst);
+	}
 err_phy_exit:
 	phy_exit(priv_data->usb3_phy);
 err:
author maintainer
#943 lore raw

PATCH 942/1005 usb: dwc3: xilinx: unwind ZynqMP platform init on probe failure and remove

In reply to Greg Kroah-Hartman

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

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

From: Radhey Shyam Pandey <[email protected]>

commit 6c6508e742b47539224eb18cb23f7ed5d401dcb6 upstream.

dwc3_xlnx_init_zynqmp() leaves the controller out of reset with the PHY powered on, but nothing undoes that if probe fails later or when the driver is removed. The resets stay deasserted and the PHY stays on with no driver bound.

Register the teardown with devm_add_action_or_reset() once init has completed, so it runs on probe failure without the driver having to track how far init progressed. The teardown only undoes the reset cycle init performed, so it carries the same usb3-phy guard: with no PHY the resets were never asserted, and asserting them could break a USB3 configuration that is live but missing from the device tree.

The resets have to be asserted while the clocks are still running, so both the probe error path and remove() run the teardown explicitly before gating the clocks rather than leaving it to devres, which would otherwise run it afterwards. devm_release_action() unlinks the action before calling it, so devres cannot run it a second time.

Running it from remove() also covers .shutdown, which shares dwc3_xlnx_remove(): device_shutdown() does not call devres_release_all(), so a teardown left to devres would never run there.

Fixes 84770f028fab ("usb: dwc3: Add driver for Xilinx platforms")
Cc stable <[email protected]>
Assisted-by Claude:claude-opus-5
---
 drivers/usb/dwc3/dwc3-xilinx.c |   44 ++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 43 insertions(+), 1 deletion(-)
drivers/usb/dwc3/dwc3-xilinx.c +43 -1
@@ -112,6 +112,39 @@ static int dwc3_xlnx_init_versal(struct
 	return 0;
 }
 
+static void dwc3_xlnx_zynqmp_teardown(void *data)
+{
+	struct dwc3_xlnx *priv_data = data;
+
+	phy_power_off(priv_data->usb3_phy);
+
+	/*
+	 * Undo only the reset cycle init performed.  As on the init error
+	 * path, the unconditional deasserts are not paired with an assert
+	 * here: with no usb3-phy, resetting the core could break a USB3
+	 * configuration that is live but missing from the device tree.
+	 */
+	if (priv_data->usb3_phy) {
+		reset_control_assert(priv_data->usb_hibrst);
+		reset_control_assert(priv_data->usb_crst);
+		reset_control_assert(priv_data->usb_apbrst);
+	}
+
+	phy_exit(priv_data->usb3_phy);
+}
+
+/*
+ * Run the platform teardown explicitly, so the resets are asserted while the
+ * clocks are still running.  devm_release_action() unlinks the action before
+ * calling it, so devres will not run it a second time.
+ */
+static void dwc3_xlnx_release_teardown(struct device *dev,
+				       struct dwc3_xlnx *priv_data)
+{
+	if (devm_is_action_added(dev, dwc3_xlnx_zynqmp_teardown, priv_data))
+		devm_release_action(dev, dwc3_xlnx_zynqmp_teardown, priv_data);
+}
+
 static int dwc3_xlnx_init_zynqmp(struct dwc3_xlnx *priv_data)
 {
 	struct device		*dev = priv_data->dev;
@@ -228,7 +261,8 @@ static int dwc3_xlnx_init_zynqmp(struct
 
 	dwc3_xlnx_set_coherency(priv_data, XLNX_USB_TRAFFIC_ROUTE_CONFIG);
 
-	return 0;
+	return devm_add_action_or_reset(dev, dwc3_xlnx_zynqmp_teardown,
+					priv_data);
 
 err_phy_power_off:
 	phy_power_off(priv_data->usb3_phy);
@@ -355,6 +389,7 @@ err_pm_set_suspended:
 	pm_runtime_set_suspended(dev);
 
 err_clk_put:
+	dwc3_xlnx_release_teardown(dev, priv_data);
 	clk_bulk_disable_unprepare(priv_data->num_clocks, priv_data->clks);
 
 	return ret;
@@ -367,6 +402,13 @@ static void dwc3_xlnx_remove(struct plat
 
 	of_platform_depopulate(dev);
 
+	/*
+	 * This is also what makes .shutdown behave the same as .remove:
+	 * device_shutdown() does not call devres_release_all(), so a teardown
+	 * left to devres would never run on the shutdown path.
+	 */
+	dwc3_xlnx_release_teardown(dev, priv_data);
+
 	clk_bulk_disable_unprepare(priv_data->num_clocks, priv_data->clks);
 	priv_data->num_clocks = 0;
 
author maintainer
#944 lore raw

PATCH 943/1005 w1: dont hold list_mutex while a slave is torn down

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 7ef382cb0ae0b2d6df4fbc5c822cd80394308839 upstream.

When the last reference to a slave is dropped, w1_unref_slave() holds list_mutex of the master until the slave has been freed. In between it calls the ->remove_slave() callback of the family driver and device_unregister(). Both wait for others: for the sysfs callbacks which are running, and in the case of w1_therm also for the file therm_bulk_read of the master and for everybody who is talking to the sensor. None of those can therefore take list_mutex, although the callbacks of therm_bulk_read walk the list which it protects.

The mutex is only needed to make the decrement of the reference count and the removal from the list one step for w1_search_slave() and w1_slave_search_device(), which look the slave up in the list and, in the first case, take a reference. Once the slave is off the list, nobody can find it any more. Drop the mutex at that point.

The callers which hold the mutex of the master, which serialises attaching and detaching, are not affected. The one which does not is w1_process_cb(), when it drops the last reference to a slave which has been detached while a netlink command for it was queued. Somebody who attaches a slave with the same ID through sysfs or netlink at that very moment used to wait until the old device was gone. Now the registration of the new device may fail because the name is still in use.

This is a preparation for "w1: w1_therm: lock the list of slaves for the bulk read".

---
 drivers/w1/w1.c |   13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)
drivers/w1/w1.c +10 -3
@@ -781,16 +781,24 @@ int w1_unref_slave(struct w1_slave *sl)
 {
 	struct w1_master *dev = sl->master;
 	int refcnt;
+
+	/*
+	 * Once it is off the list nobody can find the slave and take a new
+	 * reference.  The lock must not be held any longer than that: the rest
+	 * waits for sysfs callbacks and for users of the family data.
+	 */
 	mutex_lock(&dev->list_mutex);
 	refcnt = atomic_sub_return(1, &sl->refcnt);
+	if (refcnt == 0)
+		list_del(&sl->w1_slave_entry);
+	mutex_unlock(&dev->list_mutex);
+
 	if (refcnt == 0) {
 		struct w1_netlink_msg msg;
 
 		dev_dbg(&sl->dev, "%s: detaching %s [%p].\n", __func__,
 			sl->name, sl);
 
-		list_del(&sl->w1_slave_entry);
-
 		memset(&msg, 0, sizeof(msg));
 		memcpy(msg.id.id, &sl->reg_num, sizeof(msg.id));
 		msg.type = W1_SLAVE_REMOVE;
@@ -804,7 +812,6 @@ int w1_unref_slave(struct w1_slave *sl)
 		kfree(sl);
 	}
 	atomic_dec(&dev->refcnt);
-	mutex_unlock(&dev->list_mutex);
 	return refcnt;
 }
 
author maintainer
#945 lore raw

PATCH 944/1005 w1: ds2482: set the strong pull-up with its byte

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 e4f673632fa8292a2922bcfbb39519b08016b382 upstream.

The eight channels of a DS2482-800 are eight independent 1-wire masters for the w1 core, but share one I2C device. Each bus operation consists of several I2C transfers: select the channel, send the command, poll the status, set the read pointer, read the result. access_lock keeps the operations of the channels apart.

ds2482_w1_set_pullup() polls the status, writes the configuration and polls again without the lock. Polling sets the read pointer of the device to the status register. In the middle of a read on another channel, after that one has set the pointer to the data register, this makes the read return the status instead of the data. The cached copy of the pointer in pdev->read_prt can go wrong as well.

The lock alone is not enough. The strong pull-up is a setting of the whole chip which is used up by the next byte. If an operation of another channel gets in before the byte it was meant for, that channel gets the pull-up, and the sensor converts without power.

So only note the request in ds2482_w1_set_pullup(), and write the configuration in ds2482_w1_write_byte(), under the lock and after the channel has been selected. The w1 core calls the former right before the latter, under the bus mutex of the channel.

Fixes 9c95bb6f25ff ("w1: ds2482: Added 1-Wire pull-up support to the driver")
Cc stable <[email protected]>
---
 drivers/w1/masters/ds2482.c |   36 +++++++++++++++++++++---------------
 1 file changed, 21 insertions(+), 15 deletions(-)
drivers/w1/masters/ds2482.c +21 -15
@@ -103,6 +103,7 @@ struct ds2482_data;
 struct ds2482_w1_chan {
 	struct ds2482_data	*pdev;
 	u8			channel;
+	bool			spu;	/* strong pullup after the next byte */
 	struct w1_bus_master	w1_bm;
 };
 
@@ -336,6 +337,19 @@ static void ds2482_w1_write_byte(void *d
 	if (pdev->w1_count > 1)
 		ds2482_set_channel(pdev, pchan->channel);
 
+	if (pchan->spu) {
+		pchan->spu = false;
+		/* the wait above and this one are crucial, otherwise devices
+		 * might not be powered long enough, causing e.g. a w1_therm
+		 * sensor to provide wrong conversion results
+		 */
+		/* note: it seems like both SPU and APU have to be set! */
+		ds2482_send_cmd_data(pdev, DS2482_CMD_WRITE_CONFIG,
+				     ds2482_calculate_config(DS2482_REG_CFG_SPU |
+							     DS2482_REG_CFG_APU));
+		ds2482_wait_1wire_idle(pdev);
+	}
+
 	/* Send the write byte command */
 	ds2482_send_cmd_data(pdev, DS2482_CMD_1WIRE_WRITE_BYTE, byte);
 
@@ -420,27 +434,19 @@ static u8 ds2482_w1_reset_bus(void *data
 static u8 ds2482_w1_set_pullup(void *data, int delay)
 {
 	struct ds2482_w1_chan *pchan = data;
-	struct ds2482_data    *pdev = pchan->pdev;
-	u8 retval = 1;
 
 	/* if delay is non-zero activate the pullup,
 	 * the strong pullup will be automatically deactivated
 	 * by the master, so do not explicitly deactive it
+	 *
+	 * The setting is used up by the next byte on any channel of the chip:
+	 * ds2482_w1_write_byte() makes it, in one go with the byte.
 	 */
-	if (delay) {
-		/* both waits are crucial, otherwise devices might not be
-		 * powered long enough, causing e.g. a w1_therm sensor to
-		 * provide wrong conversion results
-		 */
-		ds2482_wait_1wire_idle(pdev);
-		/* note: it seems like both SPU and APU have to be set! */
-		retval = ds2482_send_cmd_data(pdev, DS2482_CMD_WRITE_CONFIG,
-			ds2482_calculate_config(DS2482_REG_CFG_SPU |
-						DS2482_REG_CFG_APU));
-		ds2482_wait_1wire_idle(pdev);
-	}
+	if (!delay)
+		return 1;
 
-	return retval;
+	pchan->spu = true;
+	return 0;
 }
 
 
author maintainer
#946 lore raw

PATCH 945/1005 w1: ds2805: use the bus mutex to talk on the bus

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 a2e52ccce044e13d2695bb1bbdc07942727f28dd upstream.

Since commit b02f8bede217 ("W1: split master mutex to avoid deadlocks.") the slave drivers serialise their accesses to the bus with bus_mutex. This driver takes the mutex of the master in the callbacks of its eeprom file instead.

That mutex is held while a slave which has disappeared from the bus is removed, which waits for the sysfs callbacks of the slave to return. A callback which is waiting for the mutex at that moment never does: both tasks are stuck, and with them the thread of the bus master.

Besides, it does not keep the other slave drivers off the bus, so that two transactions can get mixed up on the wire.

---
 drivers/w1/slaves/w1_ds2805.c |    8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
drivers/w1/slaves/w1_ds2805.c +4 -4
@@ -102,7 +102,7 @@ static ssize_t w1_f0d_read_bin(struct fi
 	if (count == 0)
 		return 0;
 
-	mutex_lock(&sl->master->mutex);
+	mutex_lock(&sl->master->bus_mutex);
 
 	/* read directly from the EEPROM in chunks of W1_F0D_READ_MAXLEN */
 	while (todo > 0) {
@@ -123,7 +123,7 @@ static ssize_t w1_f0d_read_bin(struct fi
 		off += W1_F0D_READ_MAXLEN;
 	}
 
-	mutex_unlock(&sl->master->mutex);
+	mutex_unlock(&sl->master->bus_mutex);
 
 	return count;
 }
@@ -211,7 +211,7 @@ static ssize_t w1_f0d_write_bin(struct f
 	if (count == 0)
 		return 0;
 
-	mutex_lock(&sl->master->mutex);
+	mutex_lock(&sl->master->bus_mutex);
 
 	/* Can only write data in blocks of the size of the scratchpad */
 	addr = off;
@@ -256,7 +256,7 @@ static ssize_t w1_f0d_write_bin(struct f
 	}
 
 out_up:
-	mutex_unlock(&sl->master->mutex);
+	mutex_unlock(&sl->master->bus_mutex);
 
 	return count;
 }
author maintainer
#947 lore raw

PATCH 946/1005 w1: ds28e04: use the bus mutex to talk on the bus

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 5bc51235d0ad4a4991e38f4e9dc3440738296850 upstream.

Since commit b02f8bede217 ("W1: split master mutex to avoid deadlocks.") the slave drivers serialise their accesses to the bus with bus_mutex. This driver, which was merged shortly afterwards, takes the mutex of the master in the callbacks of its eeprom and pio files instead.

That mutex is held while a slave which has disappeared from the bus is removed, which waits for the sysfs callbacks of the slave to return. A callback which is waiting for the mutex at that moment never does: both tasks are stuck, and with them the thread of the bus master.

Besides, it does not keep the other slave drivers off the bus, so that two transactions can get mixed up on the wire.

---
 drivers/w1/slaves/w1_ds28e04.c |   18 +++++++++---------
 1 file changed, 9 insertions(+), 9 deletions(-)
drivers/w1/slaves/w1_ds28e04.c +9 -9
@@ -123,7 +123,7 @@ static ssize_t eeprom_read(struct file *
 	if (count == 0)
 		return 0;
 
-	mutex_lock(&sl->master->mutex);
+	mutex_lock(&sl->master->bus_mutex);
 
 	if (w1_enable_crccheck) {
 		min_page = (off >> W1_PAGE_BITS);
@@ -140,7 +140,7 @@ static ssize_t eeprom_read(struct file *
 	}
 
 out_up:
-	mutex_unlock(&sl->master->mutex);
+	mutex_unlock(&sl->master->bus_mutex);
 
 	return count;
 }
@@ -253,7 +253,7 @@ static ssize_t eeprom_write(struct file
 		}
 	}
 
-	mutex_lock(&sl->master->mutex);
+	mutex_lock(&sl->master->bus_mutex);
 
 	/* Can only write data to one page at a time */
 	idx = 0;
@@ -271,7 +271,7 @@ static ssize_t eeprom_write(struct file
 	}
 
 out_up:
-	mutex_unlock(&sl->master->mutex);
+	mutex_unlock(&sl->master->bus_mutex);
 
 	return count;
 }
@@ -290,9 +290,9 @@ static ssize_t pio_read(struct file *fil
 	if (off != 0 || count != 1 || buf == NULL)
 		return -EINVAL;
 
-	mutex_lock(&sl->master->mutex);
+	mutex_lock(&sl->master->bus_mutex);
 	ret = w1_f1C_read(sl, W1_1C_REG_LOGIC_STATE, count, buf);
-	mutex_unlock(&sl->master->mutex);
+	mutex_unlock(&sl->master->bus_mutex);
 
 	return ret;
 }
@@ -310,11 +310,11 @@ static ssize_t pio_write(struct file *fi
 	if (off != 0 || count != 1 || buf == NULL)
 		return -EINVAL;
 
-	mutex_lock(&sl->master->mutex);
+	mutex_lock(&sl->master->bus_mutex);
 
 	/* Write the PIO data */
 	if (w1_reset_select_slave(sl)) {
-		mutex_unlock(&sl->master->mutex);
+		mutex_unlock(&sl->master->bus_mutex);
 		return -1;
 	}
 
@@ -328,7 +328,7 @@ static ssize_t pio_write(struct file *fi
 
 	w1_read_block(sl->master, &ack, sizeof(ack));
 
-	mutex_unlock(&sl->master->mutex);
+	mutex_unlock(&sl->master->bus_mutex);
 
 	/* check for acknowledgement */
 	if (ack != 0xAA)
author maintainer
#948 lore raw

PATCH 947/1005 w1: netlink: drop the slave after the bus is unlocked

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 847fa880a3e1b2fdbbf72d89e830566108457637 upstream.

w1_process_cb() executes the commands of a netlink message with bus_mutex held, and drops the reference to the slave which the message was addressed to before it unlocks the mutex. If the slave has been detached in the meantime, this is the last reference, and w1_unref_slave() tears the slave down on the spot. That waits

- in device_unregister(), for the sysfs callbacks of the slave which are running, and

- in w1_therm_remove_slave(), for the readers which have taken a reference to the family data,

and both kinds take bus_mutex to talk to the slave. Whoever is waiting for the mutex at that moment is never going to finish, and neither is the thread of the bus master.

Unlock the bus first. The reference keeps the slave, and with it the master, alive until then.

---
 drivers/w1/w1_netlink.c |    8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
drivers/w1/w1_netlink.c +5 -3
@@ -478,15 +478,17 @@ static void w1_process_cb(struct w1_mast
 	if (!cmd || err)
 		w1_netlink_queue_status(node->block, node->msg, cmd, err);
 
+	dev->priv = NULL;
+	mutex_unlock(&dev->bus_mutex);
+
 	/* ref taken in w1_search_slave or w1_search_master_id when building
-	 * the block
+	 * the block.  If it is the last one, the slave is removed, which waits
+	 * for users of the bus.
 	 */
 	if (sl)
 		w1_unref_slave(sl);
 	else
 		atomic_dec(&dev->refcnt);
-	dev->priv = NULL;
-	mutex_unlock(&dev->bus_mutex);
 
 	mutex_lock(&dev->list_mutex);
 	list_del(&async_cmd->async_entry);
author maintainer
#949 lore raw

PATCH 948/1005 w1: remove the masters files before taking its locks

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 dfc57752ec53c3cc6105656d3037fb2f5e80e9cc upstream.

__w1_remove_master_device() calls w1_destroy_master_attributes() with both the mutex of the master and list_mutex held. Removing the files waits for the callbacks which are running, and nearly all of them take one of these two locks:

__w1_remove_master_device() read() of .../w1_master_slaves

    mutex_lock(&dev->mutex)               kernfs active reference
    mutex_lock(&dev->list_mutex)          w1_master_attribute_show_slaves()
    w1_destroy_master_attributes()          mutex_lock(&md->list_mutex)
      sysfs_remove_group()                    waits
        waits for the reference

The files are readable for everybody, and a bus master goes away when, for instance, a DS2490 USB adapter is unplugged.

Remove the files first, before the locks are taken. That has to be done before the slaves are detached and not afterwards: as long as the files exist, a write to w1_master_add could attach a new slave behind the back of this function, which would then wait for the reference count of the master for ever. And it is done before the thread is stopped, because a write to w1_master_search wakes the thread up.

---
 drivers/w1/w1_int.c |    8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
drivers/w1/w1_int.c +7 -1
@@ -176,6 +176,13 @@ void __w1_remove_master_device(struct w1
 	mutex_unlock(&w1_mlock);
 
 	set_bit(W1_ABORT_SEARCH, &dev->flags);
+
+	/*
+	 * This waits for the callbacks, which take the locks below. One of
+	 * them wakes the thread up.
+	 */
+	w1_destroy_master_attributes(dev);
+
 	kthread_stop(dev->thread);
 
 	mutex_lock(&dev->mutex);
@@ -185,7 +192,6 @@ void __w1_remove_master_device(struct w1
 		w1_slave_detach(sl);
 		mutex_lock(&dev->list_mutex);
 	}
-	w1_destroy_master_attributes(dev);
 	mutex_unlock(&dev->list_mutex);
 	mutex_unlock(&dev->mutex);
 	atomic_dec(&dev->refcnt);
author maintainer
#950 lore raw

PATCH 949/1005 w1: use the bus mutex for the "rw" file

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 8599e08648c0b4913ea7b202511f1294d176e793 upstream.

Commit b02f8bede217 ("W1: split master mutex to avoid deadlocks.") gave the bus a mutex of its own, because the lock which protects the list of slaves is held while a slave is removed, which waits for the sysfs callbacks of the slave, so these must not take it. It converted all the slave drivers, but not the "rw" file of the default family in w1.c, which still takes the mutex of the master to talk on the bus. That has two consequences:

- A deadlock. w1_process() holds the mutex of the master while it searches the bus and detaches the slaves which have gone:

w1_process() read() of .../rw
mutex_lock(&dev->mutex) kernfs active reference
w1_search_process() rw_read()
w1_slave_detach() mutex_lock(&master->mutex)
w1_unref_slave() waits
device_unregister()
waits for the reference

The file is readable for everybody.

- The accesses through this file are not serialised with those of the slave drivers, which take bus_mutex, so that two transactions can get mixed up on the wire.

Take bus_mutex here as well. It also excludes the search, which takes it for every pass.

---
 drivers/w1/w1.c |    8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
drivers/w1/w1.c +4 -4
@@ -116,7 +116,7 @@ static ssize_t rw_write(struct file *fil
 {
 	struct w1_slave *sl = kobj_to_w1_slave(kobj);
 
-	mutex_lock(&sl->master->mutex);
+	mutex_lock(&sl->master->bus_mutex);
 	if (w1_reset_select_slave(sl)) {
 		count = 0;
 		goto out_up;
@@ -125,7 +125,7 @@ static ssize_t rw_write(struct file *fil
 	w1_write_block(sl->master, buf, count);
 
 out_up:
-	mutex_unlock(&sl->master->mutex);
+	mutex_unlock(&sl->master->bus_mutex);
 	return count;
 }
 
@@ -135,9 +135,9 @@ static ssize_t rw_read(struct file *filp
 {
 	struct w1_slave *sl = kobj_to_w1_slave(kobj);
 
-	mutex_lock(&sl->master->mutex);
+	mutex_lock(&sl->master->bus_mutex);
 	w1_read_block(sl->master, buf, count);
-	mutex_unlock(&sl->master->mutex);
+	mutex_unlock(&sl->master->bus_mutex);
 	return count;
 }
 
author maintainer
#951 lore raw

PATCH 950/1005 w1: w1_therm: leave the slaves of other families alone

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 c0eadd2e06e52563cae2b80491e56eb9712eb727 upstream.

The file therm_bulk_read belongs to the bus master. Its callbacks walk all the slaves of the bus and look at sl->family_data as if every slave were a temperature sensor. A 1-wire bus can carry other devices too:

- The family data of a slave which is driven by another driver, such as w1_ds2433, w1_ds250x, w1_ds28e04 or w1_ds28e17, is a structure of that driver. bulk_read_support() takes whatever is at the offset of specific_functions for a pointer and dereferences it, and if the result happens not to be 0, the callbacks write the state of the conversion into that foreign structure.

- For a slave without family data, which is the case for most of the other drivers and for the default family, trigger_bulk_read() gives up with -ENODEV. A single serial number chip on the bus is enough to make the bulk read unusable for all the sensors.

Only look at the slaves whose family is one of ours. A bulk conversion now works on a bus with other devices.

Fixes 57c76221d5af ("w1_therm: adding bulk read support to trigger multiple conversion on bus")
Cc stable <[email protected]>
---
 drivers/w1/slaves/w1_therm.c |   37 +++++++++++++++++++++++--------------
 1 file changed, 23 insertions(+), 14 deletions(-)
drivers/w1/slaves/w1_therm.c +23 -14
@@ -907,6 +907,19 @@ static inline bool bulk_read_support(str
 }
 
 /**
+ * bulk_read_slave() - check if a slave of the bus takes part in a bulk read
+ * @sl: any slave on the list of the master
+ *
+ * The family data of the slaves of other families is none of our business.
+ *
+ * Return: true if it is one of our devices and supports bulk read
+ */
+static bool bulk_read_slave(struct w1_slave *sl)
+{
+	return device_family(sl) && sl->family_data && bulk_read_support(sl);
+}
+
+/**
  * conversion_time() - get the Tconv for the slave
  * @sl: device to get the conversion time
  *
@@ -1496,9 +1509,7 @@ static int trigger_bulk_read(struct w1_m
 	 * so we can apply a strong pullup if required
 	 */
 	list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) {
-		if (!sl->family_data)
-			goto error;
-		if (bulk_read_support(sl)) {
+		if (bulk_read_slave(sl)) {
 			int t_cur = conversion_time(sl);
 
 			t_conv = max(t_cur, t_conv);
@@ -1536,7 +1547,7 @@ static int trigger_bulk_read(struct w1_m
 			/* set a flag to instruct that converT pending */
 			list_for_each_entry(sl,
 				&dev_master->slist, w1_slave_entry) {
-				if (bulk_read_support(sl))
+				if (bulk_read_slave(sl))
 					SLAVE_CONVERT_TRIGGERED(sl) = -1;
 			}
 
@@ -1565,7 +1576,7 @@ mt_unlock:
 set_flag:
 	/* set a flag to register convsersion is done */
 	list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) {
-		if (bulk_read_support(sl))
+		if (bulk_read_slave(sl))
 			SLAVE_CONVERT_TRIGGERED(sl) = 1;
 	}
 error:
@@ -1933,16 +1944,14 @@ static ssize_t therm_bulk_read_show(stru
 	int ret = 0;
 
 	list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) {
-		if (sl->family_data) {
-			if (bulk_read_support(sl)) {
-				if (SLAVE_CONVERT_TRIGGERED(sl) == -1) {
-					ret = -1;
-					goto show_result;
-				}
-				if (SLAVE_CONVERT_TRIGGERED(sl) == 1)
-					/* continue to check other slaves */
-					ret = 1;
+		if (bulk_read_slave(sl)) {
+			if (SLAVE_CONVERT_TRIGGERED(sl) == -1) {
+				ret = -1;
+				goto show_result;
 			}
+			if (SLAVE_CONVERT_TRIGGERED(sl) == 1)
+				/* continue to check other slaves */
+				ret = 1;
 		}
 	}
 show_result:
author maintainer
#952 lore raw

PATCH 951/1005 drm/amdkfd: skip GPUs without a VM when checkpointing the BO mappings

In reply to Greg Kroah-Hartman

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

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

From: Jesse Zhang <[email protected]>

commit 1a5ca15b558bf0e6621602c84e0a633d237dd052 upstream.

criu_checkpoint_bos() asks every device of the process whether a BO is mapped there, passing its drm_priv, which is NULL for the devices the process never acquired a VM on. On navi48 with its iGPU, checkpointing a process which acquired the VM of the dGPU only:

  Oops: general protection fault, probably for non-canonical address 0xdffffc000000002f: 0000 [#1] SMP KASAN NOPTI
  KASAN: null-ptr-deref in range [0x0000000000000178-0x000000000000017f]
  RIP: 0010:amdgpu_amdkfd_bo_mapped_to_dev+0x35/0x160 [amdgpu]
   kfd_ioctl_criu+0x30d1/0x4aa0 [amdgpu]
   kfd_ioctl+0x767/0xb10 [amdgpu]

Nothing can be mapped on such a device, skip it.

Fixes f9e292cbba21 ("drm/amdkfd: kfd_bo_mapped_dev support partition")
(cherry picked from commit 794381c358d344d8fcf8b9e6426aa2bac0a7d1f7)
---
 drivers/gpu/drm/amd/amdkfd/kfd_chardev.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/gpu/drm/amd/amdkfd/kfd_chardev.c +3 -1
@@ -2175,7 +2175,9 @@ static int criu_checkpoint_bos(struct kf
 				bo_bucket->offset = amdgpu_bo_mmap_offset(dumper_bo);
 
 			for (i = 0; i < p->n_pdds; i++) {
-				if (amdgpu_amdkfd_bo_mapped_to_dev(p->pdds[i]->drm_priv, kgd_mem))
+				/* nothing is mapped on a GPU without a VM */
+				if (p->pdds[i]->drm_priv &&
+				    amdgpu_amdkfd_bo_mapped_to_dev(p->pdds[i]->drm_priv, kgd_mem))
 					bo_priv->mapped_gpuids[dev_idx++] = p->pdds[i]->user_gpu_id;
 			}
 
author maintainer
#953 lore raw

PATCH 952/1005 drm/amdgpu: fix the error handling of amdgpu_vm_init_entities()

In reply to Greg Kroah-Hartman

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

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

From: Jesse Zhang <[email protected]>

commit de0f2a6eabd019a3129025862bffca934a5d7180 upstream.

When initializing the immediate entity fails, amdgpu_vm_init_entities() destroys that entity which was never set up, and when initializing the delayed entity fails, it returns without destroying the immediate one.

On navi48, with the allocation of the immediate entity's scheduler list failing through failslab while opening the render node:

  Oops: general protection fault, probably for non-canonical address 0xdffffc0000000001: 0000 [#1] SMP KASAN NOPTI
  KASAN: null-ptr-deref in range [0x0000000000000008-0x000000000000000f]
  RIP: 0010:do_raw_spin_lock+0x7b/0x280
   _raw_spin_lock+0x3c/0x50
   drm_sched_rq_remove_entity+0x90/0x2a0 [gpu_sched]
   drm_sched_entity_kill+0x86/0x5a0 [gpu_sched]
   drm_sched_entity_fini+0x23/0x270 [gpu_sched]
   drm_sched_entity_destroy+0x24/0x30 [gpu_sched]
   amdgpu_vm_init_entities+0xc7/0x100 [amdgpu]
   amdgpu_vm_init+0x5d1/0x1480 [amdgpu]
   amdgpu_driver_open_kms+0x2b1/0xd10 [amdgpu]

Only destroy the immediate entity once it exists and the delayed one failed.

Fixes 55bf196f60df ("drm/amdgpu: reset VM when an error is detected")
(cherry picked from commit 2f538f57501a71baeb7116ff7485f9a7025e4fb9)
---
 drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c |   10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c +7 -3
@@ -532,11 +532,15 @@ static int amdgpu_vm_init_entities(struc
 				  adev->vm_manager.vm_pte_scheds,
 				  adev->vm_manager.vm_pte_num_scheds, NULL);
 	if (r)
+		return r;
+
+	r = drm_sched_entity_init(&vm->delayed, DRM_SCHED_PRIORITY_NORMAL,
+				  adev->vm_manager.vm_pte_scheds,
+				  adev->vm_manager.vm_pte_num_scheds, NULL);
+	if (r)
 		goto error;
 
-	return drm_sched_entity_init(&vm->delayed, DRM_SCHED_PRIORITY_NORMAL,
-				     adev->vm_manager.vm_pte_scheds,
-				     adev->vm_manager.vm_pte_num_scheds, NULL);
+	return 0;
 
 error:
 	drm_sched_entity_destroy(&vm->immediate);
author maintainer
#954 lore raw

PATCH 953/1005 USB: serial: garmin_gps: validate packet data length in nat_receive()

In reply to Greg Kroah-Hartman

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

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

From: Hui Peng <[email protected]>

commit ca783a2d55b3361493917ad4a3573715ba902503 upstream.

In nat_receive() (called from garmin_write() when userspace writes to /dev/ttyUSBn in MODE_NATIVE mode), while garmin_data_p->insize is less than GARMIN_PKTHDR_LENGTH (12), the loop copies up to 12 bytes into garmin_data_p->inbuffer. Once garmin_data_p->insize reaches GARMIN_PKTHDR_LENGTH, nat_receive() computes the total packet size as:

  len = GARMIN_PKTHDR_LENGTH + getDataLength(garmin_data_p->inbuffer);

Because getDataLength() returns a signed int from __le32_to_cpup(), a 12-byte header with a negative 32-bit length field (such as 0xfffffff5, i.e., -11) causes len to underflow to a small positive value (12 + (-11) = 1) without any bounds check at that point. Then garmin_data_p->insize

Quoted 1 line

= len (12 >= 1) evaluates to true and nat_receive() calls

garmin_write_bulk(port, inbuffer, 1, 0), which allocates a 1-byte slab buffer via kmemdup() and immediately reads 4 bytes from it in getLayerId(buffer) (and again in garmin_write_bulk_callback() when the URB completes):

  BUG: KASAN: slab-out-of-bounds in garmin_write_bulk.constprop.0+0x3eb/0x500
  Read of size 4 at addr ffff888002cc0ba0 by task init/1
  Call Trace:
   <TASK>
   dump_stack_lvl+0x70/0xa0
   print_report+0x153/0x4c6
   kasan_report+0xf1/0x120
   garmin_write_bulk.constprop.0+0x3eb/0x500
   garmin_write+0x60f/0x1450
   serial_write+0x123/0x200
   n_tty_write+0x8ea/0xeb0
   file_tty_write.isra.0+0x44f/0x7a0
   vfs_write+0x671/0xd20

Validate the unsigned 32-bit data length (dlen >= GPS_IN_BUFSIZ - GARMIN_PKTHDR_LENGTH, matching the existing len >= GPS_IN_BUFSIZ bound) in nat_receive() as soon as the 12-byte header is present, resetting insize and returning -EINVPKT on invalid lengths so garmin_write_bulk() is only ever called with a full valid packet header (12 <= len < GPS_IN_BUFSIZ).

Tested in QEMU against Linux 7.3.0-rc3 by emulating a Garmin USB GPS device (091e:0003) via dummy_hcd + raw-gadget, switching /dev/ttyUSB0 to MODE_NATIVE via PRIV_PKTID_SET_MODE, and writing a 12-byte native packet with data length 0xfffffff5: on the unfixed kernel this triggers KASAN slab-out-of-bounds reads in garmin_write_bulk() and garmin_write_bulk_callback(), whereas on the fixed kernel nat_receive() rejects the packet with -EINVPKT and 0 KASAN faults.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
Assisted-by LLM
[ johan: move comment and dev_dbg(); add comment about redundant check ]
---
 drivers/usb/serial/garmin_gps.c |   19 ++++++++++++-------
 1 file changed, 12 insertions(+), 7 deletions(-)
drivers/usb/serial/garmin_gps.c +12 -7
@@ -746,11 +746,7 @@ static int nat_receive(struct garmin_dat
 			len = GARMIN_PKTHDR_LENGTH;
 
 		if (len >= GPS_IN_BUFSIZ) {
-			/* seems to be an invalid packet, ignore rest
-			   of input */
-			dev_dbg(&garmin_data_p->port->dev,
-				"%s - packet size too large: %d\n",
-				__func__, len);
+			/* should never end up here given the dlen check below */
 			garmin_data_p->insize = 0;
 			count = 0;
 			result = -EINVPKT;
@@ -769,8 +765,17 @@ static int nat_receive(struct garmin_dat
 
 		/* do we have a complete packet ? */
 		if (garmin_data_p->insize >= GARMIN_PKTHDR_LENGTH) {
-			len = GARMIN_PKTHDR_LENGTH+
-			   getDataLength(garmin_data_p->inbuffer);
+			u32 dlen = getDataLength(garmin_data_p->inbuffer);
+
+			if (dlen >= GPS_IN_BUFSIZ - GARMIN_PKTHDR_LENGTH) {
+				/* invalid packet, ignore rest of input */
+				dev_dbg(&garmin_data_p->port->dev, "%s - invalid length: %u\n",
+					__func__, dlen);
+				garmin_data_p->insize = 0;
+				result = -EINVPKT;
+				break;
+			}
+			len = GARMIN_PKTHDR_LENGTH + dlen;
 			if (garmin_data_p->insize >= len) {
 				garmin_write_bulk(garmin_data_p->port,
 						   garmin_data_p->inbuffer,
author maintainer
#955 lore raw

PATCH 954/1005 USB: serial: sierra: validate URB length in instat callback

In reply to Greg Kroah-Hartman

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

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

From: Tristan Madani <[email protected]>

commit a3d43b39032cc5565a5693a10c581844342372cd upstream.

sierra_instat_callback() reads request fields and one byte past the usb_ctrlrequest header without first checking that urb->actual_length is large enough. A short USB interrupt transfer could cause an out-of-bounds read.

Add two length checks matching the pattern already present in the option driver (option_instat_callback): one for the request header before accessing bRequestType, and one for the line-state data byte inside the serial-state notification handler. Use dev_err() since failing these checks causes the interrupt URB not to be resubmitted.

Fixes 033a3fb980b041 ("USB: Sierra Wireless driver update")
[ johan: use sizeof(*req_pkt) consistently ]
---
 drivers/usb/serial/sierra.c |   18 +++++++++++++++---
 1 file changed, 15 insertions(+), 3 deletions(-)
drivers/usb/serial/sierra.c +15 -3
@@ -575,12 +575,24 @@ static void sierra_instat_callback(struc
 				__func__);
 			return;
 		}
+		if (urb->actual_length < sizeof(*req_pkt)) {
+			dev_err(&port->dev, "%s: short transfer\n",
+				__func__);
+			return;
+		}
 		if ((req_pkt->bRequestType == 0xA1) &&
 				(req_pkt->bRequest == 0x20)) {
 			int old_dcd_state;
-			unsigned char signals = *((unsigned char *)
-					urb->transfer_buffer +
-					sizeof(struct usb_ctrlrequest));
+			unsigned char signals;
+
+			if (urb->actual_length < sizeof(*req_pkt) + 1) {
+				dev_err(&port->dev,
+					"%s: short interrupt transfer\n",
+					__func__);
+				return;
+			}
+			signals = *((unsigned char *)urb->transfer_buffer +
+					sizeof(*req_pkt));
 
 			dev_dbg(&port->dev, "%s: signal x%x\n", __func__,
 				signals);
author maintainer
#956 lore raw

PATCH 955/1005 USB: serial: upd78f0730: fix NULL-deref on hangup

In reply to Greg Kroah-Hartman

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

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

From: Johan Hovold <[email protected]>

commit 0e0b1fcfb80c0490bda7f7eb633ebb5e431c2e16 upstream.

The port tty pointer is cleared on hangup before deasserting the modem control signals and should not be used in the dtr_rts() callback.

Factor out a new upd78f0730_port_tiocmset() helper that can be used in upd78f0730_dtr_rts() to avoid dereferencing a NULL-pointer on hangup (e.g. on disconnect).

This issue was flagged by an LLM.

Fixes ea534e0b4047 ("USB: serial: add uPD78F0730 USB to Serial Adaptor Driver")
Cc Maksim Salau <[email protected]>
---
 drivers/usb/serial/upd78f0730.c |   13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)
drivers/usb/serial/upd78f0730.c +9 -4
@@ -201,10 +201,9 @@ static int upd78f0730_tiocmget(struct tt
 	return res;
 }
 
-static int upd78f0730_tiocmset(struct tty_struct *tty,
+static int upd78f0730_port_tiocmset(struct usb_serial_port *port,
 			unsigned int set, unsigned int clear)
 {
-	struct usb_serial_port *port = tty->driver_data;
 	struct upd78f0730_port_private *private;
 	struct upd78f0730_set_dtr_rts request;
 	struct device *dev = &port->dev;
@@ -238,6 +237,13 @@ static int upd78f0730_tiocmset(struct tt
 	return res;
 }
 
+static int upd78f0730_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear)
+{
+	struct usb_serial_port *port = tty->driver_data;
+
+	return upd78f0730_port_tiocmset(port, set, clear);
+}
+
 static int upd78f0730_break_ctl(struct tty_struct *tty, int break_state)
 {
 	struct upd78f0730_port_private *private;
@@ -267,7 +273,6 @@ static int upd78f0730_break_ctl(struct t
 
 static void upd78f0730_dtr_rts(struct usb_serial_port *port, int on)
 {
-	struct tty_struct *tty = port->port.tty;
 	unsigned int set = 0;
 	unsigned int clear = 0;
 
@@ -276,7 +281,7 @@ static void upd78f0730_dtr_rts(struct us
 	else
 		clear = TIOCM_DTR | TIOCM_RTS;
 
-	upd78f0730_tiocmset(tty, set, clear);
+	upd78f0730_port_tiocmset(port, set, clear);
 }
 
 static speed_t upd78f0730_get_baud_rate(struct tty_struct *tty)
author maintainer
#957 lore raw

PATCH 956/1005 USB: serial: io_edgeport: fix NULL-deref on early status

In reply to Greg Kroah-Hartman

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

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

From: Johan Hovold <[email protected]>

commit ae22e9b6412e5dc99e1cf8bd13c6176d44c7d42e upstream.

The driver submits the interrupt-in URB during probe or on first port open, which on completion may submit the bulk-in URB before all ports have been opened and their waitqueues have been initialised.

If a (malicious) device sends a status message for a port that has not yet been opened this may lead to a NULL-pointer dereference in the bulk-in completion handler when attempting to wakeup blocked tasks.

Move waitqueue initialisation from open() to port_probe() to address this.

---
 drivers/usb/serial/io_edgeport.c |   10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
drivers/usb/serial/io_edgeport.c +5 -5
@@ -877,11 +877,6 @@ static int edge_open(struct tty_struct *
 		}
 	}
 
-	/* initialize our wait queues */
-	init_waitqueue_head(&edge_port->wait_open);
-	init_waitqueue_head(&edge_port->wait_chase);
-	init_waitqueue_head(&edge_port->wait_command);
-
 	/* initialize our port settings */
 	edge_port->txCredits = 0;	/* Can't send any data yet */
 	/* Must always set this bit to enable ints! */
@@ -2965,6 +2960,11 @@ static int edge_port_probe(struct usb_se
 		return -ENOMEM;
 
 	spin_lock_init(&edge_port->ep_lock);
+
+	init_waitqueue_head(&edge_port->wait_open);
+	init_waitqueue_head(&edge_port->wait_chase);
+	init_waitqueue_head(&edge_port->wait_command);
+
 	edge_port->port = port;
 
 	usb_set_serial_port_data(port, edge_port);
author maintainer
#958 lore raw

PATCH 957/1005 USB: serial: io_edgeport: fix potential close() use-after-free

In reply to Greg Kroah-Hartman

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

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

From: Johan Hovold <[email protected]>

commit 839ff5fa30995c40cd5fba15fd976ad63416738a upstream.

Add the missing open check on write() and locking when updating the port status during close() to prevent a racing interrupt completion handler from trying to submit more data for the port while its write URB and FIFO are being deallocated.

This issue was flagged by Sashiko when reviewing a related fix.

---
 drivers/usb/serial/io_edgeport.c |    8 ++++++++
 1 file changed, 8 insertions(+)
drivers/usb/serial/io_edgeport.c +8 -0
@@ -1085,7 +1085,9 @@ static void edge_close(struct usb_serial
 
 	/* port->close = true; */
 	edge_port->closePending = false;
+	spin_lock_irq(&edge_port->ep_lock);
 	edge_port->open = false;
+	spin_unlock_irq(&edge_port->ep_lock);
 	edge_port->openPending = false;
 
 	usb_kill_urb(edge_port->write_urb);
@@ -1127,6 +1129,12 @@ static int edge_write(struct tty_struct
 
 	spin_lock_irqsave(&edge_port->ep_lock, flags);
 
+	/* avoid accessing freed fifo if tty_wakeup() races with close() */
+	if (!edge_port->open) {
+		spin_unlock_irqrestore(&edge_port->ep_lock, flags);
+		return 0;
+	}
+
 	/* calculate number of bytes to put in fifo */
 	copySize = min_t(unsigned int, count,
 				(edge_port->txCredits - fifo->count));
author maintainer
#959 lore raw

PATCH 958/1005 USB: serial: io_edgeport: fix potential NULL-deref at open

In reply to Greg Kroah-Hartman

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

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

From: Johan Hovold <[email protected]>

commit a0403880a0a638f189e5187068244d9fd5bc8d4d upstream.

Do not mark the port as open until after the write FIFO has been allocated and initialised to prevent a racing interrupt completion from attempting to send stale data and dereference the FIFO buffer pointer.

Note that the open flag defaults to false and is cleared on close() so there is no need to reinitialise it on every open().

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
---
 drivers/usb/serial/io_edgeport.c |   10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
drivers/usb/serial/io_edgeport.c +5 -5
@@ -885,9 +885,7 @@ static int edge_open(struct tty_struct *
 
 	/* send a open port command */
 	edge_port->openPending = true;
-	edge_port->open        = false;
 	response = send_iosp_ext_cmd(edge_port, IOSP_CMD_OPEN_PORT, 0);
-
 	if (response < 0) {
 		dev_err(dev, "%s - error sending open port command\n", __func__);
 		edge_port->openPending = false;
@@ -897,8 +895,7 @@ static int edge_open(struct tty_struct *
 	/* now wait for the port to be completely opened */
 	wait_event_timeout(edge_port->wait_open, !edge_port->openPending,
 								OPEN_TIMEOUT);
-
-	if (!edge_port->open) {
+	if (edge_port->openPending) {
 		/* open timed out */
 		dev_dbg(dev, "%s - open timeout\n", __func__);
 		edge_port->openPending = false;
@@ -926,6 +923,10 @@ static int edge_open(struct tty_struct *
 		return -ENOMEM;
 	}
 
+	spin_lock_irq(&edge_port->ep_lock);
+	edge_port->open = true;
+	spin_unlock_irq(&edge_port->ep_lock);
+
 	dev_dbg(dev, "%s - Initialize TX fifo to %d bytes\n",
 		__func__, edge_port->maxTxCredits);
 
@@ -1818,7 +1819,6 @@ static void process_rcvd_status(struct e
 
 		/* we have completed the open */
 		edge_port->openPending = false;
-		edge_port->open = true;
 		wake_up(&edge_port->wait_open);
 		return;
 	}
author maintainer
#960 lore raw

PATCH 959/1005 USB: serial: io_edgeport: move initial termios update to open()

In reply to Greg Kroah-Hartman

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

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

From: Johan Hovold <[email protected]>

commit febadc65a4ef8d08a12e76d6ec50834d72cc0e59 upstream.

Explicitly update the terminal settings on open() instead of doing so from the interrupt completion handler when receiving an open command response, which in theory can be received after a failed open attempt.

Note that this will be used to fix a FIFO corruption issue and also allows for switching to synchronous commands.

---
 drivers/usb/serial/io_edgeport.c |   64 ++++++---------------------------------
 1 file changed, 10 insertions(+), 54 deletions(-)
drivers/usb/serial/io_edgeport.c +10 -54
@@ -281,8 +281,7 @@ static void handle_new_lsr(struct edgepo
 static int  send_iosp_ext_cmd(struct edgeport_port *edge_port, __u8 command,
 				__u8 param);
 static int  calc_baud_rate_divisor(struct device *dev, int baud_rate, int *divisor);
-static void change_port_settings(struct tty_struct *tty,
-				struct edgeport_port *edge_port,
+static void edge_set_termios(struct tty_struct *tty, struct usb_serial_port *port,
 				const struct ktermios *old_termios);
 static int  send_cmd_write_uart_register(struct edgeport_port *edge_port,
 				__u8 regNum, __u8 regValue);
@@ -923,6 +922,9 @@ static int edge_open(struct tty_struct *
 		return -ENOMEM;
 	}
 
+	if (tty)
+		edge_set_termios(tty, port, NULL);
+
 	spin_lock_irq(&edge_port->ep_lock);
 	edge_port->open = true;
 	spin_unlock_irq(&edge_port->ep_lock);
@@ -1444,30 +1446,6 @@ static void edge_unthrottle(struct tty_s
 
 
 /*****************************************************************************
- * SerialSetTermios
- *	this function is called by the tty driver when it wants to change
- * the termios structure
- *****************************************************************************/
-static void edge_set_termios(struct tty_struct *tty,
-			     struct usb_serial_port *port,
-			     const struct ktermios *old_termios)
-{
-	struct edgeport_port *edge_port = usb_get_serial_port_data(port);
-
-	if (edge_port == NULL)
-		return;
-
-	if (!edge_port->open) {
-		dev_dbg(&port->dev, "%s - port not opened\n", __func__);
-		return;
-	}
-
-	/* change the port settings to the new ones specified */
-	change_port_settings(tty, edge_port, old_termios);
-}
-
-
-/*****************************************************************************
  * get_lsr_info - get line status register info
  *
  * Purpose: Let user call ioctl() to get info when the UART physically
@@ -1756,7 +1734,6 @@ static void process_rcvd_status(struct e
 {
 	struct usb_serial_port *port;
 	struct edgeport_port *edge_port;
-	struct tty_struct *tty;
 	struct device *dev;
 	__u8 code = edge_serial->rxStatusCode;
 
@@ -1808,15 +1785,6 @@ static void process_rcvd_status(struct e
 			__func__, edge_serial->rxPort, byte2, edge_port->txCredits);
 		handle_new_msr(edge_port, byte2);
 
-		/* send the current line settings to the port so we are
-		   in sync with any further termios calls */
-		tty = tty_port_tty_get(&edge_port->port->port);
-		if (tty) {
-			change_port_settings(tty,
-				edge_port, &tty->termios);
-			tty_kref_put(tty);
-		}
-
 		/* we have completed the open */
 		edge_port->openPending = false;
 		wake_up(&edge_port->wait_open);
@@ -2328,18 +2296,12 @@ static int send_cmd_write_uart_register(
 }
 
 
-/*****************************************************************************
- * change_port_settings
- *	This routine is called to set the UART on the device to match the
- *	specified new settings.
- *****************************************************************************/
-
-static void change_port_settings(struct tty_struct *tty,
-	struct edgeport_port *edge_port, const struct ktermios *old_termios)
+static void edge_set_termios(struct tty_struct *tty, struct usb_serial_port *port,
+		const struct ktermios *old_termios)
 {
-	struct device *dev = &edge_port->port->dev;
-	struct edgeport_serial *edge_serial =
-			usb_get_serial_data(edge_port->port->serial);
+	struct edgeport_serial *edge_serial = usb_get_serial_data(port->serial);
+	struct edgeport_port *edge_port = usb_get_serial_port_data(port);
+	struct device *dev = &port->dev;
 	int baud;
 	unsigned cflag;
 	__u8 mask = 0xff;
@@ -2350,12 +2312,6 @@ static void change_port_settings(struct
 	__u8 txFlow;
 	int status;
 
-	if (!edge_port->open &&
-	    !edge_port->openPending) {
-		dev_dbg(dev, "%s - port not opened\n", __func__);
-		return;
-	}
-
 	cflag = tty->termios.c_cflag;
 
 	switch (cflag & CSIZE) {
@@ -2489,7 +2445,7 @@ static void change_port_settings(struct
 
 	dev_dbg(dev, "%s - baud rate = %d\n", __func__, baud);
 	status = send_cmd_write_baud_rate(edge_port, baud);
-	if (status == -1) {
+	if (status == -1 && old_termios) {
 		/* Speed change was not possible - put back the old speed */
 		baud = tty_termios_baud_rate(old_termios);
 		tty_encode_baud_rate(tty, baud, baud);
author maintainer
#961 lore raw

PATCH 960/1005 USB: serial: io_edgeport: fix potential fifo corruption

In reply to Greg Kroah-Hartman

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

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

From: Johan Hovold <[email protected]>

commit 270f76c3b88c9cc3d6ca58c5c0c0f34c2373b27c upstream.

The device buffer size is determined during open() and the driver allocates a TX FIFO of corresponding size.

Add the missing sanity check to prevent memory corruption in case a malicious device sends a second open response with a different buffer size.

This issue was flagged by Sashiko when reviewing a related fix.

---
 drivers/usb/serial/io_edgeport.c |   15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)
drivers/usb/serial/io_edgeport.c +14 -1
@@ -877,13 +877,17 @@ static int edge_open(struct tty_struct *
 	}
 
 	/* initialize our port settings */
+	spin_lock_irq(&edge_port->ep_lock);
 	edge_port->txCredits = 0;	/* Can't send any data yet */
+	edge_port->maxTxCredits = 0;
+	edge_port->openPending = true;
+	spin_unlock_irq(&edge_port->ep_lock);
+
 	/* Must always set this bit to enable ints! */
 	edge_port->shadowMCR = MCR_MASTER_IE;
 	edge_port->chaseResponsePending = false;
 
 	/* send a open port command */
-	edge_port->openPending = true;
 	response = send_iosp_ext_cmd(edge_port, IOSP_CMD_OPEN_PORT, 0);
 	if (response < 0) {
 		dev_err(dev, "%s - error sending open port command\n", __func__);
@@ -1736,6 +1740,7 @@ static void process_rcvd_status(struct e
 	struct edgeport_port *edge_port;
 	struct device *dev;
 	__u8 code = edge_serial->rxStatusCode;
+	unsigned long flags;
 
 	/* switch the port pointer to the one being currently talked about */
 	if (edge_serial->rxPort >= edge_serial->serial->num_ports)
@@ -1779,6 +1784,12 @@ static void process_rcvd_status(struct e
 	}
 
 	if (code == IOSP_STATUS_OPEN_RSP) {
+		spin_lock_irqsave(&edge_port->ep_lock, flags);
+		/* reject stray open responses to avoid FIFO corruption */
+		if (!edge_port->openPending) {
+			spin_unlock_irqrestore(&edge_port->ep_lock, flags);
+			return;
+		}
 		edge_port->txCredits = GET_TX_BUFFER_SIZE(byte3);
 		edge_port->maxTxCredits = edge_port->txCredits;
 		dev_dbg(dev, "%s - Port %u Open Response Initial MSR = %02x TxBufferSize = %d\n",
@@ -1787,6 +1798,8 @@ static void process_rcvd_status(struct e
 
 		/* we have completed the open */
 		edge_port->openPending = false;
+		spin_unlock_irqrestore(&edge_port->ep_lock, flags);
+
 		wake_up(&edge_port->wait_open);
 		return;
 	}
author maintainer
#962 lore raw

PATCH 961/1005 USB: serial: io_edgeport: fix potential use-after-free on disconnect

In reply to Greg Kroah-Hartman

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

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

From: Johan Hovold <[email protected]>

commit 50613e6380db7a904ef15c60ed0c436baf308f0a upstream.

The driver submits command URBs asynchronously but fails to stop them on disconnect, something which could lead to a use-after-free when accessing driver data in the completion handler after a port has been unbound.

Add an URB anchor to track and kill outstanding command URBs on disconnect.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
---
 drivers/usb/serial/io_edgeport.c |   19 ++++++-------------
 1 file changed, 6 insertions(+), 13 deletions(-)
drivers/usb/serial/io_edgeport.c +6 -13
@@ -225,6 +225,7 @@ struct edgeport_serial {
 	__u8			rxStatusParam;			/* the receive status parameter */
 	__s16			rxBytesRemaining;		/* the number of port bytes left to read */
 	struct usb_serial	*serial;			/* loop back to the owner of this object */
+	struct usb_anchor	cmd_anchor;
 };
 
 /* baud rate information */
@@ -261,9 +262,6 @@ static const struct divisor_table_entry
 	{   230400,	1},
 };
 
-/* Number of outstanding Command Write Urbs */
-static atomic_t CmdUrbs = ATOMIC_INIT(0);
-
 
 /* function prototypes */
 
@@ -776,11 +774,6 @@ static void edge_bulk_out_cmd_callback(s
 	struct device *dev = &urb->dev->dev;
 	int status = urb->status;
 
-	atomic_dec(&CmdUrbs);
-	dev_dbg(dev, "%s - FREE URB %p (outstanding %d)\n", __func__, urb,
-		atomic_read(&CmdUrbs));
-
-
 	/* clean up the transfer buffer */
 	kfree(urb->transfer_buffer);
 
@@ -2127,24 +2120,21 @@ static int write_cmd_usb(struct edgeport
 	if (!urb)
 		return -ENOMEM;
 
-	atomic_inc(&CmdUrbs);
-	dev_dbg(dev, "%s - ALLOCATE URB %p (outstanding %d)\n",
-		__func__, urb, atomic_read(&CmdUrbs));
-
 	usb_fill_bulk_urb(urb, edge_serial->serial->dev,
 			usb_sndbulkpipe(edge_serial->serial->dev,
 					edge_serial->bulk_out_endpoint),
 			buffer, length, edge_bulk_out_cmd_callback, edge_port);
 
 	edge_port->commandPending = true;
+	usb_anchor_urb(urb, &edge_serial->cmd_anchor);
 	status = usb_submit_urb(urb, GFP_ATOMIC);
 
 	if (status) {
 		/* something went wrong */
 		dev_err(dev, "%s - usb_submit_urb(write command) failed, status = %d\n",
 			__func__, status);
+		usb_unanchor_urb(urb);
 		usb_free_urb(urb);
-		atomic_dec(&CmdUrbs);
 		return status;
 	}
 
@@ -2696,6 +2686,7 @@ static int edge_startup(struct usb_seria
 
 	spin_lock_init(&edge_serial->es_lock);
 	edge_serial->serial = serial;
+	init_usb_anchor(&edge_serial->cmd_anchor);
 	usb_set_serial_data(serial, edge_serial);
 
 	/* get the name for the device from the device */
@@ -2900,6 +2891,8 @@ static void edge_disconnect(struct usb_s
 {
 	struct edgeport_serial *edge_serial = usb_get_serial_data(serial);
 
+	usb_kill_anchored_urbs(&edge_serial->cmd_anchor);
+
 	if (edge_serial->is_epic) {
 		usb_kill_urb(edge_serial->interrupt_read_urb);
 		usb_kill_urb(edge_serial->read_urb);
author maintainer
#963 lore raw

PATCH 962/1005 USB: serial: io_edgeport: serialise MCR accesses

In reply to Greg Kroah-Hartman

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

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

From: Johan Hovold <[email protected]>

commit 6e4629504d7e5a22dd26f3b262f0a0f80e3cad6a upstream.

Add a mutex to serialise modem control register updates to prevent concurrent tasks from interfering with each other.

Note that the register updates are currently asynchronous so a task may read back a value which has not yet taken effect.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
---
 drivers/usb/serial/io_edgeport.c |   15 +++++++++++++++
 1 file changed, 15 insertions(+)
drivers/usb/serial/io_edgeport.c +15 -0
@@ -168,6 +168,7 @@ struct edgeport_port {
 	struct urb		*write_urb;		/* write URB for this port */
 	bool			write_in_progress;	/* 'true' while a write URB is outstanding */
 	spinlock_t		ep_lock;
+	struct mutex		mutex;
 
 	__u8			shadowLCR;		/* last LCR value received */
 	__u8			shadowMCR;		/* last MCR value received */
@@ -877,7 +878,10 @@ static int edge_open(struct tty_struct *
 	spin_unlock_irq(&edge_port->ep_lock);
 
 	/* Must always set this bit to enable ints! */
+	mutex_lock(&edge_port->mutex);
 	edge_port->shadowMCR = MCR_MASTER_IE;
+	mutex_unlock(&edge_port->mutex);
+
 	edge_port->chaseResponsePending = false;
 
 	/* send a open port command */
@@ -1398,9 +1402,11 @@ static void edge_throttle(struct tty_str
 
 	/* if we are implementing RTS/CTS, toggle that line */
 	if (C_CRTSCTS(tty)) {
+		mutex_lock(&edge_port->mutex);
 		edge_port->shadowMCR &= ~MCR_RTS;
 		status = send_cmd_write_uart_register(edge_port, MCR,
 							edge_port->shadowMCR);
+		mutex_unlock(&edge_port->mutex);
 		if (status != 0)
 			return;
 	}
@@ -1435,9 +1441,11 @@ static void edge_unthrottle(struct tty_s
 	}
 	/* if we are implementing RTS/CTS, toggle that line */
 	if (C_CRTSCTS(tty)) {
+		mutex_lock(&edge_port->mutex);
 		edge_port->shadowMCR |= MCR_RTS;
 		send_cmd_write_uart_register(edge_port, MCR,
 						edge_port->shadowMCR);
+		mutex_unlock(&edge_port->mutex);
 	}
 }
 
@@ -1478,6 +1486,7 @@ static int edge_tiocmset(struct tty_stru
 	struct edgeport_port *edge_port = usb_get_serial_port_data(port);
 	unsigned int mcr;
 
+	mutex_lock(&edge_port->mutex);
 	mcr = edge_port->shadowMCR;
 	if (set & TIOCM_RTS)
 		mcr |= MCR_RTS;
@@ -1496,6 +1505,7 @@ static int edge_tiocmset(struct tty_stru
 	edge_port->shadowMCR = mcr;
 
 	send_cmd_write_uart_register(edge_port, MCR, edge_port->shadowMCR);
+	mutex_unlock(&edge_port->mutex);
 
 	return 0;
 }
@@ -1509,6 +1519,7 @@ static int edge_tiocmget(struct tty_stru
 	unsigned int mcr;
 
 	msr = edge_port->shadowMSR;
+	mutex_lock(&edge_port->mutex);
 	mcr = edge_port->shadowMCR;
 	result = ((mcr & MCR_DTR)	? TIOCM_DTR: 0)	  /* 0x002 */
 		  | ((mcr & MCR_RTS)	? TIOCM_RTS: 0)   /* 0x004 */
@@ -1516,6 +1527,7 @@ static int edge_tiocmget(struct tty_stru
 		  | ((msr & EDGEPORT_MSR_CD)	? TIOCM_CAR: 0)   /* 0x040 */
 		  | ((msr & EDGEPORT_MSR_RI)	? TIOCM_RI:  0)   /* 0x080 */
 		  | ((msr & EDGEPORT_MSR_DSR)	? TIOCM_DSR: 0);  /* 0x100 */
+	mutex_unlock(&edge_port->mutex);
 
 	return result;
 }
@@ -2430,12 +2442,14 @@ static void edge_set_termios(struct tty_
 		return;
 
 	/* set up the MCR register and send it to the EdgePort */
+	mutex_lock(&edge_port->mutex);
 	edge_port->shadowMCR = MCR_MASTER_IE;
 	if (cflag & CBAUD)
 		edge_port->shadowMCR |= (MCR_DTR | MCR_RTS);
 
 	status = send_cmd_write_uart_register(edge_port, MCR,
 						edge_port->shadowMCR);
+	mutex_unlock(&edge_port->mutex);
 	if (status != 0)
 		return;
 
@@ -2930,6 +2944,7 @@ static int edge_port_probe(struct usb_se
 		return -ENOMEM;
 
 	spin_lock_init(&edge_port->ep_lock);
+	mutex_init(&edge_port->mutex);
 
 	init_waitqueue_head(&edge_port->wait_open);
 	init_waitqueue_head(&edge_port->wait_chase);
author maintainer
#964 lore raw

PATCH 963/1005 dt-bindings: iio: adc: Add syscon property for multi-SCU SoCs

In reply to Greg Kroah-Hartman

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

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

From: Billy Tsai <[email protected]>

commit 6ec0623a7c77bc2c383e9971d7b0c9df3ec988fb upstream.

The ADC's reference-voltage trimming data lives in a System Control Unit (SCU) register. SoCs with a single SCU instance let the driver locate it without any additional information, but SoCs such as AST2700 that expose more than one SCU node need an explicit phandle to disambiguate which one holds the trimming data.

Add an "aspeed,trim-syscon" phandle property, and require it for the AST2700 compatibles since they are the first multi-SCU SoCs supported by this driver.

---
 Documentation/devicetree/bindings/iio/adc/aspeed,ast2600-adc.yaml |   17 ++++++++++
 1 file changed, 17 insertions(+)
Documentation/devicetree/bindings/iio/adc/aspeed,ast2600-adc.yaml +17 -0
@@ -67,6 +67,11 @@ properties:
     description:
       Inform the driver that last channel will be used to sensor battery.
 
+  aspeed,trim-syscon:
+    $ref: /schemas/types.yaml#/definitions/phandle
+    description:
+      Phandle to the SCU holding the ADC's reference-voltage trimming data.
+
 required:
   - compatible
   - reg
@@ -74,6 +79,18 @@ required:
   - resets
   - "#io-channel-cells"
 
+allOf:
+  - if:
+      properties:
+        compatible:
+          contains:
+            enum:
+              - aspeed,ast2700-adc0
+              - aspeed,ast2700-adc1
+    then:
+      required:
+        - aspeed,trim-syscon
+
 additionalProperties: false
 
 examples:
author maintainer
#965 lore raw

PATCH 964/1005 iio: accel: adxl313: add missing buffer selections in Kconfig

In reply to Greg Kroah-Hartman

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

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

From: Alexis Bouzigues <[email protected]>

commit 4e9f192f997dc56f309090233352d62edbea42ce upstream.

The FIFO support added to the ADXL313 core uses devm_iio_kfifo_buffer_setup() and iio_push_to_buffers(), but its Kconfig entry does not select the required buffer support. Enabling either frontend without IIO_BUFFER or IIO_KFIFO_BUF causes undefined references to devm_iio_kfifo_buffer_setup_ext() and iio_push_to_buffers().

Select IIO_BUFFER and IIO_KFIFO_BUF from the shared ADXL313 core symbol so both the I2C and SPI frontends have the required dependencies.

Fixes ff8093fa6ba4 ("iio: accel: adxl313: add buffered FIFO watermark with interrupt handling")
---
 drivers/iio/accel/Kconfig |    2 ++
 1 file changed, 2 insertions(+)
drivers/iio/accel/Kconfig +2 -0
@@ -32,6 +32,8 @@ config ADIS16209
 
 config ADXL313
 	tristate
+	select IIO_BUFFER
+	select IIO_KFIFO_BUF
 
 config ADXL313_I2C
 	tristate "Analog Devices ADXL313 3-Axis Digital Accelerometer I2C Driver"
author maintainer
#966 lore raw

PATCH 965/1005 iio: accel: kxsd9: Fix potential use-after-free on removal

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 fd7334314f63a3a2a4927f209b2ca0e33d111840 upstream.

Unregistering an IIO device with an active triggered buffer detaches its poll function. Freeing the poll function first can therefore make iio_device_unregister() access freed memory.

Unregister the device before cleaning up the triggered buffer.

This issue was found by our static analysis tool under development.

Fixes 0427a106a98a ("iio: accel: kxsd9: Add triggered buffer handling")
---
 drivers/iio/accel/kxsd9.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/iio/accel/kxsd9.c +1 -1
@@ -478,8 +478,8 @@ void kxsd9_common_remove(struct device *
 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
 	struct kxsd9_state *st = iio_priv(indio_dev);
 
-	iio_triggered_buffer_cleanup(indio_dev);
 	iio_device_unregister(indio_dev);
+	iio_triggered_buffer_cleanup(indio_dev);
 	pm_runtime_get_sync(dev);
 	pm_runtime_put_noidle(dev);
 	pm_runtime_disable(dev);