Skip to contentSkip to conversation

7.3.6-rc1 review

PATCH Applied Greg Kroah-Hartman 21 participants 2,693 messages Nov 18 – Nov 21 Page 17 of 20

Subsystems (4)
lore
Share & tools
lore
author maintainer
#2192 lore raw

PATCH 2172/2651 ALSA: pcm: Protect channel-map reads against runtime detach

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit bb4834d5242c4829c0d8467ee68eb25a9bafc38d ]

Channel-map controls remain accessible between PCM opens. In-tree HDA code publishes the generic controls through add_std_chmaps(), so a SNDRV_CTL_IOCTL_ELEM_READ can overlap the final close of the same PCM substream.

pcm_chmap_ctl_get() checks substream->runtime and later reads its channel count. Final close clears and frees that runtime under pcm->open_mutex, while the control callback holds only controls_rwsem:

Control GET Final PCM close
----------- ---------------
snd_ctl_elem_read()

    down_read(controls_rwsem)
    pcm_chmap_ctl_get()
      check substream->runtime
                                      lock(pcm->open_mutex)
                                      snd_pcm_release_substream()
                                        snd_pcm_detach_substream()
                                          substream->runtime = NULL
                                          kfree(runtime)
                                      unlock(pcm->open_mutex)
      substream->runtime->channels
        NULL or freed-pointer access
    up_read(controls_rwsem)

Reloading the cleared field can fault through NULL, while retaining the old pointer can access freed storage. controls_rwsem keeps the control alive, but does not serialize the matching PCM close.

Copy the channel count under open_mutex and use that scalar for the map lookup. Use trylock with -EBUSY because snd_pcm_dev_disconnect() takes open_mutex before removing controls under controls_rwsem; blocking in the reverse order from GET could deadlock.

Fixes 2d3391ec0ecc ("ALSA: PCM: channel mapping API implementation")
Assisted-by LLM
---
 sound/core/pcm_lib.c | 16 +++++++++++++---
 1 file changed, 13 insertions(+), 3 deletions(-)
sound/core/pcm_lib.c +13 -3
index 4d665b4148d70..1ec7db324196f 100644
@@ -2496,6 +2496,7 @@ static int pcm_chmap_ctl_get(struct snd_kcontrol *kcontrol,
 	unsigned int idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id);
 	struct snd_pcm_substream *substream;
 	const struct snd_pcm_chmap_elem *map;
+	unsigned int channels;
 
 	if (!info->chmap)
 		return -EINVAL;
@@ -2504,11 +2505,20 @@ static int pcm_chmap_ctl_get(struct snd_kcontrol *kcontrol,
 		return -ENODEV;
 	memset(ucontrol->value.integer.value, 0,
 	       sizeof(long) * info->max_channels);
-	if (!substream->runtime)
-		return 0; /* no channels set */
+	/*
+	 * PCM disconnect takes open_mutex before removing controls.
+	 * Use trylock to avoid a deadlock with controls_rwsem.
+	 */
+	scoped_cond_guard(mutex_try, return -EBUSY,
+			  &info->pcm->open_mutex) {
+		if (!substream->runtime)
+			return 0; /* no channels set */
+		channels = substream->runtime->channels;
+	}
 	for (map = info->chmap; map->channels; map++) {
 		int i;
-		if (map->channels == substream->runtime->channels &&
+
+		if (map->channels == channels &&
 		    valid_chmap_channels(info, map->channels)) {
 			for (i = 0; i < map->channels; i++)
 				ucontrol->value.integer.value[i] = map->map[i];
Signature · 1 line
2.53.0
author maintainer
#2193 lore raw

PATCH 2173/2651 f2fs: refresh pinned allocation boundary after resize

In reply to Greg Kroah-Hartman

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

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

From: Wenjie Qi <[email protected]>

[ Upstream commit e4df12e37300d4e181ae76746ae0fd7f7b92aa36 ]

Online shrink updates MAIN_SECS() but leaves resizable_tail_secno and pinned_area_max_secno unchanged. The pinned allocation limit can exceed the new main area when shrinking beyond the reserved tail.

Consume the reserved tail by the number of removed sections, clamping it to zero, before refreshing the shared pinned allocation boundary. This preserves the boundary while shrinking within the reservation and limits it to the new main area otherwise, retaining the zoned limit.

Save the old tail count and restore it before rolling back the geometry if the final checkpoint fails.

Also bound pinned section allocation by the current MAIN_SECS(). Range evacuation temporarily reduces it before moving cursegs, while the cached pinned boundary still describes the old geometry. Otherwise, a pinned curseg can be reallocated into the range being removed.

Fixes c966d29e01bb ("f2fs: support resizable tail section and unify pinned allocation")
---
 Documentation/filesystems/f2fs.rst |  3 ++-
 fs/f2fs/gc.c                       |  6 +++++-
 fs/f2fs/segment.c                  |  2 +-
 fs/f2fs/segment.h                  | 11 +++++++++++
 fs/f2fs/super.c                    | 15 ++-------------
 5 files changed, 21 insertions(+), 16 deletions(-)
Documentation/filesystems/f2fs.rst +2 -1
index 771216f45207a..55798421f2c45 100644
@@ -421,7 +421,8 @@ resizable_tail_secno=%u  Control the number of sections at the tail of the
 			 (MAIN_SECS - resizable_tail_secno) - 1. If set to 0
 			 (default), there is no tail restriction unless running
 			 on a zoned block device where conventional zones are
-			 used.
+			 used. Online shrink consumes this reservation, reducing
+			 the value by the number of removed sections, down to zero.
 ======================== ============================================================
 
 Debugfs Entries
fs/f2fs/gc.c +5 -1
index 6220d55709e9c..8d620799df121 100644
@@ -2323,6 +2323,7 @@ static void update_fs_metadata(struct f2fs_sb_info *sbi, int secs)
 	SM_I(sbi)->segment_count = (int)SM_I(sbi)->segment_count + segs;
 	MAIN_SEGS(sbi) = (int)MAIN_SEGS(sbi) + segs;
 	MAIN_SECS(sbi) += secs;
+	f2fs_adjust_pinned_area_boundary(sbi);
 	if (sbi->allocate_section_hint > MAIN_SECS(sbi))
 		sbi->allocate_section_hint = MAIN_SECS(sbi);
 	FREE_I(sbi)->free_sections = (int)FREE_I(sbi)->free_sections + secs;
@@ -2354,7 +2355,7 @@ int f2fs_resize_fs(struct file *filp, __u64 block_count)
 	struct f2fs_lock_context lc;
 	struct f2fs_lock_context glc;
 	struct f2fs_lock_context clc;
-	unsigned int secs;
+	unsigned int secs, old_tail;
 	int err = 0;
 	__u32 rem;
 
@@ -2463,6 +2464,8 @@ int f2fs_resize_fs(struct file *filp, __u64 block_count)
 		goto recover_out;
 	}
 
+	old_tail = F2FS_OPTION(sbi).resizable_tail_secno;
+	F2FS_OPTION(sbi).resizable_tail_secno -= min(old_tail, secs);
 	update_fs_metadata(sbi, -secs);
 	clear_sbi_flag(sbi, SBI_IS_RESIZEFS);
 	set_sbi_flag(sbi, SBI_IS_DIRTY);
@@ -2470,6 +2473,7 @@ int f2fs_resize_fs(struct file *filp, __u64 block_count)
 	stat_inc_cp_call_count(sbi, TOTAL_CALL);
 	err = f2fs_write_checkpoint(sbi, &cpc);
 	if (err) {
+		F2FS_OPTION(sbi).resizable_tail_secno = old_tail;
 		update_fs_metadata(sbi, secs);
 		update_sb_metadata(sbi, secs);
 		f2fs_commit_super(sbi, false);
fs/f2fs/segment.c +1 -1
index 75f78ed7eb909..c1d78939ce845 100644
@@ -2980,7 +2980,7 @@ static int get_new_segment(struct f2fs_sb_info *sbi,
 		alloc_hint = MAIN_SECS(sbi);
 
 	if (pinning) {
-		max_secno = sbi->pinned_area_max_secno;
+		max_secno = min(sbi->pinned_area_max_secno, MAIN_SECS(sbi));
 		hint = 0;
 	} else if (alloc_policy == ALLOCATE_FORWARD_FROM_HINT &&
 		hint < alloc_hint) {
fs/f2fs/segment.h +11 -0
index 5949aa5200ac1..6c3af51f352c4 100644
@@ -91,6 +91,17 @@ static inline void sanity_check_seg_type(struct f2fs_sb_info *sbi,
 #define GET_ZONE_FROM_SEG(sbi, segno)				\
 	GET_ZONE_FROM_SEC(sbi, GET_SEC_FROM_SEG(sbi, segno))
 
+static inline void f2fs_adjust_pinned_area_boundary(struct f2fs_sb_info *sbi)
+{
+	sbi->pinned_area_max_secno = MAIN_SECS(sbi);
+	if (f2fs_sb_has_blkzoned(sbi) && sbi->first_seq_zone_segno != NULL_SEGNO)
+		sbi->pinned_area_max_secno = min(sbi->pinned_area_max_secno,
+				GET_SEC_FROM_SEG(sbi, sbi->first_seq_zone_segno));
+	if (F2FS_OPTION(sbi).resizable_tail_secno)
+		sbi->pinned_area_max_secno = min(sbi->pinned_area_max_secno,
+				MAIN_SECS(sbi) - F2FS_OPTION(sbi).resizable_tail_secno);
+}
+
 #define GET_SUM_BLOCK(sbi, segno)	\
 	(SM_I(sbi)->ssa_blkaddr + (segno / (sbi)->sums_per_block))
 #define GET_SUM_BLKOFF(sbi, segno) (segno % (sbi)->sums_per_block)
fs/f2fs/super.c +2 -13
index 09bc78f2d0b58..c422a0d15260c 100644
@@ -554,17 +554,6 @@ static inline void adjust_unusable_cap_perc(struct f2fs_sb_info *sbi)
 			F2FS_OPTION(sbi).unusable_cap_perc);
 }
 
-static inline void adjust_pinned_area_boundary(struct f2fs_sb_info *sbi)
-{
-	sbi->pinned_area_max_secno = MAIN_SECS(sbi);
-	if (f2fs_sb_has_blkzoned(sbi) && sbi->first_seq_zone_segno != NULL_SEGNO)
-		sbi->pinned_area_max_secno = min(sbi->pinned_area_max_secno,
-				GET_SEC_FROM_SEG(sbi, sbi->first_seq_zone_segno));
-	if (F2FS_OPTION(sbi).resizable_tail_secno)
-		sbi->pinned_area_max_secno = min(sbi->pinned_area_max_secno,
-				MAIN_SECS(sbi) - F2FS_OPTION(sbi).resizable_tail_secno);
-}
-
 static void init_once(void *foo)
 {
 	struct f2fs_inode_info *fi = (struct f2fs_inode_info *) foo;
@@ -3098,7 +3087,7 @@ static int __f2fs_remount(struct fs_context *fc, struct super_block *sb)
 	sb->s_flags = (sb->s_flags & ~SB_POSIXACL) |
 		(test_opt(sbi, POSIX_ACL) ? SB_POSIXACL : 0);
 
-	adjust_pinned_area_boundary(sbi);
+	f2fs_adjust_pinned_area_boundary(sbi);
 	limit_reserve_root(sbi);
 	fc->sb_flags = (flags & ~SB_LAZYTIME) | (sb->s_flags & SB_LAZYTIME);
 
@@ -5414,7 +5403,7 @@ static int f2fs_fill_super(struct super_block *sb, struct fs_context *fc)
 	/* get segno of first zoned block device */
 	sbi->first_seq_zone_segno = get_first_seq_zone_segno(sbi);
 
-	adjust_pinned_area_boundary(sbi);
+	f2fs_adjust_pinned_area_boundary(sbi);
 
 	sbi->reserved_pin_section = f2fs_sb_has_blkzoned(sbi) ?
 			ZONED_PIN_SEC_REQUIRED_COUNT :
Signature · 1 line
2.53.0
author maintainer
#2194 lore raw

PATCH 2174/2651 nfsv4/pnfs: use the MDS authflavor for data server connections

In reply to Greg Kroah-Hartman

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

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

From: Tigran Mkrtchyan <[email protected]>

[ Upstream commit 4b27670ea25b955b710021151471cb252240b1e0 ]

When a pNFS client connects to an NFSv4.1 data server, the EXCHANGE_ID is always attempted with RPCSEC_GSS krb5i first, even if the auth flavor with the MDS is AUTH_SYS. On a host that runs rpc.gssd but has no usable machine credential, every first contact with a data server therefore upcalls to rpc.gssd before falling back to AUTH_SYS.

As nfs4_discover_server_trunking is serialized by nfs_clid_init_mutex such an extra upcall creates a backlog of DS connections when many files accessed in parallel.

Pass the authflavor of the MDS lease to nfs4_alloc_client() and skip the krb5i attempt if the MDS already ended up with AUTH_SYS. Nothing changes for the MDS itself, or for data servers of an MDS whose lease was established with krb5i.

Fixes 4edaa308888b ("NFS: Use "krb5i" to establish NFSv4 state whenever possible")
---
 fs/nfs/internal.h   | 1 +
 fs/nfs/nfs4client.c | 7 ++++++-
 2 files changed, 7 insertions(+), 1 deletion(-)
fs/nfs/internal.h +1 -0
index 5a1967f9e319e..ec0b1289864f2 100644
@@ -86,6 +86,7 @@ struct nfs_client_initdata {
 	struct xprtsec_parms xprtsec;
 	unsigned long connect_timeout;
 	unsigned long reconnect_timeout;
+	rpc_authflavor_t authflavor;		/* Auth flavor to use for DS connection */
 };
 
 /*
fs/nfs/nfs4client.c +6 -1
index b661f446ea49e..e7b379f4b4d4b 100644
@@ -229,8 +229,12 @@ struct nfs_client *nfs4_alloc_client(const struct nfs_client_initdata *cl_init)
 	/*
 	 * Set up the connection to the server before we add add to the
 	 * global list.
+	 *
+	 * Prefer krb5i unless the caller already knows AUTH_UNIX is required.
 	 */
-	err = nfs_create_rpc_client(clp, cl_init, RPC_AUTH_GSS_KRB5I);
+	err = -EINVAL;
+	if (cl_init->authflavor != RPC_AUTH_UNIX)
+		err = nfs_create_rpc_client(clp, cl_init, RPC_AUTH_GSS_KRB5I);
 	if (err == -EINVAL)
 		err = nfs_create_rpc_client(clp, cl_init, RPC_AUTH_UNIX);
 	if (err < 0)
@@ -812,6 +816,7 @@ struct nfs_client *nfs4_set_ds_client(struct nfs_server *mds_srv,
 			.cert_serial = TLS_NO_CERT,
 			.privkey_serial = TLS_NO_PRIVKEY,
 		},
+		.authflavor = mds_clp->cl_rpcclient->cl_auth->au_flavor,
 	};
 	char buf[INET6_ADDRSTRLEN + 1];
 
Signature · 1 line
2.53.0
author maintainer
#2195 lore raw

PATCH 2175/2651 pNFS/flexfiles: make pg_init retry loops killable

In reply to Greg Kroah-Hartman

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

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

From: Tigran Mkrtchyan <[email protected]>

[ Upstream commit fde27289503beabe7e0856dac164a5ced4be0342 ]

When a task is killed while the pNFS client connects to a data server, nfs4_pnfs_ds_connect() fails with -ERESTARTSYS. If the layout has FF_FLAGS_NO_IO_THRU_MDS set, ff_layout_pg_init_read() cannot fall back to the MDS and retries after an uninterruptible ssleep. As the fatal signal stays pending, every new connect attempt is aborted the same way and the task loops forever without returning to user space:

  # grep -E 'SigPnd|ShdPnd' /proc/156021/status
  SigPnd: 0000000000000100
  ShdPnd: 0000000000000100
  # cat /proc/156021/stack
  msleep+0x2e/0x50
  ff_layout_pg_init_read+0x267/0x310 [nfs_layout_flexfiles]
  __nfs_pageio_add_request+0x1c1/0x480 [nfs]
  nfs_pageio_add_request+0x21d/0x2c0 [nfs]
  nfs_read_add_folio+0x143/0x200 [nfs]
  nfs_readahead+0x204/0x290 [nfs]
  read_pages+0x62/0x230
  page_cache_ra_unbounded+0x136/0x180
  filemap_get_pages+0xf2/0x350
  filemap_read+0xd5/0x320
  nfs_file_read+0x6d/0xc0 [nfs]
  vfs_read+0x24f/0x3a0
  __x64_sys_pread64+0x90/0xc0
  do_syscall_64+0x5f/0xe0

Previous attempt propagates the error from nfs4_ff_layout_prepare_ds(), but only ff_layout_{read,write}_pagelist() look at it. The pg_init functions test IS_ERR() and retry on any error.

Check for a fatal signal or an exiting task before sleeping in ff_layout_pg_init_read() and ff_layout_pg_init_write() and fail the I/O instead of retrying.

Fixes f06bedfa62d5 ("pNFS/flexfiles: don't attempt pnfs on fatal DS errors")
---
 fs/nfs/flexfilelayout/flexfilelayout.c | 23 ++++++++++++++++++++---
 1 file changed, 20 insertions(+), 3 deletions(-)
fs/nfs/flexfilelayout/flexfilelayout.c +20 -3
index 257c81ee47adb..989f30e7d9509 100644
@@ -964,6 +964,20 @@ ff_layout_get_ds_for_read(struct nfs_pageio_descriptor *pgio,
 						 offset, dss_id);
 }
 
+/*
+ * Wait before retrying pg_init. Returns false, with pgio->pg_error set,
+ * if the task was killed or is exiting and must not retry.
+ */
+static bool ff_layout_pg_retry_wait(struct nfs_pageio_descriptor *pgio)
+{
+	if (fatal_signal_pending(current) || nfs_current_task_exiting()) {
+		pgio->pg_error = -ERESTARTSYS;
+		return false;
+	}
+	ssleep(1);
+	return true;
+}
+
 static void
 ff_layout_pg_get_read(struct nfs_pageio_descriptor *pgio,
 		      struct nfs_page *req,
@@ -1064,7 +1078,8 @@ ff_layout_pg_init_read(struct nfs_pageio_descriptor *pgio,
 			goto out_mds;
 		pnfs_generic_pg_cleanup(pgio);
 		/* Sleep for 1 second before retrying */
-		ssleep(1);
+		if (!ff_layout_pg_retry_wait(pgio))
+			return;
 		goto retry;
 	}
 
@@ -1103,7 +1118,8 @@ ff_layout_pg_init_read(struct nfs_pageio_descriptor *pgio,
 	}
 	pgio->pg_error = 0;
 	/* Sleep for 1 second before retrying */
-	ssleep(1);
+	if (!ff_layout_pg_retry_wait(pgio))
+		return;
 	goto retry;
 out_mds:
 	trace_pnfs_mds_fallback_pg_init_read(pgio->pg_inode,
@@ -1157,7 +1173,8 @@ ff_layout_pg_init_write(struct nfs_pageio_descriptor *pgio,
 				goto out_mds;
 			pnfs_generic_pg_cleanup(pgio);
 			/* Sleep for 1 second before retrying */
-			ssleep(1);
+			if (!ff_layout_pg_retry_wait(pgio))
+				return;
 			goto retry;
 		}
 		pgm = &pgio->pg_mirrors[i];
Signature · 1 line
2.53.0
author maintainer
#2196 lore raw

PATCH 2176/2651 nfs/localio: pin UUIDs during global invalidation

In reply to Greg Kroah-Hartman

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

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

From: Jinpyo Lee <[email protected]>

[ Upstream commit 62e14699c4dfc98c514a44bf780678cf8622fc08 ]

nfs_localio_invalidate_clients() moves UUID nodes embedded in nfs_client objects to a private list, then walks that list without retaining the containing clients. Concurrent client teardown can free an entry that the iterator has already selected, causing a use-after-free.

Take a reference to each selected UUID under the namespace list lock. Keep this reference count in nfs_common, independently of cl_count, and have nfs_free_client() drain temporary UUID users before freeing the client. Releasing a UUID reference wakes waiting probes and signals completion when the last reference is dropped. It neither calls into nfs.ko nor performs final NFS client teardown in the NFSD invalidation context.

Keep the UUID on the namespace list until its files have been closed. When another thread is already disabling it, wait for that thread to finish unlinking it instead of repeatedly selecting the same head entry. The wait releases the UUID spinlock so file cleanup can make progress.

Append registrations in sequence order and capture the last sequence under the namespace list lock at the start of invalidation. Stop at that boundary so new registrations cannot indefinitely extend the sweep, even if its original last entry is removed concurrently.

Publish the LOCALIO association under the UUID and namespace list locks before making the entry visible to invalidation. A temporary UUID reference allows the handshake to drop the global lookup lock before taking the UUID lock in the documented order; recheck the lookup in case the probe was withdrawn. A new probe waits for temporary UUID users to drain, then rechecks the association before reusing the UUID. This keeps a transient invalidation reference from discarding the client's LOCALIO revalidation attempt. Withdraw pending probes before dropping the owner's UUID reference.

A deterministic same-base KASAN reproducer triggered the reported use-after-free on the unpatched tree. With this patch, the same controlled invalidation and teardown race completed without the target KASAN report or another selected kernel diagnostic. A separate all-live run recorded disable events for all 16 unique clients.

Test-only synchronization hooks verified that a second disabler waits for unlink after ->net is cleared and that client teardown waits for a temporary UUID reference to drain. NFSv4.2 and NFSv3 read, write, and unmount smoke tests, export-flush and I/O stress, NFSD restarts, network namespace lifecycle tests, and module unloads passed with KASAN and lockdep enabled.

A full x86_64 kernel and modules build with GCC 13.3, CONFIG_WERROR=y, NFS_FS=m, NFSD=m, and LOCALIO enabled completed without diagnostics. Module metadata showed that nfs_localio.ko depends only on sunrpc, while nfs.ko depends on lockd, nfs_localio, and sunrpc.

A separate NFS_FS=m, NFSD=y build also linked vmlinux successfully.

The vulnerability research and validation were conducted by members of the Tobabz team as part of the Best of the Best 15th program.

Fixes 085804110aa1 ("nfs_common: track all open nfsd_files per LOCALIO nfs_client")
Assisted-by LLM
---
 fs/nfs/client.c            |   2 +-
 fs/nfs_common/nfslocalio.c | 101 +++++++++++++++++++++++++++++++------
 include/linux/nfslocalio.h |  12 +++++
 3 files changed, 98 insertions(+), 17 deletions(-)
fs/nfs/client.c +1 -1
index 60386330aeeca..d85711edecbfc 100644
@@ -256,7 +256,7 @@ static void pnfs_init_server(struct nfs_server *server)
  */
 void nfs_free_client(struct nfs_client *clp)
 {
-	nfs_localio_disable_client(clp);
+	nfs_localio_free_client(clp);
 
 	/* -EIO all pending I/O */
 	if (!IS_ERR(clp->cl_rpcclient))
fs/nfs_common/nfslocalio.c +85 -16

173 lines not on this page · raw message

include/linux/nfslocalio.h +12 -0
index 3d91043254e64..1a8cfb045abc7 100644
@@ -8,8 +8,10 @@
 
 #if IS_ENABLED(CONFIG_NFS_LOCALIO)
 
+#include <linux/completion.h>
 #include <linux/module.h>
 #include <linux/list.h>
+#include <linux/refcount.h>
 #include <linux/uuid.h>
 #include <linux/sunrpc/clnt.h>
 #include <linux/sunrpc/svcauth.h>
@@ -28,6 +30,11 @@ struct nfs_file_localio;
 typedef struct {
 	uuid_t uuid;
 	unsigned nfs3_localio_probe_count;
+	/* Owner reference plus temporary references held by nfs_common */
+	refcount_t refs;
+	struct completion released;
+	/* Namespace registration order, protected by list_lock */
+	u64 seq;
 	/* this struct is over a cacheline, avoid bouncing */
 	spinlock_t ____cacheline_aligned lock;
 	struct list_head list;
@@ -46,6 +53,7 @@ void nfs_uuid_is_local(const uuid_t *, struct list_head *, spinlock_t *,
 
 void nfs_localio_enable_client(struct nfs_client *clp);
 void nfs_localio_disable_client(struct nfs_client *clp);
+void nfs_localio_free_client(struct nfs_client *clp);
 void nfs_localio_invalidate_clients(struct list_head *nn_local_clients,
 				    spinlock_t *nn_local_clients_lock);
 
@@ -118,6 +126,10 @@ static inline void nfs_localio_disable_client(struct nfs_client *clp)
 {
 }
 
+static inline void nfs_localio_free_client(struct nfs_client *clp)
+{
+}
+
 #endif  /* CONFIG_NFS_LOCALIO */
 
 #endif  /* __LINUX_NFSLOCALIO_H */
Signature · 1 line
2.53.0
author maintainer
#2197 lore raw

PATCH 2177/2651 PCI: rcar-gen4: Add missing PM ops

In reply to Greg Kroah-Hartman

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

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

From: Marek Vasut <[email protected]>

[ Upstream commit 6b8c12d354dfa9c80d82eea8c0c45d331a28be11 ]

The R-Car Gen4 PCIe controller is part of a power domain. On R-Car S4 and V4H, this is an always-on power domain which is not shut down in suspend. On R-Car V4M, this is a dedicated A2PCIPHY power domain, which is shut down during suspend, and the controller loses state, which prevents the PCIe from working after resume.

Fix this by adding generic suspend/resume noirq ops for the controller, which tear the link down on suspend, and restart it on resume. Use the same PM ops on all of R-Car Gen4 to gracefully suspend and resume the PCIe link on V4H and S4 too.

Test case which demonstrates the problem on R-Car V4M:

  $ hexdump -vC /sys/bus/pci/devices/0000:00:00.0/config > /tmp/pre
  $ echo s2idle > /sys/power/mem_sleep
  $ echo platform > /sys/power/pm_test
  $ echo mem > /sys/power/state
  $ hexdump -vC /sys/bus/pci/devices/0000:00:00.0/config > /tmp/post
  $ diff -Naru /tmp/pre /tmp/post
  ...
  -00000000  12 19 32 00 07 05 10 00  00 00 04 06 00 00 01 00
  +00000000  12 19 32 00 07 05 10 00  00 00 00 ff 00 00 80 00
                                            ^^^^^
                                      Class 0604->00ff
---
 drivers/pci/controller/dwc/pcie-rcar-gen4.c | 27 +++++++++++++++++++++
 1 file changed, 27 insertions(+)
drivers/pci/controller/dwc/pcie-rcar-gen4.c +27 -0
index 241adcd727894..964b45f8f9b7c 100644
@@ -524,6 +524,8 @@ static int rcar_gen4_add_dw_pcie_rp(struct rcar_gen4_pcie *rcar)
 		return -ENODEV;
 
 	pp->num_vectors = MAX_MSI_IRQS;
+	/* Reserve an iATU window for the generic PME_Turn_Off implementation. */
+	pp->use_atu_msg = true;
 	pp->ops = &rcar_gen4_pcie_host_ops;
 
 	return dw_pcie_host_init(pp);
@@ -903,6 +905,26 @@ static int rcar_gen4_pcie_ltssm_control(struct rcar_gen4_pcie *rcar, bool enable
 	return 0;
 }
 
+static int rcar_gen4_pcie_suspend_noirq(struct device *dev)
+{
+	struct rcar_gen4_pcie *rcar = dev_get_drvdata(dev);
+
+	if (rcar->drvdata->mode != DW_PCIE_RC_TYPE)
+		return 0;
+
+	return dw_pcie_suspend_noirq(&rcar->dw);
+}
+
+static int rcar_gen4_pcie_resume_noirq(struct device *dev)
+{
+	struct rcar_gen4_pcie *rcar = dev_get_drvdata(dev);
+
+	if (rcar->drvdata->mode != DW_PCIE_RC_TYPE)
+		return 0;
+
+	return dw_pcie_resume_noirq(&rcar->dw);
+}
+
 static struct rcar_gen4_pcie_drvdata drvdata_r8a779f0_pcie = {
 	.ltssm_control = r8a779f0_pcie_ltssm_control,
 	.mode = DW_PCIE_RC_TYPE,
@@ -946,10 +968,15 @@ static const struct of_device_id rcar_gen4_pcie_of_match[] = {
 };
 MODULE_DEVICE_TABLE(of, rcar_gen4_pcie_of_match);
 
+static DEFINE_NOIRQ_DEV_PM_OPS(rcar_gen4_pcie_pm_ops,
+			       rcar_gen4_pcie_suspend_noirq,
+			       rcar_gen4_pcie_resume_noirq);
+
 static struct platform_driver rcar_gen4_pcie_driver = {
 	.driver = {
 		.name = "pcie-rcar-gen4",
 		.of_match_table = rcar_gen4_pcie_of_match,
+		.pm = pm_sleep_ptr(&rcar_gen4_pcie_pm_ops),
 		.probe_type = PROBE_PREFER_ASYNCHRONOUS,
 	},
 	.probe = rcar_gen4_pcie_probe,
Signature · 1 line
2.53.0
author maintainer
#2198 lore raw

PATCH 2178/2651 ALSA: aloop: Keep shared timer callbacks alive through close

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit a7d4d780f34b9e43eefab6a7e6c9f4101f2c144e ]

The shared sound-timer callback must finish using the selected PCM runtimes before a close can detach them. loopback_snd_timer_period_elapsed() saves the active substreams under cable->lock, then drops the lock before calling snd_pcm_period_elapsed() or snd_pcm_stop_xrun(). The sound-timer backend has no per-stream close drain, and free_cable() keeps the timer open when the paired endpoint remains attached.

With both directions running on a shared sound timer, playback can be dropped and closed while a notification is pending. Capture keeps the timer alive, allowing this order:

Timer callback Playback owner
-------------- --------------
select playback under cable->lock
unlock; delay notification

                                       DROP; HW_FREE -> OPEN
                                       close: snd_pcm_drop(); unlock
                                       free_cable(); peer stays alive

snd_pcm_period_elapsed()
lock stream; cache runtime
snd_pcm_detach_substream()
free runtime and its fasync
read runtime->fasync

The stream lock taken by snd_pcm_drop() cannot protect a notification that starts after it returns, and detach does not take it. The callback can therefore read runtime->fasync after the runtime has been freed, and an escaped notification can also reach a replacement runtime if the same substream slot is reopened before the notification resumes.

Take the existing cable->stop_count reference under cable->lock when selecting the targets and release it after the PCM callbacks finish, including the XRUN path. free_cable() already removes the closing endpoint under that lock and waits for stop_count before returning, so runtime detach and slot reuse cannot overtake the notification.

Fixes 26c53379f98d ("ALSA: aloop: Support selection of snd_timer instead of jiffies")
Assisted-by LLM
---
 sound/drivers/aloop.c | 11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)
sound/drivers/aloop.c +8 -3
index ba690bdd93736..4d05accb838ca 100644
@@ -100,7 +100,7 @@ struct loopback_ops {
 struct loopback_cable {
 	spinlock_t lock;
 	struct loopback_pcm *streams[2];
-	/* in-flight peer stops running outside cable->lock */
+	/* in-flight PCM callbacks running outside cable->lock */
 	struct snd_refcount stop_count;
 	struct snd_pcm_hardware hw;
 	/* flags */
@@ -876,6 +876,8 @@ static void loopback_snd_timer_period_elapsed(struct loopback_cable *cable,
 		valid_runtime = (running & (1 << SNDRV_PCM_STREAM_PLAYBACK)) ?
 			dpcm_play->substream->runtime :
 			dpcm_capt->substream->runtime;
+		/* Keep runtimes alive through the PCM callbacks. */
+		snd_refcount_get(&cable->stop_count);
 
 		/* resolution is only valid for SNDRV_TIMER_EVENT_TICK events */
 		if (event == SNDRV_TIMER_EVENT_TICK) {
@@ -911,13 +913,16 @@ static void loopback_snd_timer_period_elapsed(struct loopback_cable *cable,
 			snd_pcm_stop_xrun(substream_play);
 		if (substream_capt)
 			snd_pcm_stop_xrun(substream_capt);
-		return;
+		goto exit;
 	}
 
 	if (substream_play)
 		snd_pcm_period_elapsed(substream_play);
 	if (substream_capt)
 		snd_pcm_period_elapsed(substream_capt);
+
+exit:
+	snd_refcount_put(&cable->stop_count);
 }
 
 static void loopback_snd_timer_function(struct snd_timer_instance *timeri,
@@ -1177,7 +1182,7 @@ static void free_cable(struct snd_pcm_substream *substream)
 		other_alive = cable->streams[!substream->stream];
 	}
 
-	/* Pair with the stop_count increment in loopback_check_format(). */
+	/* Wait for PCM callbacks running outside cable->lock. */
 	snd_refcount_sync(&cable->stop_count);
 	if (other_alive)
 		return;
Signature · 1 line
2.53.0
author maintainer
#2199 lore raw

PATCH 2179/2651 ALSA: aloop: Keep the timer source alive until card release

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit 762ef425cf0ac9c4b9e9e61e0da0950e16e6fbea ]

The timer_source string must remain valid while PCM opens can select and parse it. loopback_set_timer_source() allocates the string with parent-device devres, which can release it while the card is still registered.

A successful nonempty proc replacement after snd_card_register() adds the string allocation after trigger_card_free. Unbinding the platform device while snd_aloop remains loaded releases devres in reverse order. An open for an unused cable can run after the string is freed and before the card-free action disconnects the card:

Device unbind PCM open
devres_release_all()

    free replacement string
                                     snd_pcm_open()
                                       snd_card_file_add()
                                       loopback_open()
                                         loopback_snd_timer_open()
                                           loopback_parse_timer_id()
    trigger_card_free()
      snd_card_free()
        snd_card_disconnect()

The parser can then read freed memory. KASAN has reported a one-byte use-after-free read in strchr() from loopback_snd_timer_open(). The cable_lock mutex serializes explicit replacements with opens, but implicit devres release does not take it. The card and module references held by PCM open do not retain this separate devres allocation.

Use kstrdup() and release the current string from card->private_free. PCM admission already retains the card until each file is removed, and card disconnect drains proc callbacks before final card release. This keeps the string alive across admitted PCM opens and preserves the cable_lock serialization of replacements. Install the callback before the initial allocation so probe failures also release the string.

Fixes b072e65aadd6 ("ALSA: aloop: Allocate resources with device-managed APIs")
Assisted-by LLM
---
 sound/drivers/aloop.c | 17 +++++++++++------
 1 file changed, 11 insertions(+), 6 deletions(-)
sound/drivers/aloop.c +11 -6
index 4d05accb838ca..824d320b665bf 100644
@@ -1905,13 +1905,10 @@ static int loopback_cable_proc_new(struct loopback *loopback, int cidx)
 static void loopback_set_timer_source(struct loopback *loopback,
 				      const char *value)
 {
-	if (loopback->timer_source) {
-		devm_kfree(loopback->card->dev, loopback->timer_source);
-		loopback->timer_source = NULL;
-	}
+	kfree(loopback->timer_source);
+	loopback->timer_source = NULL;
 	if (value && *value)
-		loopback->timer_source = devm_kstrdup(loopback->card->dev,
-						      value, GFP_KERNEL);
+		loopback->timer_source = kstrdup(value, GFP_KERNEL);
 }
 
 static void print_timer_source_info(struct snd_info_entry *entry,
@@ -1942,6 +1939,13 @@ static int loopback_timer_source_proc_new(struct loopback *loopback)
 				    change_timer_source_info);
 }
 
+static void loopback_private_free(struct snd_card *card)
+{
+	struct loopback *loopback = card->private_data;
+
+	kfree(loopback->timer_source);
+}
+
 static int loopback_probe(struct platform_device *devptr)
 {
 	struct snd_card *card;
@@ -1967,6 +1971,7 @@ static int loopback_probe(struct platform_device *devptr)
 		pcm_substreams[dev] = MAX_PCM_SUBSTREAMS;
 	
 	loopback->card = card;
+	card->private_free = loopback_private_free;
 	loopback_set_timer_source(loopback, timer_source[dev]);
 
 	mutex_init(&loopback->cable_lock);
Signature · 1 line
2.53.0
author maintainer
#2200 lore raw

PATCH 2180/2651 block, bfq: initialize active lists for all actuators

In reply to Greg Kroah-Hartman

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

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

From: Li RongQing <[email protected]>

[ Upstream commit 00c2c34ead7e84d6594e20fa37a3c503823f5756 ]

Commit 2d31c684a053 ("block, bfq: inject I/O to underutilized actuators") extended bfqd->active_list from a single list_head to an array indexed by actuator, but bfq_init_queue() still only initialized the first two entries:

        INIT_LIST_HEAD(&bfqd->active_list[0]);
        INIT_LIST_HEAD(&bfqd->active_list[1]);

For devices with more than two independent access ranges, the remaining list heads stay zeroed by kzalloc() and are never set up as empty lists. When BFQ later adds a bfq_queue to one of those lists, list_add() writes through head->next, which is NULL, corrupting the list or crashing the kernel.

Initialize every actuator's active list using bfqd->num_actuators, which is already set up earlier in bfq_init_queue().

Fixes 2d31c684a053 ("block, bfq: inject I/O to underutilized actuators")
---
 block/bfq-iosched.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
block/bfq-iosched.c +2 -2
index 0f75301b3115f..b21ddba30df16 100644
@@ -7273,8 +7273,8 @@ static int bfq_init_queue(struct request_queue *q, struct elevator_queue *eq)
 	bfqd->num_groups_with_pending_reqs = 0;
 #endif
 
-	INIT_LIST_HEAD(&bfqd->active_list[0]);
-	INIT_LIST_HEAD(&bfqd->active_list[1]);
+	for (i = 0; i < bfqd->num_actuators; i++)
+		INIT_LIST_HEAD(&bfqd->active_list[i]);
 	INIT_LIST_HEAD(&bfqd->idle_list);
 	INIT_HLIST_HEAD(&bfqd->burst_list);
 
Signature · 1 line
2.53.0
author maintainer
#2201 lore raw

PATCH 2181/2651 libbpf: Keep the fd_array fill index out of bpf_program__clone()

In reply to Greg Kroah-Hartman

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

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

From: Kumar Kartikeya Dwivedi <[email protected]>

[ Upstream commit b1eaee8b9a95897a5df843c623aa55d9585cd9d8 ]

bpf_program__clone() hands the kernel the fd_array of the object along with obj->fd_array_cnt when the caller supplies neither. That counter is not a count the kernel can use: it is the index of the next free slot of an array built for the sparse fd_array API, where module BTF fds start at slot 1 and slot 0 stays empty, since a kfunc insn with offset 0 names vmlinux BTF rather than a slot. A non-zero fd_array_cnt turns the array into a continuous one, which the kernel resolves slot by slot, and slot 0 holds 0. Cloning a program from an object that calls a module kfunc thus fails with "fd 0 is not pointing to valid bpf_map or btf", for every program of the object, which is what veristat runs into on such an object. bpf_object__load() passes the array without a count.

Do the same in bpf_program__clone(), leaving the count to callers who pass an array of their own, and rename the counter to fd_array_used so that it no longer reads like the uapi field.

---
 tools/lib/bpf/libbpf.c | 21 +++++++++++++--------
 1 file changed, 13 insertions(+), 8 deletions(-)
tools/lib/bpf/libbpf.c +13 -8
index 03daf99224a3f..4c3b79239a270 100644
@@ -759,7 +759,12 @@ struct bpf_object {
 
 	int *fd_array;
 	size_t fd_array_cap;
-	size_t fd_array_cnt;
+	/*
+	 * Slots handed out so far, slot 0 included. A kfunc insn names a module
+	 * BTF slot through its offset, slot 0 stands for vmlinux BTF and stays
+	 * empty, so the array goes to the kernel without a count.
+	 */
+	size_t fd_array_used;
 
 	struct usdt_manager *usdt_man;
 
@@ -8856,22 +8861,22 @@ static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
 	/* set index for module BTF fd in fd_array, if unset */
 	if (mod_btf && !mod_btf->fd_array_idx) {
 		/* insn->off is s16 */
-		if (obj->fd_array_cnt == INT16_MAX) {
+		if (obj->fd_array_used == INT16_MAX) {
 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
 				ext->name, mod_btf->fd_array_idx);
 			return -E2BIG;
 		}
 		/* Cannot use index 0 for module BTF fd */
-		if (!obj->fd_array_cnt)
-			obj->fd_array_cnt = 1;
+		if (!obj->fd_array_used)
+			obj->fd_array_used = 1;
 
 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
-					obj->fd_array_cnt + 1);
+					obj->fd_array_used + 1);
 		if (ret)
 			return ret;
-		mod_btf->fd_array_idx = obj->fd_array_cnt;
+		mod_btf->fd_array_idx = obj->fd_array_used;
 		/* we assume module BTF FD is always >0 */
-		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
+		obj->fd_array[obj->fd_array_used++] = mod_btf->fd;
 	}
 
 	ext->is_set = true;
@@ -10036,7 +10041,7 @@ int bpf_program__clone(struct bpf_program *prog, const struct bpf_prog_load_opts
 	attr.prog_ifindex = OPTS_GET(opts, prog_ifindex, 0) ?: prog->prog_ifindex;
 	attr.kern_version = OPTS_GET(opts, kern_version, 0) ?: obj->kern_version;
 	attr.fd_array = OPTS_GET(opts, fd_array, NULL) ?: obj->fd_array;
-	attr.fd_array_cnt = OPTS_GET(opts, fd_array_cnt, 0) ?: obj->fd_array_cnt;
+	attr.fd_array_cnt = OPTS_GET(opts, fd_array_cnt, 0);
 	attr.token_fd = OPTS_GET(opts, token_fd, 0) ?: obj->token_fd;
 	if (attr.token_fd)
 		attr.prog_flags |= BPF_F_TOKEN_FD;
Signature · 1 line
2.53.0
author maintainer
#2202 lore raw

PATCH 2182/2651 cgroup/cpuset: use mems_allowed_seq when checking a policy nodemask

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit b0cec62d2867ab3ed27604d5c177b8960c43b17a ]

A cpuset update changes the task's mems_allowed and rebinds its mempolicy in separate steps under mems_allowed_seq, but the check reads both without it. This can cause a spurious numa placement miss under some cpuset/mempolicy combinations.

A reader that loads one mask before the update and the other after it can see a spurious empty intersection and drop the nodemask.

For example, a task with cpuset.mems={0} and MPOL_BIND={0}. If the cpuset moves to mems={1,2}, the policy is rebound to {1}.

The allocator can race and compare the old mems_allowed {0} against the new policy {1} - which will result in a dropped nodemask and a misplaced allocation on node 2.

Simply retry the intersection until mems_allowed_seq is stable.

This covers the task policy, which is rebound under mems_allowed_seq. VMA policies are rebound afterwards by mpol_rebind_mm(), outside mems_allowed_seq, and are not covered by this change.

Fixes cc9a6c877661 ("cpuset: mm: reduce large amounts of memory barrier related damage v3")
---
 kernel/cgroup/cpuset.c | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)
kernel/cgroup/cpuset.c +12 -1
index ab3b4ee27d3ef..4a3c8882dec88 100644
@@ -4379,10 +4379,21 @@ nodemask_t cpuset_mems_allowed(struct task_struct *tsk)
  * @nodemask: the nodemask to be checked
  *
  * Are any of the nodes in the nodemask allowed in current->mems_allowed?
+ *
+ * A cpuset update rebinds the task's mempolicy and changes mems_allowed in
+ * separate steps, so retry if an update raced with the check.
  */
 int cpuset_nodemask_valid_mems_allowed(const nodemask_t *nodemask)
 {
-	return nodes_intersects(*nodemask, current->mems_allowed);
+	unsigned int seq;
+	int ret;
+
+	do {
+		seq = read_mems_allowed_begin();
+		ret = nodes_intersects(*nodemask, current->mems_allowed);
+	} while (read_mems_allowed_retry(seq));
+
+	return ret;
 }
 
 /*
Signature · 1 line
2.53.0
author maintainer
#2203 lore raw

PATCH 2183/2651 cgroup/cpuset: Fix a missing isolated_cpus update in update_cpumasks_hier()

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit 46b885416c27214072272b85adb898ed91801062 ]

It is found that when a local isolated partition is being invalidated because its parent partition is no longer valid, the isolated_cpus cpumask may not be properly updated. Those isolated CPUs may or may not needed to be removed from isolated_cpus depending on if there is a local isolated partition ancestor that will now own those isolated CPUs instead.

Fix that by calling a new ancestor_partition() helper to return the closeset valid partition root ancestor. If that ancestor is PRS_ROOT, the isolated CPUs will have to be removed from isolated_cpus. For a PRS_ISOLATED ancestor, the isolated CPUs are checked against the ancestor's ones to see if any of them should be removed as it is possible that the invalidation of the parent may be caused by change in the effective xcpus of that ancestor. If any of the isolated CPUs should be removed, isolated_cpus_update() will be called under callback_lock.

An existing test case in test_cpuset_prs.sh is modifed and a new one added to test that.

Fixes 11e5f407b64a ("cgroup/cpuset: Keep track of CPUs in isolated partitions")
---
 kernel/cgroup/cpuset.c                        | 57 +++++++++++++++++--
 .../selftests/cgroup/test_cpuset_prs.sh       |  6 +-
 2 files changed, 55 insertions(+), 8 deletions(-)
kernel/cgroup/cpuset.c +52 -5
index 4a3c8882dec88..f4a6259e9838a 100644
@@ -2178,6 +2178,25 @@ static void compute_partition_effective_cpumask(struct cpuset *cs,
 	rcu_read_unlock();
 }
 
+/*
+ * ancestor_partition - Find and return the closest valid partition root ancestor
+ * @cs: the current cpuset
+ *
+ * Return: The closet partition root ancestor cpuset
+ */
+static struct cpuset *ancestor_partition(struct cpuset *cs)
+{
+	struct cpuset *ancestor = parent_cs(cs);
+
+	/*
+	 * The top_cpuset is always a valid partition root which will stop
+	 * the loop if it is reached.
+	 */
+	while (!is_partition_valid(ancestor))
+		ancestor = parent_cs(ancestor);
+	return ancestor;
+}
+
 /*
  * update_cpumasks_hier - Update effective cpumasks and tasks in the subtree
  * @cs:  the cpuset to consider
@@ -2270,7 +2289,10 @@ static void update_cpumasks_hier(struct cpuset *cs, struct tmpmasks *tmp,
 		 * cpuset if the parent's effective_cpus changes.
 		 */
 		if ((cp != cs) && old_prs) {
-			switch (parent->partition_root_state) {
+			int parent_prs = parent->partition_root_state;
+			struct cpumask *del_cpus = NULL;
+
+			switch (parent_prs) {
 			case PRS_ROOT:
 			case PRS_ISOLATED:
 				update_parent = true;
@@ -2278,12 +2300,37 @@ static void update_cpumasks_hier(struct cpuset *cs, struct tmpmasks *tmp,
 
 			default:
 				/*
-				 * When parent is not a partition root or is
-				 * invalid, child partition roots become
-				 * invalid too.
+				 * When parent is not a valid partition root,
+				 * child partition roots become invalid too.
+				 *
+				 * For a to be invalidated isolated partition,
+				 * its isolated CPUs may or may not need to be
+				 * removed from isolated_cpus depending on if
+				 * its closest partition root ancestor is a root
+				 * or isolated partition. With a PRS_ISOLATED
+				 * ancestor, the CPUs are checked against its
+				 * effective xcpus to see if any of them needed
+				 * to be removed.
 				 */
 				if (is_partition_valid(cp))
-					new_prs = -cp->partition_root_state;
+					new_prs = -old_prs;
+
+				if (old_prs == PRS_ISOLATED) {
+					struct cpuset *ancestor = ancestor_partition(cp);
+
+					if (ancestor->partition_root_state == PRS_ROOT)
+						del_cpus = cp->effective_xcpus;
+					else if (cpumask_andnot(tmp->delmask,
+								cp->effective_xcpus,
+								ancestor->effective_xcpus))
+						del_cpus = tmp->delmask;
+
+					if (del_cpus) {
+						spin_lock_irq(&callback_lock);
+						isolated_cpus_update(old_prs, new_prs, del_cpus);
+						spin_unlock_irq(&callback_lock);
+					}
+				}
 				WRITE_ONCE(cp->prs_err,
 					   is_partition_invalid(parent)
 					   ? PERR_INVPARENT : PERR_NOTPART);
tools/testing/selftests/cgroup/test_cpuset_prs.sh +3 -3
index f7cc9da57b556..6859cde73af1a 100755
@@ -292,9 +292,9 @@ TEST_MATRIX=(
 								       A1:P0|A2:P2|A3:P1 2-4|2-3"
 	"   C0-4    C1-4  C2-4     .    X2-4  X2-4:P2 X3-4:P1   .    0 A1:0-1|A2:2|A3:3-4 \
 								       A1:P0|A2:P2|A3:P1 2"
-	" C0-4:X2-4 C1-4:X2-4:P2 C2-4:X4:P1 \
-				   .      .      X5      .      .    0 A1:0-4|A2:1-4|A3:2-4 \
-								       A1:P0|A2:P-2|A3:P-1 ."
+	" C1-4:X2-4 C2-4:X3-4:P1 C3-4:X4:P2 \
+				   .      .      X5      .      .    0 A1:1-4|A2:2-4|A3:3-4 \
+								       A1:P0|A2:P-1|A3:P-2 ."
 	" C0-4:X2-4 C1-4:X2-4:P2 C2-4:X4:P1 \
 				   .      .      .      X1      .    0 A1:0-1|A2:2-4|A3:2-4 \
 								       A1:P0|A2:P2|A3:P-1 2-4"
Signature · 1 line
2.53.0
author maintainer
#2204 lore raw

PATCH 2184/2651 cgroup/cpuset: Consolidate isolated_cpus_can_update() into prstate_housekeeping_conflict()

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit 53bbfb33b1f4fd669c5bffcb7670c4099ecbb225 ]

The isolated_cpus_can_update() and prstate_housekeeping_conflict() are checking different aspects of upcoming cpumask changes that may conflict with the current setting of the housekeeping cpumasks. There are places where both are called together. There are also places where only one of them is called. That inconsistency can contribute to missing check where invalid cpumask changes may be allowed to move forward.

Fix that by consolidating isolated_cpus_can_update() into prstate_housekeeping_conflict() and call prstate_housekeeping_conflict() in all the places where either one of them or both are called. The exception is the validate_partition() function where the prstate_housekeeping_conflict() call is removed. It is because validate_partition() is called only from partition_cpus_change() where prstate_housekeeping_conflict() will be called from either remote_cpus_update() or update_parent_effective_cpumask() with partcmd_update if not for partition invalidatation or disablement.

Now prstate_housekeeping_conflict() will be called in the following locations:
- when a partition is enabled in remote_partition_enable() or in update_parent_effective_cpumask() with partcmd_enable*.
- when a cpumask is updated in remote_cpus_update() or in update_parent_effective_cpumask() with partcmd_update.
- when a partition state changes from root to isolated or vice versa in update_prstate().

Fixes 4a74e418881f ("cgroup/cpuset: Check partition conflict with housekeeping setup")
Fixes 103b08709e8a ("cgroup/cpuset: Fail if isolated and nohz_full don't leave any housekeeping")
---
 kernel/cgroup/cpuset.c | 148 +++++++++++++++++++++--------------------
 1 file changed, 77 insertions(+), 71 deletions(-)
kernel/cgroup/cpuset.c +77 -71
index f4a6259e9838a..b763d9a182ba4 100644
@@ -1378,65 +1378,87 @@ static void partition_xcpus_del(int old_prs, struct cpuset *parent,
 }
 
 /*
- * isolated_cpus_can_update - check for isolated & nohz_full conflicts
- * @add_cpus: cpu mask for cpus that are going to be isolated
- * @del_cpus: cpu mask for cpus that are no longer isolated, can be NULL
- * Return: false if there is conflict, true otherwise
- *
- * If nohz_full is enabled and we have isolated CPUs, their combination must
- * still leave housekeeping CPUs.
+ * prstate_housekeeping_conflict - check for partition & housekeeping conflicts
+ * @new_prs: new partition root state to be checked
+ * @parent_prs: Parent partition root state
+ * @add_cpus: additional CPUs to be added to current cpuset
+ * @del_cpus: CPUs to be removed from current cpuset, can be NULL
+ * Return: true if there is conflict, false otherwise
  *
- * TBD: Should consider merging this function into
- *      prstate_housekeeping_conflict().
+ * There are two different housekeeping conflicts to be checked:
+ * 1) If new_prs is PRS_ROOT, none of the @add_cpus can be a boot-time isolated
+ *    CPU. IOW, the whole @add_cpus must be a subset of HK_TYPE_DOMAIN_BOOT.
+ * 2) If nohz_full is enabled and we have isolated CPUs, their combination must
+ *    still leave housekeeping CPUs. This check is only needed if new_prs
+ *    differs from parent_prs and one of them is PRS_ISOLATED.
  */
-static bool isolated_cpus_can_update(struct cpumask *add_cpus,
-				     struct cpumask *del_cpus)
+static bool prstate_housekeeping_conflict(int new_prs, int parent_prs,
+					  struct cpumask *add_cpus,
+					  struct cpumask *del_cpus)
 {
 	cpumask_var_t full_hk_cpus;
-	int res = true;
+	int res;
 
-	if (!housekeeping_enabled(HK_TYPE_KERNEL_NOISE))
-		return true;
+	WARN_ON_ONCE(parent_prs <= 0);
+	if (!new_prs)
+		return false;
+
+	/*
+	 * For a currently invalid partition root state, do the check assuming
+	 * that it may be converted back to valid.
+	 *
+	 * There are code paths where an invalid partition may be reverted back
+	 * to a valid partition but we still need to run the housekeeping check
+	 * before the conversion happens to make sure the switch is valid. We
+	 * can either do the negative to positive PRS switch individually in all
+	 * these code paths or do it here which I think will make the code a bit
+	 * easier to read.
+	 */
+	if (new_prs < 0)
+		new_prs = -new_prs;
 
-	if (del_cpus && cpumask_weight_and(del_cpus,
-			housekeeping_cpumask(HK_TYPE_KERNEL_NOISE)))
+	if (housekeeping_enabled(HK_TYPE_DOMAIN_BOOT) && (new_prs == PRS_ROOT) &&
+	    !cpumask_subset(add_cpus, housekeeping_cpumask(HK_TYPE_DOMAIN_BOOT)))
 		return true;
 
-	if (!alloc_cpumask_var(&full_hk_cpus, GFP_KERNEL))
+	/*
+	 * Exit 2nd check early and return false if
+	 * 1) there is no boot time isolated nohz_full CPU
+	 * 2) parent and child has the same partition state
+	 * 3) new_prs is PRS_ROOT, parent_prs is PRS_ISOLATED and no CPU will
+	 *    be returned back to the parent.
+	 */
+	if (!housekeeping_enabled(HK_TYPE_KERNEL_NOISE) ||
+	    (new_prs == parent_prs) ||
+	    ((new_prs == PRS_ROOT) && (!del_cpus || cpumask_empty(del_cpus))))
+		return false;
+
+	/*
+	 * Now make sure that @add_cpus contains new CPUs to be isolated and
+	 * @del_cpus contains isolated CPUs to be un-isolated.
+	 * With the guards above, @add_cpus can't be NULL after the swap.
+	 */
+	if (parent_prs == PRS_ISOLATED)
+		swap(add_cpus, del_cpus);
+
+	if (del_cpus &&
+	   (cpumask_first_and_and(del_cpus, housekeeping_cpumask(HK_TYPE_KERNEL_NOISE),
+				   cpu_active_mask) < nr_cpu_ids))
 		return false;
 
+	if (!alloc_cpumask_var(&full_hk_cpus, GFP_KERNEL))
+		return true;
+
 	cpumask_and(full_hk_cpus, housekeeping_cpumask(HK_TYPE_KERNEL_NOISE),
 		    housekeeping_cpumask(HK_TYPE_DOMAIN));
 	cpumask_andnot(full_hk_cpus, full_hk_cpus, isolated_cpus);
 	cpumask_and(full_hk_cpus, full_hk_cpus, cpu_active_mask);
-	if (!cpumask_weight_andnot(full_hk_cpus, add_cpus))
-		res = false;
+	res = !cpumask_weight_andnot(full_hk_cpus, add_cpus);
 
 	free_cpumask_var(full_hk_cpus);
 	return res;
 }
 
-/*
- * prstate_housekeeping_conflict - check for partition & housekeeping conflicts
- * @prstate: partition root state to be checked
- * @new_cpus: cpu mask
- * Return: true if there is conflict, false otherwise
- *
- * CPUs outside of HK_TYPE_DOMAIN_BOOT, if defined, can only be used in an
- * isolated partition.
- */
-static bool prstate_housekeeping_conflict(int prstate, struct cpumask *new_cpus)
-{
-	if (!housekeeping_enabled(HK_TYPE_DOMAIN_BOOT))
-		return false;
-
-	if ((prstate != PRS_ISOLATED) &&
-	    !cpumask_subset(new_cpus, housekeeping_cpumask(HK_TYPE_DOMAIN_BOOT)))
-		return true;
-
-	return false;
-}
-
 /*
  * cpuset_update_sd_hk_unlock - Rebuild sched domains, update HK & unlock
  *
@@ -1618,9 +1640,7 @@ static int remote_partition_enable(struct cpuset *cs, int new_prs,
 		return PERR_INVCPUS;
 	if (cpumask_intersects(tmp->new_cpus, subpartitions_cpus))
 		return PERR_NOCPUS;
-	if (((new_prs == PRS_ISOLATED) &&
-	     !isolated_cpus_can_update(tmp->new_cpus, NULL)) ||
-	    prstate_housekeeping_conflict(new_prs, tmp->new_cpus))
+	if (prstate_housekeeping_conflict(new_prs, PRS_ROOT, tmp->new_cpus, NULL))
 		return PERR_HKEEPING;
 
 	spin_lock_irq(&callback_lock);
@@ -1722,8 +1742,8 @@ static void remote_cpus_update(struct cpuset *cs, struct cpumask *xcpus,
 		else if (cpumask_intersects(tmp->addmask, subpartitions_cpus) ||
 			 cpumask_subset(top_cpuset.effective_cpus, tmp->addmask))
 			WRITE_ONCE(cs->prs_err, PERR_NOCPUS);
-		else if ((prs == PRS_ISOLATED) &&
-			 !isolated_cpus_can_update(tmp->addmask, tmp->delmask))
+		else if (prstate_housekeeping_conflict(prs, PRS_ROOT,
+						       tmp->addmask, tmp->delmask))
 			WRITE_ONCE(cs->prs_err, PERR_HKEEPING);
 		if (cs->prs_err)
 			goto invalidate;
@@ -1865,11 +1885,7 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 		if (cpumask_empty(xcpus))
 			return PERR_INVCPUS;
 
-		if (prstate_housekeeping_conflict(new_prs, xcpus))
-			return PERR_HKEEPING;
-
-		if ((new_prs == PRS_ISOLATED) && (new_prs != parent_prs) &&
-		    !isolated_cpus_can_update(xcpus, NULL))
+		if (prstate_housekeeping_conflict(new_prs, parent_prs, xcpus, NULL))
 			return PERR_HKEEPING;
 
 		if (tasks_nocpu_error(parent, cs, xcpus))
@@ -1942,20 +1958,12 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 		}
 
 		/*
-		 * TBD: Invalidate a currently valid child root partition may
-		 * still break isolated_cpus_can_update() rule if parent is an
-		 * isolated partition.
+		 * Check for housekeeping conflicts
 		 */
-		if (is_partition_valid(cs) && (old_prs != parent_prs)) {
-			if ((parent_prs == PRS_ROOT) &&
-			    /* Adding to parent means removing isolated CPUs */
-			    !isolated_cpus_can_update(tmp->delmask, tmp->addmask))
-				part_error = PERR_HKEEPING;
-			if ((parent_prs == PRS_ISOLATED) &&
-			    /* Adding to parent means adding isolated CPUs */
-			    !isolated_cpus_can_update(tmp->addmask, tmp->delmask))
-				part_error = PERR_HKEEPING;
-		}
+		if (is_partition_valid(cs) &&
+		    prstate_housekeeping_conflict(old_prs, parent_prs,
+						  tmp->delmask, tmp->addmask))
+			part_error = PERR_HKEEPING;
 
 		/*
 		 * The new CPUs to be removed from parent's effective CPUs
@@ -2481,10 +2489,6 @@ static enum prs_errcode validate_partition(struct cpuset *cs, struct cpuset *tri
 	if (cpumask_empty(trialcs->effective_xcpus))
 		return PERR_INVCPUS;
 
-	if (prstate_housekeeping_conflict(trialcs->partition_root_state,
-					  trialcs->effective_xcpus))
-		return PERR_HKEEPING;
-
 	if (tasks_nocpu_error(parent, cs, trialcs->effective_xcpus))
 		return PERR_NOCPUS;
 
@@ -2501,7 +2505,7 @@ static enum prs_errcode validate_partition(struct cpuset *cs, struct cpuset *tri
  * CPU modifications may cause a partition to be disabled or require state updates.
  */
 static void partition_cpus_change(struct cpuset *cs, struct cpuset *trialcs,
-					struct tmpmasks *tmp)
+				  struct tmpmasks *tmp)
 {
 	enum prs_errcode prs_err;
 
@@ -3058,13 +3062,15 @@ static int update_prstate(struct cpuset *cs, int new_prs)
 			err = remote_partition_enable(cs, new_prs, &tmpmask);
 		}
 	} else if (old_prs && new_prs) {
+		int parent_prs = is_remote_partition(cs)
+				 ? PRS_ROOT : parent->partition_root_state;
+
 		/*
 		 * A change in load balance state only, no change in cpumasks.
 		 * Need to update isolated_cpus.
 		 */
-		if (((new_prs == PRS_ISOLATED) &&
-		     !isolated_cpus_can_update(cs->effective_xcpus, NULL)) ||
-		    prstate_housekeeping_conflict(new_prs, cs->effective_xcpus))
+		if (prstate_housekeeping_conflict(new_prs, parent_prs,
+						  cs->effective_xcpus, NULL))
 			err = PERR_HKEEPING;
 		else
 			isolcpus_updated = true;
Signature · 1 line
2.53.0
author maintainer
#2205 lore raw

PATCH 2185/2651 cgroup/cpuset: Consider all the exclusive CPUs when doing housekeeping check

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit 9527ff78a413e2b4089e78953926af77b98fd43f ]

When prstate_housekeeping_conflict() is called to perform housekeeping check with cpumask changes, the cpumask changes are passed in via add_cpus and del_cpus parameters. With this arrangement, the exclusive CPUs owned by the child partitions and not affected by the cpumask change, if any, are excluded in the analysis. The only places where there are separate add and delete masks are when the cpuset.cpus or cpuset.cpus.exclusive is being changed. In both cases, partition_cpus_change() is a good place to perform the housekeeping check.

If we allow a root partition to be created under an isolated partition, it is possible the cpumask change will still leave active housekeeping CPUs but then no housekeeping CPUs will be left when the child partitions are disabled or invalidated.

As a first step to protect against this possibility, all the exclusive CPUs of the cpuset should be considered to be owned by the current cpuset when doing housekeeping check. At the same time, we do want to know if some housekeeping CPUs are going to be removed from the isolated partition that there will be no danger of losing all the active housekeeping CPUs. So the current add_cpus paremeter is renamed as new_cpus to indicate that it includes the complete set of effective xcpus.

With the new check in partition_cpus_change(), the housekeeping check in update_parent_effective_cpumask() with partcmd_update and newmask is now duplicative and can be removed. The housekeeping check in remote_cpus_update(), however, will still be useful as this function can be called directly from update_cpumasks_hier() without going through partition_cpus_change(). The update_parent_effective_cpumask() call from update_cpumasks_hier() is partcmd_update with no cpumask which still have the housekeeping check and so is covered.

Fixes 103b08709e8a ("cgroup/cpuset: Fail if isolated and nohz_full don't leave any housekeeping")
---
 kernel/cgroup/cpuset.c | 46 +++++++++++++++++++++++++-----------------
 1 file changed, 27 insertions(+), 19 deletions(-)
kernel/cgroup/cpuset.c +27 -19
index b763d9a182ba4..4080e08428c4e 100644
@@ -1381,19 +1381,19 @@ static void partition_xcpus_del(int old_prs, struct cpuset *parent,
  * prstate_housekeeping_conflict - check for partition & housekeeping conflicts
  * @new_prs: new partition root state to be checked
  * @parent_prs: Parent partition root state
- * @add_cpus: additional CPUs to be added to current cpuset
- * @del_cpus: CPUs to be removed from current cpuset, can be NULL
+ * @new_cpus: the set of new effective xcpus in the current cpuset
+ * @del_cpus: old CPUs going to be removed from current cpuset, can be NULL
  * Return: true if there is conflict, false otherwise
  *
  * There are two different housekeeping conflicts to be checked:
- * 1) If new_prs is PRS_ROOT, none of the @add_cpus can be a boot-time isolated
- *    CPU. IOW, the whole @add_cpus must be a subset of HK_TYPE_DOMAIN_BOOT.
+ * 1) If new_prs is PRS_ROOT, none of the @new_cpus can be a boot-time isolated
+ *    CPU. IOW, the whole @new_cpus must be a subset of HK_TYPE_DOMAIN_BOOT.
  * 2) If nohz_full is enabled and we have isolated CPUs, their combination must
  *    still leave housekeeping CPUs. This check is only needed if new_prs
  *    differs from parent_prs and one of them is PRS_ISOLATED.
  */
 static bool prstate_housekeeping_conflict(int new_prs, int parent_prs,
-					  struct cpumask *add_cpus,
+					  struct cpumask *new_cpus,
 					  struct cpumask *del_cpus)
 {
 	cpumask_var_t full_hk_cpus;
@@ -1418,7 +1418,7 @@ static bool prstate_housekeeping_conflict(int new_prs, int parent_prs,
 		new_prs = -new_prs;
 
 	if (housekeeping_enabled(HK_TYPE_DOMAIN_BOOT) && (new_prs == PRS_ROOT) &&
-	    !cpumask_subset(add_cpus, housekeeping_cpumask(HK_TYPE_DOMAIN_BOOT)))
+	    !cpumask_subset(new_cpus, housekeeping_cpumask(HK_TYPE_DOMAIN_BOOT)))
 		return true;
 
 	/*
@@ -1434,12 +1434,12 @@ static bool prstate_housekeeping_conflict(int new_prs, int parent_prs,
 		return false;
 
 	/*
-	 * Now make sure that @add_cpus contains new CPUs to be isolated and
+	 * Now make sure that @new_cpus contains new CPUs to be isolated and
 	 * @del_cpus contains isolated CPUs to be un-isolated.
-	 * With the guards above, @add_cpus can't be NULL after the swap.
+	 * With the guards above, @new_cpus can't be NULL after the swap.
 	 */
 	if (parent_prs == PRS_ISOLATED)
-		swap(add_cpus, del_cpus);
+		swap(new_cpus, del_cpus);
 
 	if (del_cpus &&
 	   (cpumask_first_and_and(del_cpus, housekeeping_cpumask(HK_TYPE_KERNEL_NOISE),
@@ -1453,7 +1453,7 @@ static bool prstate_housekeeping_conflict(int new_prs, int parent_prs,
 		    housekeeping_cpumask(HK_TYPE_DOMAIN));
 	cpumask_andnot(full_hk_cpus, full_hk_cpus, isolated_cpus);
 	cpumask_and(full_hk_cpus, full_hk_cpus, cpu_active_mask);
-	res = !cpumask_weight_andnot(full_hk_cpus, add_cpus);
+	res = !cpumask_weight_andnot(full_hk_cpus, new_cpus);
 
 	free_cpumask_var(full_hk_cpus);
 	return res;
@@ -1743,7 +1743,7 @@ static void remote_cpus_update(struct cpuset *cs, struct cpumask *xcpus,
 			 cpumask_subset(top_cpuset.effective_cpus, tmp->addmask))
 			WRITE_ONCE(cs->prs_err, PERR_NOCPUS);
 		else if (prstate_housekeeping_conflict(prs, PRS_ROOT,
-						       tmp->addmask, tmp->delmask))
+						       excpus, tmp->delmask))
 			WRITE_ONCE(cs->prs_err, PERR_HKEEPING);
 		if (cs->prs_err)
 			goto invalidate;
@@ -1957,14 +1957,6 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 					       parent->effective_xcpus);
 		}
 
-		/*
-		 * Check for housekeeping conflicts
-		 */
-		if (is_partition_valid(cs) &&
-		    prstate_housekeeping_conflict(old_prs, parent_prs,
-						  tmp->delmask, tmp->addmask))
-			part_error = PERR_HKEEPING;
-
 		/*
 		 * The new CPUs to be removed from parent's effective CPUs
 		 * must be present.
@@ -2513,6 +2505,22 @@ static void partition_cpus_change(struct cpuset *cs, struct cpuset *trialcs,
 		return;
 
 	prs_err = validate_partition(cs, trialcs);
+	if (!prs_err && !cpumask_empty(trialcs->effective_xcpus)) {
+		int prs = cs->partition_root_state;
+		int parent_prs = is_remote_partition(cs)
+			       ? PRS_ROOT : parent_cs(cs)->partition_root_state;
+		/*
+		 * Check for housekeeping conflict by passing the whole
+		 * effective_xcpus as well as those CPUs that are to be
+		 * removed from cs as delmask.
+		 */
+		cpumask_andnot(tmp->delmask, cs->effective_xcpus, trialcs->effective_xcpus);
+		if (parent_prs > 0 &&
+		    prstate_housekeeping_conflict(prs, parent_prs,
+						  trialcs->effective_xcpus, tmp->delmask))
+			prs_err = PERR_HKEEPING;
+	}
+
 	if (prs_err) {
 		WRITE_ONCE(cs->prs_err, prs_err);
 		trialcs->prs_err = prs_err;
Signature · 1 line
2.53.0
author maintainer
#2206 lore raw

PATCH 2186/2651 cgroup/cpuset: Do housekeeping check before converting invalid partition to valid

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit 2c0a5742fc459cd8416607acff4a38a1abcb2e1b ]

When a hotplug event happens or when update_cpumasks_hier() is called, an invalid partition may be converted back to valid. However check against housekeeping conflict isn't being done which can lead to a partition state that violates the housekeeping rules. Update the code to allow reviving an invalid partition only if it can pass the housekeeping check.

Fixes 4a74e418881f ("cgroup/cpuset: Check partition conflict with housekeeping setup")
---
 kernel/cgroup/cpuset.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
kernel/cgroup/cpuset.c +8 -2
index 4080e08428c4e..7443ee44d4d4e 100644
@@ -2006,9 +2006,15 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 			bool exclusive = true;
 
 			/*
-			 * Convert invalid partition to valid has to
-			 * pass the cpu exclusivity test.
+			 * Convert invalid partition to valid has to pass the
+			 * cpu exclusivity test as well as the housekeeping
+			 * check.
 			 */
+			if (prstate_housekeeping_conflict(cs->partition_root_state,
+							  parent_prs, xcpus, NULL)) {
+				part_error = PERR_HKEEPING;
+				goto write_error;
+			}
 			rcu_read_lock();
 			cpuset_for_each_child(child, css, parent) {
 				if (child == cs)
Signature · 1 line
2.53.0
author maintainer
#2207 lore raw

PATCH 2187/2651 cgroup/cpuset: Properly disabling partition when partition state switching fails

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit db27a748a399e24af715c54c12a7e928e32d15b0 ]

Before commit 103b08709e8a ("cgroup/cpuset: Fail if isolated and nohz_full don't leave any housekeeping"), the partition state can be freely switched from "root" to "isolated" and vice versa. After that commit, the switch from "root" to "isolated" can fail if it exhausts all the housekeeping CPUs. Later on, the switch from "isolated" to "root" can also fail if some of the partition CPUs are boot-time isolated by "isolcpus".

A local or remote partition is made invalid when the switch fails. However there are 2 problems with the existing invalidation code.

1) Both the subpartitions_cpus and isolated_cpus are not properly updated.
2) In the case of remote partition with remote_partition flag set, it is not cleared.

Fix this by calling the proper partition disabling function in this case.

On an x86 test system with boot option "isolcpus=10 cgroup_debug" set and more than 16 cores, the following commands were executed after boot.

  # cd /sys/fs/cgroup
  # echo +cpuset > cgroup.subtree_control
  # cat cpuset.cpus.isolated
  10
  # mkdir A
  # echo 10-12 > A/cpuset.cpus
  # echo isolated > A/cpuset.cpus.partition
  # cat A/cpuset.cpus.partition
  isolated

Before the patch:

  # echo root > A/cpuset.cpus.partition
  # cat A/cpuset.cpus.partition
  root invalid (partition config conflicts with housekeeping setup)
  # cat cpuset.cpus.isolated .__DEBUG__.cpuset.cpus.subpartitions
  10-12
  10-12

After the patch:

  # echo root > A/cpuset.cpus.partition
  # cat A/cpuset.cpus.partition
  root invalid (partition config conflicts with housekeeping setup)
  # cat cpuset.cpus.isolated .__DEBUG__.cpuset.cpus.subpartitions
  10
Fixes 4a74e418881f ("cgroup/cpuset: Check partition conflict with housekeeping setup")
Fixes 103b08709e8a ("cgroup/cpuset: Fail if isolated and nohz_full don't leave any housekeeping")
---
 kernel/cgroup/cpuset.c | 17 ++++++++++++-----
 1 file changed, 12 insertions(+), 5 deletions(-)
kernel/cgroup/cpuset.c +12 -5
index 7443ee44d4d4e..5d1883d19319b 100644
@@ -3024,6 +3024,7 @@ static int update_prstate(struct cpuset *cs, int new_prs)
 	struct cpuset *parent = parent_cs(cs);
 	struct tmpmasks tmpmask;
 	bool isolcpus_updated = false;
+	bool disable_partition = false;
 
 	if (old_prs == new_prs)
 		return 0;
@@ -3084,15 +3085,21 @@ static int update_prstate(struct cpuset *cs, int new_prs)
 		 * Need to update isolated_cpus.
 		 */
 		if (prstate_housekeeping_conflict(new_prs, parent_prs,
-						  cs->effective_xcpus, NULL))
+						  cs->effective_xcpus, NULL)) {
+			disable_partition = true;
 			err = PERR_HKEEPING;
-		else
+		} else {
 			isolcpus_updated = true;
+		}
 	} else {
 		/*
 		 * Switching back to member is always allowed even if it
 		 * disables child partitions.
 		 */
+		disable_partition = true;
+	}
+
+	if (disable_partition) {
 		if (is_remote_partition(cs))
 			remote_partition_disable(cs, &tmpmask);
 		else
@@ -3101,7 +3108,7 @@ static int update_prstate(struct cpuset *cs, int new_prs)
 
 		/*
 		 * Invalidation of child partitions will be done in
-		 * update_cpumasks_hier().
+		 * update_cpumasks_hier() below.
 		 */
 	}
 out:
@@ -3123,8 +3130,8 @@ static int update_prstate(struct cpuset *cs, int new_prs)
 		isolated_cpus_update(old_prs, new_prs, cs->effective_xcpus);
 	spin_unlock_irq(&callback_lock);
 
-	/* Force update if switching back to member & update effective_xcpus */
-	update_cpumasks_hier(cs, &tmpmask, !new_prs);
+	/* Force update if partition is disabled & update effective_xcpus */
+	update_cpumasks_hier(cs, &tmpmask, disable_partition);
 
 	/* A newly created partition must have effective_xcpus set */
 	WARN_ON_ONCE(!old_prs && (new_prs > 0)
Signature · 1 line
2.53.0
author maintainer
#2208 lore raw

PATCH 2188/2651 bpf: Fix ksock build with BPF_LSM=y and SECURITY_NETWORK=n

In reply to Greg Kroah-Hartman

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

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

[ Upstream commit a81bd9262cde4b002b95e652453ce5b815c79a62 ]

bpf_ksock.c references bpf_lsm_socket_sendmsg() whenever CONFIG_BPF_LSM=y, but the socket LSM hooks, and with them the BPF LSM socket_sendmsg hook, only exist with CONFIG_SECURITY_NETWORK=y. Without it resolve_btfids warns:

WARN: resolve_btfids: unresolved symbol bpf_lsm_socket_sendmsg

and since commit 201a454df948 ("resolve_btfids: Fix the --fatal_warnings exit status") that fails the build with CONFIG_WERROR=y.

Only reference the hook with CONFIG_SECURITY_NETWORK=y, and use BTF_ID_UNUSED otherwise. The ID stays zero, as it was when unresolved, so bpf_ksock_kfunc_filter() keeps allowing LSM programs: none can be attached to socket_sendmsg without CONFIG_SECURITY_NETWORK.

---
 net/core/bpf_ksock.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
net/core/bpf_ksock.c +6 -1
index e9943aeeadd32..6fbbd5745d649 100644
@@ -274,7 +274,12 @@ BTF_ID_FLAGS(func, bpf_ksock_send, KF_SLEEPABLE)
 BTF_KFUNCS_END(ksock_kfunc_btf_ids)
 
 #ifdef CONFIG_BPF_LSM
-BTF_ID_LIST_SINGLE(bpf_lsm_socket_sendmsg_id, func, bpf_lsm_socket_sendmsg)
+BTF_ID_LIST(bpf_lsm_socket_sendmsg_id)
+#ifdef CONFIG_SECURITY_NETWORK
+BTF_ID(func, bpf_lsm_socket_sendmsg)
+#else
+BTF_ID_UNUSED
+#endif
 #endif
 
 static int bpf_ksock_kfunc_filter(const struct bpf_prog *prog, u32 kfunc_id)
Signature · 1 line
2.53.0
author maintainer
#2209 lore raw

PATCH 2189/2651 bpf: Revalidate faulted arena pages before installing user mappings

In reply to Greg Kroah-Hartman

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

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

From: Emil Tsalapatis <[email protected]>

[ Upstream commit 05bee0638bacf4e9298bbf0bfef749b6a8ff4478 ]

A user fault on an arena pins the page that the kernel arena maps, drops the arena spinlock and returns the page to the core fault code, which then locks the folio and installs the user PTE. A concurrent free can clear the kernel mapping in that window. The page reference prevents a use-after-free, but the fault can still install a user PTE for a page the arena has already released. User space and BPF programs then see different memory at the same arena offset.

Close the window from the fault side. Lock the page, recheck that the kernel mapping still points to it, and return it with VM_FAULT_LOCKED so that it stays locked until the core fault code has installed the user PTE. If a free removed the page, drop it and return VM_FAULT_NOPAGE so that the fault starts over. Return VM_FAULT_HWPOISON for a poisoned page.

This change alone does not close the race, because the free path does not yet wait for the page lock. The following change makes frees wait for in-flight faults before zapping user mappings.

---
 kernel/bpf/arena.c | 18 ++++++++++++++++--
 1 file changed, 16 insertions(+), 2 deletions(-)
kernel/bpf/arena.c +16 -2
index 0ff707707da04..5e0e0837980b4 100644
@@ -584,8 +584,22 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf)
 	raw_res_spin_unlock_irqrestore(&arena->spinlock, flags);
 	if (new_page)
 		free_pages_nolock(new_page, 0);
-	vmf->page = page;
-	return 0;
+
+	/*
+	 * A free clears the kernel pte and then takes the page lock before it
+	 * zaps user vma-s. Either it waits for this fault and zaps its pte, or
+	 * the page is gone from here.
+	 */
+	lock_page(page);
+	if (vmalloc_to_page((void *)kaddr) == page && !PageHWPoison(page)) {
+		vmf->page = page;
+		return VM_FAULT_LOCKED;
+	}
+	/* The page was freed meanwhile. Let the fault start over. */
+	fault_ret = PageHWPoison(page) ? VM_FAULT_HWPOISON : VM_FAULT_NOPAGE;
+	unlock_page(page);
+	put_page(page);
+	return fault_ret;
 
 out_err_locked_memcg:
 	bpf_map_memcg_exit(old_memcg, new_memcg);
Signature · 1 line
2.53.0
author maintainer
#2210 lore raw

PATCH 2190/2651 bpf: Fix arena race between page free and alloc leading to incoherency

In reply to Greg Kroah-Hartman

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

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

From: Emil Tsalapatis <[email protected]>

[ Upstream commit 7244a2e58d2167292972f9380abb3a4d17a343e3 ]

Existing arena kfunc code has an underlying race condition that can lead to writes being lost from the BPF program's point of view:

a) A memory range gets freed by operation (1), and its range is added back to the arena range tree.

b) A concurrent allocation (2) reallocates the range, and does writes to it. Writes from that CPU may follow the stale TLB entries into the pages that are about to be freed.

c) (1) invalidates the TLB. The old pages, and any writes done to them, are now inaccessible. zap_pages() similarly removes the mappings for userspace threads.

This can be triggered by particularly demanding BPF arena data structures that constantly allocate and deallocate memory, like hash table allocations.

Solve this ABA problem by keeping the range allocated until TLB invalidation and unmapping are complete. Under the arena spinlock, claim any free pages in the range and clear its kernel PTEs. Then drop the spinlock, lock and unlock each cleared page to wait for faults that are still installing a user PTE, flush the kernel TLB and zap the user page tables. Finally, retake the spinlock to release the range. Frees serialize on zap_mutex, so an overlapping free cannot release the range early. Claiming the range only allocates a range tree node when the whole range is free, and then there is nothing to free.

User faults on a range that is allocated without a page now raise SIGBUS instead of populating it. That covers a range reserved with bpf_arena_reserve_pages() and a range whose kernel PTEs a free has already cleared. Touching a page while a BPF program frees it is a user space bug, and in a BPF_F_SEGV_ON_FAULT arena it already raises SIGSEGV.

Sleepable frees run synchronously and are deferred only when the arena spinlock cannot be taken. The deferred free worker retries such a free in place instead of requeueing itself, so the flush_work() in arena_map_free() waits for all of its work.

---
 kernel/bpf/arena.c | 159 +++++++++++++++++++++------------------------
 1 file changed, 73 insertions(+), 86 deletions(-)
kernel/bpf/arena.c +73 -86
index 5e0e0837980b4..868589f073301 100644
@@ -543,6 +543,12 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf)
 		goto out_err_locked;
 	}
 
+	if (is_range_tree_set(&arena->rt, vmf->pgoff, 1)) {
+		/* Allocated without a page: reserved or being freed */
+		fault_ret = VM_FAULT_SIGBUS;
+		goto out_err_locked;
+	}
+
 	bpf_map_memcg_enter(&arena->map, &old_memcg, &new_memcg);
 
 	if (!new_page) {
@@ -868,7 +874,7 @@ static void zap_pages(struct bpf_arena *arena, long uaddr, long page_cnt)
 	 * otherwise call B's mark would make call A skip a vml that A has
 	 * not yet zapped for A's uaddr range.
 	 */
-	mutex_lock(&arena->zap_mutex);
+	lockdep_assert_held(&arena->zap_mutex);
 	mutex_lock(&arena->lock);
 	my_gen = ++arena->zap_gen;
 	for (;;) {
@@ -902,49 +908,41 @@ static void zap_pages(struct bpf_arena *arena, long uaddr, long page_cnt)
 		mutex_lock(&arena->lock);
 	}
 	mutex_unlock(&arena->lock);
-	mutex_unlock(&arena->zap_mutex);
 }
 
-static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt, bool sleepable)
+/*
+ * The range stays allocated in the range tree until the pages are unmapped
+ * from vmalloc area and from all user space vma-s, so that nobody can
+ * populate it while stale TLB entries or user ptes are still around.
+ */
+static int arena_free_range(struct bpf_arena *arena, long uaddr, long page_cnt)
 {
-	struct mem_cgroup *new_memcg, *old_memcg;
-	u64 full_uaddr, uaddr_end;
-	long kaddr, pgoff;
-	struct page *page;
-	struct llist_head free_pages;
-	struct llist_node *pos, *t;
-	struct arena_free_span *s;
+	u64 full_uaddr = clear_lo32(arena->user_vm_start) + uaddr;
+	long kaddr = bpf_arena_get_kern_vm_start(arena) + uaddr;
+	long pgoff = compute_pgoff(arena, uaddr);
 	struct clear_range_data cdata;
+	struct llist_node *pos, *t;
+	LLIST_HEAD(free_pages);
 	unsigned long flags;
-	int ret = 0;
-
-	/* only aligned lower 32-bit are relevant */
-	uaddr = (u32)uaddr;
-	uaddr &= PAGE_MASK;
-	kaddr = bpf_arena_get_kern_vm_start(arena) + uaddr;
-	full_uaddr = clear_lo32(arena->user_vm_start) + uaddr;
-	if (full_uaddr < arena->user_vm_start)
-		return;
-	uaddr_end = min(arena->user_vm_end, full_uaddr + (page_cnt << PAGE_SHIFT));
-	if (full_uaddr >= uaddr_end)
-		return;
-
-	page_cnt = (uaddr_end - full_uaddr) >> PAGE_SHIFT;
-	pgoff = compute_pgoff(arena, uaddr);
-	bpf_map_memcg_enter(&arena->map, &old_memcg, &new_memcg);
+	struct page *page;
+	int ret;
 
-	if (!sleepable)
-		goto defer;
+	/* An overlapping free must not release the range before this one is done */
+	guard(mutex)(&arena->zap_mutex);
 
 	ret = raw_res_spin_lock_irqsave(&arena->spinlock, flags);
-
-	/* Can't proceed without holding the spinlock so defer the free */
 	if (ret)
-		goto defer;
+		return ret;
 
-	range_tree_set(&arena->rt, pgoff, page_cnt);
+	/*
+	 * Take the free pages of the range too. It allocates, and can fail,
+	 * only when the whole range is free. Then there is nothing to do.
+	 */
+	if (range_tree_clear(&arena->rt, pgoff, page_cnt)) {
+		raw_res_spin_unlock_irqrestore(&arena->spinlock, flags);
+		return 0;
+	}
 
-	init_llist_head(&free_pages);
 	cdata.arena = arena;
 	cdata.free_pages = &free_pages;
 	/* clear ptes and collect struct pages */
@@ -954,6 +952,12 @@ static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt,
 	/* drop the lock to do the tlb flush and zap pages */
 	raw_res_spin_unlock_irqrestore(&arena->spinlock, flags);
 
+	/* wait for arena_vm_fault() that found the page before its pte was cleared */
+	llist_for_each_entry(page, free_pages.first, pcp_llist) {
+		lock_page(page);
+		unlock_page(page);
+	}
+
 	/* ensure no stale TLB entries */
 	flush_tlb_kernel_range(kaddr, kaddr + (page_cnt * PAGE_SIZE));
 
@@ -972,8 +976,39 @@ static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt,
 			zap_pages(arena, full_uaddr, 1);
 		__free_page(page);
 	}
-	bpf_map_memcg_exit(old_memcg, new_memcg);
 
+	/* The callers hold no other rqspinlock, so this one can only time out */
+	while (raw_res_spin_lock_irqsave(&arena->spinlock, flags))
+		cond_resched();
+	range_tree_set(&arena->rt, pgoff, page_cnt);
+	raw_res_spin_unlock_irqrestore(&arena->spinlock, flags);
+	return 0;
+}
+
+static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt, bool sleepable)
+{
+	struct mem_cgroup *new_memcg, *old_memcg;
+	u64 full_uaddr, uaddr_end;
+	struct arena_free_span *s;
+
+	/* only aligned lower 32-bit are relevant */
+	uaddr = (u32)uaddr;
+	uaddr &= PAGE_MASK;
+	full_uaddr = clear_lo32(arena->user_vm_start) + uaddr;
+	if (full_uaddr < arena->user_vm_start)
+		return;
+	uaddr_end = min(arena->user_vm_end, full_uaddr + (page_cnt << PAGE_SHIFT));
+	if (full_uaddr >= uaddr_end)
+		return;
+
+	page_cnt = (uaddr_end - full_uaddr) >> PAGE_SHIFT;
+	bpf_map_memcg_enter(&arena->map, &old_memcg, &new_memcg);
+
+	/* Can't proceed without holding the spinlock so defer the free */
+	if (!sleepable || arena_free_range(arena, uaddr, page_cnt))
+		goto defer;
+
+	bpf_map_memcg_exit(old_memcg, new_memcg);
 	return;
 
 defer:
@@ -1035,66 +1070,18 @@ static void arena_free_worker(struct work_struct *work)
 {
 	struct bpf_arena *arena = container_of(work, struct bpf_arena, free_work);
 	struct mem_cgroup *new_memcg, *old_memcg;
-	struct llist_node *list, *pos, *t;
+	struct llist_node *pos, *t;
 	struct arena_free_span *s;
-	u64 arena_vm_start, user_vm_start;
-	struct llist_head free_pages;
-	struct clear_range_data cdata;
-	struct page *page;
-	unsigned long full_uaddr;
-	long kaddr, page_cnt, pgoff;
-	unsigned long flags;
-
-	if (raw_res_spin_lock_irqsave(&arena->spinlock, flags)) {
-		schedule_work(work);
-		return;
-	}
 
 	bpf_map_memcg_enter(&arena->map, &old_memcg, &new_memcg);
 
-	init_llist_head(&free_pages);
-	cdata.arena = arena;
-	cdata.free_pages = &free_pages;
-	arena_vm_start = bpf_arena_get_kern_vm_start(arena);
-	user_vm_start = bpf_arena_get_user_vm_start(arena);
-
-	list = llist_del_all(&arena->free_spans);
-	llist_for_each(pos, list) {
-		s = llist_entry(pos, struct arena_free_span, node);
-		page_cnt = s->page_cnt;
-		kaddr = arena_vm_start + s->uaddr;
-		pgoff = compute_pgoff(arena, s->uaddr);
-
-		/* clear ptes and collect pages in free_pages llist */
-		apply_to_existing_page_range(&init_mm, kaddr, page_cnt << PAGE_SHIFT,
-					     apply_range_clear_cb, &cdata);
-
-		range_tree_set(&arena->rt, pgoff, page_cnt);
-	}
-	raw_res_spin_unlock_irqrestore(&arena->spinlock, flags);
-
-	/* Iterate the list again without holding spinlock to do the tlb flush and zap_pages */
-	llist_for_each_safe(pos, t, list) {
+	llist_for_each_safe(pos, t, llist_del_all(&arena->free_spans)) {
 		s = llist_entry(pos, struct arena_free_span, node);
-		page_cnt = s->page_cnt;
-		full_uaddr = clear_lo32(user_vm_start) + s->uaddr;
-		kaddr = arena_vm_start + s->uaddr;
-
-		/* ensure no stale TLB entries */
-		flush_tlb_kernel_range(kaddr, kaddr + (page_cnt * PAGE_SIZE));
-
-		/* remove pages from user vmas */
-		zap_pages(arena, full_uaddr, page_cnt);
-
+		while (arena_free_range(arena, s->uaddr, s->page_cnt))
+			cond_resched();
 		kfree_nolock(s);
 	}
 
-	/* free all pages collected by apply_to_existing_page_range() in the first loop */
-	llist_for_each_safe(pos, t, __llist_del_all(&free_pages)) {
-		page = llist_entry(pos, struct page, pcp_llist);
-		__free_page(page);
-	}
-
 	bpf_map_memcg_exit(old_memcg, new_memcg);
 }
 
Signature · 1 line
2.53.0
author maintainer
#2211 lore raw

PATCH 2191/2651 ipe: fix invalid sgid value in audit event documentation

In reply to Greg Kroah-Hartman

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

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

From: Manuel Ebner <[email protected]>

[ Upstream commit edf43c031902787117822b23324cf08ccc023bf6 ]

The audit event example in the IPE documentation contains 'sgid=)', which is not a valid Set Group ID value. Fix it to use 'sgid=0'.

Fixes ac6731870ed9 ("documentation: add IPE documentation")
---
 Documentation/admin-guide/LSM/ipe.rst | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
Documentation/admin-guide/LSM/ipe.rst +2 -2
index a756d81585317..bebf14fc24116 100644
@@ -502,11 +502,11 @@ The following table lists the error codes that may appear in the errno field whi
 Event Examples::
 
    type=1404 audit(1653425689.008:55): enforcing=0 old_enforcing=1 auid=4294967295 ses=4294967295 enabled=1 old-enabled=1 lsm=ipe res=1
-   type=1300 audit(1653425689.008:55): arch=c000003e syscall=1 success=yes exit=2 a0=1 a1=55c1065e5c60 a2=2 a3=0 items=0 ppid=405 pid=441 auid=0 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=)
+   type=1300 audit(1653425689.008:55): arch=c000003e syscall=1 success=yes exit=2 a0=1 a1=55c1065e5c60 a2=2 a3=0 items=0 ppid=405 pid=441 auid=0 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0
    type=1327 audit(1653425689.008:55): proctitle="-bash"
 
    type=1404 audit(1653425689.008:55): enforcing=1 old_enforcing=0 auid=4294967295 ses=4294967295 enabled=1 old-enabled=1 lsm=ipe res=1
-   type=1300 audit(1653425689.008:55): arch=c000003e syscall=1 success=yes exit=2 a0=1 a1=55c1065e5c60 a2=2 a3=0 items=0 ppid=405 pid=441 auid=0 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=)
+   type=1300 audit(1653425689.008:55): arch=c000003e syscall=1 success=yes exit=2 a0=1 a1=55c1065e5c60 a2=2 a3=0 items=0 ppid=405 pid=441 auid=0 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0
    type=1327 audit(1653425689.008:55): proctitle="-bash"
 
 This record will always be emitted in conjunction with a ``AUDITSYSCALL`` record for the ``write`` syscall.
Signature · 1 line
2.53.0
author maintainer
#2212 lore raw

PATCH 2192/2651 ipe: fix enforcement audit

In reply to Greg Kroah-Hartman

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

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

From: Fan Wu <[email protected]>

[ Upstream commit 0e5f66bf052223aa5c8caeb8554a7577b54c302f ]

ipe_audit_enforce() starts an audit buffer but writes the state change with audit_log(), which logs its own record. Ending the unused buffer then emits an extra empty AUDIT_MAC_STATUS record.

Remove the unused buffer and log the state change with audit_log() alone.

Fixes a68916eaedcd ("ipe: add permissive toggle")
Assisted-by LLM
---
 security/ipe/audit.c | 8 --------
 1 file changed, 8 deletions(-)
security/ipe/audit.c +0 -8
index 93fb59fbddd60..a299bb35e0d19 100644
@@ -262,18 +262,10 @@ void ipe_audit_policy_load(const struct ipe_policy *const p)
  */
 void ipe_audit_enforce(bool new_enforce, bool old_enforce)
 {
-	struct audit_buffer *ab;
-
-	ab = audit_log_start(audit_context(), GFP_KERNEL, AUDIT_MAC_STATUS);
-	if (!ab)
-		return;
-
 	audit_log(audit_context(), GFP_KERNEL, AUDIT_MAC_STATUS,
 		  "enforcing=%d old_enforcing=%d auid=%u ses=%u"
 		  " enabled=1 old-enabled=1 lsm=ipe res=1",
 		  new_enforce, old_enforce,
 		  from_kuid(&init_user_ns, audit_get_loginuid(current)),
 		  audit_get_sessionid(current));
-
-	audit_log_end(ab);
 }
Signature · 1 line
2.53.0
author maintainer
#2213 lore raw

PATCH 2193/2651 net/sched: act_api: reject duplicate actions in a batch

In reply to Greg Kroah-Hartman

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

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

From: Jamal Hadi Salim <[email protected]>

[ Upstream commit f67b3ed1308d7a282e2d6202d61af052ab0da39e ]

tca_action_gd() builds actions[] with one tcf_action_get_1() per nested TCA_ACT_TAB entry. Each successful lookup takes its own reference to the resolved action, so repeated TCA_ACT_INDEX entries in one request yield the same pointer in multiple slots.

For RTM_DELACTION, tcf_action_delete() then consumes two references per
slot: one in tcf_action_put() and one in tcf_idr_delete_index(). A duplicate therefore drives the refcount to zero mid-walk -- the delete frees the action and removes its IDR slot -- and the next slot calls tcf_action_put() on the freed action:

refcount_t: underflow; use-after-free.

  WARNING: lib/refcount.c:87 at refcount_dec_not_one
   refcount_dec_and_mutex_lock
   __tcf_action_put
   tca_action_gd

Three duplicate entries are enough. Reject a repeated action while a delete batch is built, dropping the reference the extra lookup took, and return -EINVAL. RTM_GETACTION balances its own references and keeps accepting duplicate entries.

Conditions to recreate the bug:
tc actions add action gact index 100
tc actions delete action gact index 100 action gact index 100 \
action gact index 100

---
 net/sched/act_api.c | 21 ++++++++++++++++++++-
 1 file changed, 20 insertions(+), 1 deletion(-)
net/sched/act_api.c +20 -1
index 9eb1dec14cb15..42b5e40b52d09 100644
@@ -2025,7 +2025,7 @@ static int
 tca_action_gd(struct net *net, struct nlattr *nla, struct nlmsghdr *n,
 	      u32 portid, int event, struct netlink_ext_ack *extack)
 {
-	int i, ret;
+	int i, j, ret;
 	struct nlattr *tb[TCA_ACT_MAX_PRIO + 1];
 	struct tc_action *act;
 	size_t attr_size = 0;
@@ -2050,6 +2050,25 @@ tca_action_gd(struct net *net, struct nlattr *nla, struct nlmsghdr *n,
 			ret = PTR_ERR(act);
 			goto err;
 		}
+
+		/* A delete consumes two references per slot (tcf_action_put()
+		 * and tcf_idr_delete_index()) but each entry takes one, so a
+		 * repeated action would hit zero mid-walk.  GET balances its
+		 * own references and keeps accepting duplicates.
+		 */
+		if (event == RTM_DELACTION) {
+			for (j = 0; j < i - 1; j++) {
+				if (actions[j] != act)
+					continue;
+
+				tcf_action_put(act);
+				NL_SET_ERR_MSG(extack,
+					       "Duplicate TC action in a delete batch");
+				ret = -EINVAL;
+				goto err;
+			}
+		}
+
 		attr_size += tcf_action_fill_size(act);
 		actions[i - 1] = act;
 	}
Signature · 1 line
2.53.0
author maintainer
#2214 lore raw

PATCH 2194/2651 RDMA/mlx5: Fix CQ resize destination index mask

In reply to Greg Kroah-Hartman

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

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

From: Li RongQing <[email protected]>

[ Upstream commit 0fe31052d948a3a993bb2f58cd5886f7ec279ea7 ]

In copy_resize_cqes, the destination CQE index is computed as (i + 1) & cq->resize_buf->nent, but resize_buf->nent is produced by roundup_pow_of_two(), so it is a power of two with exactly one bit set. Masking with a single-bit value can only yield 0 or nent itself. The buffer has nent entries, so valid indices are 0 .. nent - 1 and nent is one past the last slot; whenever the masked result is nent the following memcpy writes one entry out of bounds.

Use (nent - 1) as the wrap mask instead. For a power-of-two nent, (i + 1) & (nent - 1) is the correct modulo-nent reduction, keeping the index within [0, nent - 1]. This matches get_sw_cqe(), which addresses the CQ buffer via n & cq->ibcq.cqe, where cq->ibcq.cqe == entries - 1 is exactly the nent - 1 wrap mask.

Fixes bde51583f49b ("IB/mlx5: Add support for resize CQ")
---
 drivers/infiniband/hw/mlx5/cq.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/infiniband/hw/mlx5/cq.c +1 -1
index 1653b2747f5ff..6d4857d1c0640 100644
@@ -1315,7 +1315,7 @@ static int copy_resize_cqes(struct mlx5_ib_cq *cq)
 
 	while (get_cqe_opcode(scqe64) != MLX5_CQE_RESIZE_CQ) {
 		dcqe = mlx5_frag_buf_get_wqe(&cq->resize_buf->fbc,
-					     (i + 1) & cq->resize_buf->nent);
+					     (i + 1) & (cq->resize_buf->nent - 1));
 		dcqe64 = dsize == 64 ? dcqe : dcqe + 64;
 		sw_own = sw_ownership_bit(i + 1, cq->resize_buf->nent);
 		memcpy(dcqe, scqe, dsize);
Signature · 1 line
2.53.0
author maintainer
#2215 lore raw

PATCH 2195/2651 RDMA/mlx5: Validate priority in STEERING_ANCHOR_CREATE handler

In reply to Greg Kroah-Hartman

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

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

From: Serhat Kumral <[email protected]>

[ Upstream commit bb75e5580b15cd23ededf15683a5ad67d7b61aab ]

In MLX5_IB_METHOD_STEERING_ANCHOR_CREATE, the user-supplied u16 priority is passed directly to _get_flow_table() without an upper bound check. This can lead to out-of-bounds array accesses on dev->flow_db priority tables.

Check that priority does not exceed MLX5_IB_FLOW_LAST_PRIO before calling _get_flow_table(), matching the existing validation in raw_fs_rule_add() and mlx5_ib_create_flow().

Fixes 0c6ab0ca9a66 ("RDMA/mlx5: Expose steering anchor to userspace")
---
 drivers/infiniband/hw/mlx5/fs.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/infiniband/hw/mlx5/fs.c +3 -0
index e63fdb4bc3e3f..bc2c15c7172ba 100644
@@ -3014,6 +3014,9 @@ static int UVERBS_HANDLER(MLX5_IB_METHOD_STEERING_ANCHOR_CREATE)(
 	if (err)
 		return err;
 
+	if (priority > MLX5_IB_FLOW_LAST_PRIO)
+		return -EINVAL;
+
 	obj = kzalloc_obj(*obj);
 	if (!obj)
 		return -ENOMEM;
Signature · 1 line
2.53.0
author maintainer
#2216 lore raw

PATCH 2196/2651 net: stmmac: xgmac: do not treat TBU as a TX event

In reply to Greg Kroah-Hartman

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

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

From: Pengfei Zhang <[email protected]>

[ Upstream commit 305deb54c6c287e586bed92da2375ae1220e8dde ]

Commit 8d07a7930434 ("net: stmmac: xgmac: Do not enable TBU interrupt") removed TBUE from the default DMA interrupt mask, but did not remove the TBU check from dwxgmac2_dma_interrupt().

TBU is set whenever a TX channel runs out of descriptors. Since TBUE is not enabled and only enabled bits are cleared, the TBU status bit is never cleared. As a result, TBU stays set on every idle TX channel, regardless of whether there is any TX traffic.

With a shared interrupt, stmmac_dma_interrupt() checks all channels, so every interrupt from any source schedules TX NAPI on every idle TX channel.

Only use TI to trigger TX processing.

Fixes 8d07a7930434 ("net: stmmac: xgmac: Do not enable TBU interrupt")
---
 drivers/net/ethernet/stmicro/stmmac/dwxgmac2_dma.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/ethernet/stmicro/stmmac/dwxgmac2_dma.c +1 -1
index ff83858ebc1f3..0a6e82a155c0e 100644
@@ -346,7 +346,7 @@ static int dwxgmac2_dma_interrupt(struct stmmac_priv *priv,
 		u64_stats_update_end(&stats->syncp);
 		ret |= handle_rx;
 	}
-	if (likely(intr_status & (XGMAC_TI | XGMAC_TBU))) {
+	if (likely(intr_status & XGMAC_TI)) {
 		u64_stats_update_begin(&stats->syncp);
 		u64_stats_inc(&stats->tx_normal_irq_n[chan]);
 		u64_stats_update_end(&stats->syncp);
Signature · 1 line
2.53.0
author maintainer
#2217 lore raw

PATCH 2197/2651 mptcp: options: mpc: avoid printing uninit data

In reply to Greg Kroah-Hartman

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

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

From: Matthieu Baerts (NGI0) <[email protected]>

[ Upstream commit a234ee8eb9a20d1a272f0d2ceabdb35165071778 ]

When parsing the MP_CAPABLE suboption, this pr_debug() might read and print uninitialised values.

That's mostly harmless, but that's also confusing. Fixing that also avoids some tools to complain about accessing uninit data.

So read these fields only if they have been set.

Note: this was initially reported by Clashiko as an existing issue. The code has been analysed by a human and confirmed. This is a non-urgent fix.

---
 net/mptcp/options.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
net/mptcp/options.c +5 -2
index ce0de02f5a3a1..564d10cdb7d12 100644
@@ -126,8 +126,11 @@ static void mptcp_parse_option(const struct sk_buff *skb,
 			ptr += 2;
 		}
 		pr_debug("MP_CAPABLE version=%x, flags=%x, optlen=%d sndr=%llu, rcvr=%llu len=%d csum=%u\n",
-			 version, flags, opsize, mp_opt->sndr_key,
-			 mp_opt->rcvr_key, mp_opt->data_len, mp_opt->csum);
+			 version, flags, opsize,
+			 opsize >= TCPOLEN_MPTCP_MPC_SYNACK ? mp_opt->sndr_key : 0,
+			 opsize >= TCPOLEN_MPTCP_MPC_ACK ? mp_opt->rcvr_key : 0,
+			 opsize >= TCPOLEN_MPTCP_MPC_ACK_DATA ? mp_opt->data_len : 0,
+			 opsize == TCPOLEN_MPTCP_MPC_ACK_DATA_CSUM ? mp_opt->csum : 0);
 		break;
 
 	case MPTCPOPT_MP_JOIN:
Signature · 1 line
2.53.0
author maintainer
#2218 lore raw

PATCH 2198/2651 mptcp: options: dss: avoid printing uninit csum

In reply to Greg Kroah-Hartman

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

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

From: Matthieu Baerts (NGI0) <[email protected]>

[ Upstream commit 00e2690c9dad0e09cd2a4435b98de6d8efd5fbc2 ]

When parsing the DSS suboption, this pr_debug() might read and print uninitialised checksum value.

That's mostly harmless, but that's also confusing. Fixing that also avoids some tools to complain about accessing uninit data.

So read this csum field only if it has been set.

Note: this was initially reported by Clashiko as an existing issue. The code has been analysed by a human and confirmed. This is a non-urgent fix.

---
 net/mptcp/options.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/mptcp/options.c +1 -1
index 564d10cdb7d12..966e785a4f0fe 100644
@@ -259,7 +259,7 @@ static void mptcp_parse_option(const struct sk_buff *skb,
 			pr_debug("data_seq=%llu subflow_seq=%u data_len=%u csum=%d:%u\n",
 				 mp_opt->data_seq, mp_opt->subflow_seq,
 				 mp_opt->data_len, !!(mp_opt->suboptions & OPTION_MPTCP_CSUMREQD),
-				 mp_opt->csum);
+				 (mp_opt->suboptions & OPTION_MPTCP_CSUMREQD) ? mp_opt->csum : 0);
 		}
 
 		break;
Signature · 1 line
2.53.0
author maintainer
#2219 lore raw

PATCH 2199/2651 selftests: tc-testing: use $IP in hfsc test 8c39 setup

In reply to Greg Kroah-Hartman

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

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

From: Ivan Vecera <[email protected]>

[ Upstream commit b6ef0d965fe8ce0ee4b4dcb58b3511f83003e42d ]

Test 8c39 brings up lo with a bare "ip" command. nsPlugin runs it as "$IP netns exec <ns> ip ...", and as tdc runs commands with an empty environment, "ip netns exec" searches only the default execvp() path (/bin:/usr/bin). On systems that install ip only in /sbin, like Fedora, the setup fails:

  # ./tdc.py -e 8c39
  Test 8c39: HFSC classify walk still reaches leaf after lateral drift
  -----> prepare stage *** Could not execute: "ip link set lo up"
  -----> prepare stage *** Error message: "exec of "ip" failed: No such file or directory

Use $IP like all other tdc tests do.

Fixes 1e24c4f2ee44 ("selftests: tc-testing: add a lateral-drift hfsc classify-walk test")
---
 tools/testing/selftests/tc-testing/tc-tests/qdiscs/hfsc.json | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/testing/selftests/tc-testing/tc-tests/qdiscs/hfsc.json +1 -1
index 4f6bbb8b57f93..557730eef0559 100644
@@ -181,7 +181,7 @@
             "requires": "nsPlugin"
         },
         "setup": [
-            "ip link set lo up",
+            "$IP link set lo up",
             "$TC qdisc add dev lo handle 1: root hfsc default 30",
             "$TC class add dev lo parent 1: classid 1:1 hfsc rt m2 100kbit",
             "$TC class add dev lo parent 1:1 classid 1:10 hfsc rt m2 50kbit",
Signature · 1 line
2.53.0
author maintainer
#2220 lore raw

PATCH 2200/2651 ntfs: fix directory lookup on large-page systems

In reply to Greg Kroah-Hartman

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

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

From: Marek Wesołowski <[email protected]>

[ Upstream commit 3581ef455875aead551f9b92fd1e82c8e6fe3fe1 ]

ntfs_lookup_inode_by_name() copies PAGE_SIZE bytes from the index allocation mapping and applies MST fixups to that entire buffer before selecting the requested INDX block.

When PAGE_SIZE is larger than the NTFS index block size, the USA count belongs to the smaller INDX block. post_read_mst_fixup() therefore treats the PAGE_SIZE call as not applicable and leaves the update sequence words in place. A directory entry crossing a sector boundary can then be returned by readdir but missed by lookup.

Select the INDX block first, apply the fixup using its actual block size, and propagate fixup failures before validating the block. Report fixup failures through ntfs_error() so the configured errors= policy is applied.

Return -EIO when post_read_mst_fixup() detects an incomplete multi sector transfer, since this indicates an on-disk metadata integrity error.

Reproduced on arm64 with 16 KiB pages and 4 KiB NTFS index blocks. The affected entry was visible in readdir but stat returned ENOENT. Both exact and case-insensitive lookup succeed after this change.

Fixes 0a8ac0c1fa0b ("ntfs: update directory operations")
---
 fs/ntfs/dir.c | 9 ++++++++-
 fs/ntfs/mst.c | 4 ++--
 2 files changed, 10 insertions(+), 3 deletions(-)
fs/ntfs/dir.c +8 -1
index 09b890b41c4a9..173ba95c0dfd7 100644
@@ -331,7 +331,6 @@ u64 ntfs_lookup_inode_by_name(struct ntfs_inode *dir_ni, const __le16 *uname,
 	}
 
 	memcpy_from_folio(kaddr, folio, 0, PAGE_SIZE);
-	post_read_mst_fixup((struct ntfs_record *)kaddr, PAGE_SIZE);
 	folio_unlock(folio);
 	folio_put(folio);
 fast_descend_into_child_node:
@@ -352,6 +351,14 @@ u64 ntfs_lookup_inode_by_name(struct ntfs_inode *dir_ni, const __le16 *uname,
 			   vcn, dir_ni->mft_no);
 		goto unm_err_out;
 	}
+	err = post_read_mst_fixup((struct ntfs_record *)ia,
+				  dir_ni->itype.index.block_size);
+	if (err) {
+		ntfs_error(sb,
+			   "MST fixup failed for index block vcn %lld in directory inode 0x%llx.",
+			   vcn, dir_ni->mft_no);
+		goto unm_err_out;
+	}
 	err = ntfs_index_block_inconsistent(vol, ia,
 					    dir_ni->itype.index.block_size,
 					    vcn, COLLATION_FILE_NAME,
fs/ntfs/mst.c +2 -2
index 7f9faad924adf..cc6363413449d 100644
@@ -19,7 +19,7 @@
  * magic of the ntfs record header being processed with "BAAD" (in memory only!)
  * and abort processing.
  *
- * Return 0 on success and -EINVAL on error ("BAAD" magic will be present).
+ * Return 0 on success and -EIO on error ("BAAD" magic will be present).
  *
  * NOTE: We consider the absence / invalidity of an update sequence array to
  * mean that the structure is not protected at all and hence doesn't need to
@@ -71,7 +71,7 @@ int post_read_mst_fixup(struct ntfs_record *b, const u32 size)
 			 * Note that magic_BAAD is already converted to le32.
 			 */
 			b->magic = magic_BAAD;
-			return -EINVAL;
+			return -EIO;
 		}
 		data_pos += NTFS_BLOCK_SIZE / sizeof(u16);
 	}
Signature · 1 line
2.53.0
author maintainer
#2221 lore raw

PATCH 2201/2651 ntfs: fix FITRIM bitmap indexing for large pages

In reply to Greg Kroah-Hartman

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

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

From: Hyunchul Lee <[email protected]>

[ Upstream commit 055a8d19788f16d27f07e6ac40155460e3d227b3 ]

The LCN bitmap has one bit per cluster, so a bitmap page represents PAGE_SIZE * 8 clusters. ntfs_trim_fs() still used a 15-bit shift when selecting the page. On arm64 with 16 KiB pages this selects the wrong bitmap page and can test or discard the wrong clusters.

Compute bitmap indices from buf_clusters, use the page cluster base as the bit-search origin, and keep the requested range as the clipping boundary.

Fixes 11ccc9107dc4 ("ntfs: update runlist handling and cluster allocator")
Cc Marek Wesołowski <[email protected]>
---
 fs/ntfs/bitmap.c | 19 ++++++++++---------
 1 file changed, 10 insertions(+), 9 deletions(-)
fs/ntfs/bitmap.c +10 -9
index 5a4457551306d..912fdcca8e011 100644
@@ -20,7 +20,7 @@ int ntfs_trim_fs(struct ntfs_volume *vol, struct fstrim_range *range)
 	struct folio *folio;
 	unsigned long *bitmap;
 	char *kaddr;
-	u64 end, trimmed = 0, start_buf, end_buf, end_cluster;
+	u64 end, trimmed = 0, start_buf, end_buf, end_cluster, page_cluster;
 	u64 start_cluster = ntfs_bytes_to_cluster(vol, range->start);
 	u32 dq = bdev_discard_granularity(vol->sb->s_bdev);
 	int ret = 0;
@@ -45,8 +45,8 @@ int ntfs_trim_fs(struct ntfs_volume *vol, struct fstrim_range *range)
 		return -ENOMEM;
 
 	buf_clusters = PAGE_SIZE * 8;
-	start_index = start_cluster >> 15;
-	end_index = (end_cluster + buf_clusters - 1) >> 15;
+	start_index = start_cluster / buf_clusters;
+	end_index = DIV_ROUND_UP_ULL(end_cluster, buf_clusters);
 
 	for (index = start_index; index < end_index; index++) {
 		folio = ntfs_get_locked_folio(vol->lcnbmp_ino->i_mapping,
@@ -59,19 +59,20 @@ int ntfs_trim_fs(struct ntfs_volume *vol, struct fstrim_range *range)
 		kaddr = kmap_local_folio(folio, 0);
 		bitmap = (unsigned long *)kaddr;
 
-		start_buf = max_t(u64, index * buf_clusters, start_cluster);
-		end_buf = min_t(u64, (index + 1) * buf_clusters, end_cluster);
+		page_cluster = (u64)index * buf_clusters;
+		start_buf = max_t(u64, page_cluster, start_cluster);
+		end_buf = min_t(u64, page_cluster + buf_clusters, end_cluster);
 
 		end = start_buf;
 		while (end < end_buf) {
 			u64 aligned_start, aligned_end, aligned_count;
-			u64 start = find_next_zero_bit(bitmap, end_buf - start_buf,
-					end - start_buf) + start_buf;
+			u64 start = find_next_zero_bit(bitmap, end_buf - page_cluster,
+					end - page_cluster) + page_cluster;
 			if (start >= end_buf)
 				break;
 
-			end = find_next_bit(bitmap, end_buf - start_buf,
-					start - start_buf) + start_buf;
+			end = find_next_bit(bitmap, end_buf - page_cluster,
+					start - page_cluster) + page_cluster;
 
 			aligned_start = ALIGN(ntfs_cluster_to_bytes(vol, start), dq);
 			aligned_end = ALIGN_DOWN(ntfs_cluster_to_bytes(vol, end), dq);
Signature · 1 line
2.53.0
author maintainer
#2222 lore raw

PATCH 2202/2651 ntfs: require page-aligned full-page attribute writes

In reply to Greg Kroah-Hartman

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

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

From: Hyunchul Lee <[email protected]>

[ Upstream commit 2455958526f9458e2663c079a10e2216131c4438 ]

__ntfs_inode_non_resident_attr_pwrite() treats count == PAGE_SIZE as proof that the request covers the complete folio. it allocates the folio without reading it and copies at offset zero. That proof is valid only when pos is page aligned.

Fixes af0db57d4293 ("ntfs: update inode operations")
Cc Marek Wesołowski <[email protected]>
---
 fs/ntfs/inode.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/ntfs/inode.c +2 -2
index 213c4a12b33aa..f6bf51c84795f 100644
@@ -3747,7 +3747,7 @@ static s64 __ntfs_inode_non_resident_attr_pwrite(struct inode *vi,
 
 	index = pos >> PAGE_SHIFT;
 	while (count) {
-		if (count == PAGE_SIZE) {
+		if (count == PAGE_SIZE && !offset_in_page(pos)) {
 			folio = __filemap_get_folio(vi->i_mapping, index,
 					FGP_CREAT | FGP_LOCK,
 					mapping_gfp_mask(mapping));
@@ -3769,7 +3769,7 @@ static s64 __ntfs_inode_non_resident_attr_pwrite(struct inode *vi,
 
 		folio_wait_writeback(folio);
 
-		if (count == PAGE_SIZE) {
+		if (count == PAGE_SIZE && !offset_in_page(pos)) {
 			offset = 0;
 			attr_len = count;
 		} else {
Signature · 1 line
2.53.0
author maintainer
#2223 lore raw

PATCH 2203/2651 ntfs: preserve the 64-bit FITRIM minimum length

In reply to Greg Kroah-Hartman

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

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

From: Xuewen Wang <[email protected]>

[ Upstream commit 406747e46dc8eb73b0976b1e459830927d6022b9 ]

The minlen member of struct fstrim_range is a 64-bit byte count, but ntfs_ioctl_fitrim() uses max_t(u32, ...) to compare it with the device's discard granularity. This truncates the requested minimum length before passing it to ntfs_trim_fs().

For example, a minimum length of 4 GiB is reduced to the discard granularity, allowing smaller free extents to be discarded. The truncated minimum length is also copied back to userspace.

Use max_t(u64, ...) to preserve the requested minimum length. The bitmap scan already compares the aligned extent length against range->minlen using 64-bit values.

Fixes 9c87959601e8 ("ntfs: update file operations")
---
 fs/ntfs/file.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/ntfs/file.c +1 -1
index f8f4418cbcda8..bb8b5613c7a5f 100644
@@ -888,7 +888,7 @@ static int ntfs_ioctl_fitrim(struct ntfs_volume *vol, unsigned long arg)
 	if (range.len < vol->cluster_size)
 		return -EINVAL;
 
-	range.minlen = max_t(u32, range.minlen, bdev_discard_granularity(dev));
+	range.minlen = max_t(u64, range.minlen, bdev_discard_granularity(dev));
 
 	err = ntfs_trim_fs(vol, &range);
 	if (err < 0)
Signature · 1 line
2.53.0
author maintainer
#2224 lore raw

PATCH 2204/2651 ntfs: return -EINVAL from ntfs_collate_ntofs_ulongs() on bad length

In reply to Greg Kroah-Hartman

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

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

From: Baolin Liu <[email protected]>

[ Upstream commit 41001a72daa35ead23d74ee7b6f2373f237c0d72 ]

ntfs_collate_ntofs_ulongs() returns -1 when the key lengths differ or are not a multiple of 4. But -1 is also what cmp_int() returns for "collates before", so the error is indistinguishable from an ordinary result.

ntfs_ie_lookup() acts on that difference: it maps -EINVAL to -ERANGE, but treats -1 as a tree-descent hint and breaks out of the loop. A malformed entry in $Reparse/$R or $ObjId/$O is therefore silently taken as a lookup miss.

Return -EINVAL, as the sibling ntfs_collate_ntofs_ulong() already does. Well-formed keys are unaffected; both indexes use key sizes that are multiples of 4.

Fixes 5218cd102aec ("ntfs: update misc operations")
---
 fs/ntfs/collate.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/ntfs/collate.c +1 -1
index 77e34038902d1..744fdfd7bf585 100644
@@ -73,7 +73,7 @@ static int ntfs_collate_ntofs_ulongs(struct ntfs_volume *vol,
 
 	if (data1_len != data2_len || data1_len & 3) {
 		ntfs_error(vol->sb, "data1_len or data2_len not valid\n");
-		return -1;
+		return -EINVAL;
 	}
 
 	len = data1_len;
Signature · 1 line
2.53.0
author maintainer
#2225 lore raw

PATCH 2205/2651 ntfs: preserve the truncate error in ntfs_enlarge_attribute()

In reply to Greg Kroah-Hartman

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

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

From: Baolin Liu <[email protected]>

[ Upstream commit 5cd6692db2725b111806a813014db864264ad8f9 ]

ntfs_enlarge_attribute() discards the error from ntfs_attr_truncate() and returns -1, which reaches userspace as EPERM. The discarded codes are
meaningful: -ENOSPC when the attribute cannot grow, -EACCES when it is encrypted, -EOPNOTSUPP when compressed, plus -EINVAL and -ENOMEM.

Most callers of ntfs_inode_attr_pwrite() compare the result against the requested length and substitute -EIO, masking this. ntfs_ib_write() does not; it returns the value verbatim, which propagates through ntfs_index_add_filename() to __ntfs_create() and __ntfs_link(), so a full volume reports EPERM instead of ENOSPC from create(), mkdir() and link().

Fixes af0db57d4293 ("ntfs: update inode operations")
---
 fs/ntfs/inode.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
fs/ntfs/inode.c +3 -2
index f6bf51c84795f..5e53a50edeea3 100644
@@ -3657,9 +3657,10 @@ static inline int ntfs_enlarge_attribute(struct inode *vi, s64 pos, s64 count,
 		return -EOPNOTSUPP;
 
 	if (pos + count > ni->data_size) {
-		if (ntfs_attr_truncate(ni, pos + count)) {
+		ret = ntfs_attr_truncate(ni, pos + count);
+		if (ret) {
 			ntfs_debug("Failed to truncate attribute");
-			return -1;
+			return ret;
 		}
 
 		ntfs_attr_reinit_search_ctx(ctx);
Signature · 1 line
2.53.0
author maintainer
#2226 lore raw

PATCH 2206/2651 ntfs: propagate the map_mft_record() error in ntfs_attrlist_entry_add()

In reply to Greg Kroah-Hartman

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

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

From: Baolin Liu <[email protected]>

[ Upstream commit 2db4627c57d608df40647f553a3b5cad1691c1c6 ]

ntfs_attrlist_entry_add() replaces the map_mft_record() error with -EIO, so an -ENOMEM allocation failure is reported as an I/O error. Both callers pass the value on to ntfs_attr_add(), which no longer collapses it since commit 8efe00b098b5 ("ntfs: preserve error code in ntfs_resident_attr_record_add()").

Return PTR_ERR(ni_mrec) instead. Also fix the debug message.

Fixes 495e90fa3348 ("ntfs: update attrib operations")
---
 fs/ntfs/attrlist.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/ntfs/attrlist.c +2 -2
index 78e9a1dc79251..3660e7fd24b13 100644
@@ -337,8 +337,8 @@ int ntfs_attrlist_entry_add(struct ntfs_inode *ni, struct attr_record *attr)
 
 	ni_mrec = map_mft_record(ni);
 	if (IS_ERR(ni_mrec)) {
-		ntfs_debug("Invalid arguments.\n");
-		return -EIO;
+		ntfs_debug("Failed to map mft record.\n");
+		return PTR_ERR(ni_mrec);
 	}
 
 	mref = MK_LE_MREF(ni->mft_no, le16_to_cpu(ni_mrec->sequence_number));
Signature · 1 line
2.53.0
author maintainer
#2227 lore raw

PATCH 2207/2651 ntfs: propagate the ntfs_attr_iget() error in update_reparse_data()

In reply to Greg Kroah-Hartman

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

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

From: Baolin Liu <[email protected]>

[ Upstream commit acb8042c76cbbb8a8a54f4fa1e98aa4f569491c5 ]

update_reparse_data() replaces the ntfs_attr_iget() error with -EINVAL, so an -ENOMEM from iget5_locked() or a read failure from ntfs_read_locked_attr_inode() is reported to userspace as EINVAL.

The path is reached from __ntfs_create() via the three ntfs_reparse_set_*() helpers, so symlink() and mknod() are affected.

Return PTR_ERR(rp_inode) instead.

Fixes fc053f05ca28 ("ntfs: add reparse and ea operations")
---
 fs/ntfs/reparse.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/ntfs/reparse.c +1 -1
index 1a6073e22677c..2a6480211fe32 100644
@@ -676,7 +676,7 @@ static int update_reparse_data(struct ntfs_inode *ni, struct ntfs_index_context
 
 	rp_inode = ntfs_attr_iget(VFS_I(ni), AT_REPARSE_POINT, AT_UNNAMED, 0);
 	if (IS_ERR(rp_inode))
-		return -EINVAL;
+		return PTR_ERR(rp_inode);
 	rp_ni = NTFS_I(rp_inode);
 
 	/* remove the existing reparse data */
Signature · 1 line
2.53.0
author maintainer
#2228 lore raw

PATCH 2208/2651 ntfs: fix error handling in ntfs_extent_inode_open and propagate errors

In reply to Greg Kroah-Hartman

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

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

From: Baolin Liu <[email protected]>

[ Upstream commit 67f27176e2ca8161f212b72ec48d8c8d6e7f5e7e ]

ntfs_extent_inode_open() has two issues:

1. When map_mft_record() fails or a stale extent reference is found, it returns the non-NULL 'ni' pointer instead of an error, causing the caller to treat the failure as success.

2. For allocation failures, it returns NULL, losing information about what actually went wrong (-ENOMEM).

Fix both by converting the function to return ERR_PTR() on error, and update the single caller (ntfs_inode_attach_all_extents) to check with IS_ERR() and propagate the actual error code with PTR_ERR().

Fixes af0db57d4293 ("ntfs: update inode operations")
---
 fs/ntfs/inode.c | 28 ++++++++++++++--------------
 1 file changed, 14 insertions(+), 14 deletions(-)
fs/ntfs/inode.c +14 -14
index 5e53a50edeea3..302089f7f83a4 100644
@@ -2943,8 +2943,7 @@ int __ntfs_write_inode(struct inode *vi, int sync)
  * abort if deprotection or checks fail.
  *
  * Finally attach the ntfs inode to its base inode @base_ni and return a
- * pointer to the ntfs_inode structure on success or NULL on error, with errno
- * set to the error code.
+ * pointer to the ntfs_inode structure on success or ERR_PTR() on error.
  *
  * Note, extent inodes are never closed directly. They are automatically
  * disposed off by the closing of the base inode.
@@ -2960,7 +2959,7 @@ static struct ntfs_inode *ntfs_extent_inode_open(struct ntfs_inode *base_ni,
 	struct super_block *sb;
 
 	if (!base_ni)
-		return NULL;
+		return ERR_PTR(-EINVAL);
 
 	sb = base_ni->vol->sb;
 	ntfs_debug("Opening extent inode %llu (base mft record %llu).\n",
@@ -2979,7 +2978,7 @@ static struct ntfs_inode *ntfs_extent_inode_open(struct ntfs_inode *base_ni,
 			if (IS_ERR(ni_mrec)) {
 				ntfs_error(sb, "failed to map mft record for %llu",
 						ni->mft_no);
-				goto out;
+				return ERR_CAST(ni_mrec);
 			}
 			/* Verify the sequence number if given. */
 			seq_no = MSEQNO_LE(mref);
@@ -2988,7 +2987,7 @@ static struct ntfs_inode *ntfs_extent_inode_open(struct ntfs_inode *base_ni,
 				ntfs_error(sb, "Found stale extent mft reference mft=%llu",
 						ni->mft_no);
 				unmap_mft_record(ni);
-				goto out;
+				return ERR_PTR(-EIO);
 			}
 			unmap_mft_record(ni);
 			goto out;
@@ -2997,7 +2996,7 @@ static struct ntfs_inode *ntfs_extent_inode_open(struct ntfs_inode *base_ni,
 	/* Wasn't there, we need to load the extent inode. */
 	ni = ntfs_new_extent_inode(base_ni->vol->sb, mft_no);
 	if (!ni)
-		goto out;
+		return ERR_PTR(-ENOMEM);
 
 	ni->seq_no = (u16)MSEQNO_LE(mref);
 	ni->nr_extents = -1;
@@ -3007,8 +3006,10 @@ static struct ntfs_inode *ntfs_extent_inode_open(struct ntfs_inode *base_ni,
 		i = (base_ni->nr_extents + 4) * sizeof(struct ntfs_inode *);
 
 		extent_nis = kvzalloc(i, GFP_NOFS);
-		if (!extent_nis)
-			goto err_out;
+		if (!extent_nis) {
+			ntfs_destroy_ext_inode(ni);
+			return ERR_PTR(-ENOMEM);
+		}
 		if (base_ni->nr_extents) {
 			memcpy(extent_nis, base_ni->ext.extent_ntfs_inos,
 					i - 4 * sizeof(struct ntfs_inode *));
@@ -3021,10 +3022,6 @@ static struct ntfs_inode *ntfs_extent_inode_open(struct ntfs_inode *base_ni,
 out:
 	ntfs_debug("\n");
 	return ni;
-err_out:
-	ntfs_destroy_ext_inode(ni);
-	ni = NULL;
-	goto out;
 }
 
 /*
@@ -3062,9 +3059,12 @@ int ntfs_inode_attach_all_extents(struct ntfs_inode *ni)
 	while ((u8 *)ale < ni->attr_list + ni->attr_list_size) {
 		if (ni->mft_no != MREF_LE(ale->mft_reference) &&
 				prev_attached != MREF_LE(ale->mft_reference)) {
-			if (!ntfs_extent_inode_open(ni, ale->mft_reference)) {
+			struct ntfs_inode *ext_ni;
+
+			ext_ni = ntfs_extent_inode_open(ni, ale->mft_reference);
+			if (IS_ERR(ext_ni)) {
 				ntfs_debug("Couldn't attach extent inode.\n");
-				return -1;
+				return PTR_ERR(ext_ni);
 			}
 			prev_attached = MREF_LE(ale->mft_reference);
 		}
Signature · 1 line
2.53.0
author maintainer
#2229 lore raw

PATCH 2209/2651 ntfs: fix runlist marker allocation and count

In reply to Greg Kroah-Hartman

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

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

From: pwngets <[email protected]>

[ Upstream commit c1bd2f1c22c2fa8c5f0f51f82afad23f2dd1bcf1 ]

The marker path can append an unmapped element and an ENOENT terminator after the merge helpers have already computed the resulting runlist count. In that case, allocating ds + 2 elements leaves no room for the terminator at ds + 2. The path also increments new_rl_count even though the merge helper already accounted for the final runlist size, causing a later merge to start past the terminator.

Allocate space through ds + 2, and derive new_rl_count from the final terminator index instead of incrementing the count a second time.

A crafted NTFS image can reach this path through a normal read after the image has been mounted and trigger out-of-bounds kernel heap accesses.

Fixes 11ccc9107dc4 ("ntfs: update runlist handling and cluster allocator")
Assisted-by OpenAI Codex:GPT-5
---
 fs/ntfs/runlist.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
fs/ntfs/runlist.c +2 -3
index 89e13a452a845..76ba6ab72b8a6 100644
@@ -702,9 +702,8 @@ static struct runlist_element *__ntfs_runlists_merge(struct runlist *d_runlist,
 				/* Add an unmapped runlist element. */
 				if (!slots) {
 					drl = ntfs_rl_realloc_nofail(drl, ds,
-							ds + 2);
+							ds + 3);
 					slots = 2;
-					*new_rl_count += 2;
 				}
 				ds++;
 				/* Need to set vcn if it isn't set already. */
@@ -720,11 +719,11 @@ static struct runlist_element *__ntfs_runlists_merge(struct runlist *d_runlist,
 			ds++;
 			if (!slots) {
 				drl = ntfs_rl_realloc_nofail(drl, ds, ds + 1);
-				*new_rl_count += 1;
 			}
 			drl[ds].vcn = marker_vcn;
 			drl[ds].lcn = LCN_ENOENT;
 			drl[ds].length = (s64)0;
+			*new_rl_count = ds + 1;
 		}
 	}
 	}
Signature · 1 line
2.53.0
author maintainer
#2230 lore raw

PATCH 2210/2651 ntfs: wait for the bitmap scan before MFT bitmap extension

In reply to Greg Kroah-Hartman

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

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

From: Xuewen Wang <[email protected]>

[ Upstream commit 0c3f2944e9060c31a221f32906267b827659b0c7 ]

If MFT bitmap extension fails before the initial $Bitmap scan completes, rollback calls ntfs_bitmap_clear_bit(), which holds a folio lock while ntfs_set_lcn_empty_bits() waits for the scan. The scanner deadlocks if it still needs that folio.

Wait for the initial scan before taking the runlist or bitmap folio locks and attempting allocation.

Fixes 11ccc9107dc4 ("ntfs: update runlist handling and cluster allocator")
---
 fs/ntfs/mft.c | 4 ++++
 1 file changed, 4 insertions(+)
fs/ntfs/mft.c +4 -0
index 482a216ade2cb..3192c018653b3 100644
@@ -1352,6 +1352,10 @@ static int ntfs_mft_bitmap_extend_allocation_nolock(struct ntfs_volume *vol)
 	size_t new_rl_count;
 
 	ntfs_debug("Extending mft bitmap allocation.");
+	/* The initial bitmap scan must finish before we lock or change a folio. */
+	if (!NVolFreeClusterKnown(vol))
+		wait_event(vol->free_waitq, NVolFreeClusterKnown(vol));
+
 	mft_ni = NTFS_I(vol->mft_ino);
 	mftbmp_ni = NTFS_I(vol->mftbmp_ino);
 	/*
Signature · 1 line
2.53.0
author maintainer
#2231 lore raw

PATCH 2211/2651 ntfs: account for direct MFT bitmap cluster allocation

In reply to Greg Kroah-Hartman

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

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

From: Xuewen Wang <[email protected]>

[ Upstream commit 109c9b0f67f97a34b19491fa82242a2130114903 ]

The MFT bitmap extension fast path sets $Bitmap directly, bypassing ntfs_cluster_alloc() and its free_clusters and lcn_empty_bits_per_page updates. Successful extensions overreport free space, and rollback adds back counts that were never deducted.

Update both counts under lcnbmp_lock and the bitmap folio lock. Require a nonzero page count and space remaining after delayed-allocation reservations; otherwise use the regular allocator. The page check also prevents underflow when the initial scan recorded zero after a read error.

Fixes 6251f0b0de7d ("ntfs: update super block operations")
---
 fs/ntfs/mft.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
fs/ntfs/mft.c +9 -1
index 3192c018653b3..04ea38a824380 100644
@@ -1399,10 +1399,18 @@ static int ntfs_mft_bitmap_extend_allocation_nolock(struct ntfs_volume *vol)
 	folio_lock(folio);
 	b = (u8 *)kmap_local_folio(folio, 0) + (ll & ~PAGE_MASK);
 	tb = 1 << (lcn & 7ull);
-	if (*b != 0xff && !(*b & tb)) {
+	/*
+	 * A page skipped by the initial scan has no free bits recorded.
+	 * Honor that and the space reserved for delayed allocation.
+	 */
+	if (*b != 0xff && !(*b & tb) &&
+	    vol->lcn_empty_bits_per_page[ll >> PAGE_SHIFT] &&
+	    ntfs_available_clusters_count(vol, 1) > 0) {
 		/* Next cluster is free, allocate it. */
 		*b |= tb;
 		folio_mark_dirty(folio);
+		ntfs_dec_free_clusters(vol, 1);
+		ntfs_set_lcn_empty_bits(vol, ll >> PAGE_SHIFT, 1, 1);
 		folio_unlock(folio);
 		kunmap_local(b);
 		folio_put(folio);
Signature · 1 line
2.53.0
author maintainer
#2232 lore raw

PATCH 2212/2651 ntfs: avoid misclassifying directory reparse points

In reply to Greg Kroah-Hartman

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

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

From: Hyunchul Lee <[email protected]>

[ Upstream commit 22002cb8b6594830dc0b2d26faf1aa5fa3de94c1 ]

Windows directory symlinks and junctions can carry FILE_ATTR_DUP_FILE_NAME_INDEX_PRESENT in their entry while the reparse flag is stored only in. The old directory enumeration path treated such entries as DT_DIR, allowing no-follow userspace scanners to recurse through symlink targets.

Fixes 0a8ac0c1fa0b ("ntfs: update directory operations")
---
 fs/ntfs/dir.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
fs/ntfs/dir.c +3 -3
index 173ba95c0dfd7..b72990c2dd58d 100644
@@ -635,11 +635,11 @@ static inline int ntfs_filldir(struct ntfs_volume *vol,
 	}
 
 	mref = MREF_LE(ie->data.dir.indexed_file);
-	if (ie->key.file_name.file_attributes &
+	if (ie->key.file_name.file_attributes & FILE_ATTR_REPARSE_POINT)
+		dt_type = ntfs_reparse_tag_dt_types(vol, mref);
+	else if (ie->key.file_name.file_attributes &
 			FILE_ATTR_DUP_FILE_NAME_INDEX_PRESENT)
 		dt_type = DT_DIR;
-	else if (ie->key.file_name.file_attributes & FILE_ATTR_REPARSE_POINT)
-		dt_type = ntfs_reparse_tag_dt_types(vol, mref);
 	else
 		dt_type = DT_REG;
 
Signature · 1 line
2.53.0
author maintainer
#2233 lore raw

PATCH 2213/2651 ntfs: accept standard sparse compression unit

In reply to Greg Kroah-Hartman

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

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

From: Hyunchul Lee <[email protected]>

[ Upstream commit 87a548005f7a56e4171ff5d2050c591547b5449f ]

Windows native sparse-file inspection shows that a non-resident $DATA attribute can be marked sparse and record the standard compression unit
(4) even when the file is not compressed.

Fixes af0db57d4293 ("ntfs: update inode operations")
---
 fs/ntfs/inode.c | 13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)
fs/ntfs/inode.c +10 -3
index 302089f7f83a4..71b364e2ca73f 100644
@@ -1148,14 +1148,21 @@ static int ntfs_read_locked_inode(struct inode *vi)
 					goto unm_err_out;
 				}
 
+				/*
+				 * Windows stores the standard compression unit in
+				 * sparse attributes even when the data is not compressed.
+				 */
 				if (NInoSparse(ni) &&
 				    a->data.non_resident.compression_unit &&
 				    a->data.non_resident.compression_unit !=
-				     vol->sparse_compression_unit) {
+				     vol->sparse_compression_unit &&
+				    a->data.non_resident.compression_unit !=
+				     STANDARD_COMPRESSION_UNIT) {
 					ntfs_error(vi->i_sb,
-						   "Found non-standard compression unit (%u instead of 0 or %d).  Cannot handle this.",
+						   "Found non-standard compression unit (%u instead of 0, %d, or %d).  Cannot handle this.",
 						   a->data.non_resident.compression_unit,
-						   vol->sparse_compression_unit);
+						   vol->sparse_compression_unit,
+						   STANDARD_COMPRESSION_UNIT);
 					err = -EOPNOTSUPP;
 					goto unm_err_out;
 				}
Signature · 1 line
2.53.0
author maintainer
#2234 lore raw

PATCH 2214/2651 ntfs: reject non-resident attributes whose sizes exceed their allocation

In reply to Greg Kroah-Hartman

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

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

From: Matthias Goergens <[email protected]>

[ Upstream commit 8e91379152204a9cc18fa7e16724646ad3aec759 ]

ntfs_read_locked_inode(), ntfs_read_locked_attr_inode() and ntfs_read_locked_index_inode() take a non-resident attribute's data_size and initialized_size from disk without checking them against its allocated_size. The runlist ends at allocated_size and the read path maps what lies beyond it as a hole, so a data_size larger than the allocation makes reads return zeros that are not on disk, with no error.

On a crafted volume with 4 KiB clusters where a 6144000-byte file claims a data_size and initialized_size 64 KiB beyond its allocation, reading the file returns 16 clusters of such zeros. A sparse file behaves the same. A compressed file instead fails with -EIO after a burst of "Still have pages left!" errors from ntfs_read_compressed_block().

Require 0 <= initialized_size <= data_size <= allocated_size, with allocated_size a multiple of the cluster size, when the inode is read, as fs/ntfs3 does in mi_enum_attr(), and fail with -EIO otherwise, which marks the inode bad and the volume as having errors. initialized_size above data_size is rejected too because an extending write zeroes the gap it opens only from initialized_size onwards. An unaligned allocated_size ends inside a cluster that the read path treats as past the end: a crafted 66440-byte file with 4 KiB clusters reads its last 904 bytes as zeros.

Sparse and compressed attributes need no exception. Every non-resident attribute has a cluster-aligned allocated_size >= data_size, holes included, on eight public test volumes (seven written by Windows, with LZNT1-compressed files, a sparse $UsnJrnl:$J and a OneDrive placeholder whose unnamed $DATA is one hole, and one by mkntfs), on a volume written by ntfs-3g and on one written by this driver, and the patched driver reads every file on them as before. fs/ntfs3 has enforced the same checks since v6.6, also without exceptions. The layout.h comment saying that data_size can exceed allocated_size for compressed and sparse attributes is corrected.

This also covers a non-resident attribute list, which load_attribute_list() reads through ntfs_attr_iget(), and $MFT, whose inode goes through ntfs_read_locked_inode() after the previous patch's check. $MFT's own non-resident attribute list goes through neither:
ntfs_read_inode_mount() loads it with load_attribute_list_mount() and ntfs_read_locked_inode() skips it for $MFT, so the check is added there too. The check was already missing in the classic driver; the Fixes tag names the commit that brought that code back.

Fixes 1e9ea7e04472 ("Revert "fs: Remove NTFS classic"")
---
 fs/ntfs/inode.c  | 27 +++++++++++++++++++++++++++
 fs/ntfs/layout.h | 13 ++++++++-----
 2 files changed, 35 insertions(+), 5 deletions(-)
fs/ntfs/inode.c +27 -0
index 71b364e2ca73f..f3e42ec65bdc7 100644
@@ -651,6 +651,25 @@ void ntfs_set_vfs_operations(struct inode *inode, mode_t mode, dev_t dev)
 	}
 }
 
+static bool ntfs_non_resident_sizes_inconsistent(struct inode *vi,
+						 const struct attr_record *a)
+{
+	s64 allocated_size = le64_to_cpu(a->data.non_resident.allocated_size);
+	s64 data_size = le64_to_cpu(a->data.non_resident.data_size);
+	s64 initialized_size = le64_to_cpu(a->data.non_resident.initialized_size);
+
+	if (initialized_size >= 0 && initialized_size <= data_size &&
+	    data_size <= allocated_size &&
+	    !ntfs_bytes_to_cluster_off(NTFS_I(vi)->vol, allocated_size))
+		return false;
+
+	ntfs_error(vi->i_sb,
+		   "Attribute 0x%x of inode 0x%llx is corrupt (initialized size %lld, data size %lld, allocated size %lld).",
+		   le32_to_cpu(a->type), NTFS_I(vi)->mft_no, initialized_size,
+		   data_size, allocated_size);
+	return true;
+}
+
 /*
  * ntfs_read_locked_inode - read an inode from its device
  * @vi:		inode to read
@@ -1191,6 +1210,8 @@ static int ntfs_read_locked_inode(struct inode *vi)
 					"First extent of $DATA attribute has non zero lowest_vcn.");
 				goto unm_err_out;
 			}
+			if (ntfs_non_resident_sizes_inconsistent(vi, a))
+				goto unm_err_out;
 			vi->i_size = ni->data_size = le64_to_cpu(a->data.non_resident.data_size);
 			ni->initialized_size = le64_to_cpu(a->data.non_resident.initialized_size);
 			ni->allocated_size = le64_to_cpu(a->data.non_resident.allocated_size);
@@ -1453,6 +1474,8 @@ static int ntfs_read_locked_attr_inode(struct inode *base_vi, struct inode *vi)
 			ntfs_error(vi->i_sb, "First extent of attribute has non-zero lowest_vcn.");
 			goto unm_err_out;
 		}
+		if (ntfs_non_resident_sizes_inconsistent(vi, a))
+			goto unm_err_out;
 		vi->i_size = ni->data_size = le64_to_cpu(a->data.non_resident.data_size);
 		ni->initialized_size = le64_to_cpu(a->data.non_resident.initialized_size);
 		ni->allocated_size = le64_to_cpu(a->data.non_resident.allocated_size);
@@ -1682,6 +1705,8 @@ static int ntfs_read_locked_index_inode(struct inode *base_vi, struct inode *vi)
 			"First extent of $INDEX_ALLOCATION attribute has non zero lowest_vcn.");
 		goto unm_err_out;
 	}
+	if (ntfs_non_resident_sizes_inconsistent(vi, a))
+		goto unm_err_out;
 	vi->i_size = ni->data_size = le64_to_cpu(a->data.non_resident.data_size);
 	ni->initialized_size = le64_to_cpu(a->data.non_resident.initialized_size);
 	ni->allocated_size = le64_to_cpu(a->data.non_resident.allocated_size);
@@ -2015,6 +2040,8 @@ int ntfs_read_inode_mount(struct inode *vi)
 					"Attribute list has non zero lowest_vcn. $MFT is corrupt. You should run chkdsk.");
 				goto put_err_out;
 			}
+			if (ntfs_non_resident_sizes_inconsistent(vi, a))
+				goto put_err_out;
 
 			rl = ntfs_mapping_pairs_decompress(vol, a, NULL, &new_rl_count);
 			if (IS_ERR(rl)) {
fs/ntfs/layout.h +8 -5
index 9438fd9b668e2..e4d246f0159fe 100644
@@ -811,14 +811,17 @@ enum {
  *                                  on XP SP2+.
  * @data.non_resident.reserved:     5 bytes for 8-byte alignment.
  * @data.non_resident.allocated_size:
- *                                  Allocated disk space in bytes.
- *                                  For compressed: logical allocated size.
+ *                                  Allocated size in bytes, a multiple of
+ *                                  the cluster size.  For compressed and
+ *                                  sparse attributes holes count as
+ *                                  allocated; the clusters actually in use
+ *                                  are in compressed_size.
  * @data.non_resident.data_size:    Logical attribute value size in bytes.
- *                                  Can be larger than allocated_size if
- *                                  compressed/sparse.
+ *                                  Never larger than allocated_size, also
+ *                                  when compressed/sparse.
  * @data.non_resident.initialized_size:
  *                                  Initialized portion size in bytes.
- *                                  Usually equals data_size.
+ *                                  Usually equals data_size, never larger.
  * @data.non_resident.compressed_size:
  *                                  Compressed on-disk size in bytes.
  *                                  Only present when compressed or sparse.
Signature · 1 line
2.53.0
author maintainer
#2235 lore raw

PATCH 2215/2651 ntfs: set the attribute list size before reserving space for it

In reply to Greg Kroah-Hartman

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

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

From: Matthias Goergens <[email protected]>

[ Upstream commit 4985f322659f1e667226370e4a7129ebd850c990 ]

ntfs_attrlist_update_locked() resizes the attribute list and then, for $MFT, tries to reserve the maximum list size. When that allocation fails with -ENOSPC it falls back to ntfs_attrlist_repack(), which reads the list through ntfs_inode_attr_pread(). The read stops at i_size, but i_size is only updated after the reserve, so when the list has just grown the repack gets a short read and returns -EIO. Only -ENOSPC from the reserve is ignored, so the -EIO fails the $MFT extension and with it the file creation that needed a new mft record.

On a 32 MiB volume with 512-byte clusters whose $MFT has a non-resident attribute list, 591 of 1500 creations of empty files succeed and the rest fail with EIO while 742 KiB is still free:

ntfs: (device vda): ntfs_attrlist_update_locked(): Failed to reserve attribute list space
ntfs: Failed add attr entry to attrlist
ntfs: MP update failed
ntfs: (device vda): ntfs_mft_record_alloc(): Failed to extend mft data allocation.

Update i_size as soon as the list has been resized. File creation then goes on until the volume is full and fails with ENOSPC.

Fixes b1d732e62a5b ("ntfs: repack $MFT/$ATTRIBUTE LIST")
---
 fs/ntfs/attrlist.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
fs/ntfs/attrlist.c +3 -2
index 3660e7fd24b13..6edd5d2d9bf24 100644
@@ -256,6 +256,9 @@ int ntfs_attrlist_update_locked(struct ntfs_inode *base_ni,
 		return err;
 	}
 
+	/* ntfs_attrlist_repack() below reads the list up to i_size. */
+	i_size_write(attr_vi, base_ni->attr_list_size);
+
 	/*
 	 * Reserve the maximum legal list size while the MFT metadata area is
 	 * still easy to allocate contiguously. This prevents a later list entry
@@ -283,8 +286,6 @@ int ntfs_attrlist_update_locked(struct ntfs_inode *base_ni,
 		}
 	}
 
-	i_size_write(attr_vi, base_ni->attr_list_size);
-
 	if (NInoNonResident(attr_ni) && !NInoAttrListNonResident(base_ni))
 		NInoSetAttrListNonResident(base_ni);
 
Signature · 1 line
2.53.0
author maintainer
#2236 lore raw

PATCH 2216/2651 ntfs: restart the zone search when the allocation hint fails

In reply to Greg Kroah-Hartman

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

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

From: Matthias Goergens <[email protected]>

[ Upstream commit 18d4d2a3ce756af690a620a5199616ce2611c2c9 ]

When ntfs_cluster_alloc() is given a start_lcn, it first tries the clusters from there on. If that does not satisfy the request, it moves on to the zone's current position, but keeps the pass, the zone_end and the has_guess state it had. That loses free clusters in two ways. If the search had already moved on to pass 2, whose range ends at the hint, it scans only from the zone position to the hint and misses every free cluster between the start of the zone and the zone position. If no cluster had been tested yet, has_guess is still set, so the cluster at the zone position is tried as if it had been the hint, and when that cluster is in use the rest of the bitmap buffer is skipped.

Both happen when the hint lies at or past the end of the volume, which ntfs_attr_map_cluster() produces when it extrapolates from the last allocated run across a hole. The allocator then finds nothing, shrinks the MFT zone to nothing trying to satisfy the request, and fails with -ENOSPC.

To reproduce on a 128 MiB volume with 4 KiB clusters, extend two files in turn by one cluster at a time, alternating between fallocate(), write() past EOF and truncate() up, so that the runs of each file are separated by holes. When the volume is full, truncate both files back to 1 MiB and start again. During the second round a one-cluster fallocate() fails with ENOSPC while 40 MiB is free.

Start the zone over as if no hint had been given. A contiguous request can get there with the run from the hint already allocated, when that run reached the end of a bitmap buffer or of the zone. Return that run instead, as when a cluster in use ends it; going on at the zone position gives the request a second run that its caller does not expect. That could happen before this patch too, whenever the cluster at the zone position was free. ntfs_attr_map_cluster() reports and zeroes only the first run, so after a fallocate() of 20 clusters over a hole, with the hint 4 clusters before the end of the volume, 16 of them read back the data of a deleted file.

Fixes 11ccc9107dc4 ("ntfs: update runlist handling and cluster allocator")
---
 fs/ntfs/lcnalloc.c | 25 ++++++++++++++++++++++---
 1 file changed, 22 insertions(+), 3 deletions(-)
fs/ntfs/lcnalloc.c +22 -3
index 0d6cd08ee2e76..c58e689fb5852 100644
@@ -506,13 +506,32 @@ struct runlist_element *ntfs_cluster_alloc(struct ntfs_volume *vol, const s64 st
 		}
 
 		if (!used_zone_pos) {
+			/*
+			 * The run at @start_lcn reached the end of the buffer
+			 * or the zone.  A contiguous request gets that run
+			 * alone, not a second one from the zone position.
+			 */
+			if (is_contig && rlpos)
+				goto out;
+			/*
+			 * Leaving @start_lcn for the zone position starts the
+			 * zone over as if no hint had been given, even if the
+			 * search had already reached pass 2, whose range ends
+			 * at @start_lcn.
+			 */
 			used_zone_pos = 1;
-			if (search_zone == 1)
+			has_guess = 0;
+			pass = 1;
+			if (search_zone == 1) {
 				zone_start = vol->mft_zone_pos;
-			else if (search_zone == 2)
+				zone_end = vol->mft_zone_end;
+			} else if (search_zone == 2) {
 				zone_start = vol->data1_zone_pos;
-			else
+				zone_end = vol->nr_clusters;
+			} else {
 				zone_start = vol->data2_zone_pos;
+				zone_end = vol->mft_zone_start;
+			}
 
 			if (!zone_start || zone_start == vol->mft_zone_start ||
 			    zone_start == vol->mft_zone_end)
Signature · 1 line
2.53.0
author maintainer
#2237 lore raw

PATCH 2217/2651 ntfs: do not refuse fallocate() when the MFT zone is empty

In reply to Greg Kroah-Hartman

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

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

From: Matthias Goergens <[email protected]>

[ Upstream commit 540fe7e8cf432a7de22064a50bb8c33d1240c1e9 ]

ntfs_fallocate() fails with -ENOSPC whenever the MFT zone has shrunk to nothing. The cluster allocator gives the MFT zone up when it cannot find free clusters elsewhere, and nothing restores it before the next mount, so after one such failure every fallocate() on the volume fails with ENOSPC, punching holes included, however much space is freed. The allocator failure fixed by the previous patch was enough to get there:
afterwards a one-cluster fallocate() failed with ENOSPC while 123 MiB of the 128 MiB volume were free.

write() and truncate() do not look at the MFT zone, and ntfs_allocate_range() already fails with -ENOSPC when too few clusters are free. Remove the check.

Fixes 9c87959601e8 ("ntfs: update file operations")
---
 fs/ntfs/file.c | 3 ---
 1 file changed, 3 deletions(-)
fs/ntfs/file.c +0 -3
index bb8b5613c7a5f..20b6019e6bd19 100644
@@ -1163,9 +1163,6 @@ static long ntfs_fallocate(struct file *file, int mode, loff_t offset, loff_t le
 	if (!NVolFreeClusterKnown(vol))
 		wait_event(vol->free_waitq, NVolFreeClusterKnown(vol));
 
-	if ((ni->vol->mft_zone_end - ni->vol->mft_zone_start) == 0)
-		return -ENOSPC;
-
 	if (NInoNonResident(ni) && !NInoFullyMapped(ni)) {
 		down_write(&ni->runlist.lock);
 		err = ntfs_attr_map_whole_runlist(ni);
Signature · 1 line
2.53.0
author maintainer
#2238 lore raw

PATCH 2218/2651 ntfs: do not give a contiguous cluster allocation a second run

In reply to Greg Kroah-Hartman

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

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

From: Matthias Goergens <[email protected]>

[ Upstream commit b05a67615b982cfaa903df8a6fb055d18ebafe11 ]

ntfs_attr_map_cluster() asks ntfs_cluster_alloc() for contiguous clusters and merges the whole result into the runlist, but reports only its first run, so its callers zero only that run. Within a bitmap page the allocator keeps such a request to one run, because a cluster in use ends it. The zone search can also move on without testing the clusters after the run, though: it skips a bitmap page that has no free clusters, it goes from the end of the zone to the start of pass 2, and once every zone has been searched it shrinks the MFT zone by half and goes on at its new end. After each of these jumps the first cluster tested is still taken as the next one of the run, and if it is free it starts a second run elsewhere on the volume.

fallocate() over a hole then leaves the clusters of that second run holding whatever they held before: on a nearly full volume, 16 of 20 fallocated clusters read back a deleted file's data, in each of the three cases.

Delayed allocation gets a second run without punching any holes: filling the same volume with write() reaches the last case when the MFT zone is shrunk. The allocator then takes only the first run off the dirty-cluster count, and after the fill statfs() reported no free space while 939 clusters were still free, until the next mount.

Before setting the bit of a cluster for a contiguous request, check that the cluster comes right after the run, and return the run as it is if not; no bit has to be cleared. ntfs_attr_map_cluster() already handles a short run, which a cluster in use produces in the same way: its callers ask again for the rest.

---
 fs/ntfs/lcnalloc.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
fs/ntfs/lcnalloc.c +10 -0
index c58e689fb5852..3ebcac4c28648 100644
@@ -375,6 +375,16 @@ struct runlist_element *ntfs_cluster_alloc(struct ntfs_volume *vol, const s64 st
 				has_guess = 1;
 				continue;
 			}
+			/*
+			 * A contiguous request gets a single run.  The scan can
+			 * move on without testing the clusters after the run
+			 * (past a bitmap page that is full, to pass 2 or to
+			 * another zone), so return the run when this cluster
+			 * does not follow it.
+			 */
+			if (is_contig && rlpos &&
+			    lcn + bmp_pos != prev_lcn + prev_run_len)
+				goto out;
 			/*
 			 * Allocate more memory if needed, including space for
 			 * the terminator element.
Signature · 1 line
2.53.0
author maintainer
#2239 lore raw

PATCH 2219/2651 ntfs: drain in-flight DIO before buffered write fallback

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]>

[ Upstream commit c10e0c37697c4dd47006709af49b98cd3af45ddd ]

An asynchronous direct write can remain in flight after the inode lock is released. If another direct write falls back to buffered I/O while the first write is still pending, iomap_file_buffered_write() can dirty pages before the first write completes its post-I/O page cache invalidation. The invalidation then finds dirty pages, reports a page cache invalidation failure, and records -EIO in the mapping error sequence. A later fsync() therefore returns -EIO.

Commit 15cdefd0c0522f9d5e12d947fa04f4c11649b699 ("ext4: drain in-flight DIO before buffered write fallback") fixed the same race in ext4. NTFS has an equivalent fallback after iomap_dio_rw() returns -ENOTBLK or a short write, but does not drain other in-flight DIO before dirtying the page cache.

Wait for in-flight DIO before calling iomap_file_buffered_write() in the fallback path. Since NTFS supports IOCB_NOWAIT, do not enter the blocking fallback for such requests. Return -EAGAIN if no bytes were written, or preserve the positive short-write result if the direct write made partial progress.

A reproducer using concurrent AIO direct writes and buffered fallback triggered the following warning and made a subsequent fsync() return -EIO:

Page cache invalidation failure on direct I/O. Possible data corruption due to collision with buffered I/O!

---
 fs/ntfs/file.c | 13 +++++++++++++
 1 file changed, 13 insertions(+)
fs/ntfs/file.c +13 -0
index 20b6019e6bd19..acfce7670248d 100644
@@ -540,8 +540,21 @@ static ssize_t ntfs_dio_write_iter(struct kiocb *iocb, struct iov_iter *from)
 		ssize_t written;
 		int ret2;
 
+		if (iocb->ki_flags & IOCB_NOWAIT) {
+			if (!ret)
+				ret = -EAGAIN;
+			goto out;
+		}
+
 		offset = iocb->ki_pos;
 		iocb->ki_flags &= ~IOCB_DIRECT;
+
+		/*
+		 * Prevent concurrent direct I/O and buffered I/O to the same file
+		 * range. Wait for in-flight DIO to finish before dirtying pages.
+		 */
+		inode_dio_wait(file_inode(iocb->ki_filp));
+
 		written = iomap_file_buffered_write(iocb, from,
 				&ntfs_write_iomap_ops, &ntfs_iomap_folio_ops,
 				NULL);
Signature · 1 line
2.53.0
author maintainer
#2240 lore raw

PATCH 2220/2651 ntfs: only require compressed size on first extent

In reply to Greg Kroah-Hartman

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

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

From: Hyunchul Lee <[email protected]>

[ Upstream commit 8deea344965f44d2ccde3e6153f8272196242501 ]

The attribute validator required the compressed_size field for every sparse or compressed extent. Continuation extents omit that field, so their valid mapping_pairs_offset of 64 was rejected and compressed reads failed.

Fixes ffc755828de1 ("ntfs: Fix min_len for compressed/sparse attributes in ntfs_non_resident_attr_value_is_valid()")
---
 fs/ntfs/attrib.c |  8 ++++++--
 fs/ntfs/inode.c  | 18 +++++++++---------
 2 files changed, 15 insertions(+), 11 deletions(-)
fs/ntfs/attrib.c +6 -2
index 1f64680d5c8fe..22afc03cbf6fc 100644
@@ -733,8 +733,12 @@ static bool ntfs_non_resident_attr_value_is_valid(const struct attr_record *a)
 	min_len = offsetof(struct attr_record, data.non_resident.initialized_size) +
 		  sizeof(a->data.non_resident.initialized_size);
 
-	/* Sparse and compressed attributes have the extra compressed_size field */
-	if (a->flags & (ATTR_IS_SPARSE | ATTR_COMPRESSION_MASK))
+	/*
+	 * Only the first extent of sparse and compressed attributes has the
+	 * extra compressed_size field.
+	 */
+	if ((a->flags & (ATTR_IS_SPARSE | ATTR_COMPRESSION_MASK)) &&
+	    !a->data.non_resident.lowest_vcn)
 		min_len += sizeof(a->data.non_resident.compressed_size);
 
 	if (attr_len < min_len)
fs/ntfs/inode.c +9 -9
index f3e42ec65bdc7..3acb20c9bd226 100644
@@ -1157,6 +1157,11 @@ static int ntfs_read_locked_inode(struct inode *vi)
 		}
 		if (a->non_resident) {
 			NInoSetNonResident(ni);
+			if (a->data.non_resident.lowest_vcn) {
+				ntfs_error(vi->i_sb,
+					   "First extent of $DATA attribute has non zero lowest_vcn.");
+				goto unm_err_out;
+			}
 			if (NInoCompressed(ni) || (NInoSparse(ni) && !NInoWofCompressed(ni))) {
 				if (NInoCompressed(ni) &&
 				    a->data.non_resident.compression_unit != 4) {
@@ -1205,11 +1210,6 @@ static int ntfs_read_locked_inode(struct inode *vi)
 				ni->itype.compressed.size = le64_to_cpu(
 						a->data.non_resident.compressed_size);
 			}
-			if (a->data.non_resident.lowest_vcn) {
-				ntfs_error(vi->i_sb,
-					"First extent of $DATA attribute has non zero lowest_vcn.");
-				goto unm_err_out;
-			}
 			if (ntfs_non_resident_sizes_inconsistent(vi, a))
 				goto unm_err_out;
 			vi->i_size = ni->data_size = le64_to_cpu(a->data.non_resident.data_size);
@@ -1435,6 +1435,10 @@ static int ntfs_read_locked_attr_inode(struct inode *base_vi, struct inode *vi)
 		}
 	} else {
 		NInoSetNonResident(ni);
+		if (a->data.non_resident.lowest_vcn) {
+			ntfs_error(vi->i_sb, "First extent of attribute has non-zero lowest_vcn.");
+			goto unm_err_out;
+		}
 		/*
 		 * Ensure the attribute name is placed before the mapping pairs
 		 * array.
@@ -1470,10 +1474,6 @@ static int ntfs_read_locked_attr_inode(struct inode *base_vi, struct inode *vi)
 			ni->itype.compressed.size = le64_to_cpu(
 					a->data.non_resident.compressed_size);
 		}
-		if (a->data.non_resident.lowest_vcn) {
-			ntfs_error(vi->i_sb, "First extent of attribute has non-zero lowest_vcn.");
-			goto unm_err_out;
-		}
 		if (ntfs_non_resident_sizes_inconsistent(vi, a))
 			goto unm_err_out;
 		vi->i_size = ni->data_size = le64_to_cpu(a->data.non_resident.data_size);
Signature · 1 line
2.53.0
author maintainer
#2241 lore raw

PATCH 2221/2651 ntfs: sync attribute inode size after resize

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit 3e38885ff66c797fc90cf90ab94c372bb4386e84 ]

Internal attribute truncation bypasses truncate_setsize(), so successful resizes must update the attribute inode's i_size. Restrict the update to attribute inodes to keep KEEP_SIZE fallocate from changing a file's i_size.

Fixes 495e90fa3348 ("ntfs: update attrib operations")
---
 fs/ntfs/attrib.c | 2 ++
 1 file changed, 2 insertions(+)
fs/ntfs/attrib.c +2 -0
index 22afc03cbf6fc..ee54ebdeb7c71 100644
@@ -5187,6 +5187,8 @@ int ntfs_attr_truncate_i_locked(struct ntfs_inode *ni, const s64 newsize,
 					ni, newsize, locked_ni, false);
 	} else
 		err = ntfs_resident_attr_resize(ni, newsize, 0, holes);
+	if (!err && NInoAttr(ni))
+		i_size_write(VFS_I(ni), newsize);
 	ntfs_debug("Return status %d\n", err);
 	return err;
 }
Signature · 1 line
2.53.0
author maintainer
#2242 lore raw

PATCH 2222/2651 ntfs: clear stale pagecache on initialized-size extension

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit 58442927b729acbe2b7c7f7ad888d040c44faa3e ]

iomap_zero_range() skips holes, so EOF-polluted cache data can survive gap zeroing. Discard the uninitialized cache range before advancing initialized_size so later reads cannot expose stale bytes.

Perform the cleanup in ntfs_extend_initialized_size() so both file writes and shared writable mmap preparation use it. Hold the invalidate lock while reading initialized_size, clearing the cache, zeroing the gap, and updating the attribute. Release the lock on every exit path.

Fixes af0db57d4293 ("ntfs: update inode operations")
---
 fs/ntfs/inode.c | 41 +++++++++++++++++++++++++++--------------
 1 file changed, 27 insertions(+), 14 deletions(-)
fs/ntfs/inode.c +27 -14
index 3acb20c9bd226..64c415edc398c 100644
@@ -8,6 +8,7 @@
 
 #include <linux/writeback.h>
 #include <linux/seq_file.h>
+#include <linux/mm.h>
 
 #include "lcnalloc.h"
 #include "time.h"
@@ -2484,38 +2485,50 @@ int ntfs_extend_initialized_size(struct inode *vi, const loff_t offset,
 				 const loff_t new_size)
 {
 	struct ntfs_inode *ni = NTFS_I(vi);
-	loff_t old_init_size;
+	loff_t old_init_size, clear_size;
 	unsigned long flags;
-	int err;
+	int err = 0;
+
+	if (!NInoNonResident(ni))
+		return -EINVAL;
 
+	filemap_invalidate_lock(vi->i_mapping);
 	read_lock_irqsave(&ni->size_lock, flags);
 	old_init_size = ni->initialized_size;
 	read_unlock_irqrestore(&ni->size_lock, flags);
 
-	if (!NInoNonResident(ni))
-		return -EINVAL;
 	if (old_init_size >= new_size)
-		return 0;
+		goto out;
 
 	err = ntfs_attr_map_whole_runlist(ni);
 	if (err)
-		return err;
+		goto out;
 
-	if (!NInoCompressed(ni) && old_init_size < offset) {
-		err = iomap_zero_range(vi, old_init_size,
-				       offset - old_init_size,
-				       NULL, &ntfs_seek_iomap_ops,
-				       &ntfs_iomap_folio_ops, NULL);
-		if (err)
-			return err;
+	if (!NInoCompressed(ni)) {
+		/*
+		 * Zeroing skips holes, so discard cached uninitialized bytes
+		 * before making them visible to writes or shared mappings.
+		 */
+		clear_size = max_t(loff_t, i_size_read(vi), new_size);
+		truncate_pagecache_range(vi, old_init_size, clear_size - 1);
+
+		if (old_init_size < offset) {
+			err = iomap_zero_range(vi, old_init_size,
+					       offset - old_init_size,
+					       NULL, &ntfs_seek_iomap_ops,
+					       &ntfs_iomap_folio_ops, NULL);
+			if (err)
+				goto out;
+		}
 	}
 
-
 	mutex_lock(&ni->mrec_lock);
 	err = ntfs_attr_set_initialized_size(ni, new_size);
 	mutex_unlock(&ni->mrec_lock);
 	if (err)
 		truncate_setsize(vi, old_init_size);
+out:
+	filemap_invalidate_unlock(vi->i_mapping);
 	return err;
 }
 
Signature · 1 line
2.53.0
author maintainer
#2243 lore raw

PATCH 2223/2651 ntfs: propagate EA truncate errors

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit 27110888543c046fecdb947fc34bcc3b64313488 ]

Propagate errors from truncating an EA stream so callers do not report a successful xattr update after a failed resize.

Fixes fc053f05ca28 ("ntfs: add reparse and ea operations")
---
 fs/ntfs/ea.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/ntfs/ea.c +1 -1
index 9e00588ff9b5c..082db077a4ede 100644
@@ -37,7 +37,7 @@ static int ntfs_write_ea(struct ntfs_inode *ni, __le32 type, char *value, s64 ea
 		struct ntfs_inode *ea_ni = NTFS_I(ea_vi);
 
 		if (need_truncate && ea_ni->data_size > ea_off + ea_size)
-			ntfs_attr_truncate(ea_ni, ea_off + ea_size);
+			err = ntfs_attr_truncate(ea_ni, ea_off + ea_size);
 		mark_mft_record_dirty(ni);
 	}
 
Signature · 1 line
2.53.0
author maintainer
#2244 lore raw

PATCH 2224/2651 ntfs: do not read ahead encrypted files

In reply to Greg Kroah-Hartman

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

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

From: Zhan Xusheng <[email protected]>

[ Upstream commit 5db65a43ed8bd1a4c0b01a20e494384bc45e4312 ]

ntfs_read_folio() refuses EFS-encrypted files with -EOPNOTSUPP because decryption is not implemented. ntfs_readahead() has no NInoEncrypted() test and passes them to iomap_readahead(), which maps the runlist and fills the folios with the raw on-disk ciphertext. The folios are marked uptodate, so the read that follows never reaches ->read_folio and returns ciphertext instead of -EOPNOTSUPP.

ntfs_read_locked_inode() sets NInoEncrypted() and NInoNonResident() for a non-resident encrypted $DATA attribute and rejects the encrypted-and-compressed combination, so none of the three existing conditions fires. read(), mmap(), splice() and fadvise() all populate the page cache through readahead.

Skipping readahead leaves the folio unpopulated, so the read falls back to ntfs_read_folio() and gets the intended error.

Fixes b041ca562526 ("ntfs: update iomap and address space operations")
---
 fs/ntfs/aops.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
fs/ntfs/aops.c +4 -3
index 517d9a1563e7d..ad781674fef1a 100644
@@ -240,10 +240,11 @@ static void ntfs_readahead(struct readahead_control *rac)
 	};
 
 	/*
-	 * Resident files are not cached in the page cache,
-	 * and readahead is not implemented for compressed files.
+	 * Resident files are not cached in the page cache, readahead is not
+	 * implemented for compressed files, and ntfs_read_folio() refuses
+	 * encrypted files because decryption is not implemented.
 	 */
-	if (!NInoNonResident(ni) || NInoCompressed(ni) ||
+	if (!NInoNonResident(ni) || NInoEncrypted(ni) || NInoCompressed(ni) ||
 	    NInoWofCompressed(ni))
 		return;
 	iomap_readahead(&ntfs_read_iomap_ops, &ctx, NULL);
Signature · 1 line
2.53.0
author maintainer
#2245 lore raw

PATCH 2225/2651 ntfs: reject direct I/O reads of encrypted files

In reply to Greg Kroah-Hartman

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

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

From: Zhan Xusheng <[email protected]>

[ Upstream commit b08619bf3c213cd5605d72b363dd3000663c35c1 ]

ntfs_file_read_iter() refuses direct I/O for compressed and WOF compressed attributes but lets encrypted ones reach iomap_dio_rw(). ntfs_read_iomap_begin_non_resident() has no NInoEncrypted() test, so it reports IOMAP_MAPPED for the attribute's real clusters and the raw on-disk ciphertext is copied to the caller. Buffered reads are refused by ntfs_read_folio(), but direct I/O never calls it.

Fixes 9c87959601e8 ("ntfs: update file operations")
---
 fs/ntfs/file.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/ntfs/file.c +2 -2
index acfce7670248d..dd98cb3ac5e5c 100644
@@ -475,8 +475,8 @@ static ssize_t ntfs_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
 	if (NVolShutdown(NTFS_SB(sb)))
 		return -EIO;
 
-	if ((NInoCompressed(NTFS_I(vi)) || NInoWofCompressed(NTFS_I(vi))) &&
-	    iocb->ki_flags & IOCB_DIRECT)
+	if ((NInoCompressed(NTFS_I(vi)) || NInoWofCompressed(NTFS_I(vi)) ||
+	     NInoEncrypted(NTFS_I(vi))) && iocb->ki_flags & IOCB_DIRECT)
 		return -EOPNOTSUPP;
 
 	inode_lock_shared(vi);
Signature · 1 line
2.53.0
author maintainer
#2246 lore raw

PATCH 2226/2651 ntfs: widen the sub-block offsets in ntfs_decompress()

In reply to Greg Kroah-Hartman

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

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

From: Zhan Xusheng <[email protected]>

[ Upstream commit d45f99f816c9e40cf89b93b90396b1503eda1e47 ]

ntfs_decompress() tracks where the current sub-block starts and ends inside the destination page with two u16s:

	u16 do_sb_start;
	u16 do_sb_end;
	...
	do_sb_start = *dest_ofs;
	do_sb_end = do_sb_start + NTFS_SB_SIZE;

*dest_ofs is an int page offset masked with ~PAGE_MASK, and NTFS_SB_SIZE is 0x1000, so do_sb_end needs PAGE_SIZE + 0xfff of range. That exceeds u16 once PAGE_SIZE reaches 0x10000: the last sub-block of a page starts at 0xf000 and do_sb_end wraps from 0x10000 to 0.

The zero-fill that pads a short sub-block then computes a negative length:

	if (dp_addr < dp_sb_end) {
		int nr_bytes = do_sb_end - *dest_ofs;

		memset(dp_addr, 0, nr_bytes);

A sub-block made only of symbol tokens reaches this without consulting do_sb_end on the way, because that path just does

	*dp_addr++ = *cb++;
	++*dest_ofs;

and is bounded by dp_addr against dp_sb_end. With do_sb_start at 0xf000 and eight literal bytes emitted, nr_bytes is -61448 and the memset() runs for 18446744073709490168 bytes.

Getting there is cheap: fifteen sub-blocks of eleven bytes each advance *dest_ofs to 0xf000, since the same zero-fill pads each of them out to 0x1000 while do_sb_end is still exact, and the sixteenth one triggers the wrap. A compression block is 0x10000 bytes with 4 KiB clusters and the fixed compression unit of 4, so all sixteen fit with room to spare.

Phrase tokens are bounded against do_sb_end and so return -EOVERFLOW instead, and the

	if (*dest_index == dest_max_index && do_sb_end > dest_max_ofs)

check at the top of the sub-block stops firing for the same reason.

Use int for both, matching *dest_ofs and dest_max_ofs. The narrow type came in with the original import and survived the removal and revert of the driver.

Fixes 1e9ea7e04472 ("Revert "fs: Remove NTFS classic"")
---
 fs/ntfs/compress.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/ntfs/compress.c +2 -2
index 075b57fc1de61..82c7c7d290737 100644
@@ -182,8 +182,8 @@ static int ntfs_decompress(struct page *dest_pages[], int completed_pages[],
 	u8 *dp_addr;		/* Current pointer into dp. */
 	u8 *dp_sb_start;	/* Start of current sub-block in dp. */
 	u8 *dp_sb_end;		/* End of current sb in dp (dp_sb_start + NTFS_SB_SIZE). */
-	u16 do_sb_start;	/* @dest_ofs when starting this sub-block. */
-	u16 do_sb_end;		/* @dest_ofs of end of this sb (do_sb_start + NTFS_SB_SIZE). */
+	int do_sb_start;	/* @dest_ofs when starting this sub-block. */
+	int do_sb_end;		/* @dest_ofs of end of this sb (do_sb_start + NTFS_SB_SIZE). */
 
 	/* Variables for tag and token parsing. */
 	u8 tag;			/* Current tag. */
Signature · 1 line
2.53.0
author maintainer
#2247 lore raw

PATCH 2227/2651 ntfs: fix NULL dereference on index allocation open failure

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit 9365c4a1357e2a5d7f1aff140429028ad292161f ]

ntfs_index_lookup() returns -ENOENT when ntfs_ia_open() fails to open the index allocation. This error path leaves icx->ib unset, unlike a missing key in an otherwise valid index, which returns an insertion context.

ntfs_ie_add() treats -ENOENT as a valid insertion position and dereferences icx->ib when the lookup is not in the index root. A corrupt $I30 bitmap attribute can therefore cause a NULL pointer dereference when adding a directory entry.

Return -EIO for index allocation open failures so insertion aborts through the existing error path. Keep -ENOENT for genuinely missing keys and document that other errors leave no valid index entry.

Fixes 0a8ac0c1fa0b ("ntfs: update directory operations")
---
 fs/ntfs/index.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
fs/ntfs/index.c +4 -1
index 580998990bc95..03de4c97c1620 100644
@@ -812,6 +812,9 @@ static int ntfs_icx_parent_dec(struct ntfs_index_context *icx)
  * after the search @key, i.e. this is the position in the index at which
  * an index entry with a key of @key would need to be inserted.
  *
+ * If the index cannot be searched, a negative error code other than -ENOENT
+ * is returned and @icx does not describe a valid index entry.
+ *
  * When finished with the entry and its data, call ntfs_index_ctx_put() to free
  * the context and other associated resources.
  *
@@ -877,7 +880,7 @@ int ntfs_index_lookup(const void *key, const u32 key_len, struct ntfs_index_cont
 	/* Child node present, descend into it. */
 	icx->ia_ni = ntfs_ia_open(icx, ni);
 	if (!icx->ia_ni) {
-		err = -ENOENT;
+		err = -EIO;
 		goto err_out;
 	}
 
Signature · 1 line
2.53.0
author maintainer
#2248 lore raw

PATCH 2228/2651 net: phy: qca83xx: read resolved QCA8337 link status

In reply to Greg Kroah-Hartman

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

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

From: Yongzhao Chen <[email protected]>

[ Upstream commit 42a91cbfc7a3ab99d05cb2ed0de5a24b9652cfed ]

After a QCA8337 SmartSpeed downshift, genphy_read_status() can report 1000 Mbit/s from the advertised modes when the PHY is running at 100 Mbit/s. On a Redmi AX5400 running downstream OpenWrt Linux 6.18.52, this caused qca8k to program the user-port MAC for 1000 Mbit/s and traffic failed. An earlier prototype that read the resolved speed from the PHY restored traffic.

Wrap genphy_read_status() and use at803x_read_specific_status() to replace its speed and duplex result when an autonegotiated link comes up. Resolve pause for the resulting duplex. Until the PHY reports a resolved speed and duplex, report the link as down so that the next poll reads them again, as marvell_read_status_page_an() does. In that case also clear the duplex, master/slave state and link partner modes that genphy_read_status() read for an up link. QCA8337's register layout matches the helper (data sheet 80-Y0619-3 Rev. D, pages 327-328).

Keep the generic master/slave read order and the early return for a steady autonegotiated link. This avoids additional reads of the clear-on-read idle error count in MII_STAT1000. Forced mode continues to use BMCR. Report the MDI-X state read at link-up and invalidate it when the link goes down or autonegotiation is disabled. Clear mdix_ctrl because this driver does not implement MDI-X configuration.

The QCA8327 entries keep genphy_read_status(). The AR8327 data sheet (MKG-15791 Rev. 1.0) lists the QCA8327-A PHY ID and documents the same PHY-specific status layout, with SmartSpeed enabled after a hardware reset, so those PHYs may have the same problem. That is untested on QCA8327 hardware, so limit this change to QCA8337.

Fixes b3591c2a3661 ("net: dsa: qca8k: Switch to PHYLINK instead of PHYLIB")
Assisted-by LLM
---
 drivers/net/phy/qcom/qca83xx.c | 58 ++++++++++++++++++++++++++++++++++
 1 file changed, 58 insertions(+)
drivers/net/phy/qcom/qca83xx.c +58 -0
index bc70ed8efd86a..2c4d085bacdba 100644
@@ -92,6 +92,63 @@ static int qca83xx_probe(struct phy_device *phydev)
 	return 0;
 }
 
+static int qca8337_read_status(struct phy_device *phydev)
+{
+	struct at803x_ss_mask ss_mask = {
+		.speed_mask = AT803X_SS_SPEED_MASK,
+		.speed_shift = __bf_shf(AT803X_SS_SPEED_MASK),
+	};
+	int ret, old_link = phydev->link;
+
+	ret = genphy_read_status(phydev);
+	if (ret)
+		return ret;
+
+	/* Keep the state resolved at link-up while the link stays up */
+	if (phydev->autoneg == AUTONEG_ENABLE && old_link && phydev->link)
+		goto out;
+
+	phydev->mdix = ETH_TP_MDI_INVALID;
+
+	/* genphy_read_status() derives speed and duplex from the
+	 * advertisements, which is wrong after a SmartSpeed downshift.
+	 * Use what the PHY resolved instead.
+	 */
+	if (phydev->autoneg == AUTONEG_ENABLE && phydev->autoneg_complete &&
+	    phydev->link) {
+		phydev->speed = SPEED_UNKNOWN;
+		phydev->duplex = DUPLEX_UNKNOWN;
+		phydev->pause = false;
+		phydev->asym_pause = false;
+
+		ret = at803x_read_specific_status(phydev, ss_mask);
+		if (ret)
+			return ret;
+
+		/* Report the link down until speed and duplex are resolved,
+		 * so that the next poll reads them again. Also clear what
+		 * genphy_read_status() read for an up link, as the
+		 * PHY_HALTED path of the state machine does.
+		 */
+		if (phydev->speed == SPEED_UNKNOWN ||
+		    phydev->duplex == DUPLEX_UNKNOWN) {
+			phydev->link = 0;
+			phydev->duplex = DUPLEX_UNKNOWN;
+			phydev->mdix = ETH_TP_MDI_INVALID;
+			phydev->master_slave_state = MASTER_SLAVE_STATE_UNKNOWN;
+			linkmode_zero(phydev->lp_advertising);
+		} else {
+			phy_resolve_aneg_pause(phydev);
+		}
+	}
+
+out:
+	/* MDI-X configuration is not implemented */
+	phydev->mdix_ctrl = ETH_TP_MDI_INVALID;
+
+	return 0;
+}
+
 static int qca83xx_config_init(struct phy_device *phydev)
 {
 	u8 switch_revision;
@@ -220,6 +277,7 @@ static struct phy_driver qca83xx_driver[] = {
 	.flags			= PHY_IS_INTERNAL,
 	.config_init		= qca83xx_config_init,
 	.soft_reset		= genphy_soft_reset,
+	.read_status		= qca8337_read_status,
 	.get_sset_count		= qca83xx_get_sset_count,
 	.get_strings		= qca83xx_get_strings,
 	.get_stats		= qca83xx_get_stats,
Signature · 1 line
2.53.0
author maintainer
#2249 lore raw

PATCH 2229/2651 RDMA/irdma: Bound in-flight CQP ops across deferred completions

In reply to Greg Kroah-Hartman

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

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

From: Sunny Tiwari <[email protected]>

[ Upstream commit c3e8e9451e6f1b69f685b75e0fbf14f3d0fb2539 ]

On IRDMA_GEN_3+ devices, CQP operations can complete in two stages:
Stage-1 on the CCQ acknowledges receipt and moves an entry from cqp->ooo_avail to cqp->ooo_pnd, while Stage-2 signals final completion via an AEQ event or a subsequent CCQ CQE.

In irdma_sc_ccq_get_cqe_info(), Stage-1 processing advances cqp->sq_ring.tail so the SQ descriptor slot can be reused once consumed by hardware, whereas cqp->completed_ops is only incremented on Stage-2. Because irdma_cqp_ring_full() only checks cqp->sq_ring, a burst of backlogged commands in dev->cqp_cmd_head allows irdma_process_bh() to submit more concurrent in-flight CQP commands than the maximum supported limit (cqp->sq_size - 1) while earlier commands await Stage-2. This causes CQP completions to be lost and synchronous waiters to time out with -ETIMEDOUT (-110).

Fix this by:
- Updating irdma_cqp_ring_full() to bound total in-flight CQP

    operations (cqp->requested_ops - cqp->completed_ops) to
    (cqp->sq_size - 1).

- Calling irdma_process_bh() at the end of irdma_process_ae_def_cmpl() so backlogged commands are drained after Stage-2 AEQ completions increment cqp->completed_ops and free in-flight capacity.

Fixes c7db0abe5f2b ("RDMA/irdma: Add GEN3 CQP support with deferred completions")
Assisted-by Gemini
---
 drivers/infiniband/hw/irdma/ctrl.c | 6 +++++-
 drivers/infiniband/hw/irdma/hw.c   | 1 +
 2 files changed, 6 insertions(+), 1 deletion(-)
drivers/infiniband/hw/irdma/ctrl.c +5 -1
index 970b61aa3e24f..ade451a4eb23e 100644
@@ -5329,7 +5329,11 @@ int irdma_sc_static_hmc_pages_allocated(struct irdma_sc_cqp *cqp, u64 scratch,
  */
 static bool irdma_cqp_ring_full(struct irdma_sc_cqp *cqp)
 {
-	return IRDMA_RING_FULL_ERR(cqp->sq_ring);
+	u64 in_flight = cqp->requested_ops -
+			atomic64_read(&cqp->completed_ops);
+
+	return IRDMA_RING_FULL_ERR(cqp->sq_ring) ||
+	       in_flight >= (cqp->sq_size - 1);
 }
 
 /**
drivers/infiniband/hw/irdma/hw.c +1 -0
index b060ddc8b67bc..554f5d8962b9d 100644
@@ -265,6 +265,7 @@ static void irdma_process_ae_def_cmpl(struct irdma_pci_f *rf,
 		irdma_sc_cqp_def_cmpl_ae_handler(&rf->sc_dev, info, false,
 						 &scratch, &sw_def_info);
 	}
+	irdma_process_bh(&rf->sc_dev);
 }
 
 /**
Signature · 1 line
2.53.0
author maintainer
#2250 lore raw

PATCH 2230/2651 xsk: freeze deferred pool teardown without blocking unregister

In reply to Greg Kroah-Hartman

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

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

From: James Hilliard <[email protected]>

[ Upstream commit fece8420e76fe53ee84f0439f18d026b4c7641da ]

Deferred pool destruction calls ndo_bpf() under RTNL. system_wq is not frozen during system sleep, so that callback can run after a device has suspended and gated its clocks. Use system_freezable_wq so running destruction finishes before device suspend and new work waits until process thaw.

Keep assigned pools visible to NETDEV_UNREGISTER independently of the socket list. A released socket has already left that list, but its final pool put can queue destruction after workqueues freeze. A resume-time unregister would then wait for a device reference whose release cannot run until the resume completes.

Track assigned pools per netdev with netdev operations locking and detach remaining pools after the notifier socket walk, including copy-mode pools. This also covers leased queues without scanning pools from unrelated devices or network namespaces. Remove the entry on assignment failure and normal teardown. The deferred worker still owns the pool and later observes the cleared device pointer, avoiding a second driver detach or put.

The lifetime problem was identified by code inspection of the deferred release and system-sleep paths.

---
 include/linux/netdevice.h   |  5 ++++
 include/net/xsk_buff_pool.h |  3 +++
 net/xdp/xsk.c               |  5 ++++
 net/xdp/xsk_buff_pool.c     | 46 ++++++++++++++++++++++++++++++-------
 4 files changed, 51 insertions(+), 8 deletions(-)
include/linux/netdevice.h +5 -0
index 02119fa153c97..1fb51c576758c 100644
@@ -2547,6 +2547,11 @@ struct net_device {
 	/* protected by rtnl_lock */
 	struct bpf_xdp_entity	xdp_state[__MAX_XDP_MODE];
 
+#ifdef CONFIG_XDP_SOCKETS
+	/** @xsk_pools: assigned AF_XDP pools, ops protected */
+	struct hlist_head	xsk_pools;
+#endif
+
 	u8 dev_addr_shadow[MAX_ADDR_LEN];
 	netdevice_tracker	linkwatch_dev_tracker;
 	netdevice_tracker	watchdog_dev_tracker;
include/net/xsk_buff_pool.h +3 -0
index a7df573784fd6..02e89350faf9a 100644
@@ -48,6 +48,8 @@ struct xsk_buff_pool {
 	struct device *dev;
 	struct net_device *netdev;
 	struct list_head xsk_tx_list;
+	/* Assigned pools, including deferred releases; ops protected. */
+	struct hlist_node dev_node;
 	/* Protects modifications to the xsk_tx_list */
 	spinlock_t xsk_tx_list_lock;
 	refcount_t users;
@@ -119,6 +121,7 @@ bool xp_put_pool(struct xsk_buff_pool *pool);
 void xp_clear_dev(struct xsk_buff_pool *pool);
 void xp_add_xsk(struct xsk_buff_pool *pool, struct xdp_sock *xs);
 void xp_del_xsk(struct xsk_buff_pool *pool, struct xdp_sock *xs);
+void xp_clear_dev_all(struct net_device *dev);
 
 /* AF_XDP, and XDP core. */
 void xp_free(struct xdp_buff_xsk *xskb);
net/xdp/xsk.c +5 -0
index 33475b180ea6f..781ba46eb1525 100644
@@ -2145,6 +2145,11 @@ static int xsk_notifier(struct notifier_block *this,
 			mutex_unlock(&xs->mutex);
 		}
 		mutex_unlock(&net->xdp.lock);
+		/*
+		 * A released socket is no longer on xdp.list. Its pool can still
+		 * hold a device reference on the frozen release workqueue.
+		 */
+		xp_clear_dev_all(dev);
 		break;
 	}
 	return NOTIFY_DONE;
net/xdp/xsk_buff_pool.c +38 -8

90 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#2251 lore raw

PATCH 2231/2651 net/mlx5: HWS, fix reformat pool creation race

In reply to Greg Kroah-Hartman

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

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

From: Alexandre Cassen <[email protected]>

[ Upstream commit d730ca15cf3e4806e38fa8fc6f2af8d7405ef2a4 ]

mlx5_fs_get_pr_encap_pool() inserts a new pool when the lookup misses. Two callers allocating the first reformat of a size at once both create one and the second fails with -EBUSY. TC serializes these allocations under encap_tbl_lock while RDMA flow actions on the FDB don't.

Sashiko AI review of an earlier series spotted this issue.

Tested for regressions on ConnectX-7 with firmware 28.48.1000.

---
 .../mellanox/mlx5/core/steering/hws/fs_hws.c        | 13 +++++++------
 1 file changed, 7 insertions(+), 6 deletions(-)
drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.c +7 -6
index 54761754e6577..fcef2b64f62cc 100644
@@ -1229,7 +1229,7 @@ static struct mlx5_fs_pool *
 mlx5_fs_get_pr_encap_pool(struct mlx5_core_dev *dev, struct xarray *pr_pools,
 			  enum mlx5hws_action_type reformat_type, size_t size)
 {
-	struct mlx5_fs_pool *pr_pool;
+	struct mlx5_fs_pool *pr_pool, *old;
 	unsigned long index = size;
 	int err;
 
@@ -1243,13 +1243,14 @@ mlx5_fs_get_pr_encap_pool(struct mlx5_core_dev *dev, struct xarray *pr_pools,
 	err = mlx5_fs_hws_pr_pool_init(pr_pool, dev, size, reformat_type);
 	if (err)
 		goto free_pr_pool;
-	err = xa_insert(pr_pools, index, pr_pool, GFP_KERNEL);
-	if (err)
-		goto cleanup_pr_pool;
-	return pr_pool;
+	old = xa_cmpxchg(pr_pools, index, NULL, pr_pool, GFP_KERNEL);
+	if (!old)
+		return pr_pool;
 
-cleanup_pr_pool:
 	mlx5_fs_hws_pr_pool_cleanup(pr_pool);
+	kfree(pr_pool);
+	return xa_is_err(old) ? ERR_PTR(xa_err(old)) : old;
+
 free_pr_pool:
 	kfree(pr_pool);
 	return ERR_PTR(err);
Signature · 1 line
2.53.0
author maintainer
#2252 lore raw

PATCH 2232/2651 net/mlx5: HWS, fix modify header pool creation race

In reply to Greg Kroah-Hartman

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

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

From: Alexandre Cassen <[email protected]>

[ Upstream commit e4ab8ab27ab1c9f0cd1589bee471d93319e20c95 ]

mlx5_cmd_hws_modify_header_alloc() creates a pool at the index after the last one if no pool matches the pattern. TC and CT allocate modify headers concurrently, meaning two callers can take the same index and the second call fails with -EBUSY.

Its error path also destroys the pool it just created although another caller may already use it. Keep such a pool since cleanup releases it.

Pools now live until cleanup so the lookup needs no lock. A miss looks again under a mutex before creating the pool.

Tested for regressions on ConnectX-7 with firmware 28.48.1000.

---
 .../mellanox/mlx5/core/steering/hws/fs_hws.c  | 53 +++++++++++--------
 .../mellanox/mlx5/core/steering/hws/fs_hws.h  |  1 +
 2 files changed, 33 insertions(+), 21 deletions(-)
drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.c +32 -21
index fcef2b64f62cc..d6958ba5dcc29 100644
@@ -63,6 +63,7 @@ static int mlx5_fs_init_hws_actions_pool(struct mlx5_core_dev *dev,
 	xa_init(&hws_pool->el2tol3tnl_pools);
 	xa_init(&hws_pool->el2tol2tnl_pools);
 	xa_init(&hws_pool->mh_pools);
+	mutex_init(&hws_pool->mh_pools_lock);
 	xa_init(&hws_pool->table_dests);
 	xa_init(&hws_pool->vport_dests);
 	xa_init(&hws_pool->vport_vhca_dests);
@@ -111,6 +112,7 @@ static void mlx5_fs_cleanup_hws_actions_pool(struct mlx5_fs_hws_context *fs_ctx)
 	xa_for_each(&hws_pool->mh_pools, i, pool)
 		mlx5_fs_destroy_mh_pool(pool, &hws_pool->mh_pools, i);
 	xa_destroy(&hws_pool->mh_pools);
+	mutex_destroy(&hws_pool->mh_pools_lock);
 	xa_for_each(&hws_pool->el2tol2tnl_pools, i, pool)
 		mlx5_fs_destroy_pr_pool(pool, &hws_pool->el2tol2tnl_pools, i);
 	xa_destroy(&hws_pool->el2tol2tnl_pools);
@@ -1458,6 +1460,23 @@ mlx5_fs_destroy_mh_pool(struct mlx5_fs_pool *pool, struct xarray *mh_pools,
 	kfree(pool);
 }
 
+static struct mlx5_fs_pool *
+mlx5_fs_find_mh_pool(struct xarray *mh_pools,
+		     struct mlx5hws_action_mh_pattern *pattern,
+		     unsigned long *cnt)
+{
+	struct mlx5_fs_pool *pool;
+	unsigned long i;
+
+	*cnt = 0;
+	xa_for_each(mh_pools, i, pool) {
+		if (mlx5_fs_hws_mh_pool_match(pool, pattern))
+			return pool;
+		(*cnt)++;
+	}
+	return NULL;
+}
+
 static int mlx5_cmd_hws_modify_header_alloc(struct mlx5_flow_root_namespace *ns,
 					    u8 namespace, u8 num_actions,
 					    void *modify_actions,
@@ -1468,33 +1487,28 @@ static int mlx5_cmd_hws_modify_header_alloc(struct mlx5_flow_root_namespace *ns,
 	struct mlx5_fs_hws_mh *mh_data = NULL;
 	struct mlx5hws_action *hws_action;
 	struct mlx5_fs_pool *pool;
-	unsigned long i, cnt = 0;
-	bool known_pattern;
+	unsigned long cnt;
 	int err;
 
 	pattern.sz = MLX5_UN_SZ_BYTES(set_add_copy_action_in_auto) * num_actions;
 	pattern.data = modify_actions;
 
-	known_pattern = false;
-	xa_for_each(&hws_pool->mh_pools, i, pool) {
-		if (mlx5_fs_hws_mh_pool_match(pool, &pattern)) {
-			known_pattern = true;
-			break;
-		}
-		cnt++;
-	}
-
-	if (!known_pattern) {
-		pool = mlx5_fs_create_mh_pool(ns->dev, &pattern,
-					      &hws_pool->mh_pools, cnt);
+	pool = mlx5_fs_find_mh_pool(&hws_pool->mh_pools, &pattern, &cnt);
+	if (!pool) {
+		mutex_lock(&hws_pool->mh_pools_lock);
+		pool = mlx5_fs_find_mh_pool(&hws_pool->mh_pools, &pattern,
+					    &cnt);
+		if (!pool)
+			pool = mlx5_fs_create_mh_pool(ns->dev, &pattern,
+						      &hws_pool->mh_pools, cnt);
+		mutex_unlock(&hws_pool->mh_pools_lock);
 		if (IS_ERR(pool))
 			return PTR_ERR(pool);
 	}
+
 	mh_data = mlx5_fs_hws_mh_pool_acquire_mh(pool);
-	if (IS_ERR(mh_data)) {
-		err = PTR_ERR(mh_data);
-		goto destroy_pool;
-	}
+	if (IS_ERR(mh_data))
+		return PTR_ERR(mh_data);
 	hws_action = mh_data->bulk->hws_action;
 	mh_data->data = kmemdup(pattern.data, pattern.sz, GFP_KERNEL);
 	if (!mh_data->data) {
@@ -1510,9 +1524,6 @@ static int mlx5_cmd_hws_modify_header_alloc(struct mlx5_flow_root_namespace *ns,
 
 release_mh:
 	mlx5_fs_hws_mh_pool_release_mh(pool, mh_data);
-destroy_pool:
-	if (!known_pattern)
-		mlx5_fs_destroy_mh_pool(pool, &hws_pool->mh_pools, cnt);
 	return err;
 }
 
drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.h +1 -0
index 20cdacd8f12ee..cf068fb5bdbf9 100644
@@ -19,6 +19,7 @@ struct mlx5_fs_hws_actions_pool {
 	struct xarray el2tol3tnl_pools;
 	struct xarray el2tol2tnl_pools;
 	struct xarray mh_pools;
+	struct mutex mh_pools_lock; /* serializes pool creation */
 	struct xarray table_dests;
 	struct xarray vport_vhca_dests;
 	struct xarray vport_dests;
Signature · 1 line
2.53.0
author maintainer
#2253 lore raw

PATCH 2233/2651 net: stmmac: avoid duplicate XSK TX completions

In reply to Greg Kroah-Hartman

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

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

From: James Hilliard <[email protected]>

[ Upstream commit daac93975b8ff0a0a036a5e3562236c0b40c3e36 ]

stmmac_tx_clean() reports completed AF_XDP TX descriptors through xsk_tx_completed(), but leaves their buffer type as STMMAC_TXBUF_T_XSK_TX. The slots retain that type until they are reused for another buffer type.

On interface close or XDP teardown, dma_free_tx_skbufs() walks the entire TX ring, not just the dirty_tx..cur_tx range. stmmac_free_tx_buffer() counts the stale XSK_TX slots again, causing xsk_tx_completed() to advance the completion-ring producer for buffers that have already been returned. This publishes completion entries without matching outstanding TX reservations and corrupts completion accounting for a socket which stays bound across the teardown.

Reset the XSK buffer type after counting the completion in both stmmac_tx_clean() and stmmac_free_tx_buffer(). XSK TX slots have a NULL skb pointer and no per-slot DMA mapping, so the SKB type represents an empty slot. Pending XSK descriptors keep their type until they are completed or released, and a released slot can no longer be counted again by a later cleanup.

---
 drivers/net/ethernet/stmicro/stmmac/stmmac_main.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +7 -2
index 300e898e21993..388575cf588ad 100644
@@ -1742,8 +1742,10 @@ static void stmmac_free_tx_buffer(struct stmmac_priv *priv,
 		tx_q->xdpf[i] = NULL;
 	}
 
-	if (tx_q->tx_skbuff_dma[i].buf_type == STMMAC_TXBUF_T_XSK_TX)
+	if (tx_q->tx_skbuff_dma[i].buf_type == STMMAC_TXBUF_T_XSK_TX) {
 		tx_q->xsk_frames_done++;
+		tx_q->tx_skbuff_dma[i].buf_type = STMMAC_TXBUF_T_SKB;
+	}
 
 	if (tx_q->tx_skbuff[i] &&
 	    tx_q->tx_skbuff_dma[i].buf_type == STMMAC_TXBUF_T_SKB) {
@@ -2924,8 +2926,11 @@ static int stmmac_tx_clean(struct stmmac_priv *priv, int budget, u32 queue,
 			tx_q->xdpf[entry] = NULL;
 		}
 
-		if (tx_q->tx_skbuff_dma[entry].buf_type == STMMAC_TXBUF_T_XSK_TX)
+		if (tx_q->tx_skbuff_dma[entry].buf_type == STMMAC_TXBUF_T_XSK_TX) {
 			tx_q->xsk_frames_done++;
+			/* Teardown must not count this slot again. */
+			tx_q->tx_skbuff_dma[entry].buf_type = STMMAC_TXBUF_T_SKB;
+		}
 
 		if (tx_q->tx_skbuff_dma[entry].buf_type == STMMAC_TXBUF_T_SKB) {
 			if (likely(skb)) {
Signature · 1 line
2.53.0
author maintainer
#2254 lore raw

PATCH 2234/2651 rtc: mpfs: Fix alarm register word order

In reply to Greg Kroah-Hartman

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

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

From: Baek Kyu, Kim <[email protected]>

[ Upstream commit d691a96370b6cd7e684e4da1c473c09df963611b ]

mpfs_rtc_readalarm() swaps the low and high words of the alarm time. The RTC core reads this value during device registration to initialize its alarm timer. This can populate the cached alarm and timer queue with an incorrect expiry time, or leave an enabled hardware alarm out of the timer queue if the decoded time appears to be in the past.

Read the low 32 bits from ALARM_LOWER_REG and place the masked high 11 bits from ALARM_UPPER_REG in bits 42:32. This matches the layout used by mpfs_rtc_setalarm() and the low/high assembly in mpfs_rtc_readtime(), so the RTC core imports the programmed alarm time correctly during device registration.

Fixes 0b31d703598d ("rtc: Add driver for Microchip PolarFire SoC")
---
 drivers/rtc/rtc-mpfs.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/rtc/rtc-mpfs.c +2 -2
index 60596b0ea9d80..6616ca1f02c75 100644
@@ -131,8 +131,8 @@ static int mpfs_rtc_readalarm(struct device *dev, struct rtc_wkalrm *alrm)
 
 	alrm->enabled = mode & MODE_WAKE_EN;
 
-	time = (u64)readl(rtcdev->base + ALARM_LOWER_REG) << 32;
-	time |= (readl(rtcdev->base + ALARM_UPPER_REG) & ALARM_UPPER_MASK);
+	time = readl(rtcdev->base + ALARM_LOWER_REG);
+	time |= ((u64)readl(rtcdev->base + ALARM_UPPER_REG) & ALARM_UPPER_MASK) << 32;
 	rtc_time64_to_tm(time, &alrm->time);
 
 	return 0;
Signature · 1 line
2.53.0
author maintainer
#2255 lore raw

PATCH 2235/2651 rtc: class: Make the time32 hctosys limit configurable

In reply to Greg Kroah-Hartman

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

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

From: Karl Mehltretter <[email protected]>

[ Upstream commit b253c2e96a80aac8e2bc67b425bf007ed78d4d8c ]

The RTC_HCTOSYS feature faces an impossible dilemma on 32-bit systems:

a) systemd requires RTC_HCTOSYS=y with the correct timestamp for its intended operation

b) broken RTC hardware can produce random future timestamps beyond 2038 at boot time

c) time32 userspace immediately hangs if the time is set to a date beyond 2038 and requires timestamps to be clamped

d) time64 userspace is intended to survive the actual 2038 date and requires timestamps to not be clamped

Commit b3a5ac42ab18 ("rtc: hctosys: Ensure system time doesn't overflow time_t") introduced this limit to protect time32 userspace from future RTC dates that can break boot and address constraints a), b) and c), but broke d) in the process by limiting RTC_HCTOSYS to the time32 range and falling back to RTC_HCTOSYS=n behavior when the RTC time overflows that.

Make the behavior configurable with a new RTC_HCTOSYS_TIME32_LIMIT option that chooses between breaking c) or d). On systems with COMPAT_32BIT_TIME=n, only RTC_HCTOSYS_TIME32_LIMIT=n is allowed since userspace can be assumed to be fully built for time64. 64-bit kernels running 32-bit userland never had the cutoff and continue to not offer the option.

Warn on rejection with the RTC date and option name so users can identify the cause and find the setting.

[arnd: reword Kconfig text and patch description,
add COMPAT_32BIT_TIME dependency]
----
I ended up rewriting most of the text but kept Karl's ownership as he did the original patch.

---
 drivers/rtc/Kconfig | 21 +++++++++++++++++++++
 drivers/rtc/class.c |  8 +++++---
 2 files changed, 26 insertions(+), 3 deletions(-)
drivers/rtc/Kconfig +21 -0
index 05b9233b94189..dcf9bdaeacb01 100644
@@ -30,6 +30,27 @@ config RTC_HCTOSYS
 	  the value read from a specified RTC device. This is useful to avoid
 	  unnecessary fsck runs at boot time, and to network better.
 
+config RTC_HCTOSYS_TIME32_LIMIT
+	bool "Reject RTC dates after the 2038 cutoff"
+	depends on RTC_HCTOSYS && COMPAT_32BIT_TIME && !64BIT
+	default y
+	help
+	  Reject RTC dates after 03:14:07 UTC on 19 January 2038 when
+	  initializing the system clock in order to work around broken
+	  RTC implementations that produce nondeterministic timestamps
+	  without a working backup battery.
+
+	  A rejected date leaves system time unchanged, normally near
+	  the Unix epoch, and the RTC's hctosys sysfs attribute reads
+	  0. Userspace must supply the time if no other source has
+	  initialized it.
+
+	  Say Y here if the kernel may have to run old time32 userspace on
+	  hardware that can produce unpredictable RTC timestamps.  If the
+	  kernel is intended to only run time64 compatible userspace and
+	  continue working past 2038, you must pick N here in order to
+	  have a working RTC_HCTOSYS functionality.
+
 config RTC_HCTOSYS_DEVICE
 	string "RTC used to set the system time"
 	depends on RTC_HCTOSYS
drivers/rtc/class.c +5 -3
index 01ba04028f1f1..18ea141ab8c22 100644
@@ -72,12 +72,14 @@ static void rtc_hctosys(struct rtc_device *rtc)
 
 	tv64.tv_sec = rtc_tm_to_time64(&tm);
 
-#if BITS_PER_LONG == 32
-	if (tv64.tv_sec > INT_MAX) {
+	if (IS_ENABLED(CONFIG_RTC_HCTOSYS_TIME32_LIMIT) &&
+	    tv64.tv_sec > INT_MAX) {
+		dev_warn(rtc->dev.parent,
+			 "hctosys: rejecting %ptR UTC due to CONFIG_RTC_HCTOSYS_TIME32_LIMIT=y\n",
+			 &tm);
 		err = -ERANGE;
 		goto err_read;
 	}
-#endif
 
 	err = do_settimeofday64(&tv64);
 
Signature · 1 line
2.53.0
author maintainer
#2256 lore raw

PATCH 2236/2651 net/mlx5: DPLL, fix fractional frequency offset scaling

In reply to Greg Kroah-Hartman

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

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

From: Carolina Jubran <[email protected]>

[ Upstream commit 0edb8222b852f430e5b5e0475cc2650d409214a0 ]

The frequency_diff is reported by firmware in parts-per-trillion, which is exactly what the DPLL core now expects from the ffo_get callback.

Commit bc443c253fcd ("dpll: expose fractional frequency offset in ppt") switched the callback contract to ppt but assumed frequency_diff was in ppm and scaled it by 1000000 to "convert" it. Since the value was already ppt, this makes both exported attributes wrong.

Report frequency_diff as is and let the core divide it down for the legacy ppm attribute.

---
 drivers/net/ethernet/mellanox/mlx5/core/dpll.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/ethernet/mellanox/mlx5/core/dpll.c +1 -1
index 7c69d9029bfa4..54ba7c330d667 100644
@@ -138,7 +138,7 @@ mlx5_dpll_pin_ffo_get(struct mlx5_dpll_synce_status *synce_status,
 {
 	if (!synce_status->oper_freq_measure)
 		return -ENODATA;
-	*ffo = 1000000LL * synce_status->frequency_diff;
+	*ffo = synce_status->frequency_diff;
 	return 0;
 }
 
Signature · 1 line
2.53.0
author maintainer
#2257 lore raw

PATCH 2237/2651 net/mlx5e: Fix NULL deref in PTP TX timestamp recovery warn

In reply to Greg Kroah-Hartman

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

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

From: Carolina Jubran <[email protected]>

[ Upstream commit 0df412012a26389582b120844d098e1e961f10a6 ]

PTP SQs are allocated via mlx5e_ptp_alloc_txqsq(), which never sets sq->channel. The excessive port timestamp delta recovery path incorrectly used sq->channel->netdev for netdev_warn(), causing a NULL pointer dereference. Use sq->netdev instead.

---
 drivers/net/ethernet/mellanox/mlx5/core/en/ptp.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/ethernet/mellanox/mlx5/core/en/ptp.c +1 -1
index 723f66a6bd634..2e1c3bb5a959c 100644
@@ -98,7 +98,7 @@ static void mlx5e_skb_cb_hwtstamp_tx(struct sk_buff *skb,
 		ptpsq->cq_stats->abort_abs_diff_ns += diff;
 		if (diff > (NSEC_PER_SEC >> 1) &&
 		    !test_and_set_bit(MLX5E_SQ_STATE_RECOVERING, &sq->state)) {
-			netdev_warn(sq->channel->netdev,
+			netdev_warn(sq->netdev,
 				    "PTP TX timestamp difference between CQE and port exceeds threshold: %lld ns, recovering SQ %u\n",
 				    (s64)diff, sq->sqn);
 			queue_work(sq->priv->wq, &ptpsq->report_unhealthy_work);
Signature · 1 line
2.53.0
author maintainer
#2258 lore raw

PATCH 2238/2651 timers: Clear pending_map on CPU hotplug

In reply to Greg Kroah-Hartman

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

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

From: Liang Hao <[email protected]>

[ Upstream commit e7cad586d73276cbd4466de81b2092287d7475c0 ]

CPU hotplug migration leaves pending_map bits set on the outgoing CPU while its wheel vectors are empty. After re-online, a later next_expiry recalc can treat those empty buckets as pending and temporarily pull next_expiry forward until collect drains the bits.

Clear pending_map under the base lock after migration in timers_dead_cpu().

Fixes 500462a9de65 ("timers: Switch to a non-cascading wheel")
---
 kernel/time/timer.c | 2 ++
 1 file changed, 2 insertions(+)
kernel/time/timer.c +2 -0
index ae9abf14688e0..fc374444acb63 100644
@@ -44,6 +44,7 @@
 #include <linux/compat.h>
 #include <linux/random.h>
 #include <linux/sysctl.h>
+#include <linux/bitmap.h>
 
 #include <linux/uaccess.h>
 #include <asm/unistd.h>
@@ -2541,6 +2542,7 @@ int timers_dead_cpu(unsigned int cpu)
 		for (i = 0; i < WHEEL_SIZE; i++)
 			migrate_timer_list(new_base, old_base->vectors + i);
 
+		bitmap_zero(old_base->pending_map, WHEEL_SIZE);
 		raw_spin_unlock(&old_base->lock);
 		raw_spin_unlock_irq(&new_base->lock);
 		put_cpu_ptr(&timer_bases);
Signature · 1 line
2.53.0
author maintainer
#2259 lore raw

PATCH 2239/2651 sched/mmcid: Fix affinity-triggered switch back to per-task mode

In reply to Greg Kroah-Hartman

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

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

From: Hui Su <[email protected]>

[ Upstream commit 7dbc307b6c72a5412e3f4e9fa2e0e926925fc5d6 ]

MM CID switches to per-CPU ownership when the number of users of an mm exceeds the maximum number of CIDs. When the affinity union grows, the per-CPU threshold is recalculated and the MM can switch back to per-task ownership through deferred work.

mm_cid_calc_pcpu_thrs() incorrectly uses min(nr_cpus_allowed, users) to calculate that switch-back threshold. This makes pcpu_thrs no larger than users, so the users < pcpu_thrs check in mm_update_cpus_allowed() can never succeed.

For example, with three users restricted to two CPUs, the MM enters per-CPU mode. On an eight-CPU system, widening the affinity union to all eight CPUs should produce a threshold of four, but the old calculation produces three and returns early. The MM therefore remains in per-CPU mode even though the widened CPU set makes per-task ownership preferable.

Calculate pcpu_thrs from nr_cpus_allowed directly. The users bound in __mm_update_max_cids() still controls when per-CPU mode is entered, so this does not change the threshold calculated when switching from per-task to per-CPU ownership.

Tested with an x86_64 QEMU reproducer using three users, an initial two-CPU affinity, and an eight-CPU affinity expansion. The baseline does not invoke mm_cid_work_fn() after the affinity expansion. The fixed kernel invokes the deferred work once and completes the switch back to per-task mode.

Fixes fbd0e71dc370 ("sched/mmcid: Provide CID ownership mode fixup functions")
---
 kernel/sched/core.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
kernel/sched/core.c +2 -3
index 025ed33aa5600..0ba69c11a3f52 100644
@@ -10864,11 +10864,10 @@ static void __mm_update_max_cids(struct mm_mm_cid *mc)
 
 static inline unsigned int mm_cid_calc_pcpu_thrs(struct mm_mm_cid *mc)
 {
-	unsigned int opt_cids;
+	unsigned int nr_cpus = mc->nr_cpus_allowed;
 
-	opt_cids = min(mc->nr_cpus_allowed, mc->users);
 	/* Has to be at least 1 because 0 indicates PCPU mode off */
-	return max(min(opt_cids - opt_cids / 4, num_possible_cpus() / 2), 1);
+	return max(min(nr_cpus - nr_cpus / 4, num_possible_cpus() / 2), 1);
 }
 
 static bool mm_update_max_cids(struct mm_struct *mm)
Signature · 1 line
2.53.0
author maintainer
#2260 lore raw

PATCH 2240/2651 ASoC: cs42l56: Remove the ADC Mute Switch control

In reply to Greg Kroah-Hartman

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

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

From: HyeongJun An <[email protected]>

[ Upstream commit ff404ef11b975baf38c4472c51a6674c239e8021 ]

The ADC Mute Switch control writes bits 2 and 3 of the Misc ADC Control register. These are the ADCA Invert and ADCB Invert bits, which have their own controls. The ADC mute bits are bits 0 and 1, and the DAI mute callback already sets them.

So the control has never muted the ADCs, and nobody can be relying on it. Remove it rather than point it at the mute bits, so the ADCs are muted in one place only.

---
 sound/soc/codecs/cs42l56.c | 1 -
 1 file changed, 1 deletion(-)
sound/soc/codecs/cs42l56.c +0 -1
index f0ea5309a6d49..a259440db0f57 100644
@@ -419,7 +419,6 @@ static const struct snd_kcontrol_new cs42l56_snd_controls[] = {
 			      CS42L56_PGAB_MUX_VOLUME, 0, 0x34, 0x24, pga_tlv),
 	SOC_DOUBLE_R_TLV("ADC Volume", CS42L56_ADCA_ATTENUATOR,
 			      CS42L56_ADCB_ATTENUATOR, 0, 0x00, 1, adc_tlv),
-	SOC_DOUBLE("ADC Mute Switch", CS42L56_MISC_ADC_CTL, 2, 3, 1, 1),
 	SOC_DOUBLE("ADC Boost Switch", CS42L56_GAIN_BIAS_CTL, 3, 2, 1, 1),
 
 	SOC_DOUBLE_R_SX_TLV("Headphone Volume", CS42L56_HPA_VOLUME,
Signature · 1 line
2.53.0
author maintainer
#2261 lore raw

PATCH 2241/2651 dt-bindings: clock: mediatek: Add MT8516 fallbacks

In reply to Greg Kroah-Hartman

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

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

From: Rob Herring (Arm) <[email protected]>

[ Upstream commit 1d48ecb48e2ab9dd2564e735a1c1b29a5eeeb599 ]

MT8516 topckgen and apmixedsys nodes use the common syscon fallback form. Add the MT8516 compatibles to the branches that allow the syscon fallback.

Fixes cd9fdd06b0e8 ("dt-bindings: arm: mediatek: topckgen: Convert to DT schema")
Fixes 16a146735df3 ("dt-bindings: arm: mediatek: apmixedsys: Convert to DT schema")
---
 .../devicetree/bindings/clock/mediatek,apmixedsys.yaml          | 2 +-
 Documentation/devicetree/bindings/clock/mediatek,topckgen.yaml  | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
Documentation/devicetree/bindings/clock/mediatek,apmixedsys.yaml +1 -1
index 591a9e862c7d4..438723d253207 100644
@@ -26,7 +26,6 @@ properties:
           - mediatek,mt7988-apmixedsys
           - mediatek,mt8135-apmixedsys
           - mediatek,mt8173-apmixedsys
-          - mediatek,mt8516-apmixedsys
       - items:
           - const: mediatek,mt7623-apmixedsys
           - const: mediatek,mt2701-apmixedsys
@@ -42,6 +41,7 @@ properties:
               - mediatek,mt7629-apmixedsys
               - mediatek,mt8167-apmixedsys
               - mediatek,mt8183-apmixedsys
+              - mediatek,mt8516-apmixedsys
           - const: syscon
 
   reg:
Documentation/devicetree/bindings/clock/mediatek,topckgen.yaml +1 -1
index c080fb0a16181..6594d491e215b 100644
@@ -23,7 +23,6 @@ properties:
           - mediatek,mt7622-topckgen
           - mediatek,mt8135-topckgen
           - mediatek,mt8173-topckgen
-          - mediatek,mt8516-topckgen
       - items:
           - const: mediatek,mt7623-topckgen
           - const: mediatek,mt2701-topckgen
@@ -43,6 +42,7 @@ properties:
               - mediatek,mt7988-topckgen
               - mediatek,mt8167-topckgen
               - mediatek,mt8183-topckgen
+              - mediatek,mt8516-topckgen
           - const: syscon
 
   reg:
Signature · 1 line
2.53.0
author maintainer
#2262 lore raw

PATCH 2242/2651 vhost: vringh: use get_user()/put_user() for IOTLB 16-bit accesses

In reply to Greg Kroah-Hartman

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

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

From: Linus Torvalds <[email protected]>

[ Upstream commit 95a214f31a3b1ef40034f1e1cb3b9d758a374f01 ]

getu16_iotlb() and putu16_iotlb() use __get_user() and __put_user() when the IOTLB maps to user virtual addresses. Nothing nearby checks the translated address: that relies on the mapping having been validated against the user's VMAs when it was set up.

Use get_user() and put_user(), which do the same single, untorn access and also check the address. The only atomic-context use, the vdpa simulators' notification check, now disables page faults around it, so the might_fault() in the checked accessors stays quiet there.

This is part of getting rid of __get_user() and __put_user() entirely.

Fixes 42823a871fd4 ("vringh: support VA with iotlb")
---
 drivers/vhost/vringh.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/vhost/vringh.c +2 -2
index f027f669460f4..12809fced6087 100644
@@ -1214,7 +1214,7 @@ static inline int getu16_iotlb(const struct vringh *vrh,
 		return ret;
 
 	if (vrh->use_va) {
-		ret = __get_user(tmp, (__virtio16 __user *)ivec.iov.iovec[0].iov_base);
+		ret = get_user(tmp, (__virtio16 __user *)ivec.iov.iovec[0].iov_base);
 		if (ret)
 			return ret;
 	} else {
@@ -1252,7 +1252,7 @@ static inline int putu16_iotlb(const struct vringh *vrh,
 	tmp = cpu_to_vringh16(vrh, val);
 
 	if (vrh->use_va) {
-		ret = __put_user(tmp, (__virtio16 __user *)ivec.iov.iovec[0].iov_base);
+		ret = put_user(tmp, (__virtio16 __user *)ivec.iov.iovec[0].iov_base);
 		if (ret)
 			return ret;
 	} else {
Signature · 1 line
2.53.0
author maintainer
#2263 lore raw

PATCH 2243/2651 sched_ext: Use irq_work for deferred actions with proxy execution

In reply to Greg Kroah-Hartman

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

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

From: Andrea Righi <[email protected]>

[ Upstream commit 9b5ce4345bf4d01dbf9ae5f6f6b1fb9cfdfc7b48 ]

maybe_queue_balance_callback() clears SCX_RQ_BAL_CB_PENDING when it queues the deferred callback. Proxy resolution can then zap the callback without running it, leaving the deferred actions unscheduled until a later wakeup or deferred request.

Use the existing irq_work fallback for dispatch-time deferred requests when proxy execution is enabled. This keeps the work scheduled even if proxy resolution retries the pick or falls back to idle, without relying on another SCX dispatch to restore a discarded callback.

Fixes a8ad873113d3 ("sched_ext: defer queue_balance_callback() until after ops.dispatch")
---
 kernel/sched/ext/ext.c | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)
kernel/sched/ext/ext.c +5 -4
index 30198a4db2b9d..b1c28516ff2cb 100644
@@ -1059,9 +1059,10 @@ static void schedule_deferred_locked(struct rq *rq)
 		return;
 
 	/*
-	 * If in dispatch, the balance callbacks will be called before rq lock
-	 * is released. Schedule one.
-	 *
+	 * If in dispatch without proxy execution, the balance callbacks will
+	 * be called before rq lock is released. Schedule one. With proxy
+	 * execution, proxy resolution can zap the callbacks without another
+	 * SCX dispatch to requeue them, so use irq_work instead.
 	 *
 	 * We can't directly insert the callback into the
 	 * rq's list: The call can drop its lock and make the pending balance
@@ -1069,7 +1070,7 @@ static void schedule_deferred_locked(struct rq *rq)
 	 *
 	 * Just let dispatch_one() know that it must do it itself.
 	 */
-	if (rq->scx.flags & SCX_RQ_IN_DISPATCH) {
+	if ((rq->scx.flags & SCX_RQ_IN_DISPATCH) && !sched_proxy_exec()) {
 		rq->scx.flags |= SCX_RQ_BAL_CB_PENDING;
 		return;
 	}
Signature · 1 line
2.53.0
author maintainer
#2264 lore raw

PATCH 2244/2651 net: openvswitch: skip IPv4 later fragments on TCP/UDP set actions

In reply to Greg Kroah-Hartman

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

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

From: Fernando Fernandez Mancera <[email protected]>

[ Upstream commit 14c0350142ab0a10ebeefed03b779df23749e16a ]

An IPv4 later fragment carries no L4 header, but key extraction leaves ip.proto set to the real protocol and the flow may wildcard the frag field, so validate_set() accepts such packets. set_tcp() and set_udp() then treat the first bytes of the fragment payload as an L4 header, rewrite them as ports and patch the bytes at the checksum offset, corrupting the packet.

Skip these actions for OVS_FRAG_TYPE_LATER. IPv6 later fragments are not affected, since their ip.proto is NEXTHDR_FRAGMENT and validate_set() rejects L4 set actions for them.

---
 net/openvswitch/actions.c | 6 ++++++
 1 file changed, 6 insertions(+)
net/openvswitch/actions.c +6 -0
index 27152bca8a8ce..4aade471afc45 100644
@@ -595,6 +595,9 @@ static int set_udp(struct sk_buff *skb, struct sw_flow_key *flow_key,
 	__be16 src, dst;
 	int err;
 
+	if (flow_key->ip.frag == OVS_FRAG_TYPE_LATER)
+		return 0;
+
 	err = skb_ensure_writable(skb, skb_transport_offset(skb) +
 				  sizeof(struct udphdr));
 	if (unlikely(err))
@@ -638,6 +641,9 @@ static int set_tcp(struct sk_buff *skb, struct sw_flow_key *flow_key,
 	__be16 src, dst;
 	int err;
 
+	if (flow_key->ip.frag == OVS_FRAG_TYPE_LATER)
+		return 0;
+
 	err = skb_ensure_writable(skb, skb_transport_offset(skb) +
 				  sizeof(struct tcphdr));
 	if (unlikely(err))
Signature · 1 line
2.53.0
author maintainer
#2265 lore raw

PATCH 2245/2651 net: openvswitch: drop IP fragments on SCTP set action

In reply to Greg Kroah-Hartman

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

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

From: Fernando Fernandez Mancera <[email protected]>

[ Upstream commit 4d0d8f491307f22aea34b22f73351e1cd2ede735 ]

The SCTP checksum is a CRC32c over the whole SCTP packet. set_sctp() updates it as old_csum ^ old_correct_csum ^ new_csum, with the two CRCs computed over the bytes of the current skb only. That is correct only when the skb holds the whole SCTP packet. For a first fragment, and for a later fragment, it holds just a part of it, and the CRC delta of a change at the start of the packet depends on how many bytes follow, so the checksum written is wrong. The receiver drops the reassembled packet.

validate_set() accepts SCTP set action for any flow with ip.proto set to SCTP, regardless of the fragmentation bits, as it only receives the masked key. As the checksum cannot be fixed up without the whole datagram, fail the action for packets that are IP fragments of either family, so the packet is dropped with OVS_DROP_ACTION_ERROR instead of being forwarded with modified ports and an invalid checksum.

---
 net/openvswitch/actions.c | 3 +++
 1 file changed, 3 insertions(+)
net/openvswitch/actions.c +3 -0
index 4aade471afc45..12e339cbf7912 100644
@@ -674,6 +674,9 @@ static int set_sctp(struct sk_buff *skb, struct sw_flow_key *flow_key,
 	__le32 old_correct_csum, new_csum, old_csum;
 	int err;
 
+	if (flow_key->ip.frag != OVS_FRAG_TYPE_NONE)
+		return -EINVAL;
+
 	err = skb_ensure_writable(skb, sctphoff + sizeof(struct sctphdr));
 	if (unlikely(err))
 		return err;
Signature · 1 line
2.53.0
author maintainer
#2267 lore raw

PATCH 2246/2651 tcp: tcp_metrics: use the socket netns, not the dst device netns

In reply to Greg Kroah-Hartman

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

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

From: Eric Dumazet <[email protected]>

[ Upstream commit 504bdcb8c1566a6f887f9accebe1aa99b502ae97 ]

tcp_get_metrics(), __tcp_get_metrics_req() and tcpm_new() look up and create metrics entries in the netns of the cached dst device rather than in the netns of the socket.

These usually match, but not after the device has been moved to another netns or unregistered: a socket can keep a stale dst in sk_dst_cache until it is checked again, and tcp_update_metrics() reads it with __sk_dst_get() without any dst_check(). Once dst_dev_put() has run, the dst device is blackhole_netdev and the entry is created in init_net. Before that, for instance for routes through nexthop objects whose cached dsts are released from a nested RCU callback, it is the netns the device has just been moved to.

A TCP socket of netns A that enters TIME_WAIT in that window then creates or updates an entry carrying A's addresses and RTT in another netns, where TCP_METRICS_CMD_GET can dump it and where new connections to the same peer inherit those metrics.

The metrics belong to the netns of the socket, so use sock_net() for full sockets and request sockets, and pass it to tcpm_new().

Kernel sockets that do not hold a netns reference can still reach tcp_time_wait() after tcp_net_metrics_exit_batch() has flushed the entries of their dismantling netns, and an entry created then would never be flushed and would keep a dangling tcpm_net. Make tcpm_new() refuse to create entries when check_net() fails. Its callers are in an RCU read-side section, and cleanup_net() waits for a grace period between the refcount reaching zero and the flush, so an entry added after a successful check is always seen by the flush.

---
 net/ipv4/tcp_metrics.c | 20 +++++++++++++++-----
 1 file changed, 15 insertions(+), 5 deletions(-)
net/ipv4/tcp_metrics.c +15 -5
index dc0c081fc1f33..d58f99c67d4dc 100644
@@ -161,16 +161,26 @@ static void tcpm_check_stamp(struct tcp_metrics_block *tm,
 	rcu_dereference_protected(p, lockdep_is_held(&tcp_metrics_lock))
 
 static struct tcp_metrics_block *tcpm_new(struct dst_entry *dst,
+					  struct net *net,
 					  struct inetpeer_addr *saddr,
 					  struct inetpeer_addr *daddr,
 					  unsigned int hash)
 {
 	struct tcp_metrics_block *tm;
 	bool reclaim = false;
-	struct net *net;
 
 	spin_lock_bh(&tcp_metrics_lock);
-	net = dst_dev_net_rcu(dst);
+
+	/* Do not add entries to a dismantling netns: they would not be
+	 * flushed again. Callers are in an RCU read-side section, and
+	 * cleanup_net() waits for a grace period after the netns refcount
+	 * reached zero and before tcp_metrics_flush_all(NULL) runs, so an
+	 * entry added after a successful check_net() is seen by the flush.
+	 */
+	if (unlikely(!check_net(net))) {
+		tm = NULL;
+		goto out_unlock;
+	}
 
 	/* While waiting for the spin-lock the cache might have been populated
 	 * with this entry and so we have to check again.
@@ -273,7 +283,7 @@ static struct tcp_metrics_block *__tcp_get_metrics_req(struct request_sock *req,
 		return NULL;
 	}
 
-	net = dst_dev_net_rcu(dst);
+	net = sock_net(req_to_sk(req));
 	hash ^= net_hash_mix(net);
 	hash = hash_32(hash, tcp_metrics_hash_log);
 
@@ -318,7 +328,7 @@ static struct tcp_metrics_block *tcp_get_metrics(struct sock *sk,
 	else
 		return NULL;
 
-	net = dst_dev_net_rcu(dst);
+	net = sock_net(sk);
 	hash ^= net_hash_mix(net);
 	hash = hash_32(hash, tcp_metrics_hash_log);
 
@@ -326,7 +336,7 @@ static struct tcp_metrics_block *tcp_get_metrics(struct sock *sk,
 	if (tm == TCP_METRICS_RECLAIM_PTR)
 		tm = NULL;
 	if (!tm && create)
-		tm = tcpm_new(dst, &saddr, &daddr, hash);
+		tm = tcpm_new(dst, net, &saddr, &daddr, hash);
 	else
 		tcpm_check_stamp(tm, dst);
 
Signature · 1 line
2.53.0
author maintainer
#2268 lore raw

PATCH 2247/2651 tls: device: protect async RX resync state during device-down

In reply to Greg Kroah-Hartman

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

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

From: Rishikesh Jethwani <[email protected]>

[ Upstream commit f89a228125238f8d4c7e2b8161e2a85fe35307b6 ]

tls_device_rx_resync_new_rec() can run in process context with the socket lock held, but without an RCU read lock: from the strparser work item (tls_strp_work()) and from the receive paths (tls_rx_rec_wait(), tls_rx_rec_done()). The resync_async pointer belongs to the driver RX context, which tls_device_down() tears down from the netdev notifier without taking the socket lock; only the softirq entry to the parser is implicitly inside an RCU section.

If the parser passes the TLS_RX_DEV_DEGRADED check before device-down sets it, tls_device_down() can complete synchronize_net() and delete the driver context before the parser accesses resync_async->req or its record log. In the asynchronous stage the parser also writes the record log, so this is a write to freed memory, not only a stale read. The RCU section in tls_device_resync_rx() starts after those accesses and therefore does not prevent the use-after-free.

Found by code inspection; not reproduced. Hitting the window requires the parser to be preempted between the DEGRADED check and the resync_async access across the device-down grace period and the driver's teardown.

---
 net/tls/tls_device.c | 21 +++++++++++++++------
 1 file changed, 15 insertions(+), 6 deletions(-)
net/tls/tls_device.c +15 -6
index f11d0528fc431..69522aaeb7dc2 100644
@@ -783,8 +783,15 @@ void tls_device_rx_resync_new_rec(struct sock *sk, u32 rcd_len, u32 seq)
 
 	if (tls_ctx->rx_conf != TLS_HW)
 		return;
+
+	/* The parser also runs in process context, without an RCU read lock.
+	 * Protect the driver's resync_async state before checking the flags:
+	 * device-down sets DEGRADED and waits for synchronize_net() before
+	 * freeing it, without taking the socket lock.
+	 */
+	rcu_read_lock();
 	if (unlikely(test_bit(TLS_RX_DEV_DEGRADED, &tls_ctx->flags)))
-		return;
+		goto out;
 
 	prot = &tls_ctx->prot_info;
 	rx_ctx = tls_offload_ctx_rx(tls_ctx);
@@ -799,11 +806,11 @@ void tls_device_rx_resync_new_rec(struct sock *sk, u32 rcd_len, u32 seq)
 
 		if (likely(!is_req_pending) || req_seq != seq ||
 		    !atomic64_try_cmpxchg(&rx_ctx->resync_req, &resync_req, 0))
-			return;
+			goto out;
 		break;
 	case TLS_OFFLOAD_SYNC_TYPE_CORE_NEXT_HINT:
 		if (likely(!rx_ctx->resync_nh_do_now))
-			return;
+			goto out;
 
 		/* head of next rec is already in, note that the sock_inq will
 		 * include the currently parsed message when called from parser
@@ -812,7 +819,7 @@ void tls_device_rx_resync_new_rec(struct sock *sk, u32 rcd_len, u32 seq)
 		if (sock_data > rcd_len) {
 			trace_tls_device_rx_resync_nh_delay(sk, sock_data,
 							    rcd_len);
-			return;
+			goto out;
 		}
 
 		rx_ctx->resync_nh_do_now = 0;
@@ -823,16 +830,18 @@ void tls_device_rx_resync_new_rec(struct sock *sk, u32 rcd_len, u32 seq)
 		resync_req = atomic64_read(&rx_ctx->resync_async->req);
 		is_req_pending = resync_req;
 		if (likely(!is_req_pending))
-			return;
+			goto out;
 
 		if (!tls_device_rx_resync_async(rx_ctx->resync_async,
 						resync_req, &seq, &rcd_delta))
-			return;
+			goto out;
 		tls_bigint_subtract(rcd_sn, rcd_delta);
 		break;
 	}
 
 	tls_device_resync_rx(tls_ctx, sk, seq, rcd_sn);
+out:
+	rcu_read_unlock();
 }
 
 static void tls_device_core_ctrl_rx_resync(struct tls_context *tls_ctx,
Signature · 1 line
2.53.0
author maintainer
#2269 lore raw

PATCH 2248/2651 octeontx2: Fix use-after-free of qos node in delete path

In reply to Greg Kroah-Hartman

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

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

From: Binbin Deng <[email protected]>

[ Upstream commit dcaa6219648955f7a8160313f1685321dbd1bf28 ]

hash_del_rcu() only unlinks the node; a reader that already holds the bucket iterator still uses the node. The immediate kfree() has no grace period, so a concurrent transmit on a socket whose skb priority carries the deleted classid reads node->classid / node->qid from freed memory (use-after-free in the softirq transmit path).

Fix this by calling synchronize_net() before the node is freed, as mlx5e does.

Found during a static-analysis-assisted audit: candidate sites were surfaced by a Coccinelle rule, and the reader/writer paths were confirmed by LLM-assisted (GLM-5.3) code inspection. The issue was not observed at runtime; it is identified by code inspection only.

---
 drivers/net/ethernet/marvell/octeontx2/nic/qos.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/net/ethernet/marvell/octeontx2/nic/qos.c +2 -0
index f160b1618efa2..2ede0b84e5f52 100644
@@ -331,6 +331,8 @@ static void otx2_qos_sw_node_delete(struct otx2_nic *pfvf,
 		otx2_qos_update_tx_netdev_queues(pfvf);
 	}
 
+	synchronize_net();
+
 	list_del(&node->list);
 	kfree(node);
 }
Signature · 1 line
2.53.0
author maintainer
#2270 lore raw

PATCH 2249/2651 net: qede: initialize extack in qede_flow_spec_to_rule()

In reply to Greg Kroah-Hartman

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

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

From: Anirudh Virdi <[email protected]>

[ Upstream commit 106e562966a02f61917c2e0b83909aa2b088447f ]

qede_flow_spec_to_rule() declares a netlink_ext_ack on the stack without initializing it. qede_parse_flow_attr() and qede_flow_spec_validate() only set extack._msg on error paths via NL_SET_ERR_MSG_MOD(), so on a successful parse the err_out block reads an uninitialized pointer. If that garbage happens to be non-NULL, DP_NOTICE("%s", extack._msg) dereferences it inside vsnprintf, causing a page fault and kernel panic.

This manifests when configuring ethtool ntuple flow rules (ethtool -U flow-type tcp4/udp4) on kernels built with CONFIG_INIT_STACK_NONE=y. With CONFIG_INIT_STACK_ALL_ZERO=y the bug is masked because the compiler zero-initializes extack, making _msg NULL.

Reproduced on RHEL 9.8 (kernel-5.14.0-687.47.1.el9_8) and mainline (v7.3-rc6) with the following reproducer:

  IFACE=ens2f0
  ip link set $IFACE up
  ethtool -K $IFACE ntuple on
  for i in $(seq 1 100); do
    ethtool -U $IFACE flow-type udp4 src-ip 192.168.2.$i action -1
  done

The loop panics reliably after 10-15 iterations with:

  BUG: unable to handle page fault
  RIP: string+0x49/0xd0
  Call Trace:
   vsnprintf
   qede_flow_spec_to_rule+0x2b6/0x4b0 [qede]
   qede_add_cls_rule
   ethtool_set_rxnfc

Zero-initialize extack so _msg is NULL unless explicitly set by an error path.

---
 drivers/net/ethernet/qlogic/qede/qede_filter.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/ethernet/qlogic/qede/qede_filter.c +1 -1
index ab8b818588e23..5bf32f1034e0b 100644
@@ -1991,8 +1991,8 @@ static int qede_flow_spec_to_rule(struct qede_dev *edev,
 				  struct ethtool_rx_flow_spec *fs)
 {
 	struct ethtool_rx_flow_spec_input input = {};
+	struct netlink_ext_ack extack = {};
 	struct ethtool_rx_flow_rule *flow;
-	struct netlink_ext_ack extack;
 	__be16 proto;
 	int err;
 
Signature · 1 line
2.53.0
author maintainer
#2271 lore raw

PATCH 2250/2651 net: phy: realtek: restore RTL8211F RGMII delays on resume

In reply to Greg Kroah-Hartman

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

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

From: Karl Mehltretter <[email protected]>

[ Upstream commit 20c0c677362468b0af23e26e5fdb871ea911bc25 ]

RTL8211F and RTL8211F-VD both use rtl8211f_config_rgmii_delay() during initialization and share rtl821x_resume(). The RTL8211F-VD loses its RGMII TX and RX delay enable bits across a software power-down, but the shared resume path only clears BMCR_PDOWN and waits for the receive clock to stabilize.

On a BeagleV Ahead configured for rgmii-id, carrier and the negotiated speed return after an interface close/open, but the receive path does not work. At 100 Mbit/s no frames were received. At 1000 Mbit/s all 11 observed frames had CRC errors.

Reapply the RGMII delay configuration after the existing resume delay.

Tested on a BeagleV Ahead with an RTL8211F-VD at 100 and 1000 Mbit/s, including close/open without a link partner.

Fixes bb726b753f75 ("net: phy: realtek: add support for RTL8211F(D)(I)-VD-CG")
---
 drivers/net/phy/realtek/realtek_main.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/phy/realtek/realtek_main.c +1 -1
index 177b62a7b2d16..c867e5213216b 100644
@@ -1375,7 +1375,7 @@ static int rtl821x_resume(struct phy_device *phydev)
 
 	msleep(20);
 
-	return 0;
+	return rtl8211f_config_rgmii_delay(phydev);
 }
 
 static int rtl8211f_resume(struct phy_device *phydev)
Signature · 1 line
2.53.0
author maintainer
#2272 lore raw

PATCH 2251/2651 net: hix5hd2: serialize timeout recovery with interface teardown

In reply to Greg Kroah-Hartman

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

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

From: Myeonghun Pak <[email protected]>

[ Upstream commit 87cce46329a811ea3fe108ac721e0a2400d0a3bb ]

The timeout worker calls the driver's close and open methods without RTNL or a running-state check. A timeout queued before an interface is closed can call close again after ndo_stop has disabled NAPI. The second napi_disable() can then wait indefinitely. The worker can also race with an ongoing close.

Take RTNL and skip recovery when the interface is no longer running. Use the netdev core close and open helpers so a failed reopen leaves the interface down, rather than leaving it marked running with NAPI disabled.

After unregister_netdev() has stopped the watchdog, drain the worker before releasing its MDIO and descriptor resources. This wait is outside RTNL, allowing an already queued worker to take RTNL, observe the down state, and finish.

This issue was identified as part of our ongoing research while reviewing kernel code.

---
 drivers/net/ethernet/hisilicon/hix5hd2_gmac.c | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)
drivers/net/ethernet/hisilicon/hix5hd2_gmac.c +9 -3
index 02282dc86faf4..12a5657653f85 100644
@@ -12,6 +12,7 @@
 #include <linux/of_net.h>
 #include <linux/of_mdio.h>
 #include <linux/reset.h>
+#include <linux/rtnetlink.h>
 #include <linux/clk.h>
 #include <linux/circ_buf.h>
 
@@ -890,8 +891,13 @@ static void hix5hd2_tx_timeout_task(struct work_struct *work)
 	struct hix5hd2_priv *priv;
 
 	priv = container_of(work, struct hix5hd2_priv, tx_timeout_task);
-	hix5hd2_net_close(priv->netdev);
-	hix5hd2_net_open(priv->netdev);
+
+	rtnl_lock();
+	if (netif_running(priv->netdev)) {
+		dev_close(priv->netdev);
+		dev_open(priv->netdev, NULL);
+	}
+	rtnl_unlock();
 }
 
 static void hix5hd2_net_timeout(struct net_device *dev, unsigned int txqueue)
@@ -1283,6 +1289,7 @@ static void hix5hd2_dev_remove(struct platform_device *pdev)
 	struct hix5hd2_priv *priv = netdev_priv(ndev);
 
 	unregister_netdev(ndev);
+	cancel_work_sync(&priv->tx_timeout_task);
 	mdiobus_unregister(priv->bus);
 	mdiobus_free(priv->bus);
 
@@ -1290,7 +1297,6 @@ static void hix5hd2_dev_remove(struct platform_device *pdev)
 		hix5hd2_destroy_sg_desc_queue(priv);
 	hix5hd2_destroy_hw_desc_queue(priv);
 	of_node_put(priv->phy_node);
-	cancel_work_sync(&priv->tx_timeout_task);
 	free_netdev(ndev);
 }
 
Signature · 1 line
2.53.0
author maintainer
#2273 lore raw

PATCH 2252/2651 net: bcmasp: fix mib counters struct alignment with ethtool stats

In reply to Greg Kroah-Hartman

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

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

From: Florian Fainelli <[email protected]>

[ Upstream commit db45c15c98134f5ebd13c4dc5b6be5d1cd3fc706 ]

When EDPKT stats were removed in commit e9f31435ee7d ("net: bcmasp: Add support for asp-v3.0"), the corresponding entries were removed from bcmasp_gstrings_stats in bcmasp_ethtool.c, but the edpkt_* fields were left at the beginning of struct bcmasp_mib_counters in bcmasp.h.

Because bcmasp_update_mib_counters() and bcmasp_get_ethtool_stats() index into struct bcmasp_mib_counters sequentially based on the order of bcmasp_gstrings_stats, this 16-byte offset caused ethtool to read from shifted offsets: the first four software counters read unused fields and reported 0, the next four software counters reported the values of alloc_rx_skb_failed, tx_dma_failed, mc_filters_full_cnt, and uc_filters_full_cnt, while filters_combine_cnt, promisc_filters_cnt, tx_realloc_offload_failed, and tx_timeout_cnt were never reported.

Remove the obsolete edpkt_* fields from struct bcmasp_mib_counters so that it aligns with bcmasp_gstrings_stats.

---
 drivers/net/ethernet/broadcom/asp2/bcmasp.h | 4 ----
 1 file changed, 4 deletions(-)
drivers/net/ethernet/broadcom/asp2/bcmasp.h +0 -4
index 8c8ffaeadc79f..9c9721da1662b 100644
@@ -250,10 +250,6 @@ struct bcmasp_intf_stats64 {
 };
 
 struct bcmasp_mib_counters {
-	u32	edpkt_ts;
-	u32	edpkt_rx_pkt_cnt;
-	u32	edpkt_hdr_ext_cnt;
-	u32	edpkt_hdr_out_cnt;
 	u32	umac_frm_cnt;
 	u32	fb_frm_cnt;
 	u32	fb_rx_fifo_depth;
Signature · 1 line
2.53.0
author maintainer
#2274 lore raw

PATCH 2253/2651 net: bcmasp: unmap previous DMA mappings on TX map failure

In reply to Greg Kroah-Hartman

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

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

From: Florian Fainelli <[email protected]>

[ Upstream commit a3cf9877558ab2c51182af558815dde64fc17cb9 ]

When mapping an skb with fragments for transmission in bcmasp_xmit(), if mapping fails on fragment i > 0, the error handler calls bcmasp_clean_txcb() for previous iterations j < i. However, bcmasp_clean_txcb() only zeroes the control block fields without unmapping the DMA buffers, leaking the DMA mappings allocated for the head and earlier fragments.

Call dma_unmap_single() before calling bcmasp_clean_txcb() in the error cleanup loop.

Fixes 490cb412007d ("net: bcmasp: Add support for ASP2.0 Ethernet controller")
---
 drivers/net/ethernet/broadcom/asp2/bcmasp_intf.c | 5 +++++
 1 file changed, 5 insertions(+)
drivers/net/ethernet/broadcom/asp2/bcmasp_intf.c +5 -0
index f2176ef3a127b..9ad5a982542f5 100644
@@ -285,6 +285,11 @@ static netdev_tx_t bcmasp_xmit(struct sk_buff *skb, struct net_device *dev)
 			intf->mib.tx_dma_failed++;
 			spb_index = intf->tx_spb_index;
 			for (j = 0; j < i; j++) {
+				txcb = &intf->tx_cbs[spb_index];
+				dma_unmap_single(kdev,
+						 dma_unmap_addr(txcb, dma_addr),
+						 dma_unmap_len(txcb, dma_len),
+						 DMA_TO_DEVICE);
 				bcmasp_clean_txcb(intf, spb_index);
 				spb_index = incr_ring(spb_index,
 						      DESC_RING_COUNT);
Signature · 1 line
2.53.0
author maintainer
#2275 lore raw

PATCH 2254/2651 net: bcmasp: validate minimum RX packet size in bcmasp_rx_poll()

In reply to Greg Kroah-Hartman

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

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

From: Florian Fainelli <[email protected]>

[ Upstream commit 07b624d2f5a4517d7d0022fbd4aef17e884b5686 ]

In bcmasp_rx_poll(), the driver removes a 2-byte alignment pad and optionally strips the ETH_FCS_LEN CRC from received packets before passing them to eth_type_trans().

If the hardware reports a descriptor size smaller than the sum of the 2-byte pad, the Ethernet header (ETH_HLEN), and optional CRC (ETH_FCS_LEN), subtracting the pad and CRC lengths underflows u32 len. This adds ~4 GiB to rx_bytes statistics, while the undersized frame reaches eth_type_trans(), which reads past skb->len into stale buffer data.

Check that desc->size is at least (2 + ETH_HLEN + (crc_fwd ? ETH_FCS_LEN : 0)) before proceeding to process the descriptor.

Fixes 490cb412007d ("net: bcmasp: Add support for ASP2.0 Ethernet controller")
---
 drivers/net/ethernet/broadcom/asp2/bcmasp_intf.c | 6 ++++++
 1 file changed, 6 insertions(+)
drivers/net/ethernet/broadcom/asp2/bcmasp_intf.c +6 -0
index 9ad5a982542f5..d679c796c8c20 100644
@@ -523,6 +523,12 @@ static int bcmasp_rx_poll(struct napi_struct *napi, int budget)
 					DMA_FROM_DEVICE);
 
 		len = desc->size;
+		if (unlikely(len < 2 + ETH_HLEN + (intf->crc_fwd ? ETH_FCS_LEN : 0))) {
+			u64_stats_update_begin(&stats->syncp);
+			u64_stats_inc(&stats->rx_dropped);
+			u64_stats_update_end(&stats->syncp);
+			goto next;
+		}
 
 		/* Allocate a page pool page as the SKB data area so the
 		 * kernel can recycle it efficiently after the packet is
Signature · 1 line
2.53.0
author maintainer
#2276 lore raw

PATCH 2255/2651 net: bcmasp: fix OF node reference leak for phy_dn

In reply to Greg Kroah-Hartman

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

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

From: Florian Fainelli <[email protected]>

[ Upstream commit a31623d91c6e48b08c74dc95567aeb62f1f35938 ]

In bcmasp_interface_create(), intf->phy_dn is obtained via of_parse_phandle() or assigned ndev_dn. of_parse_phandle() returns a node reference with its refcount incremented, but of_node_put() was never called on intf->phy_dn in bcmasp_interface_destroy() or the error unwind path in bcmasp_interface_create().

Acquire a reference on ndev_dn for the fixed-link case as well so that intf->phy_dn consistently holds a reference, and release it with of_node_put() on teardown and error.

Fixes 490cb412007d ("net: bcmasp: Add support for ASP2.0 Ethernet controller")
---
 drivers/net/ethernet/broadcom/asp2/bcmasp_intf.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/net/ethernet/broadcom/asp2/bcmasp_intf.c +3 -1
index d679c796c8c20..693e8cdfe9604 100644
@@ -1298,7 +1298,7 @@ struct bcmasp_intf *bcmasp_interface_create(struct bcmasp_priv *priv,
 				 ndev_dn->name);
 			goto err_free_netdev;
 		}
-		intf->phy_dn = ndev_dn;
+		intf->phy_dn = of_node_get(ndev_dn);
 	}
 
 	/* Map resource */
@@ -1338,6 +1338,7 @@ struct bcmasp_intf *bcmasp_interface_create(struct bcmasp_priv *priv,
 err_deregister_fixed_link:
 	if (of_phy_is_fixed_link(ndev_dn))
 		of_phy_deregister_fixed_link(ndev_dn);
+	of_node_put(intf->phy_dn);
 err_free_netdev:
 	free_netdev(ndev);
 err:
@@ -1350,6 +1351,7 @@ void bcmasp_interface_destroy(struct bcmasp_intf *intf)
 		unregister_netdev(intf->ndev);
 	if (of_phy_is_fixed_link(intf->ndev_dn))
 		of_phy_deregister_fixed_link(intf->ndev_dn);
+	of_node_put(intf->phy_dn);
 	free_netdev(intf->ndev);
 }
 
Signature · 1 line
2.53.0
author maintainer
#2277 lore raw

PATCH 2256/2651 net: bcmasp: account for offload header in TX short packet padding

In reply to Greg Kroah-Hartman

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

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

From: Florian Fainelli <[email protected]>

[ Upstream commit 74667a55122ad2fad88af4fd7672e4c8175c2558 ]

When hardware checksum offload is enabled for an skb, bcmasp_csum_offload() prepends a struct bcmasp_pkt_offload header (20 bytes) to the skb via skb_push(). This increases skb->len and skb_headlen(skb) by sizeof(struct bcmasp_pkt_offload).

Because the hardware descriptor processor strips this offload header before transmitting the packet on the wire, the wire packet length is smaller by sizeof(struct bcmasp_pkt_offload). The padding calculation must account for this extra header; otherwise, short frames are sent on the wire smaller than the minimum Ethernet frame size (ETH_ZLEN + ETH_FCS_LEN).

Furthermore, small frames with payload in page fragments (such as small TCP segments with CHECKSUM_PARTIAL) have nr_frags > 0 and were skipping padding entirely because the padding check was restricted to nr_frags == 0.

Perform the padding check on skb->len before the descriptor loop using skb_put_padto(), adding sizeof(struct bcmasp_pkt_offload) to min_size when checksum offload is enabled, and re-read nr_frags after padding in case the skb was linearized.

Fixes 490cb412007d ("net: bcmasp: Add support for ASP2.0 Ethernet controller")
---
 .../net/ethernet/broadcom/asp2/bcmasp_intf.c    | 17 +++++++++++------
 1 file changed, 11 insertions(+), 6 deletions(-)
drivers/net/ethernet/broadcom/asp2/bcmasp_intf.c +11 -6
index 693e8cdfe9604..a855e637b6f01 100644
@@ -236,7 +236,7 @@ static struct sk_buff *bcmasp_csum_offload(struct net_device *dev,
 static netdev_tx_t bcmasp_xmit(struct sk_buff *skb, struct net_device *dev)
 {
 	struct bcmasp_intf *intf = netdev_priv(dev);
-	unsigned int total_bytes, size;
+	unsigned int total_bytes, size, min_size;
 	int spb_index, nr_frags, i, j;
 	struct bcmasp_tx_cb *txcb;
 	dma_addr_t mapping, valid;
@@ -262,16 +262,21 @@ static netdev_tx_t bcmasp_xmit(struct sk_buff *skb, struct net_device *dev)
 	if (!skb)
 		return NETDEV_TX_OK;
 
+	min_size = ETH_ZLEN + ETH_FCS_LEN;
+	if (csum_hw)
+		min_size += sizeof(struct bcmasp_pkt_offload);
+
+	if (skb->len < min_size) {
+		if (skb_put_padto(skb, min_size))
+			return NETDEV_TX_OK;
+		nr_frags = skb_shinfo(skb)->nr_frags;
+	}
+
 	spb_index = intf->tx_spb_index;
 	valid = intf->tx_spb_dma_valid;
 	for (i = 0; i <= nr_frags; i++) {
 		if (!i) {
 			size = skb_headlen(skb);
-			if (!nr_frags && size < (ETH_ZLEN + ETH_FCS_LEN)) {
-				if (skb_put_padto(skb, ETH_ZLEN + ETH_FCS_LEN))
-					return NETDEV_TX_OK;
-				size = skb->len;
-			}
 			mapping = dma_map_single(kdev, skb->data, size,
 						 DMA_TO_DEVICE);
 		} else {
Signature · 1 line
2.53.0
author maintainer
#2278 lore raw

PATCH 2257/2651 net: bcmasp: fix network filter lookup and wake filter pair allocation

In reply to Greg Kroah-Hartman

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

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

From: Florian Fainelli <[email protected]>

[ Upstream commit fa1459375794f14fb65039cd19c9398d759b491e ]

In bcmasp_netfilt_get_init(), when looking up an existing filter (!init) for a specified location, if the filter at loc was not claimed, the previous loop continued searching higher indices and could return an arbitrary unrelated filter belonging to the port. This caused flow get or delete operations on an empty rule location to return or delete an unintended filter.

Fix this by checking only the requested location on lookup and rejecting RX_CLS_LOC_ANY when !init. In addition, harden wake filter allocation and release by ensuring wake filter pair searches stay on even boundaries where both entries are free, checking that loc + 1 is free for positioned wake filters, and validating parity and bounds on release.

Fixes c5d511c49587 ("net: bcmasp: Add support for wake on net filters")
---
 drivers/net/ethernet/broadcom/asp2/bcmasp.c | 121 +++++++++++---------
 1 file changed, 70 insertions(+), 51 deletions(-)
drivers/net/ethernet/broadcom/asp2/bcmasp.c +70 -51
index 972474893a6bc..f41a79529f100 100644
@@ -511,6 +511,13 @@ static int bcmasp_netfilt_wr_to_hw(struct bcmasp_priv *priv,
 	return 0;
 }
 
+static bool bcmasp_netfilt_is_companion(struct bcmasp_priv *priv, int i)
+{
+	return i > 0 && (i % 2) &&
+	       priv->net_filters[i].wake_filter &&
+	       priv->net_filters[i - 1].wake_filter;
+}
+
 void bcmasp_netfilt_suspend(struct bcmasp_intf *intf)
 {
 	struct bcmasp_priv *priv = intf->parent;
@@ -524,9 +531,7 @@ void bcmasp_netfilt_suspend(struct bcmasp_intf *intf)
 		    priv->net_filters[i].port != intf->port)
 			continue;
 
-		if (i > 0 && (i % 2) &&
-		    priv->net_filters[i].wake_filter &&
-		    priv->net_filters[i - 1].wake_filter)
+		if (bcmasp_netfilt_is_companion(priv, i))
 			continue;
 
 		ret = bcmasp_netfilt_wr_to_hw(priv, &priv->net_filters[i]);
@@ -556,9 +561,7 @@ int bcmasp_netfilt_get_all_active(struct bcmasp_intf *intf, u32 *rule_locs,
 		    priv->net_filters[i].port != intf->port)
 			continue;
 
-		if (i > 0 && (i % 2) &&
-		    priv->net_filters[i].wake_filter &&
-		    priv->net_filters[i - 1].wake_filter)
+		if (bcmasp_netfilt_is_companion(priv, i))
 			continue;
 
 		if (j == *rule_cnt)
@@ -583,9 +586,7 @@ int bcmasp_netfilt_get_active(struct bcmasp_intf *intf)
 			continue;
 
 		/* Skip over a wake filter pair */
-		if (i > 0 && (i % 2) &&
-		    priv->net_filters[i].wake_filter &&
-		    priv->net_filters[i - 1].wake_filter)
+		if (bcmasp_netfilt_is_companion(priv, i))
 			continue;
 
 		cnt++;
@@ -607,6 +608,9 @@ bool bcmasp_netfilt_check_dup(struct bcmasp_intf *intf,
 		    priv->net_filters[i].port != intf->port)
 			continue;
 
+		if (bcmasp_netfilt_is_companion(priv, i))
+			continue;
+
 		cur = &priv->net_filters[i].fs;
 
 		if (cur->flow_type != fs->flow_type ||
@@ -659,7 +663,7 @@ bool bcmasp_netfilt_check_dup(struct bcmasp_intf *intf,
 }
 
 /* If no network filter found, return open filter.
- * If no more open filters return NULL
+ * If no more open filters return error.
  */
 struct bcmasp_net_filter *bcmasp_netfilt_get_init(struct bcmasp_intf *intf,
 						  u32 loc, bool wake_filter,
@@ -669,45 +673,55 @@ struct bcmasp_net_filter *bcmasp_netfilt_get_init(struct bcmasp_intf *intf,
 	struct bcmasp_priv *priv = intf->parent;
 	int i, open_index = -1;
 
-	/* Check whether we exceed the filter table capacity */
+	if (!init) {
+		if (loc == RX_CLS_LOC_ANY || loc >= priv->num_net_filters)
+			return ERR_PTR(-EINVAL);
+
+		if (priv->net_filters[loc].claimed &&
+		    priv->net_filters[loc].port == intf->port &&
+		    !bcmasp_netfilt_is_companion(priv, loc))
+			return &priv->net_filters[loc];
+
+		return ERR_PTR(-ENOENT);
+	}
+
 	if (loc != RX_CLS_LOC_ANY && loc >= priv->num_net_filters)
 		return ERR_PTR(-EINVAL);
 
 	/* If the filter location is busy (already claimed) and we are initializing
 	 * the filter (insertion), return a busy error code.
 	 */
-	if (loc != RX_CLS_LOC_ANY && init && priv->net_filters[loc].claimed)
-		return ERR_PTR(-EBUSY);
-
-	/* We need two filters for wake-up, so we cannot use an odd filter */
-	if (wake_filter && loc != RX_CLS_LOC_ANY && (loc % 2))
-		return ERR_PTR(-EINVAL);
-
-	/* Initialize the loop index based on the desired location or from 0 */
-	i = loc == RX_CLS_LOC_ANY ? 0 : loc;
-
-	for ( ; i < priv->num_net_filters; i++) {
-		/* Found matching network filter */
-		if (!init &&
-		    priv->net_filters[i].claimed &&
-		    priv->net_filters[i].hw_index == i &&
-		    priv->net_filters[i].port == intf->port)
-			return &priv->net_filters[i];
-
-		/* If we don't need a new filter or new filter already found */
-		if (!init || open_index >= 0)
-			continue;
-
-		/* Wake filter conslidates two filters to cover more bytes
-		 * Wake filter is open if...
-		 * 1. It is an even filter
-		 * 2. The current and next filter is not claimed
-		 */
-		if (wake_filter && !(i % 2) && !priv->net_filters[i].claimed &&
-		    !priv->net_filters[i + 1].claimed)
-			open_index = i;
-		else if (!priv->net_filters[i].claimed)
-			open_index = i;
+	if (loc != RX_CLS_LOC_ANY) {
+		if (priv->net_filters[loc].claimed)
+			return ERR_PTR(-EBUSY);
+
+		/* We need two filters for wake-up, so we cannot use an odd filter */
+		if (wake_filter) {
+			if ((loc % 2) || loc + 1 >= priv->num_net_filters)
+				return ERR_PTR(-EINVAL);
+			if (priv->net_filters[loc + 1].claimed)
+				return ERR_PTR(-EBUSY);
+		}
+		open_index = loc;
+	} else {
+		for (i = 0; i < priv->num_net_filters; i++) {
+			/* Wake filter consolidates two filters to cover more bytes.
+			 * Wake filter is open if:
+			 * 1. It is an even filter
+			 * 2. The current and next filter is not claimed
+			 */
+			if (wake_filter) {
+				if (!(i % 2) && (i + 1 < priv->num_net_filters) &&
+				    !priv->net_filters[i].claimed &&
+				    !priv->net_filters[i + 1].claimed) {
+					open_index = i;
+					break;
+				}
+			} else if (!priv->net_filters[i].claimed) {
+				open_index = i;
+				break;
+			}
+		}
 	}
 
 	if (open_index >= 0) {
@@ -716,16 +730,20 @@ struct bcmasp_net_filter *bcmasp_netfilt_get_init(struct bcmasp_intf *intf,
 		nfilter->port = intf->port;
 		nfilter->ch = intf->channel + priv->tx_chan_offset;
 		nfilter->hw_index = open_index;
-	}
 
-	if (wake_filter && open_index >= 0) {
-		/* Claim next filter */
-		priv->net_filters[open_index + 1].claimed = true;
-		priv->net_filters[open_index + 1].wake_filter = true;
-		nfilter->wake_filter = true;
+		if (wake_filter) {
+			/* Claim next filter */
+			priv->net_filters[open_index + 1].claimed = true;
+			priv->net_filters[open_index + 1].wake_filter = true;
+			priv->net_filters[open_index + 1].hw_index = open_index + 1;
+			priv->net_filters[open_index + 1].port = intf->port;
+			priv->net_filters[open_index + 1].ch = intf->channel +
+							       priv->tx_chan_offset;
+			nfilter->wake_filter = true;
+		}
 	}
 
-	return nfilter ? nfilter : ERR_PTR(-EINVAL);
+	return nfilter ? nfilter : ERR_PTR(-ENOSPC);
 }
 
 void bcmasp_netfilt_release(struct bcmasp_intf *intf,
@@ -733,7 +751,8 @@ void bcmasp_netfilt_release(struct bcmasp_intf *intf,
 {
 	struct bcmasp_priv *priv = intf->parent;
 
-	if (nfilt->wake_filter) {
+	if (nfilt->wake_filter && !(nfilt->hw_index % 2) &&
+	    nfilt->hw_index + 1 < priv->num_net_filters) {
 		memset(&priv->net_filters[nfilt->hw_index + 1], 0,
 		       sizeof(struct bcmasp_net_filter));
 	}
Signature · 1 line
2.53.0
author maintainer
#2279 lore raw

PATCH 2258/2651 bridge: mcast: Delete empty MDB entry when port group creation fails

In reply to Greg Kroah-Hartman

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

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

From: Ido Schimmel <[email protected]>

[ Upstream commit 1d0590f96fa4133578b7370ea9ce1d871f6bfc21 ]

When a port group cannot be created for a new group, the MDB entry that was created for it is left with no ports and is not joined by the host. Its timer is never armed, so the entry is never deleted, but it is counted towards mcast_hash_max. When this maximum is reached, the bridge disables multicast snooping.

Since commit b57e8d870d52 ("net: bridge: Maintain number of MDB entries in net_bridge_mcast_port"), port group creation also fails when the port reached its mcast_max_groups limit. A host behind such a port can therefore disable snooping by sending reports for new groups, which is what the limit is meant to prevent. The RTM_NEWMDB path has the same problem.

Fix by deleting the entry after a failure if it is unused. Delete it immediately rather than arming its timer, so that it stops counting towards the maximum right away.

---
 net/bridge/br_mdb.c       | 16 +++++++++++++---
 net/bridge/br_multicast.c |  9 +++++++++
 net/bridge/br_private.h   |  1 +
 3 files changed, 23 insertions(+), 3 deletions(-)
net/bridge/br_mdb.c +13 -3
index a01bd280c722b..0adcd1524ab24 100644
@@ -819,6 +819,7 @@ static int br_mdb_add_group_src_fwd(const struct br_mdb_config *cfg,
 	struct br_mdb_config sg_cfg;
 	struct br_ip sg_ip;
 	u8 flags = 0;
+	int err;
 
 	sg_ip = cfg->group;
 	sg_ip.src = src_ip->src;
@@ -842,7 +843,11 @@ static int br_mdb_add_group_src_fwd(const struct br_mdb_config *cfg,
 	sg_cfg.filter_mode = MCAST_INCLUDE;
 	sg_cfg.rt_protocol = cfg->rt_protocol;
 	sg_cfg.nlflags = cfg->nlflags;
-	return br_mdb_add_group_sg(&sg_cfg, sgmp, brmctx, flags, extack);
+	err = br_mdb_add_group_sg(&sg_cfg, sgmp, brmctx, flags, extack);
+	if (err)
+		br_multicast_del_group(sgmp);
+
+	return err;
 }
 
 static int br_mdb_add_group_src(const struct br_mdb_config *cfg,
@@ -1047,6 +1052,7 @@ static int br_mdb_add_group(const struct br_mdb_config *cfg,
 	struct net_bridge_mcast *brmctx;
 	struct br_ip group = cfg->group;
 	unsigned char flags = 0;
+	int err;
 
 	brmctx = __br_mdb_choose_context(br, entry, extack);
 	if (!brmctx)
@@ -1073,9 +1079,13 @@ static int br_mdb_add_group(const struct br_mdb_config *cfg,
 		flags |= MDB_PG_FLAGS_PERMANENT;
 
 	if (br_multicast_is_star_g(&group))
-		return br_mdb_add_group_star_g(cfg, mp, brmctx, flags, extack);
+		err = br_mdb_add_group_star_g(cfg, mp, brmctx, flags, extack);
 	else
-		return br_mdb_add_group_sg(cfg, mp, brmctx, flags, extack);
+		err = br_mdb_add_group_sg(cfg, mp, brmctx, flags, extack);
+	if (err)
+		br_multicast_del_group(mp);
+
+	return err;
 }
 
 static int __br_mdb_add(const struct br_mdb_config *cfg,
net/bridge/br_multicast.c +9 -0
index 3fbad7b597695..ecc74b73a3e1c 100644
@@ -647,6 +647,14 @@ static void br_multicast_del_mdb_entry(struct net_bridge_mdb_entry *mp)
 	queue_work(system_long_wq, &br->mcast_gc_work);
 }
 
+void br_multicast_del_group(struct net_bridge_mdb_entry *mp)
+{
+	if (mp->ports || mp->host_joined)
+		return;
+
+	br_multicast_del_mdb_entry(mp);
+}
+
 static void br_multicast_group_expired(struct timer_list *t)
 {
 	struct net_bridge_mdb_entry *mp = timer_container_of(mp, t, timer);
@@ -1554,6 +1562,7 @@ __br_multicast_add_group(struct net_bridge_mcast *brmctx,
 	p = br_multicast_new_port_group(pmctx->port, group, *pp, 0, src,
 					filter_mode, RTPROT_KERNEL, NULL);
 	if (unlikely(!p)) {
+		br_multicast_del_group(mp);
 		p = ERR_PTR(-ENOMEM);
 		goto out;
 	}
net/bridge/br_private.h +1 -0
index b01997ea95089..ff746f036f548 100644
@@ -998,6 +998,7 @@ struct net_bridge_mdb_entry *
 br_mdb_ip_get(struct net_bridge *br, struct br_ip *dst);
 struct net_bridge_mdb_entry *
 br_multicast_new_group(struct net_bridge *br, struct br_ip *group);
+void br_multicast_del_group(struct net_bridge_mdb_entry *mp);
 struct net_bridge_port_group *
 br_multicast_new_port_group(struct net_bridge_port *port,
 			    const struct br_ip *group,
Signature · 1 line
2.53.0
author maintainer
#2280 lore raw

PATCH 2259/2651 PCI: qcom: Ignore -ENODEV after Root Port reset

In reply to Greg Kroah-Hartman

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

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

From: Konrad Dybcio <[email protected]>

[ Upstream commit bea2ff3b9de1e32716bc517082b7e3c7330e2151 ]

Root Port recovery may race with a device hot-unplug. In that case, dw_pcie_wait_for_link() returns -ENODEV because no device is detected after the controller has been successfully reset.

This is a valid outcome and should not cause Root Port recovery to fail. Ignore -ENODEV while continuing to propagate other link-training errors.

---
 drivers/pci/controller/dwc/pcie-qcom.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/pci/controller/dwc/pcie-qcom.c +3 -0
index 95db0f866909f..13c172bf4933c 100644
@@ -1859,6 +1859,9 @@ static int qcom_pcie_reset_root_port(struct pci_host_bridge *bridge,
 	qcom_pcie_start_link(pci);
 
 	ret = dw_pcie_wait_for_link(pci);
+	/* This linkdown might have been a hot-unplug */
+	if (ret == -ENODEV)
+		ret = 0;
 	if (ret)
 		return ret;
 
Signature · 1 line
2.53.0
author maintainer
#2281 lore raw

PATCH 2260/2651 net: axienet: release every RX buffer in axienet_dma_bd_release()

In reply to Greg Kroah-Hartman

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

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

From: Sagi Maimon <[email protected]>

[ Upstream commit b59787892d04a5647a7e662fbb02cd0abdb1a993 ]

The RX walk in axienet_dma_bd_release() stops at the first descriptor without an skb, assuming that such a slot and all after it were never filled. That holds on the axienet_dma_bd_init() error path, but not once the ring has been running: when axienet_rx_poll() fails to allocate or map a replacement buffer it leaves the slot it emptied with a NULL skb, in the middle of a populated ring, until a later poll refills it. Closing the interface before then leaks the skb and the streaming DMA mapping of every descriptor after that slot, which can be most of the ring, and is most likely under memory pressure.

The walk also frees each skb before unmapping it. With swiotlb, the DMA_FROM_DEVICE unmap copies the bounce buffer back into the skb data that was just freed, and on non-coherent platforms it invalidates cache lines that may already belong to a new owner.

Skip empty slots instead of stopping at the first one. An emptied slot still has a non-zero cntrl but its buffer is already unmapped, so the skip has to cover the unmap too, which it does by coming before it. Then unmap before freeing, as axienet_rx_poll() does.

This was reported by the Sashiko AI review bot.

Tested on the AXI Ethernet MAC of an ADVA TimeCard X2 (PCIe card, with the built-in AXI DMA): traffic passes after each of ten down/up cycles, each running axienet_dma_bd_release(), so the unmap-then-free order is exercised on every buffer. A failed RX refill was not reproduced, so the skip over an empty slot was not exercised.

Fixes f26667a373f3 ("net: axienet: Fix DMA descriptor cleanup path")
Fixes 7a7d340ba4d9 ("net: axienet: fix RX ring refill allocation failure handling")
---
 drivers/net/ethernet/xilinx/xilinx_axienet_main.c | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)
drivers/net/ethernet/xilinx/xilinx_axienet_main.c +7 -5
index 318ff03b04e69..567ac8aed4745 100644
@@ -245,13 +245,13 @@ static void axienet_dma_bd_release(struct net_device *ndev)
 	for (i = 0; i < lp->rx_bd_num; i++) {
 		dma_addr_t phys;
 
-		/* A NULL skb means this descriptor has not been initialised
-		 * at all.
+		/* A NULL skb means the descriptor holds no buffer: it was
+		 * never filled, or axienet_rx_poll() took its skb and could
+		 * not refill it, having already unmapped the old buffer.
+		 * Such slots can sit anywhere in a ring that has been running.
 		 */
 		if (!lp->rx_bd_v[i].skb)
-			break;
-
-		dev_kfree_skb(lp->rx_bd_v[i].skb);
+			continue;
 
 		/* For each descriptor, we programmed cntrl with the (non-zero)
 		 * descriptor size, after it had been successfully allocated.
@@ -262,6 +262,8 @@ static void axienet_dma_bd_release(struct net_device *ndev)
 			dma_unmap_single(lp->dev, phys,
 					 lp->max_frm_size, DMA_FROM_DEVICE);
 		}
+
+		dev_kfree_skb(lp->rx_bd_v[i].skb);
 	}
 
 	dma_free_coherent(lp->dev,
Signature · 1 line
2.53.0
author maintainer
#2282 lore raw

PATCH 2261/2651 ipv6: account route exceptions to the netns of their dst

In reply to Greg Kroah-Hartman

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

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

From: Eric Dumazet <[email protected]>

[ Upstream commit 8ff017b891e89276c15f06dfd7155981d572af77 ]

rt6_insert_exception() and rt6_remove_exception() update rt6_stats->fib_rt_cache of dev_net(rt6i->dst.dev), but the device of an exception dst can move to another netns while the exception is still in its bucket.

This happens when the bucket is flushed from an RCU callback, for instance from nexthop_free_rcu() for the nh_info of a replaced nexthop, whose exceptions still point to live routes. If the device moves to another netns before that callback runs, the decrement hits the other netns, whose u32 counter underflows in /proc/net/rt6_stats, while the counter of the original netns never goes back down.

Account exceptions to the netns their dst was allocated in, derived from dst->ops as ip6_dst_gc() already does, which does not depend on the device. The dst already relies on that netns' ip6_dst_ops being alive when it is destroyed, which happens after the exception is removed.

---
 net/ipv6/route.c | 13 +++++++++++--
 1 file changed, 11 insertions(+), 2 deletions(-)
net/ipv6/route.c +11 -2
index bd6bc9ada5398..3688280742e48 100644
@@ -1503,6 +1503,15 @@ static struct rt6_info *rt6_make_pcpu_route(struct net *net,
  */
 static DEFINE_SPINLOCK(rt6_exception_lock);
 
+/* Exceptions are accounted to the netns their dst was allocated in.
+ * Unlike dev_net(dst->dev), it does not change when the device moves to
+ * another netns or when dst_dev_put() points the dst to blackhole_netdev.
+ */
+static struct net *rt6_exception_net(const struct rt6_info *rt)
+{
+	return container_of(rt->dst.ops, struct net, ipv6.ip6_dst_ops);
+}
+
 /* Remove rt6_ex from hash table and free the memory
  * Caller must hold rt6_exception_lock
  */
@@ -1514,7 +1523,7 @@ static void rt6_remove_exception(struct rt6_exception_bucket *bucket,
 	if (!bucket || !rt6_ex)
 		return;
 
-	net = dev_net(rt6_ex->rt6i->dst.dev);
+	net = rt6_exception_net(rt6_ex->rt6i);
 	net->ipv6.rt6_stats->fib_rt_cache--;
 
 	/* purge completely the exception to allow releasing the held resources:
@@ -1783,7 +1792,7 @@ static int rt6_insert_exception(struct rt6_info *nrt,
 	rt6_ex->stamp = jiffies;
 	hlist_add_head_rcu(&rt6_ex->hlist, &bucket->chain);
 	bucket->depth++;
-	net->ipv6.rt6_stats->fib_rt_cache++;
+	rt6_exception_net(nrt)->ipv6.rt6_stats->fib_rt_cache++;
 
 	/* Randomize max depth to avoid some side channels attacks. */
 	max_depth = FIB6_MAX_DEPTH + get_random_u32_below(FIB6_MAX_DEPTH);
Signature · 1 line
2.53.0
author maintainer
#2283 lore raw

PATCH 2262/2651 platform/x86: gpd pocket fan: Cancel work before releasing GPIOs

In reply to Greg Kroah-Hartman

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

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

From: Myeonghun Pak <[email protected]>

[ Upstream commit 9962770049c715fc30a7b3274d8f245167c0a410 ]

The fan worker changes the direction of both GPIOs and schedules its next run. Its managed cancellation action is registered before the GPIOs are acquired, so devres releases the GPIOs before cancelling the work. A running worker can therefore change a GPIO after the driver has released it.

Register the work cancellation action after both GPIO acquisitions. This makes devres cancel and drain the worker before releasing either GPIO. No work has been queued yet if GPIO acquisition or action registration fails.

This issue was identified as part of our ongoing research while reviewing kernel code.

---
 drivers/platform/x86/gpd-pocket-fan.c | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)
drivers/platform/x86/gpd-pocket-fan.c +5 -4
index c9236738f8960..ced93795c5d4b 100644
@@ -153,10 +153,6 @@ static int gpd_pocket_fan_probe(struct platform_device *pdev)
 		return -ENOMEM;
 
 	fan->dev = &pdev->dev;
-	ret = devm_delayed_work_autocancel(&pdev->dev, &fan->work,
-					   gpd_pocket_fan_worker);
-	if (ret)
-		return ret;
 
 	/* Note this returns a "weak" reference which we don't need to free */
 	fan->dts0 = thermal_zone_get_zone_by_name("soc_dts0");
@@ -175,6 +171,11 @@ static int gpd_pocket_fan_probe(struct platform_device *pdev)
 	if (IS_ERR(fan->gpio1))
 		return PTR_ERR(fan->gpio1);
 
+	ret = devm_delayed_work_autocancel(&pdev->dev, &fan->work,
+					   gpd_pocket_fan_worker);
+	if (ret)
+		return ret;
+
 	gpd_pocket_fan_force_update(fan);
 
 	platform_set_drvdata(pdev, fan);
Signature · 1 line
2.53.0
author maintainer
#2284 lore raw

PATCH 2263/2651 net: phy: marvell: keep WOL_EIE across interrupt reconfiguration

In reply to Greg Kroah-Hartman

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

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

From: Rosen Penev <[email protected]>

[ Upstream commit f434191f93884c9de58c38f18ac7fc7f1fdf9e42 ]

marvell_config_intr() rewrites the whole interrupt enable register, so the config_intr call from phy_init_hw() on resume silently cleared WOL_EIE on the 88E1318S and 88E1510: m88e1318_get_wol() still reported WAKE_MAGIC, but a matched magic packet was no longer routed to INTn and the board did not wake.

Bit 7 of that register is WOL_EIE only on these two PHYs; on others, such as the 88E1111, it enables a FIFO error interrupt. So give the 88E1318S and 88E1510 their own config_intr and handle_interrupt, and leave the shared callbacks unchanged.

m88e1318_set_wol() now records whether WoL is enabled, and both it and the new config_intr derive WOL_EIE from that state under the MDIO bus lock. WOL_EIE stays set across config_intr while WoL is enabled, except when the PHY has an interrupt line and interrupts are being disabled, as in phy_free_interrupt(): INTn is then the PHY IRQ, and nothing would read IEVENT after free_irq() to release it. The bit is set again once interrupts are re-enabled. phy_probe() still clears a WOL_EIE left by a previous boot, since WoL starts out disabled. The new handler also claims WoL events, so they do not go unacknowledged when the PHY IRQ is in use.

Helios4 (Armada 388, 88E1512), 7.2.9. With this patch WOL_EIE stays set over 3 link down/up cycles, "wol d" clears it, and a magic packet on a running board is a handled interrupt. Without it, WOL_EIE is lost on the first down/up, survives "wol d", and the magic packet is an unhandled interrupt.

Fixes 3871c3876f80 ("mv643xx_eth with 88E1318S: support Wake on LAN")
---
 drivers/net/phy/marvell.c | 97 ++++++++++++++++++++++++++++++---------
 1 file changed, 75 insertions(+), 22 deletions(-)
drivers/net/phy/marvell.c +75 -22
index f71cffa884062..94e8dbe9a859f 100644
@@ -55,6 +55,8 @@
 #define MII_M1011_IMASK			0x12
 #define MII_M1011_IMASK_INIT		0x6400
 #define MII_M1011_IMASK_CLEAR		0x0000
+/* WOL Event Interrupt Enable, 88E1318S and 88E1510 only */
+#define MII_M1011_IMASK_WOL		BIT(7)
 
 #define MII_M1011_PHY_SCR			0x10
 #define MII_M1011_PHY_SCR_DOWNSHIFT_EN		BIT(11)
@@ -139,11 +141,6 @@
 #define MII_88E1318S_PHY_MSCR1_REG	16
 #define MII_88E1318S_PHY_MSCR1_PAD_ODD	BIT(6)
 
-/* Copper Specific Interrupt Enable Register */
-#define MII_88E1318S_PHY_CSIER				0x12
-/* WOL Event Interrupt Enable */
-#define MII_88E1318S_PHY_CSIER_WOL_EIE			BIT(7)
-
 #define MII_88E1318S_PHY_LED_FUNC		0x10
 #define MII_88E1318S_PHY_LED_FUNC_OFF		(0x8)
 #define MII_88E1318S_PHY_LED_FUNC_ON		(0x9)
@@ -354,6 +351,7 @@ struct marvell_priv {
 	u32 step;
 	s8 pair;
 	u8 vct_phase;
+	bool wol_enabled;
 };
 
 static int marvell_read_page(struct phy_device *phydev)
@@ -407,7 +405,8 @@ static int marvell_config_intr(struct phy_device *phydev)
 	return err;
 }
 
-static irqreturn_t marvell_handle_interrupt(struct phy_device *phydev)
+static irqreturn_t __marvell_handle_interrupt(struct phy_device *phydev,
+					      u16 mask)
 {
 	int irq_status;
 
@@ -417,7 +416,7 @@ static irqreturn_t marvell_handle_interrupt(struct phy_device *phydev)
 		return IRQ_NONE;
 	}
 
-	if (!(irq_status & MII_M1011_IMASK_INIT))
+	if (!(irq_status & mask))
 		return IRQ_NONE;
 
 	phy_trigger_machine(phydev);
@@ -425,6 +424,57 @@ static irqreturn_t marvell_handle_interrupt(struct phy_device *phydev)
 	return IRQ_HANDLED;
 }
 
+static irqreturn_t marvell_handle_interrupt(struct phy_device *phydev)
+{
+	return __marvell_handle_interrupt(phydev, MII_M1011_IMASK_INIT);
+}
+
+/* WOL_EIE also routes WoL events to INTn. Keep it set while WoL is enabled,
+ * unless INTn is the PHY interrupt and that interrupt is being disabled:
+ * nothing would read IEVENT after free_irq() to release the line.
+ */
+static u16 m88e1318_wol_imask(struct phy_device *phydev)
+{
+	struct marvell_priv *priv = phydev->priv;
+
+	if (priv->wol_enabled &&
+	    (phydev->interrupts == PHY_INTERRUPT_ENABLED ||
+	     !phy_interrupt_is_valid(phydev)))
+		return MII_M1011_IMASK_WOL;
+
+	return 0;
+}
+
+static int m88e1318_config_intr(struct phy_device *phydev)
+{
+	bool enable = phydev->interrupts == PHY_INTERRUPT_ENABLED;
+	u16 imask;
+	int err;
+
+	if (enable) {
+		err = marvell_ack_interrupt(phydev);
+		if (err)
+			return err;
+	}
+
+	/* Serialise against m88e1318_set_wol() updating wol_enabled */
+	phy_lock_mdio_bus(phydev);
+	imask = enable ? MII_M1011_IMASK_INIT : MII_M1011_IMASK_CLEAR;
+	imask |= m88e1318_wol_imask(phydev);
+	err = __phy_write(phydev, MII_M1011_IMASK, imask);
+	phy_unlock_mdio_bus(phydev);
+	if (err || enable)
+		return err;
+
+	return marvell_ack_interrupt(phydev);
+}
+
+static irqreturn_t m88e1318_handle_interrupt(struct phy_device *phydev)
+{
+	return __marvell_handle_interrupt(phydev, MII_M1011_IMASK_INIT |
+					  MII_M1011_IMASK_WOL);
+}
+
 static int marvell_set_polarity(struct phy_device *phydev, int polarity)
 {
 	u16 val;
@@ -1969,18 +2019,27 @@ static void m88e1318_get_wol(struct phy_device *phydev,
 static int m88e1318_set_wol(struct phy_device *phydev,
 			    struct ethtool_wolinfo *wol)
 {
+	struct marvell_priv *priv = phydev->priv;
 	int err = 0, oldpage;
 
 	oldpage = phy_save_page(phydev);
 	if (oldpage < 0)
 		goto error;
 
-	if (wol->wolopts & (WAKE_MAGIC | WAKE_PHY)) {
-		/* Explicitly switch to page 0x00, just to be sure */
-		err = marvell_write_page(phydev, MII_MARVELL_COPPER_PAGE);
-		if (err < 0)
-			goto error;
+	priv->wol_enabled = !!(wol->wolopts & (WAKE_MAGIC | WAKE_PHY));
 
+	/* Explicitly switch to page 0x00, just to be sure */
+	err = marvell_write_page(phydev, MII_MARVELL_COPPER_PAGE);
+	if (err < 0)
+		goto error;
+
+	/* Update the WOL interrupt enable */
+	err = __phy_modify(phydev, MII_M1011_IMASK, MII_M1011_IMASK_WOL,
+			   m88e1318_wol_imask(phydev));
+	if (err < 0)
+		goto error;
+
+	if (priv->wol_enabled) {
 		/* If WOL event happened once, the LED[2] interrupt pin
 		 * will not be cleared unless we reading the interrupt status
 		 * register. If interrupts are in use, the normal interrupt
@@ -1990,12 +2049,6 @@ static int m88e1318_set_wol(struct phy_device *phydev,
 		if (!phy_interrupt_is_valid(phydev))
 			__phy_read(phydev, MII_M1011_IEVENT);
 
-		/* Enable the WOL interrupt */
-		err = __phy_set_bits(phydev, MII_88E1318S_PHY_CSIER,
-				     MII_88E1318S_PHY_CSIER_WOL_EIE);
-		if (err < 0)
-			goto error;
-
 		err = marvell_write_page(phydev, MII_MARVELL_LED_PAGE);
 		if (err < 0)
 			goto error;
@@ -3817,8 +3870,8 @@ static struct phy_driver marvell_drivers[] = {
 		.config_init = m88e1318_config_init,
 		.config_aneg = m88e1318_config_aneg,
 		.read_status = marvell_read_status,
-		.config_intr = marvell_config_intr,
-		.handle_interrupt = marvell_handle_interrupt,
+		.config_intr = m88e1318_config_intr,
+		.handle_interrupt = m88e1318_handle_interrupt,
 		.get_wol = m88e1318_get_wol,
 		.set_wol = m88e1318_set_wol,
 		.resume = genphy_resume,
@@ -3925,8 +3978,8 @@ static struct phy_driver marvell_drivers[] = {
 		.config_init = m88e1510_config_init,
 		.config_aneg = m88e1510_config_aneg,
 		.read_status = marvell_read_status,
-		.config_intr = marvell_config_intr,
-		.handle_interrupt = marvell_handle_interrupt,
+		.config_intr = m88e1318_config_intr,
+		.handle_interrupt = m88e1318_handle_interrupt,
 		.get_wol = m88e1318_get_wol,
 		.set_wol = m88e1318_set_wol,
 		.resume = m88e1510_resume,
Signature · 1 line
2.53.0
author maintainer
#2285 lore raw

PATCH 2264/2651 net/mlx5e: Update netdev features only after a successful ringparam set

In reply to Greg Kroah-Hartman

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

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

From: Dimitri Daskalakis <[email protected]>

[ Upstream commit 23dd5be7e19ceab8c1c79110ee3552bcabc463ef ]

mlx5 couples HW-GRO with tcp-data-split. If a user sets rx-gro-hw on -> tcp-data-split on -> rx-gro-hw off, the driver will leave HW-GRO on. mlx5e_ethtool_set_tcp_data_split() calls netdev_update_features() when tcp-data-split goes from enabled to disabled in case HW-GRO needs to be released. mlx5e_fix_features() reads the new HDS config from dev->cfg_pending, so HW-GRO is released before all ring parameters are validated.

If the subsequent call to mlx5e_ethtool_set_ringparam() fails, the ethtool core discards the pending change and reports tcp-data-split enabled. The device is no longer splitting, and subsequent ring changes are blocked.

Move the call to netdev_update_features() after
mlx5e_ethtool_set_ringparam() exits successfully.

The issue was discovered by manual code inspection during review of a change that stops mlx5 users from disabling tcp-data-split. It was reproduced on a ConnectX-7 with ethtool alone.

Steps to reproduce:
ethtool -K eth0 rx-gro-hw on
ethtool -G eth0 tcp-data-split on
ethtool -K eth0 rx-gro-hw off # HW-GRO kept on for tcp-data-split

ethtool -G eth0 tcp-data-split off rx 1 # de-sync driver & kernel state
netlink error: mlx5_core: rx (1) < min (16)
netlink error: Invalid argument

ethtool -G eth0 rx 1024 # valid ring changes are now blocked
netlink error: mlx5_core: TCP-data-split is not supported when GRO HW is disabled netlink error: Invalid argument

This is not a terminal state, users can recover by setting rx-gro-hw on. With the fix, the failing ringparam set leaves rx-gro-hw on and later ring changes succeed.

---
 .../ethernet/mellanox/mlx5/core/en_ethtool.c    | 17 +++++++++++------
 1 file changed, 11 insertions(+), 6 deletions(-)
drivers/net/ethernet/mellanox/mlx5/core/en_ethtool.c +11 -6
index 3ed59ced0407a..f38e033ab8faf 100644
@@ -403,11 +403,6 @@ static bool mlx5e_ethtool_set_tcp_data_split(struct mlx5e_priv *priv,
 		return false;
 	}
 
-	/* Might need to disable HW-GRO if it was kept on due to hds. */
-	if (tcp_data_split == ETHTOOL_TCP_DATA_SPLIT_DISABLED &&
-	    dev->cfg->hds_config == ETHTOOL_TCP_DATA_SPLIT_ENABLED)
-		netdev_update_features(priv->netdev);
-
 	return true;
 }
 
@@ -468,13 +463,23 @@ static int mlx5e_set_ringparam(struct net_device *dev,
 			       struct netlink_ext_ack *extack)
 {
 	struct mlx5e_priv *priv = netdev_priv(dev);
+	int err;
 
 	if (!mlx5e_ethtool_set_tcp_data_split(priv,
 					      kernel_param->tcp_data_split,
 					      extack))
 		return -EINVAL;
 
-	return mlx5e_ethtool_set_ringparam(priv, param, extack);
+	err = mlx5e_ethtool_set_ringparam(priv, param, extack);
+	if (err)
+		return err;
+
+	/* Might need to disable HW-GRO if it was kept on due to hds. */
+	if (kernel_param->tcp_data_split == ETHTOOL_TCP_DATA_SPLIT_DISABLED &&
+	    dev->cfg->hds_config == ETHTOOL_TCP_DATA_SPLIT_ENABLED)
+		netdev_update_features(priv->netdev);
+
+	return 0;
 }
 
 void mlx5e_ethtool_get_channels(struct mlx5e_priv *priv,
Signature · 1 line
2.53.0
author maintainer
#2286 lore raw

PATCH 2265/2651 ip6mr: clear skb->cb[] in reg_vif_xmit()

In reply to Greg Kroah-Hartman

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

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

From: Eric Dumazet <[email protected]>

[ Upstream commit 238164201431a425e48dfcb8e9a59de63caf175b ]

reg_vif_xmit() hands the skb to ip6mr_cache_report() as an MRT6MSG_WHOLEPKT report. skb_realloc_headroom() copies skb->cb[] into the report, which is queued to the mroute socket, where rawv6_recvmsg() reads it as IP6CB.

By the time the pim6reg device transmits the packet, skb->cb[] is not IP6CB anymore: qdisc_pkt_len_init() overwrites iif and ra, and any qdisc installed on the device (fq, fq_codel, pie, cake...) or a tc BPF program writing skb->cb[] fills the area holding dst0, srcrt, dst1, lastopt and flags.

Since commit dd433671fef3 ("ipv6: validate extension header length before copying to cmsg") these stale offsets can no longer cause out-of-bounds reads, but the mroute socket can still receive bogus IPV6_PKTINFO ifindex and extension header ancillary data.

Clear IP6CB before building the report. The skb is freed right after, so nothing else depends on its control block.

Fixes 14fb64e1f449 ("[IPV6] MROUTE: Support PIM-SM (SSM).")
---
 net/ipv6/ip6mr.c | 6 ++++++
 1 file changed, 6 insertions(+)
net/ipv6/ip6mr.c +6 -0
index ed9d786f1a423..8e647213ade1b 100644
@@ -652,6 +652,12 @@ static netdev_tx_t reg_vif_xmit(struct sk_buff *skb,
 	DEV_STATS_ADD(dev, tx_bytes, skb->len);
 	DEV_STATS_INC(dev, tx_packets);
 
+	/* skb->cb[] holds qdisc/tc state at this point, not IP6CB.
+	 * ip6mr_cache_report() copies it to the report delivered to
+	 * the mroute socket, where it is read as IP6CB.
+	 */
+	memset(IP6CB(skb), 0, sizeof(*IP6CB(skb)));
+
 	ip6mr_cache_report(mrt, skb, READ_ONCE(mrt->mroute_reg_vif_num),
 			   MRT6MSG_WHOLEPKT);
 	rcu_read_unlock();
Signature · 1 line
2.53.0
author maintainer
#2287 lore raw

PATCH 2266/2651 ipv6: Hold RCU when emitting route hardware flags notification

In reply to Greg Kroah-Hartman

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

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

From: Ido Schimmel <[email protected]>

[ Upstream commit 7c9cb1edaf8fd8e1af25e39741e603500986ef66 ]

fib6_info_hw_flags_set() is called by drivers from process context without RTNL or RCU. When the route uses a nexthop object, rt6_nlmsg_size() and rt6_fill_node() access the nexthop's RCU protected nexthop info and group pointers via rcu_dereference_rtnl(), resulting in suspicious RCU usage splats [1].

Fix by holding RCU while sizing and filling the notification, like fib_alias_hw_flags_set() already does. Switch to GFP_ATOMIC for the skb allocation accordingly.

Reproducer:

 # echo "10 0" > /sys/bus/netdevsim/new_device
 # sysctl -wq net.ipv6.fib_notify_on_flag_change=1
 # sysctl -wq net.ipv4.nexthop_compat_mode=1
 # ip -6 nexthop add id 1 blackhole
 # ip -6 route add 2001:db8:1::1/128 nhid 1

[1]
WARNING: suspicious RCU usage 7.3.0-rc7-virtme-g191aa41548b2 #38 Not tainted net/ipv4/nexthop.c:1539 suspicious rcu_dereference_check() usage! [...]

Workqueue: events nsim_fib_event_work
Call Trace:
 <TASK>
 dump_stack_lvl (lib/dump_stack.c:94 lib/dump_stack.c:120)
 lockdep_rcu_suspicious.cold (kernel/locking/lockdep.c:6972)
 nexthop_for_each_fib6_nh (net/ipv4/nexthop.c:1539 (discriminator 16))
 rt6_nlmsg_size (net/ipv6/route.c:5728)
 fib6_info_hw_flags_set (net/ipv6/route.c:6503)
 nsim_fib6_rt_add (drivers/net/netdevsim/fib.c:671 drivers/net/netdevsim/fib.c:694)
 nsim_fib6_rt_insert (drivers/net/netdevsim/fib.c:759)
 nsim_fib_event_work (drivers/net/netdevsim/fib.c:856 drivers/net/netdevsim/fib.c:889 drivers/net/netdevsim/fib.c:1493)
 process_one_work (kernel/workqueue.c:3396)
 worker_thread (kernel/workqueue.c:3479 kernel/workqueue.c:3560)
 kthread (kernel/kthread.c:436)
 ret_from_fork (arch/x86/kernel/process.c:158)
 ret_from_fork_asm (arch/x86/entry/entry_64.S:245)
 </TASK>
---
 net/ipv6/route.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
net/ipv6/route.c +6 -1
index 3688280742e48..d989df6ccea5b 100644
@@ -6509,7 +6509,9 @@ void fib6_info_hw_flags_set(struct net *net, struct fib6_info *f6i,
 	if (!fib_notify_on_flag_change)
 		return;
 
-	skb = nlmsg_new(rt6_nlmsg_size(f6i), GFP_KERNEL);
+	rcu_read_lock();
+
+	skb = nlmsg_new(rt6_nlmsg_size(f6i), GFP_ATOMIC);
 	if (!skb) {
 		err = -ENOBUFS;
 		goto errout;
@@ -6522,10 +6524,13 @@ void fib6_info_hw_flags_set(struct net *net, struct fib6_info *f6i,
 		goto errout;
 	}
 
+	rcu_read_unlock();
+
 	rtnl_notify(skb, net, 0, RTNLGRP_IPV6_ROUTE, NULL, GFP_KERNEL);
 	return;
 
 errout:
+	rcu_read_unlock();
 	rtnl_set_sk_err(net, RTNLGRP_IPV6_ROUTE, err);
 }
 EXPORT_SYMBOL(fib6_info_hw_flags_set);
Signature · 1 line
2.53.0
author maintainer
#2288 lore raw

PATCH 2267/2651 team: reject CAN, IEEE 802.15.4 and 6LoWPAN devices in team_port_add

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]>

[ Upstream commit 9043be310c6a4c5e57f7bba4b9870554eac7aa96 ]

When the first port has a non-Ethernet type, team_setup_by_port() copies port_dev->type to the team device while netdev_priv() of the team device still holds a struct team. Several L2 stacks identify their devices by dev->type alone and then access type specific data that the team driver never sets up:

- CAN protocols rely on the CAN mid-layer private data (ml_priv)
- IEEE 802.15.4 code dereferences ieee802154_ptr and the mlme ops in ml_priv
- the 6LoWPAN netdev notifier writes through lowpan_dev(dev) on NETDEV_DOWN and reads it on NETDEV_UP/NETDEV_CHANGE

Enslaving such a device (e.g. vxcan, wpan0, lowpan0) therefore leads to NULL pointer dereferences or to writes into struct team.

This is the same problem that syzbot reported for the bonding driver with a vxcan device enslaved to a bond master, which crashed in can_rx_unregister() and was fixed by commit 8ba68464e478 ("bonding:
refuse to enslave CAN devices"). The team driver has the same gap.

Reject ARPHRD_CAN, ARPHRD_IEEE802154, ARPHRD_IEEE802154_MONITOR and ARPHRD_6LOWPAN devices in team_port_add().

---
 drivers/net/team/team_core.c | 11 +++++++++++
 1 file changed, 11 insertions(+)
drivers/net/team/team_core.c +11 -0
index ca75f08e3c593..957cc7885d2fb 100644
@@ -1225,6 +1225,17 @@ static int team_port_add(struct team *team, struct net_device *port_dev,
 		return -EINVAL;
 	}
 
+	if (port_dev->type == ARPHRD_CAN ||
+	    port_dev->type == ARPHRD_IEEE802154 ||
+	    port_dev->type == ARPHRD_IEEE802154_MONITOR ||
+	    port_dev->type == ARPHRD_6LOWPAN) {
+		NL_SET_ERR_MSG(extack,
+			       "CAN, IEEE 802.15.4 and 6LoWPAN devices can't be added as a team port");
+		netdev_err(dev, "Device %s is CAN, IEEE 802.15.4 or 6LoWPAN. These device types can't be added as a team port\n",
+			   portname);
+		return -EINVAL;
+	}
+
 	if (netif_is_team_port(port_dev)) {
 		NL_SET_ERR_MSG(extack, "Device is already a port of a team device");
 		netdev_err(dev, "Device %s is already a port "
Signature · 1 line
2.53.0
author maintainer
#2289 lore raw

PATCH 2268/2651 net: stmmac: Track the TX DMA threshold per queue

In reply to Greg Kroah-Hartman

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

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

From: Ovidiu Panait <[email protected]>

[ Upstream commit 9dd53418781900f02897c805eed397555cf98417 ]

Commit 3a6c12a0c6c3 ("net: stmmac: bump tc when get underflow error from DMA descriptor") made dwmac4 raise the DMA threshold of the queues that report TX underflows. This is done by incrementing a module global parameter 'tc' by 64 on each underflow.

This leads to inconsistent TX DMA thresholds between queues and causes issues on platforms with multiple stmmac controllers, as 'tc' is shared by all of them. Once 'tc' goes over 256 the bumping stops, and queues that did not underflow before are left at the initial threshold.

On the Renesas RZ/V2H platform, which has two dwmac4 controllers, we observed sporadic iperf3 TCP TX failures:

  iperf3 -c <server> -t5 --bind-dev end1
  ...
  [  5]   0.00-5.00   sec  1.00 MBytes  1.68 Mbits/sec   87       sender
  [  5]   0.00-5.00   sec   768 KBytes  1.26 Mbits/sec            receiver

This happens because the TX queues of end1 were underflowing on a large fraction of the packets, but the DMA TX threshold was never raised from the default of 64 bytes. The threshold was not raised because end0 had underflowed first and had already pushed 'tc' past 256. Which controller is affected depends on which one underflows first.

To fix this, make the TX DMA threshold per queue instead of global. Each time an underflow happens on a queue, its TX DMA threshold gets incremented, without affecting other queues or controllers. With this change, 'tc' is only used as the initial value, and the RX threshold is no longer bumped together with the TX one, as TX underflows have nothing to do with the RX side.

Fixes 3a6c12a0c6c3 ("net: stmmac: bump tc when get underflow error from DMA descriptor")
---
 drivers/net/ethernet/stmicro/stmmac/stmmac.h  |  1 +
 .../net/ethernet/stmicro/stmmac/stmmac_main.c | 33 +++++++++++--------
 2 files changed, 21 insertions(+), 13 deletions(-)
drivers/net/ethernet/stmicro/stmmac/stmmac.h +1 -0
index ee128111cb2d5..9cdad84308568 100644
@@ -270,6 +270,7 @@ struct stmmac_priv {
 	bool sph_capable;
 	u32 sarc_type;
 	u32 rx_riwt[MTL_MAX_RX_QUEUES];
+	u32 tx_threshold[MTL_MAX_TX_QUEUES];
 	int hwts_rx_en;
 	bool tsfupdt_coarse;
 
drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +20 -13
index 388575cf588ad..80489d1fe3036 100644
@@ -2593,7 +2593,6 @@ static void stmmac_dma_operation_mode(struct stmmac_priv *priv)
 	}
 
 	if (priv->plat->force_thresh_dma_mode) {
-		txmode = tc;
 		rxmode = tc;
 	} else if (priv->plat->force_sf_dma_mode || priv->plat->tx_coe) {
 		/*
@@ -2607,7 +2606,6 @@ static void stmmac_dma_operation_mode(struct stmmac_priv *priv)
 		rxmode = SF_DMA_MODE;
 		priv->xstats.threshold = SF_DMA_MODE;
 	} else {
-		txmode = tc;
 		rxmode = SF_DMA_MODE;
 	}
 
@@ -2626,8 +2624,11 @@ static void stmmac_dma_operation_mode(struct stmmac_priv *priv)
 	for (chan = 0; chan < tx_channels_count; chan++) {
 		qmode = priv->plat->tx_queues_cfg[chan].mode_to_use;
 
-		stmmac_dma_tx_mode(priv, priv->ioaddr, txmode, chan,
-				txfifosz, qmode);
+		if (txmode == SF_DMA_MODE)
+			priv->tx_threshold[chan] = SF_DMA_MODE;
+
+		stmmac_dma_tx_mode(priv, priv->ioaddr, priv->tx_threshold[chan],
+				   chan, txfifosz, qmode);
 	}
 }
 
@@ -2794,17 +2795,20 @@ static bool stmmac_xdp_xmit_zc(struct stmmac_priv *priv, u32 queue, u32 budget)
 
 static void stmmac_bump_dma_threshold(struct stmmac_priv *priv, u32 chan)
 {
-	if (unlikely(priv->xstats.threshold != SF_DMA_MODE) && tc <= 256) {
-		tc += 64;
+	u32 thresh = priv->tx_threshold[chan];
 
-		if (priv->plat->force_thresh_dma_mode)
-			stmmac_set_dma_operation_mode(priv, tc, tc, chan);
-		else
-			stmmac_set_dma_operation_mode(priv, tc, SF_DMA_MODE,
-						      chan);
+	if (unlikely(thresh == SF_DMA_MODE) || thresh > 256)
+		return;
 
-		priv->xstats.threshold = tc;
-	}
+	thresh += 64;
+
+	if (priv->plat->force_thresh_dma_mode)
+		stmmac_set_dma_operation_mode(priv, thresh, tc, chan);
+	else
+		stmmac_set_dma_operation_mode(priv, thresh, SF_DMA_MODE, chan);
+
+	priv->tx_threshold[chan] = thresh;
+	priv->xstats.threshold = thresh;
 }
 
 /**
@@ -8034,6 +8038,9 @@ static int __stmmac_dvr_probe(struct device *device,
 
 	priv->xstats.threshold = tc;
 
+	for (i = 0; i < MTL_MAX_TX_QUEUES; i++)
+		priv->tx_threshold[i] = tc;
+
 	/* Initialize RSS */
 	rxq = priv->plat->rx_queues_to_use;
 	netdev_rss_key_fill(priv->rss.key, sizeof(priv->rss.key));
Signature · 1 line
2.53.0
author maintainer
#2290 lore raw

PATCH 2269/2651 ibmveth: fix netpoll races with RX replenish

In reply to Greg Kroah-Hartman

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

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

From: Mingming Cao <[email protected]>

[ Upstream commit 8d9ecac6b96e61d0e6d126c60644829fd9f66952 ]

ibmveth_poll_controller() runs RX replenish outside NAPI and without a lock, racing NAPI's replenish on another CPU. Both can fill the same slot, so an skb and its DMA mapping leak and PHYP can write into an unmapped buffer. netpoll calls it from netconsole and from netpoll-enabled bonds.

ibmveth_open() also enables NAPI before the RX resources exist. ibmveth_change_mtu(), veth_pool_store(), ibmveth_set_csum_offload() and ibmveth_set_tso() call close() and open() directly, so while open() is still setting up, netpoll and the direct ibmveth_interrupt() calls can replenish NULL pools and read freed memory.

Remove the callback, as Eric Dumazet did for many drivers after commit ac3d9dd034e5 ("netpoll: make ndo_poll_controller() optional"), including ibmvnic in commit 0c3b9d1b37df ("ibmvnic: remove ndo_poll_controller"). netpoll then polls NAPI itself with budget 0. napi->poll_owner serializes that with NAPI, but not with a NAPI poll that was already running when netpoll was set up, so skip RX replenish at budget 0, which netpoll uses for TX only. TX completes synchronously, so ibmveth_poll() has nothing else to do for netpoll.

Enable NAPI just before request_irq(), once everything ibmveth_poll() touches exists.

Found in review of the ibmveth multi-queue RX series and confirmed by code inspection of poll_one_napi() and the direct close()/open() callers; neither race was reproduced. Tested on a POWER10 LPAR with netconsole over ibmveth: a ping flood (678,470 packets, no loss) during a printk flood, and MTU changes and buffer pool toggles under traffic, with no warnings. No kernel selftests cover ibmveth.

Fixes 6b4223748895 ("[PATCH] ibmveth: Add netpoll function")
Fixes bea3348eef27 ("[NET]: Make NAPI polling independent of struct net_device objects.")
---
 drivers/net/ethernet/ibm/ibmveth.c | 28 +++++++++++++---------------
 1 file changed, 13 insertions(+), 15 deletions(-)
drivers/net/ethernet/ibm/ibmveth.c +13 -15
index abebdb1fc2628..4a5869183be66 100644
@@ -628,8 +628,6 @@ static int ibmveth_open(struct net_device *netdev)
 
 	netdev_dbg(netdev, "open starting\n");
 
-	napi_enable(&adapter->napi);
-
 	for(i = 0; i < IBMVETH_NUM_BUFF_POOLS; i++)
 		rxq_entries += adapter->rx_buff_pool[i].size;
 
@@ -717,10 +715,18 @@ static int ibmveth_open(struct net_device *netdev)
 		}
 	}
 
+	/* NAPI can run as soon as it is enabled, from netpoll during the
+	 * direct close()/open() pairs or from a direct ibmveth_interrupt()
+	 * call, so enable it only once everything ibmveth_poll() touches
+	 * exists.
+	 */
+	napi_enable(&adapter->napi);
+
 	netdev_dbg(netdev, "registering irq 0x%x\n", netdev->irq);
 	rc = request_irq(netdev->irq, ibmveth_interrupt, 0, netdev->name,
 			 netdev);
 	if (rc != 0) {
+		napi_disable(&adapter->napi);
 		netdev_err(netdev, "unable to request irq 0x%x, rc %d\n",
 			   netdev->irq, rc);
 		goto out_free_buffer_pools;
@@ -765,7 +771,6 @@ static int ibmveth_open(struct net_device *netdev)
 out_free_buffer_list:
 	free_page((unsigned long)adapter->buffer_list_addr);
 out:
-	napi_disable(&adapter->napi);
 	return rc;
 }
 
@@ -1542,7 +1547,11 @@ static int ibmveth_poll(struct napi_struct *napi, int budget)
 		}
 	}
 
-	ibmveth_replenish_task(adapter);
+	/* netpoll polls with budget 0 for TX only, and is not serialized
+	 * with a NAPI poll that was already running when it was set up
+	 */
+	if (budget)
+		ibmveth_replenish_task(adapter);
 
 	if (frames_processed == budget)
 		goto out;
@@ -1682,14 +1691,6 @@ static int ibmveth_change_mtu(struct net_device *dev, int new_mtu)
 	return -EINVAL;
 }
 
-#ifdef CONFIG_NET_POLL_CONTROLLER
-static void ibmveth_poll_controller(struct net_device *dev)
-{
-	ibmveth_replenish_task(netdev_priv(dev));
-	ibmveth_interrupt(dev->irq, dev);
-}
-#endif
-
 /**
  * ibmveth_get_desired_dma - Calculate IO memory desired by the driver
  *
@@ -1791,9 +1792,6 @@ static const struct net_device_ops ibmveth_netdev_ops = {
 	.ndo_validate_addr	= eth_validate_addr,
 	.ndo_set_mac_address    = ibmveth_set_mac_addr,
 	.ndo_features_check	= ibmveth_features_check,
-#ifdef CONFIG_NET_POLL_CONTROLLER
-	.ndo_poll_controller	= ibmveth_poll_controller,
-#endif
 };
 
 static int ibmveth_probe(struct vio_dev *dev, const struct vio_device_id *id)
Signature · 1 line
2.53.0
author maintainer
#2291 lore raw

PATCH 2270/2651 ibmveth: do not close twice after a failed reopen

In reply to Greg Kroah-Hartman

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

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

From: Mingming Cao <[email protected]>

[ Upstream commit 95811c873d1b97c424a7e6e731730cbf6656ab7e ]

ibmveth_change_mtu(), veth_pool_store(), ibmveth_set_csum_offload() and ibmveth_set_tso() call close() and open() directly. If open() fails, NAPI is left disabled while IFF_UP stays set, so the next close() (ifdown, unregister or another reconfiguration) calls napi_disable() again and waits forever with RTNL held. Networking and shutdown hang; only a reboot recovers. ethtool -L in that state also wakes queues that have no TX buffer and dereferences NULL in ibmveth_start_xmit().

Any open() failure on those paths triggers it, for example an allocation failure on an MTU change to jumbo frames.

Track a successful open in adapter->opened. close() returns early when it is clear, and set_channels() checks it instead of IFF_UP.

The open() error-path leaks were fixed separately in net by commit af0524bf4ce1 ("ibmveth: h_free logical LAN on open-fail after register") and commit 84bec0bf0352 ("ibmveth: fix TX LTB and filter unwind on open-fail"), which are now in net-next too, so a failed open() no longer leaves TX buffers or the logical LAN registration behind for the early return to skip.

Found in review of the ibmveth multi-queue RX series and confirmed by code inspection. Tested on a POWER10 LPAR with ibmveth_open() forced to fail by a test-only module parameter (not part of this patch): 'ip link set dev eth1 mtu 9000' fails, then 'ip link set dev eth1 down' returns at once and 'ip link set dev eth1 up' recovers the interface. No kernel selftests cover ibmveth.

Fixes 860f242eb534 ("[PATCH] ibmveth change buffer pools dynamically")
---
 drivers/net/ethernet/ibm/ibmveth.c | 24 +++++++++++++++++-------
 drivers/net/ethernet/ibm/ibmveth.h |  2 ++
 2 files changed, 19 insertions(+), 7 deletions(-)
drivers/net/ethernet/ibm/ibmveth.c +17 -7
index 4a5869183be66..4665447997eaa 100644
@@ -739,6 +739,7 @@ static int ibmveth_open(struct net_device *netdev)
 
 	netif_tx_start_all_queues(netdev);
 
+	adapter->opened = true;
 	netdev_dbg(netdev, "open complete\n");
 
 	return 0;
@@ -781,6 +782,14 @@ static int ibmveth_close(struct net_device *netdev)
 	long lpar_rc;
 	int i;
 
+	/* change_mtu, pool sysfs, set_csum and set_tso call close() and
+	 * open() directly. If that open() fails, IFF_UP stays set and
+	 * NAPI is disabled; a second close() would hang in napi_disable().
+	 */
+	if (!adapter->opened)
+		return 0;
+	adapter->opened = false;
+
 	netdev_dbg(netdev, "close starting\n");
 
 	napi_disable(&adapter->napi);
@@ -832,10 +841,10 @@ static int ibmveth_close(struct net_device *netdev)
  *
  * @w: pointer to work_struct embedded in adapter structure
  *
- * Context: This routine acquires rtnl_mutex and disables its NAPI through
- *          ibmveth_close. It can't be called directly in a context that has
- *          already acquired rtnl_mutex or disabled its NAPI, or directly from
- *          a poll routine.
+ * Context: This routine acquires rtnl_mutex and, if the device is open,
+ *          disables its NAPI through ibmveth_close. It can't be called
+ *          directly in a context that has already acquired rtnl_mutex or
+ *          disabled its NAPI, or directly from a poll routine.
  *
  * Return: void
  */
@@ -1129,10 +1138,11 @@ static int ibmveth_set_channels(struct net_device *netdev,
 		     goal = channels->tx_count;
 	int rc, i;
 
-	/* If ndo_open has not been called yet then don't allocate, just set
-	 * desired netdev_queue's and return
+	/* If the device is not open (including a failed close/open with
+	 * IFF_UP still set) then don't allocate, just set desired
+	 * netdev_queue's and return
 	 */
-	if (!(netdev->flags & IFF_UP))
+	if (!adapter->opened)
 		return netif_set_real_num_tx_queues(netdev, goal);
 
 	/* We have IBMVETH_MAX_QUEUES netdev_queue's allocated
drivers/net/ethernet/ibm/ibmveth.h +2 -0
index d87713668ed30..3f2240823f6a3 100644
@@ -172,6 +172,8 @@ struct ibmveth_adapter {
 	int rx_csum;
 	int large_send;
 	bool is_active_trunk;
+	/* Set by a successful ibmveth_open(), cleared by ibmveth_close(). */
+	bool opened;
 	unsigned int rx_buffers_per_hcall;
 
 	u64 fw_ipv6_csum_support;
Signature · 1 line
2.53.0
author maintainer
#2292 lore raw

PATCH 2271/2651 ibmveth: disable the reset work before unregister in remove

In reply to Greg Kroah-Hartman

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

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

From: Mingming Cao <[email protected]>

[ Upstream commit 1412235447869922eb0ee041a31fab6176e60ab0 ]

ibmveth_remove() cancels the reset work before unregister_netdev(), but NAPI keeps running until unregister closes the device and can queue the reset again, on an interrupt enable failure, a bad free_map entry or a bad RX slot. The reset can then run on the adapter after free_netdev(), or reopen the device during unregister.

Use disable_work_sync(), which waits for a running reset and keeps the work from being queued again. A bad RX slot also makes poll spin, which can stall unregister; a later patch in this series fixes that.

Found in review of the ibmveth multi-queue RX series and confirmed by code inspection; it was not reproduced. Tested on a POWER10 LPAR with unbind and bind cycles under traffic. No kernel selftests cover ibmveth.

Fixes 2c91e2319ed9 ("net: ibmveth: Reset the adapter when unexpected states are detected")
---
 drivers/net/ethernet/ibm/ibmveth.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/ethernet/ibm/ibmveth.c +1 -1
index 4665447997eaa..cee0e9783b2ab 100644
@@ -1956,7 +1956,7 @@ static void ibmveth_remove(struct vio_dev *dev)
 	struct ibmveth_adapter *adapter = netdev_priv(netdev);
 	int i;
 
-	cancel_work_sync(&adapter->work);
+	disable_work_sync(&adapter->work);
 
 	for (i = 0; i < IBMVETH_NUM_BUFF_POOLS; i++)
 		kobject_put(&adapter->rx_buff_pool[i].kobj);
Signature · 1 line
2.53.0
author maintainer
#2293 lore raw

PATCH 2272/2651 ibmveth: step past bad RX correlators instead of spinning or oopsing

In reply to Greg Kroah-Hartman

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

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

From: Mingming Cao <[email protected]>

[ Upstream commit c9b95adc755f2396307be676ce838161fb011986 ]

ibmveth_poll() mishandles a bad RX correlator from PHYP in two ways.

If harvest fails or ibmveth_rxq_get_buffer() returns NULL, poll breaks out without advancing the ring and restarts on the same slot forever. For an out-of-range correlator it also fires a WARN_ON() and schedules a reset each pass, but the reset is queued on that CPU and never runs, and the CPU stalls RCU, so RTNL holders hang too. This dates from the first commit in Fixes:, which turned the BUG_ON()s here into WARN_ON() plus a reset.

The range check also accepts a correlator naming an inactive buffer pool (pools 2 and 3 by default), whose skbuff array is NULL, so the lookup dereferences NULL in softirq. Pools became inactive with the second commit in Fixes:.

Validate the correlator in one helper that also rejects a pool with no skbuff array. On a bad slot, advance the ring, count the drop in rx_dropped and still schedule the reset, which rebuilds the pools. The slot has moved, so stay in the budget loop and count it in frames_processed. Breaking out would complete NAPI, re-arm, and napi_schedule() with budget left. When the final check finds more work, queue the NAPI and return instead of going back to
restart_poll: after napi_complete_done() the NAPI is no longer this call's, and with threaded NAPI and busy polling the kthread can already be polling it on another CPU. frames_processed is below budget there, so busy_poll_stop() does not queue it a second time. Mask the interrupt before queueing, as ibmveth_interrupt() does; masking after napi_schedule() could land after that kthread has finished and unmasked, leaving RX masked with nothing scheduled.

Drop a frame whose offset + length does not fit the pool buffer:
copybreak would read past the RX buffer and skb_put() would BUG(). Also drop one shorter than an Ethernet header, which eth_type_trans() would read past. Read the correlator once per slot and use that value for the lookup, the bound and the harvest.

The base driver never checked frame bounds, and they have not been seen in the field, so they have no Fixes: tag of their own. The tags below are for the correlator hang.

The correlator comes from PHYP, and with the ring advancing a burst of bad slots would WARN once per slot (and panic with panic_on_warn), so use a ratelimited netdev_err() instead. Also free the rx_copybreak skb if harvest fails there.

Add a KUnit case for harvest advancing on errors and extend the existing cases to an inactive pool. Run against the unfixed driver, with the calls changed back to its signatures, the first fails and the others oops.

Found in review of the ibmveth multi-queue RX series (the frame bound by the Sashiko review of v2 of this series) and confirmed by code inspection and the KUnit cases above. Hitting either correlator bug needs PHYP to return a bad correlator, so neither was reproduced on hardware. Tested with KUnit on qemu pseries (ppc64le), and on a POWER10 LPAR with a ping flood and MTU changes under traffic. No kernel selftests cover ibmveth.

Fixes 2c91e2319ed9 ("net: ibmveth: Reset the adapter when unexpected states are detected")
Fixes 860f242eb534 ("[PATCH] ibmveth change buffer pools dynamically")
---
 drivers/net/ethernet/ibm/ibmveth.c | 265 +++++++++++++++++++++++------
 1 file changed, 216 insertions(+), 49 deletions(-)
drivers/net/ethernet/ibm/ibmveth.c +216 -49
index cee0e9783b2ab..919b5831d875c 100644
@@ -135,6 +135,13 @@ static inline int ibmveth_rxq_frame_length(struct ibmveth_adapter *adapter)
 	return be32_to_cpu(adapter->rx_queue.queue_addr[adapter->rx_queue.index].length);
 }
 
+static u64 ibmveth_rxq_correlator(struct ibmveth_adapter *adapter)
+{
+	unsigned int idx = adapter->rx_queue.index;
+
+	return READ_ONCE(adapter->rx_queue.queue_addr[idx].correlator);
+}
+
 static inline int ibmveth_rxq_csum_good(struct ibmveth_adapter *adapter)
 {
 	return ibmveth_rxq_flags(adapter) & IBMVETH_RXQ_CSUM_GOOD;
@@ -443,6 +450,37 @@ static void ibmveth_free_buffer_pool(struct ibmveth_adapter *adapter,
 	}
 }
 
+/* The correlator comes back from PHYP; a bad one schedules a reset. */
+static bool ibmveth_rxq_correlator_valid(struct ibmveth_adapter *adapter,
+					 u64 correlator)
+{
+	unsigned int index = correlator & 0xffffffffUL;
+	unsigned int pool = correlator >> 32;
+
+	/* An inactive pool keeps its size but has no skbuff array. */
+	if (pool < IBMVETH_NUM_BUFF_POOLS &&
+	    index < adapter->rx_buff_pool[pool].size &&
+	    adapter->rx_buff_pool[pool].skbuff)
+		return true;
+
+	if (net_ratelimit())
+		netdev_err(adapter->netdev,
+			   "invalid RX correlator %llx, resetting\n",
+			   correlator);
+	schedule_work(&adapter->work);
+	return false;
+}
+
+static void ibmveth_rxq_no_skb(struct ibmveth_adapter *adapter,
+			       u64 correlator)
+{
+	if (net_ratelimit())
+		netdev_err(adapter->netdev,
+			   "no buffer for RX correlator %llx, resetting\n",
+			   correlator);
+	schedule_work(&adapter->work);
+}
+
 /**
  * ibmveth_remove_buffer_from_pool - remove a buffer from a pool
  * @adapter: adapter instance
@@ -451,7 +489,8 @@ static void ibmveth_free_buffer_pool(struct ibmveth_adapter *adapter,
  *
  * Return:
  * * %0       - success
- * * %-EINVAL - correlator maps to pool or index out of range
+ * * %-EINVAL - correlator maps to pool or index out of range, or to an
+ *              inactive pool
  * * %-EFAULT - pool and index map to null skb
  */
 static int ibmveth_remove_buffer_from_pool(struct ibmveth_adapter *adapter,
@@ -462,15 +501,12 @@ static int ibmveth_remove_buffer_from_pool(struct ibmveth_adapter *adapter,
 	unsigned int free_index;
 	struct sk_buff *skb;
 
-	if (WARN_ON(pool >= IBMVETH_NUM_BUFF_POOLS) ||
-	    WARN_ON(index >= adapter->rx_buff_pool[pool].size)) {
-		schedule_work(&adapter->work);
+	if (!ibmveth_rxq_correlator_valid(adapter, correlator))
 		return -EINVAL;
-	}
 
 	skb = adapter->rx_buff_pool[pool].skbuff[index];
-	if (WARN_ON(!skb)) {
-		schedule_work(&adapter->work);
+	if (!skb) {
+		ibmveth_rxq_no_skb(adapter, correlator);
 		return -EFAULT;
 	}
 
@@ -504,51 +540,56 @@ static int ibmveth_remove_buffer_from_pool(struct ibmveth_adapter *adapter,
 	return 0;
 }
 
-/* get the current buffer on the rx queue */
-static inline struct sk_buff *ibmveth_rxq_get_buffer(struct ibmveth_adapter *adapter)
+/* get the buffer for @correlator, read once from the current rx queue entry */
+static struct sk_buff *ibmveth_rxq_get_buffer(struct ibmveth_adapter *adapter,
+					      u64 correlator)
 {
-	u64 correlator = adapter->rx_queue.queue_addr[adapter->rx_queue.index].correlator;
 	unsigned int pool = correlator >> 32;
 	unsigned int index = correlator & 0xffffffffUL;
+	struct sk_buff *skb;
 
-	if (WARN_ON(pool >= IBMVETH_NUM_BUFF_POOLS) ||
-	    WARN_ON(index >= adapter->rx_buff_pool[pool].size)) {
-		schedule_work(&adapter->work);
+	if (!ibmveth_rxq_correlator_valid(adapter, correlator))
 		return NULL;
-	}
 
-	return adapter->rx_buff_pool[pool].skbuff[index];
+	skb = adapter->rx_buff_pool[pool].skbuff[index];
+	if (!skb)
+		ibmveth_rxq_no_skb(adapter, correlator);
+	return skb;
+}
+
+static void ibmveth_rxq_advance(struct ibmveth_adapter *adapter)
+{
+	if (++adapter->rx_queue.index == adapter->rx_queue.num_slots) {
+		adapter->rx_queue.index = 0;
+		adapter->rx_queue.toggle = !adapter->rx_queue.toggle;
+	}
 }
 
 /**
  * ibmveth_rxq_harvest_buffer - Harvest buffer from pool
  *
- * @adapter: pointer to adapter
- * @reuse:   whether to reuse buffer
+ * @adapter:    pointer to adapter
+ * @correlator: correlator of the current rx queue entry, as read by poll
+ * @reuse:      whether to reuse buffer
  *
  * Context: called from ibmveth_poll
  *
+ * The ring advances even on error, so poll does not return to a bad
+ * slot before the scheduled reset can run.
+ *
  * Return:
  * * %0    - success
  * * other - non-zero return from ibmveth_remove_buffer_from_pool
  */
 static int ibmveth_rxq_harvest_buffer(struct ibmveth_adapter *adapter,
-				      bool reuse)
+				      u64 correlator, bool reuse)
 {
-	u64 cor;
 	int rc;
 
-	cor = adapter->rx_queue.queue_addr[adapter->rx_queue.index].correlator;
-	rc = ibmveth_remove_buffer_from_pool(adapter, cor, reuse);
-	if (unlikely(rc))
-		return rc;
+	rc = ibmveth_remove_buffer_from_pool(adapter, correlator, reuse);
+	ibmveth_rxq_advance(adapter);
 
-	if (++adapter->rx_queue.index == adapter->rx_queue.num_slots) {
-		adapter->rx_queue.index = 0;
-		adapter->rx_queue.toggle = !adapter->rx_queue.toggle;
-	}
-
-	return 0;
+	return rc;
 }
 
 static void ibmveth_free_tx_ltb(struct ibmveth_adapter *adapter, int idx)
@@ -1469,31 +1510,60 @@ static int ibmveth_poll(struct napi_struct *napi, int budget)
 	struct net_device *netdev = adapter->netdev;
 	int frames_processed = 0;
 	unsigned long lpar_rc;
+	u64 correlator;
 	u16 mss = 0;
+	int rc;
 
-restart_poll:
 	while (frames_processed < budget) {
 		if (!ibmveth_rxq_pending_buffer(adapter))
 			break;
 
 		smp_rmb();
+		correlator = ibmveth_rxq_correlator(adapter);
 		if (!ibmveth_rxq_buffer_valid(adapter)) {
 			wmb(); /* suggested by larson1 */
 			adapter->rx_invalid_buffer++;
 			netdev_dbg(netdev, "recycling invalid buffer\n");
-			if (unlikely(ibmveth_rxq_harvest_buffer(adapter, true)))
-				break;
+			rc = ibmveth_rxq_harvest_buffer(adapter, correlator, true);
+			if (unlikely(rc)) {
+				netdev->stats.rx_dropped++;
+				frames_processed++;
+				continue;
+			}
 		} else {
 			struct sk_buff *skb, *new_skb;
 			int length = ibmveth_rxq_frame_length(adapter);
 			int offset = ibmveth_rxq_frame_offset(adapter);
 			int csum_good = ibmveth_rxq_csum_good(adapter);
 			int lrg_pkt = ibmveth_rxq_large_packet(adapter);
+			unsigned int pool, room, off, len;
 			__sum16 iph_check = 0;
 
-			skb = ibmveth_rxq_get_buffer(adapter);
-			if (unlikely(!skb))
-				break;
+			skb = ibmveth_rxq_get_buffer(adapter, correlator);
+			if (unlikely(!skb)) {
+				ibmveth_rxq_advance(adapter);
+				netdev->stats.rx_dropped++;
+				frames_processed++;
+				continue;
+			}
+
+			pool = correlator >> 32;
+			room = min_t(unsigned int, skb_tailroom(skb),
+				     adapter->rx_buff_pool[pool].buff_size);
+			off = offset;
+			len = length;
+			if (unlikely(len < ETH_HLEN || off >= room ||
+				     len > room - off)) {
+				if (net_ratelimit())
+					netdev_err(netdev,
+						   "bad RX frame offset %u length %u (buffer %u), dropping\n",
+						   off, len, room);
+				ibmveth_rxq_harvest_buffer(adapter, correlator,
+							   true);
+				netdev->stats.rx_dropped++;
+				frames_processed++;
+				continue;
+			}
 
 			/* if the large packet bit is set in the rx queue
 			 * descriptor, the mss will be written by PHYP eight
@@ -1517,12 +1587,25 @@ static int ibmveth_poll(struct napi_struct *napi, int budget)
 				if (rx_flush)
 					ibmveth_flush_buffer(skb->data,
 						length + offset);
-				if (unlikely(ibmveth_rxq_harvest_buffer(adapter, true)))
-					break;
+				rc = ibmveth_rxq_harvest_buffer(adapter,
+								correlator,
+								true);
+				if (unlikely(rc)) {
+					dev_kfree_skb_any(new_skb);
+					netdev->stats.rx_dropped++;
+					frames_processed++;
+					continue;
+				}
 				skb = new_skb;
 			} else {
-				if (unlikely(ibmveth_rxq_harvest_buffer(adapter, false)))
-					break;
+				rc = ibmveth_rxq_harvest_buffer(adapter,
+								correlator,
+								false);
+				if (unlikely(rc)) {
+					netdev->stats.rx_dropped++;
+					frames_processed++;
+					continue;
+				}
 				skb_reserve(skb, offset);
 			}
 
@@ -1578,10 +1661,13 @@ static int ibmveth_poll(struct napi_struct *napi, int budget)
 		goto out;
 	}
 
-	if (ibmveth_rxq_pending_buffer(adapter) && napi_schedule(napi)) {
+	/* Mask before queueing, as ibmveth_interrupt() does: a threaded
+	 * NAPI can start polling, and unmask, as soon as it is queued.
+	 */
+	if (ibmveth_rxq_pending_buffer(adapter) && napi_schedule_prep(napi)) {
 		lpar_rc = h_vio_signal(adapter->vdev->unit_address,
 				       VIO_IRQ_DISABLE);
-		goto restart_poll;
+		__napi_schedule(napi);
 	}
 
 out:
@@ -2206,8 +2292,7 @@ static void ibmveth_reset_kunit(struct work_struct *w)
  * @test: pointer to kunit structure
  *
  * Tests the error returns from ibmveth_remove_buffer_from_pool.
- * ibmveth_remove_buffer_from_pool also calls WARN_ON, so dmesg should be
- * checked to see that these warnings happened.
+ * Each error also logs a ratelimited netdev_err.
  *
  * Return: void
  */
@@ -2216,6 +2301,7 @@ static void ibmveth_remove_buffer_from_pool_test(struct kunit *test)
 	struct ibmveth_adapter *adapter = kunit_kzalloc(test, sizeof(*adapter), GFP_KERNEL);
 	struct ibmveth_buff_pool *pool;
 	u64 correlator;
+	int ret;
 
 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, adapter);
 
@@ -2239,6 +2325,13 @@ static void ibmveth_remove_buffer_from_pool_test(struct kunit *test)
 	KUNIT_EXPECT_EQ(test, -EINVAL, ibmveth_remove_buffer_from_pool(adapter, correlator, false));
 	KUNIT_EXPECT_EQ(test, -EINVAL, ibmveth_remove_buffer_from_pool(adapter, correlator, true));
 
+	/* Pool 2 is in range but has no skbuff array, like an inactive pool. */
+	correlator = ((u64)2 << 32) | 0;
+	ret = ibmveth_remove_buffer_from_pool(adapter, correlator, false);
+	KUNIT_EXPECT_EQ(test, -EINVAL, ret);
+	ret = ibmveth_remove_buffer_from_pool(adapter, correlator, true);
+	KUNIT_EXPECT_EQ(test, -EINVAL, ret);
+
 	correlator = (u64)0 | 0;
 	pool->skbuff[0] = NULL;
 	KUNIT_EXPECT_EQ(test, -EFAULT, ibmveth_remove_buffer_from_pool(adapter, correlator, false));
@@ -2251,9 +2344,8 @@ static void ibmveth_remove_buffer_from_pool_test(struct kunit *test)
  * ibmveth_rxq_get_buffer_test - unit test for ibmveth_rxq_get_buffer
  * @test: pointer to kunit structure
  *
- * Tests ibmveth_rxq_get_buffer. ibmveth_rxq_get_buffer also calls WARN_ON for
- * the NULL returns, so dmesg should be checked to see that these warnings
- * happened.
+ * Tests ibmveth_rxq_get_buffer. Each NULL return also logs a ratelimited
+ * netdev_err.
  *
  * Return: void
  */
@@ -2262,6 +2354,7 @@ static void ibmveth_rxq_get_buffer_test(struct kunit *test)
 	struct ibmveth_adapter *adapter = kunit_kzalloc(test, sizeof(*adapter), GFP_KERNEL);
 	struct sk_buff *skb = kunit_kzalloc(test, sizeof(*skb), GFP_KERNEL);
 	struct ibmveth_buff_pool *pool;
+	u64 cor;
 
 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, adapter);
 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, skb);
@@ -2285,14 +2378,87 @@ static void ibmveth_rxq_get_buffer_test(struct kunit *test)
 	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, pool->skbuff);
 
 	adapter->rx_queue.queue_addr[0].correlator = (u64)IBMVETH_NUM_BUFF_POOLS << 32 | 0;
-	KUNIT_EXPECT_PTR_EQ(test, NULL, ibmveth_rxq_get_buffer(adapter));
+	cor = ibmveth_rxq_correlator(adapter);
+	KUNIT_EXPECT_PTR_EQ(test, NULL,
+			    ibmveth_rxq_get_buffer(adapter, cor));
 
 	adapter->rx_queue.queue_addr[0].correlator = (u64)0 << 32 | adapter->rx_buff_pool[0].size;
-	KUNIT_EXPECT_PTR_EQ(test, NULL, ibmveth_rxq_get_buffer(adapter));
+	cor = ibmveth_rxq_correlator(adapter);
+	KUNIT_EXPECT_PTR_EQ(test, NULL,
+			    ibmveth_rxq_get_buffer(adapter, cor));
+
+	/* Pool 2 is in range but has no skbuff array, like an inactive pool. */
+	adapter->rx_queue.queue_addr[0].correlator = (u64)2 << 32 | 0;
+	cor = ibmveth_rxq_correlator(adapter);
+	KUNIT_EXPECT_PTR_EQ(test, NULL,
+			    ibmveth_rxq_get_buffer(adapter, cor));
 
 	pool->skbuff[0] = skb;
 	adapter->rx_queue.queue_addr[0].correlator = (u64)0 << 32 | 0;
-	KUNIT_EXPECT_PTR_EQ(test, skb, ibmveth_rxq_get_buffer(adapter));
+	cor = ibmveth_rxq_correlator(adapter);
+	KUNIT_EXPECT_PTR_EQ(test, skb,
+			    ibmveth_rxq_get_buffer(adapter, cor));
+
+	flush_work(&adapter->work);
+}
+
+/**
+ * ibmveth_rxq_harvest_buffer_test - unit test for ibmveth_rxq_harvest_buffer
+ * @test: pointer to kunit structure
+ *
+ * A bad correlator must still advance the RX ring, wrapping and flipping
+ * the toggle at the end. This covers the harvest path; the advance after
+ * ibmveth_rxq_get_buffer() fails in ibmveth_poll() is not tested here.
+ *
+ * Return: void
+ */
+static void ibmveth_rxq_harvest_buffer_test(struct kunit *test)
+{
+	struct ibmveth_adapter *adapter;
+	struct ibmveth_buff_pool *pool;
+	u64 cor;
+	int ret;
+
+	adapter = kunit_kzalloc(test, sizeof(*adapter), GFP_KERNEL);
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, adapter);
+
+	INIT_WORK(&adapter->work, ibmveth_reset_kunit);
+
+	adapter->rx_queue.num_slots = 2;
+	adapter->rx_queue.index = 0;
+	adapter->rx_queue.toggle = 1;
+	adapter->rx_queue.queue_addr =
+		kunit_kcalloc(test, 2, sizeof(struct ibmveth_rx_q_entry),
+			      GFP_KERNEL);
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, adapter->rx_queue.queue_addr);
+
+	/* Set sane values for buffer pools */
+	for (int i = 0; i < IBMVETH_NUM_BUFF_POOLS; i++)
+		ibmveth_init_buffer_pool(&adapter->rx_buff_pool[i], i,
+					 pool_count[i], pool_size[i],
+					 pool_active[i]);
+
+	pool = &adapter->rx_buff_pool[0];
+	pool->skbuff = kunit_kcalloc(test, pool->size, sizeof(void *),
+				     GFP_KERNEL);
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, pool->skbuff);
+
+	/* Slot 0: pool out of range. Slot 1: valid, but no skb. */
+	adapter->rx_queue.queue_addr[0].correlator =
+		(u64)IBMVETH_NUM_BUFF_POOLS << 32 | 0;
+	adapter->rx_queue.queue_addr[1].correlator = (u64)0 << 32 | 0;
+
+	cor = ibmveth_rxq_correlator(adapter);
+	ret = ibmveth_rxq_harvest_buffer(adapter, cor, true);
+	KUNIT_EXPECT_EQ(test, -EINVAL, ret);
+	KUNIT_EXPECT_EQ(test, 1ULL, adapter->rx_queue.index);
+	KUNIT_EXPECT_EQ(test, 1ULL, adapter->rx_queue.toggle);
+
+	cor = ibmveth_rxq_correlator(adapter);
+	ret = ibmveth_rxq_harvest_buffer(adapter, cor, true);
+	KUNIT_EXPECT_EQ(test, -EFAULT, ret);
+	KUNIT_EXPECT_EQ(test, 0ULL, adapter->rx_queue.index);
+	KUNIT_EXPECT_EQ(test, 0ULL, adapter->rx_queue.toggle);
 
 	flush_work(&adapter->work);
 }
@@ -2300,6 +2466,7 @@ static void ibmveth_rxq_get_buffer_test(struct kunit *test)
 static struct kunit_case ibmveth_test_cases[] = {
 	KUNIT_CASE(ibmveth_remove_buffer_from_pool_test),
 	KUNIT_CASE(ibmveth_rxq_get_buffer_test),
+	KUNIT_CASE(ibmveth_rxq_harvest_buffer_test),
 	{}
 };
 
Signature · 1 line
2.53.0
author maintainer
#2294 lore raw

PATCH 2273/2651 ibmveth: release the pool kobjects when probe fails

In reply to Greg Kroah-Hartman

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

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

From: Mingming Cao <[email protected]>

[ Upstream commit fd052c6823b31eb45f824660567ab3f2da2d5195 ]

If register_netdev() fails in ibmveth_probe(), for example with -EINTR when the binding task is killed, probe frees the netdev but leaves the pool%d kobjects embedded in it registered in sysfs. Reading /sys/devices/vio/<unit>/pool0/num is then a use-after-free, and the next probe cannot add pool0.

Put the kobjects before freeing the netdev, as ibmveth_remove() does, on this path and on the netif_set_real_num_tx_queues() one.

The kobjects also have no release(). With CONFIG_DEBUG_KOBJECT_RELEASE, kobject_put() defers their cleanup, including removing the sysfs files, to a work item, so free_netdev() can free them first, here and in remove(). Add a release() that signals a per-pool completion, and wait for it in both places before free_netdev(). Without that config, release() runs from kobject_put() and the wait returns at once.

Found in review of the ibmveth multi-queue RX series and confirmed by code inspection; the release() part was raised by the Sashiko review of the first version. Tested on a POWER10 LPAR with register_netdev() forced to fail with -EINTR by a test-only module parameter (not part of this patch): no pool%d directories remain and the device binds again. No kernel selftests cover ibmveth.

Fixes 860f242eb534 ("[PATCH] ibmveth change buffer pools dynamically")
---
 drivers/net/ethernet/ibm/ibmveth.c | 52 +++++++++++++++++++++++++-----
 drivers/net/ethernet/ibm/ibmveth.h |  3 ++
 2 files changed, 47 insertions(+), 8 deletions(-)
drivers/net/ethernet/ibm/ibmveth.c +44 -8
index 919b5831d875c..42aa9f7bd49de 100644
@@ -1890,6 +1890,40 @@ static const struct net_device_ops ibmveth_netdev_ops = {
 	.ndo_features_check	= ibmveth_features_check,
 };
 
+/**
+ * ibmveth_pool_kobj_release - Mark a pool kobject finished
+ * @kobj: kobject embedded in the pool
+ *
+ * The pool kobjects live in netdev_priv(), so the last put must wait
+ * for this before free_netdev().
+ */
+static void ibmveth_pool_kobj_release(struct kobject *kobj)
+{
+	struct ibmveth_buff_pool *pool = container_of(kobj,
+						      struct ibmveth_buff_pool,
+						      kobj);
+
+	complete(&pool->released);
+}
+
+/**
+ * ibmveth_put_pool_kobjs - Drop the pool kobjects and wait for release
+ * @adapter: ibmveth adapter
+ *
+ * With CONFIG_DEBUG_KOBJECT_RELEASE the cleanup, including removing the
+ * sysfs files, runs later from a work item in the kobject; wait for it
+ * so free_netdev() cannot free the pools first.
+ */
+static void ibmveth_put_pool_kobjs(struct ibmveth_adapter *adapter)
+{
+	int i;
+
+	for (i = 0; i < IBMVETH_NUM_BUFF_POOLS; i++)
+		kobject_put(&adapter->rx_buff_pool[i].kobj);
+	for (i = 0; i < IBMVETH_NUM_BUFF_POOLS; i++)
+		wait_for_completion(&adapter->rx_buff_pool[i].released);
+}
+
 static int ibmveth_probe(struct vio_dev *dev, const struct vio_device_id *id)
 {
 	int rc, i, mac_len;
@@ -2000,6 +2034,7 @@ static int ibmveth_probe(struct vio_dev *dev, const struct vio_device_id *id)
 		ibmveth_init_buffer_pool(&adapter->rx_buff_pool[i], i,
 					 pool_count[i], pool_size[i],
 					 pool_active[i]);
+		init_completion(&adapter->rx_buff_pool[i].released);
 		error = kobject_init_and_add(kobj, &ktype_veth_pool,
 					     &dev->dev.kobj, "pool%d", i);
 		if (!error)
@@ -2011,8 +2046,7 @@ static int ibmveth_probe(struct vio_dev *dev, const struct vio_device_id *id)
 	if (rc) {
 		netdev_dbg(netdev, "failed to set number of tx queues rc=%d\n",
 			   rc);
-		free_netdev(netdev);
-		return rc;
+		goto err_put_pools;
 	}
 	adapter->tx_ltb_size = PAGE_ALIGN(IBMVETH_MAX_TX_BUF_SIZE);
 	for (i = 0; i < IBMVETH_MAX_QUEUES; i++)
@@ -2027,25 +2061,27 @@ static int ibmveth_probe(struct vio_dev *dev, const struct vio_device_id *id)
 
 	if (rc) {
 		netdev_dbg(netdev, "failed to register netdev rc=%d\n", rc);
-		free_netdev(netdev);
-		return rc;
+		goto err_put_pools;
 	}
 
 	netdev_dbg(netdev, "registered\n");
 
 	return 0;
+
+err_put_pools:
+	ibmveth_put_pool_kobjs(adapter);
+	free_netdev(netdev);
+	return rc;
 }
 
 static void ibmveth_remove(struct vio_dev *dev)
 {
 	struct net_device *netdev = dev_get_drvdata(&dev->dev);
 	struct ibmveth_adapter *adapter = netdev_priv(netdev);
-	int i;
 
 	disable_work_sync(&adapter->work);
 
-	for (i = 0; i < IBMVETH_NUM_BUFF_POOLS; i++)
-		kobject_put(&adapter->rx_buff_pool[i].kobj);
+	ibmveth_put_pool_kobjs(adapter);
 
 	unregister_netdev(netdev);
 
@@ -2221,7 +2257,7 @@ static const struct sysfs_ops veth_pool_ops = {
 };
 
 static struct kobj_type ktype_veth_pool = {
-	.release        = NULL,
+	.release        = ibmveth_pool_kobj_release,
 	.sysfs_ops      = &veth_pool_ops,
 	.default_groups = veth_pool_groups,
 };
drivers/net/ethernet/ibm/ibmveth.h +3 -0
index 3f2240823f6a3..be0939caa328e 100644
@@ -14,6 +14,8 @@
 #ifndef _IBMVETH_H
 #define _IBMVETH_H
 
+#include <linux/completion.h>
+
 /* constants for H_MULTICAST_CTRL */
 #define IbmVethMcastReceptionModifyBit     0x80000UL
 #define IbmVethMcastReceptionEnableBit     0x20000UL
@@ -143,6 +145,7 @@ struct ibmveth_buff_pool {
     struct sk_buff **skbuff;
     int active;
     struct kobject kobj;
+	struct completion released;
 };
 
 struct ibmveth_rx_q {
Signature · 1 line
2.53.0
author maintainer
#2295 lore raw

PATCH 2274/2651 ibmveth: return the error when set_channels cannot add TX queues

In reply to Greg Kroah-Hartman

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

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

From: Mingming Cao <[email protected]>

[ Upstream commit 16abfa871dc840e55f1726408c5994c66a9773e2 ]

When ibmveth_set_channels() cannot allocate a TX buffer for a new queue, it falls back to the old queue count, and the successful netif_set_real_num_tx_queues() call then overwrites rc. ethtool -L reports success while the queue count is unchanged.

Return the allocation error when the fallback succeeds.

Found in review of the ibmveth multi-queue RX series and confirmed by code inspection. Tested on a POWER10 LPAR with the TX buffer allocation forced to fail by a test-only module parameter (not part of this patch):
ethtool -L tx 8 now fails with -ENOMEM and the device keeps its four queues and passes traffic. No kernel selftests cover ibmveth.

Fixes 10c2aba89cc0 ("ibmveth: Ethtool set queue support")
---
 drivers/net/ethernet/ibm/ibmveth.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/net/ethernet/ibm/ibmveth.c +4 -1
index 42aa9f7bd49de..48bc4406396bd 100644
@@ -1177,7 +1177,7 @@ static int ibmveth_set_channels(struct net_device *netdev,
 	struct ibmveth_adapter *adapter = netdev_priv(netdev);
 	unsigned int old = netdev->real_num_tx_queues,
 		     goal = channels->tx_count;
-	int rc, i;
+	int rc, i, alloc_rc = 0;
 
 	/* If the device is not open (including a failed close/open with
 	 * IFF_UP still set) then don't allocate, just set desired
@@ -1203,6 +1203,7 @@ static int ibmveth_set_channels(struct net_device *netdev,
 		/* if something goes wrong, free everything we just allocated */
 		netdev_err(netdev, "Failed to allocate more tx queues, returning to %d queues\n",
 			   old);
+		alloc_rc = rc;
 		goal = old;
 		old = i;
 		break;
@@ -1213,6 +1214,8 @@ static int ibmveth_set_channels(struct net_device *netdev,
 			   old);
 		goal = old;
 		old = i;
+	} else if (alloc_rc) {
+		rc = alloc_rc;
 	}
 	/* Free any that are no longer needed */
 	for (i = old; i > goal; i--) {
Signature · 1 line
2.53.0
author maintainer
#2296 lore raw

PATCH 2275/2651 ibmveth: wait for in-flight transmits in ibmveth_close()

In reply to Greg Kroah-Hartman

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

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

From: Mingming Cao <[email protected]>

[ Upstream commit c807573ea58e615339a9c72675c45c157ffe245c ]

ibmveth_close() frees the TX buffers after netif_tx_stop_all_queues(), which does not wait for an ibmveth_start_xmit() already running on another CPU. That transmit can copy into a freed buffer and hand PHYP a stale DMA address.

MTU, csum/TSO and buffer pool changes call ibmveth_close() directly while traffic flows. ifdown and the reset work go through dev_close(), which waits for running transmits only when the qdisc has an enqueue function, so with noqueue they race the same way.

Use netif_tx_disable(), which waits for running transmits.

Found in review of the ibmveth multi-queue RX series and confirmed by code inspection; the race was not reproduced. Tested on a POWER10 LPAR with MTU changes during a ping flood, with no warnings. No kernel selftests cover ibmveth.

Fixes d6832ca48d8a ("ibmveth: Copy tx skbs into a premapped buffer")
---
 drivers/net/ethernet/ibm/ibmveth.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/ethernet/ibm/ibmveth.c +1 -1
index 48bc4406396bd..f2570d637301b 100644
@@ -835,7 +835,7 @@ static int ibmveth_close(struct net_device *netdev)
 
 	napi_disable(&adapter->napi);
 
-	netif_tx_stop_all_queues(netdev);
+	netif_tx_disable(netdev);
 
 	h_vio_signal(adapter->vdev->unit_address, VIO_IRQ_DISABLE);
 
Signature · 1 line
2.53.0
author maintainer
#2297 lore raw

PATCH 2276/2651 ibmveth: wait for the RX poll to return before freeing the RX queue

In reply to Greg Kroah-Hartman

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

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

From: Mingming Cao <[email protected]>

[ Upstream commit 3f872b34368c7c1d2a8900950e0fee4cb4dd9a34 ]

napi_disable() returns once ibmveth_poll() has called napi_complete_done(), but the poll is not finished: it then re-enables the interrupt and calls ibmveth_rxq_pending_buffer(), which reads the RX queue. ibmveth_close() can free that queue in the meantime, and the late enable can leave the interrupt unmasked after close() masked it. The request_irq() failure path in ibmveth_open() frees the same memory after napi_disable() too.

Call synchronize_net() after napi_disable() on both paths. Every caller of ibmveth_poll() runs it with bottom halves or interrupts disabled, so this waits for the poll to return.

Found in review of the ibmveth multi-queue RX series and confirmed by code inspection; also raised by the Sashiko review of the first version of this series. The race was not reproduced. Tested on a POWER10 LPAR under an incoming ping flood with 30 rapid link down/up cycles and 30 rapid MTU cycles (1500 <-> 9000); ran cleanly with no warnings or faults. No kernel selftests cover ibmveth.

Fixes bea3348eef27 ("[NET]: Make NAPI polling independent of struct net_device objects.")
---
 drivers/net/ethernet/ibm/ibmveth.c | 6 ++++++
 1 file changed, 6 insertions(+)
drivers/net/ethernet/ibm/ibmveth.c +6 -0
index f2570d637301b..85e176d0ed321 100644
@@ -768,6 +768,7 @@ static int ibmveth_open(struct net_device *netdev)
 			 netdev);
 	if (rc != 0) {
 		napi_disable(&adapter->napi);
+		synchronize_net();
 		netdev_err(netdev, "unable to request irq 0x%x, rc %d\n",
 			   netdev->irq, rc);
 		goto out_free_buffer_pools;
@@ -834,6 +835,11 @@ static int ibmveth_close(struct net_device *netdev)
 	netdev_dbg(netdev, "close starting\n");
 
 	napi_disable(&adapter->napi);
+	/* napi_disable() returns once ibmveth_poll() has called
+	 * napi_complete_done(), but the poll still re-enables the
+	 * interrupt and reads the RX queue after that.
+	 */
+	synchronize_net();
 
 	netif_tx_disable(netdev);
 
Signature · 1 line
2.53.0
author maintainer
#2298 lore raw

PATCH 2277/2651 ibmveth: check headers in the RX large send and checksum helpers

In reply to Greg Kroah-Hartman

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

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

From: Mingming Cao <[email protected]>

[ Upstream commit 9486c89a8e157cedecfb561c3d86053e654d32ab ]

ibmveth_rx_mss_helper() and ibmveth_rx_csum_helper() trust the IP and TCP headers of received frames, which come from another partition on the virtual LAN.

The worst case is an IPv4 frame with ihl 0 and iph->check 0xffff: the checksum helper calls ip_fast_csum(iph, 0), and the ppc64 version loops ihl - 1 times on an unsigned count, reading up to 16 GiB in
softirq: a long stall, or an oops once the read leaves mapped memory. Both helpers also read and write header fields past the end of a short frame. The large send helper takes the segment size from the TCP checksum field and gso_segs from a TCP header length it never checks, and treats an IPv4 TCP fragment as a large send, which can zero two of its bytes; the checksum helper can write a checksum into a later fragment's payload.

The ihl problem dates from the first commit in Fixes:, the large send helper from the second, and the checksum helper from the third.

Before using a header, check that it fits the frame, that the IPv4 ihl is at least 5, and that an IPv4 TCP frame is not a fragment. In the large send helper, also require a TCP doff of at least 5, TCP payload within the IP length, and an IP length equal to the frame length:
Ethernet padding or other bytes past the IP length would otherwise stay in a bridged or switched frame, which the stack does not trim, and be segmented but not counted in gso_segs. Compute gso_segs from the IP length, and keep the segment size at or above TCP_MIN_GSO_SIZE, as virtio_net_hdr_to_skb() does since commit c27c449d455a ("virtio-net:
Ensure that TCP packets don't overflow gso_segs"), and below GSO_BY_FRAGS, which virtio rejects. With the headers checked and gso_segs computed, the skb is not marked SKB_GSO_DODGY, which would also keep it from hardware TSO on the egress device.

A frame that fails a check is passed up unchanged, without the GSO fields or CHECKSUM_UNNECESSARY, so nothing downstream trusts its segment count or checksum. The skb is linear, so the checks use skb_headlen(); pskb_may_pull() could reallocate the head under the helpers' header pointers.

Add KUnit cases for both helpers: valid IPv4 and IPv6 large sends, the segment size clamp, and refused frames. With any one of the ihl, doff, IP length, TCP payload, fragment or clamp checks, or the checksum helper's IPv4 options, IPv6 header or TCP header length checks, removed, a case fails; without the checksum helper's ihl check, ip_fast_csum() oopses on qemu.

Found by the Sashiko review of the previous version of this series and confirmed by code inspection and the KUnit cases above. Tested with KUnit on qemu pseries (ppc64le) and on a POWER10 LPAR with iperf3 large sends over IPv4 and IPv6 at MTU 1500 and 9000, threaded NAPI and busy polling, with no new drops or InCsumErrors. No kernel selftests cover ibmveth.

Fixes 9c7e8bc584f5 ("ibmveth: Add support for Large Receive Offload")
Fixes 7b5967389f5a ("ibmveth: set correct gso_size and gso_type")
Fixes 66aa0678efc2 ("ibmveth: Support to enable LSO/CSO for Trunk VEA.")
---
 drivers/net/ethernet/ibm/ibmveth.c | 286 ++++++++++++++++++++++++++++-
 1 file changed, 277 insertions(+), 9 deletions(-)
drivers/net/ethernet/ibm/ibmveth.c +277 -9
index 85e176d0ed321..e9874dfedf378 100644
@@ -1396,8 +1396,12 @@ static netdev_tx_t ibmveth_start_xmit(struct sk_buff *skb,
 
 }
 
-static void ibmveth_rx_mss_helper(struct sk_buff *skb, u16 mss, int lrg_pkt)
+/* Returns false when the IP or TCP headers fail the checks; the frame is
+ * then left unchanged and not marked GSO.
+ */
+static bool ibmveth_rx_mss_helper(struct sk_buff *skb, u16 mss, int lrg_pkt)
 {
+	unsigned int gso_type, ip_len;
 	struct tcphdr *tcph;
 	int offset = 0;
 	int hdr_len;
@@ -1406,28 +1410,41 @@ static void ibmveth_rx_mss_helper(struct sk_buff *skb, u16 mss, int lrg_pkt)
 	if (skb->protocol == htons(ETH_P_IP)) {
 		struct iphdr *iph = (struct iphdr *)skb->data;
 
+		if (skb_headlen(skb) < sizeof(*iph) || iph->ihl < 5)
+			return false;
 		if (iph->protocol == IPPROTO_TCP) {
+			/* only a whole datagram has a TCP header to segment */
+			if (ip_is_fragment(iph))
+				return false;
 			offset = iph->ihl * 4;
-			skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4;
+			ip_len = ntohs(iph->tot_len);
+			gso_type = SKB_GSO_TCPV4;
 		} else {
-			return;
+			return true;
 		}
 	} else if (skb->protocol == htons(ETH_P_IPV6)) {
 		struct ipv6hdr *iph6 = (struct ipv6hdr *)skb->data;
 
+		if (skb_headlen(skb) < sizeof(*iph6))
+			return false;
 		if (iph6->nexthdr == IPPROTO_TCP) {
 			offset = sizeof(struct ipv6hdr);
-			skb_shinfo(skb)->gso_type = SKB_GSO_TCPV6;
+			ip_len = offset + ntohs(iph6->payload_len);
+			gso_type = SKB_GSO_TCPV6;
 		} else {
-			return;
+			return true;
 		}
 	} else {
-		return;
+		return true;
 	}
 	/* if mss is not set through Large Packet bit/mss in rx buffer,
 	 * expect that the mss will be written to the tcp header checksum.
 	 */
 	tcph = (struct tcphdr *)(skb->data + offset);
+	if (skb_headlen(skb) < offset + sizeof(*tcph) || tcph->doff < 5 ||
+	    ip_len != skb_headlen(skb) || ip_len <= offset + tcph->doff * 4)
+		return false;
+	skb_shinfo(skb)->gso_type = gso_type;
 	if (lrg_pkt) {
 		skb_shinfo(skb)->gso_size = mss;
 	} else if (offset) {
@@ -1436,11 +1453,18 @@ static void ibmveth_rx_mss_helper(struct sk_buff *skb, u16 mss, int lrg_pkt)
 	}
 
 	if (skb_shinfo(skb)->gso_size) {
+		/* chosen by the sending partition: at least the floor
+		 * virtio_net_hdr_to_skb() uses, and never GSO_BY_FRAGS
+		 */
+		skb_shinfo(skb)->gso_size =
+			clamp_t(u16, skb_shinfo(skb)->gso_size,
+				TCP_MIN_GSO_SIZE, GSO_BY_FRAGS - 1);
 		hdr_len = offset + tcph->doff * 4;
 		skb_shinfo(skb)->gso_segs =
-				DIV_ROUND_UP(skb->len - hdr_len,
+				DIV_ROUND_UP(ip_len - hdr_len,
 					     skb_shinfo(skb)->gso_size);
 	}
+	return true;
 }
 
 static void ibmveth_rx_csum_helper(struct sk_buff *skb,
@@ -1457,6 +1481,10 @@ static void ibmveth_rx_csum_helper(struct sk_buff *skb,
 
 	if (skb_proto == ETH_P_IP) {
 		iph = (struct iphdr *)skb->data;
+		if (skb_headlen(skb) < sizeof(*iph) || iph->ihl < 5 ||
+		    skb_headlen(skb) < iph->ihl * 4 ||
+		    (iph->protocol == IPPROTO_TCP && ip_is_fragment(iph)))
+			goto bad_hdr;
 
 		/* If the IP checksum is not offloaded and if the packet
 		 *  is large send, the checksum must be rebuilt.
@@ -1471,6 +1499,8 @@ static void ibmveth_rx_csum_helper(struct sk_buff *skb,
 		iph_proto = iph->protocol;
 	} else if (skb_proto == ETH_P_IPV6) {
 		iph6 = (struct ipv6hdr *)skb->data;
+		if (skb_headlen(skb) < sizeof(*iph6))
+			goto bad_hdr;
 		iphlen = sizeof(struct ipv6hdr);
 		iph_proto = iph6->nexthdr;
 	}
@@ -1493,6 +1523,8 @@ static void ibmveth_rx_csum_helper(struct sk_buff *skb,
 	if (iph_proto == IPPROTO_TCP) {
 		struct tcphdr *tcph = (struct tcphdr *)(skb->data + iphlen);
 
+		if (skb_headlen(skb) < iphlen + sizeof(*tcph))
+			goto bad_hdr;
 		if (tcph->check == 0x0000) {
 			/* Recompute TCP pseudo header checksum  */
 			tcphdrlen = skb->len - iphlen;
@@ -1510,6 +1542,13 @@ static void ibmveth_rx_csum_helper(struct sk_buff *skb,
 			skb_reset_network_header(skb);
 		}
 	}
+	return;
+
+bad_hdr:
+	/* headers do not fit the frame, or a fragment has no whole TCP
+	 * segment; let the stack check it
+	 */
+	skb->ip_summed = CHECKSUM_NONE;
 }
 
 static int ibmveth_poll(struct napi_struct *napi, int budget)
@@ -1624,7 +1663,8 @@ static int ibmveth_poll(struct napi_struct *napi, int budget)
 			/* PHYP without PLSO support places a -1 in the ip
 			 * checksum for large send frames.
 			 */
-			if (skb->protocol == cpu_to_be16(ETH_P_IP)) {
+			if (skb->protocol == cpu_to_be16(ETH_P_IP) &&
+			    skb_headlen(skb) >= sizeof(struct iphdr)) {
 				struct iphdr *iph = (struct iphdr *)skb->data;
 
 				iph_check = iph->check;
@@ -1632,7 +1672,8 @@ static int ibmveth_poll(struct napi_struct *napi, int budget)
 
 			if ((length > netdev->mtu + ETH_HLEN) ||
 			    lrg_pkt || iph_check == 0xffff) {
-				ibmveth_rx_mss_helper(skb, mss, lrg_pkt);
+				if (!ibmveth_rx_mss_helper(skb, mss, lrg_pkt))
+					csum_good = 0;
 				adapter->rx_large_packets++;
 			}
 
@@ -2508,10 +2549,237 @@ static void ibmveth_rxq_harvest_buffer_test(struct kunit *test)
 	flush_work(&adapter->work);
 }
 
+KUNIT_DEFINE_ACTION_WRAPPER(ibmveth_kfree_skb, kfree_skb, struct sk_buff *);
+
+/* A TCP frame after eth_type_trans(): IP header, 20 byte TCP header and
+ * payload bytes of data, with the IP length matching the frame.
+ */
+static struct sk_buff *ibmveth_test_tcp_skb(struct kunit *test, bool ipv6,
+					    unsigned int payload)
+{
+	unsigned int iplen = ipv6 ? sizeof(struct ipv6hdr) :
+				    sizeof(struct iphdr);
+	unsigned int len = iplen + sizeof(struct tcphdr) + payload;
+	struct sk_buff *skb = alloc_skb(len, GFP_KERNEL);
+	struct tcphdr *tcph;
+
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, skb);
+	KUNIT_ASSERT_EQ(test, 0, kunit_add_action_or_reset(test,
+							   ibmveth_kfree_skb,
+							   skb));
+	skb_put_zero(skb, len);
+	if (ipv6) {
+		struct ipv6hdr *iph6 = (struct ipv6hdr *)skb->data;
+
+		skb->protocol = htons(ETH_P_IPV6);
+		iph6->version = 6;
+		iph6->nexthdr = IPPROTO_TCP;
+		iph6->payload_len = htons(len - iplen);
+	} else {
+		struct iphdr *iph = (struct iphdr *)skb->data;
+
+		skb->protocol = htons(ETH_P_IP);
+		iph->version = 4;
+		iph->ihl = 5;
+		iph->protocol = IPPROTO_TCP;
+		iph->tot_len = htons(len);
+	}
+	tcph = (struct tcphdr *)(skb->data + iplen);
+	tcph->doff = 5;
+	return skb;
+}
+
+/**
+ * ibmveth_rx_mss_helper_test - unit test for ibmveth_rx_mss_helper
+ * @test: pointer to kunit structure
+ *
+ * Large send frames get gso_size from the descriptor or the TCP checksum
+ * field, clamped, and gso_segs from the IP length. Frames whose headers
+ * do not fit, whose IP length is not the frame length, with no TCP
+ * payload within the IP length, or that are IPv4 fragments, are refused
+ * and left without GSO.
+ *
+ * Return: void
+ */
+static void ibmveth_rx_mss_helper_test(struct kunit *test)
+{
+	struct sk_buff *skb;
+	struct tcphdr *tcph;
+	struct iphdr *iph;
+
+	skb = ibmveth_test_tcp_skb(test, false, 2896);
+	tcph = (struct tcphdr *)(skb->data + sizeof(*iph));
+	tcph->check = (__force __sum16)htons(1448);
+	KUNIT_EXPECT_TRUE(test, ibmveth_rx_mss_helper(skb, 0, 0));
+	KUNIT_EXPECT_EQ(test, SKB_GSO_TCPV4, skb_shinfo(skb)->gso_type);
+	KUNIT_EXPECT_EQ(test, 1448, skb_shinfo(skb)->gso_size);
+	KUNIT_EXPECT_EQ(test, 2, skb_shinfo(skb)->gso_segs);
+	KUNIT_EXPECT_EQ(test, 0, (__force u16)tcph->check);
+
+	skb = ibmveth_test_tcp_skb(test, false, 2896);
+	KUNIT_EXPECT_TRUE(test, ibmveth_rx_mss_helper(skb, 1000, 1));
+	KUNIT_EXPECT_EQ(test, 1000, skb_shinfo(skb)->gso_size);
+	KUNIT_EXPECT_EQ(test, 3, skb_shinfo(skb)->gso_segs);
+
+	skb = ibmveth_test_tcp_skb(test, true, 2896);
+	tcph = (struct tcphdr *)(skb->data + sizeof(struct ipv6hdr));
+	tcph->check = (__force __sum16)htons(1448);
+	KUNIT_EXPECT_TRUE(test, ibmveth_rx_mss_helper(skb, 0, 0));
+	KUNIT_EXPECT_EQ(test, SKB_GSO_TCPV6, skb_shinfo(skb)->gso_type);
+	KUNIT_EXPECT_EQ(test, 1448, skb_shinfo(skb)->gso_size);
+	KUNIT_EXPECT_EQ(test, 2, skb_shinfo(skb)->gso_segs);
+
+	skb = ibmveth_test_tcp_skb(test, false, 2896);
+	KUNIT_EXPECT_TRUE(test, ibmveth_rx_mss_helper(skb, 1, 1));
+	KUNIT_EXPECT_EQ(test, TCP_MIN_GSO_SIZE, skb_shinfo(skb)->gso_size);
+
+	skb = ibmveth_test_tcp_skb(test, false, 2896);
+	KUNIT_EXPECT_TRUE(test, ibmveth_rx_mss_helper(skb, GSO_BY_FRAGS, 1));
+	KUNIT_EXPECT_EQ(test, GSO_BY_FRAGS - 1, skb_shinfo(skb)->gso_size);
+
+	/* refused: ihl 0, doff 4, IP length past the frame. With ihl 0 the
+	 * TCP header would overlap the IP header; saddr makes its doff 5.
+	 */
+	skb = ibmveth_test_tcp_skb(test, false, 2896);
+	((struct iphdr *)skb->data)->ihl = 0;
+	((struct iphdr *)skb->data)->saddr = htonl(0x50000000);
+	KUNIT_EXPECT_FALSE(test, ibmveth_rx_mss_helper(skb, 1448, 1));
+	KUNIT_EXPECT_EQ(test, 0, skb_shinfo(skb)->gso_size);
+
+	skb = ibmveth_test_tcp_skb(test, false, 2896);
+	((struct tcphdr *)(skb->data + sizeof(*iph)))->doff = 4;
+	KUNIT_EXPECT_FALSE(test, ibmveth_rx_mss_helper(skb, 1448, 1));
+
+	skb = ibmveth_test_tcp_skb(test, false, 2896);
+	((struct iphdr *)skb->data)->tot_len = htons(skb->len + 1);
+	KUNIT_EXPECT_FALSE(test, ibmveth_rx_mss_helper(skb, 1448, 1));
+
+	/* refused: bytes past the IP length, its large send fields left
+	 * alone; gso_segs from the IP length would undercount them
+	 */
+	skb = ibmveth_test_tcp_skb(test, false, 2896);
+	((struct iphdr *)skb->data)->tot_len = htons(skb->len - 100);
+	tcph = (struct tcphdr *)(skb->data + sizeof(*iph));
+	tcph->check = (__force __sum16)htons(1448);
+	KUNIT_EXPECT_FALSE(test, ibmveth_rx_mss_helper(skb, 0, 0));
+	KUNIT_EXPECT_EQ(test, 0, skb_shinfo(skb)->gso_size);
+	KUNIT_EXPECT_EQ(test, 1448, ntohs((__force __be16)tcph->check));
+
+	/* refused: a fragment past the first, its payload left alone */
+	skb = ibmveth_test_tcp_skb(test, false, 2896);
+	((struct iphdr *)skb->data)->frag_off = htons(185);
+	tcph = (struct tcphdr *)(skb->data + sizeof(*iph));
+	tcph->check = (__force __sum16)htons(1448);
+	KUNIT_EXPECT_FALSE(test, ibmveth_rx_mss_helper(skb, 0, 0));
+	KUNIT_EXPECT_EQ(test, 0, skb_shinfo(skb)->gso_size);
+	KUNIT_EXPECT_EQ(test, 1448, ntohs((__force __be16)tcph->check));
+
+	/* refused: only Ethernet padding past the TCP header */
+	skb = ibmveth_test_tcp_skb(test, false, 6);
+	((struct iphdr *)skb->data)->tot_len = htons(40);
+	KUNIT_EXPECT_FALSE(test, ibmveth_rx_mss_helper(skb, 1448, 1));
+	KUNIT_EXPECT_EQ(test, 0, skb_shinfo(skb)->gso_size);
+
+	skb = ibmveth_test_tcp_skb(test, true, 2896);
+	((struct ipv6hdr *)skb->data)->payload_len = 0;
+	KUNIT_EXPECT_FALSE(test, ibmveth_rx_mss_helper(skb, 1448, 1));
+
+	/* refused: no TCP payload, with the IP length matching the frame */
+	skb = ibmveth_test_tcp_skb(test, false, 0);
+	KUNIT_EXPECT_FALSE(test, ibmveth_rx_mss_helper(skb, 1448, 1));
+	KUNIT_EXPECT_EQ(test, 0, skb_shinfo(skb)->gso_size);
+
+	skb = ibmveth_test_tcp_skb(test, true, 0);
+	KUNIT_EXPECT_FALSE(test, ibmveth_rx_mss_helper(skb, 1448, 1));
+	KUNIT_EXPECT_EQ(test, 0, skb_shinfo(skb)->gso_size);
+
+	/* not TCP: accepted and left alone */
+	skb = ibmveth_test_tcp_skb(test, false, 2896);
+	((struct iphdr *)skb->data)->protocol = IPPROTO_UDP;
+	KUNIT_EXPECT_TRUE(test, ibmveth_rx_mss_helper(skb, 1448, 1));
+	KUNIT_EXPECT_EQ(test, 0, skb_shinfo(skb)->gso_size);
+}
+
+/**
+ * ibmveth_rx_csum_helper_test - unit test for ibmveth_rx_csum_helper
+ * @test: pointer to kunit structure
+ *
+ * A large send IPv4 header checksum of 0xffff is rebuilt. Headers that
+ * do not fit the frame, an IPv4 ihl below 5, or a TCP fragment, clear
+ * CHECKSUM_UNNECESSARY instead of being read.
+ *
+ * Return: void
+ */
+static void ibmveth_rx_csum_helper_test(struct kunit *test)
+{
+	struct sk_buff *skb;
+	struct tcphdr *tcph;
+	struct iphdr *iph;
+
+	skb = ibmveth_test_tcp_skb(test, false, 100);
+	iph = (struct iphdr *)skb->data;
+	iph->check = (__force __sum16)0xffff;
+	tcph = (struct tcphdr *)(skb->data + sizeof(*iph));
+	tcph->check = (__force __sum16)htons(1);
+	skb->ip_summed = CHECKSUM_UNNECESSARY;
+	ibmveth_rx_csum_helper(skb, NULL);
+	KUNIT_EXPECT_EQ(test, 0, (__force u16)ip_fast_csum(iph, iph->ihl));
+	KUNIT_EXPECT_EQ(test, CHECKSUM_UNNECESSARY, (int)skb->ip_summed);
+
+	skb = ibmveth_test_tcp_skb(test, false, 100);
+	iph = (struct iphdr *)skb->data;
+	iph->ihl = 0;
+	iph->check = (__force __sum16)0xffff;
+	skb->ip_summed = CHECKSUM_UNNECESSARY;
+	ibmveth_rx_csum_helper(skb, NULL);
+	KUNIT_EXPECT_EQ(test, CHECKSUM_NONE, (int)skb->ip_summed);
+	KUNIT_EXPECT_EQ(test, 0xffff, (__force u16)iph->check);
+
+	/* IPv4 options past the frame; UDP, so no TCP check follows */
+	skb = ibmveth_test_tcp_skb(test, false, 0);
+	iph = (struct iphdr *)skb->data;
+	iph->protocol = IPPROTO_UDP;
+	iph->ihl = 15;
+	iph->check = (__force __sum16)0xffff;
+	skb->ip_summed = CHECKSUM_UNNECESSARY;
+	ibmveth_rx_csum_helper(skb, NULL);
+	KUNIT_EXPECT_EQ(test, CHECKSUM_NONE, (int)skb->ip_summed);
+
+	/* a TCP fragment past the first: header and payload left alone */
+	skb = ibmveth_test_tcp_skb(test, false, 100);
+	iph = (struct iphdr *)skb->data;
+	iph->frag_off = htons(185);
+	iph->check = (__force __sum16)0xffff;
+	skb->ip_summed = CHECKSUM_UNNECESSARY;
+	ibmveth_rx_csum_helper(skb, NULL);
+	KUNIT_EXPECT_EQ(test, CHECKSUM_NONE, (int)skb->ip_summed);
+	KUNIT_EXPECT_EQ(test, 0xffff, (__force u16)iph->check);
+	KUNIT_EXPECT_EQ(test, 0,
+			(__force u16)((struct tcphdr *)(skb->data +
+							sizeof(*iph)))->check);
+
+	/* TCP header past the frame */
+	skb = ibmveth_test_tcp_skb(test, false, 0);
+	skb_trim(skb, sizeof(struct iphdr));
+	skb->ip_summed = CHECKSUM_UNNECESSARY;
+	ibmveth_rx_csum_helper(skb, NULL);
+	KUNIT_EXPECT_EQ(test, CHECKSUM_NONE, (int)skb->ip_summed);
+
+	/* IPv6 header past the frame; UDP, so no TCP check follows */
+	skb = ibmveth_test_tcp_skb(test, true, 0);
+	((struct ipv6hdr *)skb->data)->nexthdr = IPPROTO_UDP;
+	skb_trim(skb, sizeof(struct ipv6hdr) - 1);
+	skb->ip_summed = CHECKSUM_UNNECESSARY;
+	ibmveth_rx_csum_helper(skb, NULL);
+	KUNIT_EXPECT_EQ(test, CHECKSUM_NONE, (int)skb->ip_summed);
+}
+
 static struct kunit_case ibmveth_test_cases[] = {
 	KUNIT_CASE(ibmveth_remove_buffer_from_pool_test),
 	KUNIT_CASE(ibmveth_rxq_get_buffer_test),
 	KUNIT_CASE(ibmveth_rxq_harvest_buffer_test),
+	KUNIT_CASE(ibmveth_rx_mss_helper_test),
+	KUNIT_CASE(ibmveth_rx_csum_helper_test),
 	{}
 };
 
Signature · 1 line
2.53.0
author maintainer
#2299 lore raw

PATCH 2278/2651 exfat: fix used_clusters accounting during cluster allocation

In reply to Greg Kroah-Hartman

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

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

From: Chi Zhiling <[email protected]>

[ Upstream commit cb9dbf8a4e34b4fdf311598835ab4d76ed7e07c1 ]

In the current exfat_alloc_cluster(), p_chain->size is incremented as each cluster is allocated so that the partially allocated chain can be freed by __exfat_free_cluster() on the error path.

However, sbi->used_clusters is still updated only after all clusters have been allocated, while __exfat_free_cluster() unconditionally subtracts the number of freed clusters from sbi->used_clusters. Therefore, when allocation fails partway through, the partially allocated clusters are subtracted from sbi->used_clusters even though they were never added to it. This corrupts the free-space accounting and can cause sbi->used_clusters to underflow.

Increment sbi->used_clusters together with p_chain->size as each cluster is allocated. This keeps the accounting consistent with __exfat_free_cluster() on both the success and error paths.

This issue is caught by generic/476 with 256k cluster size:

Ran: generic/476
Failures: generic/476
Failed 1 of 1 tests

*** fsck.exfat output ***
ERROR: <path>: more clusters are allocated. truncate to N bytes
...
/dev/vdc: corrupted. directories 331, files 526 /dev/vdc: files corrupted 9, files fixed 0
*** end fsck.exfat output ***

Fixes d5c514b6a0c0 ("exfat: fix the newly allocated clusters are not freed in error handling")
---
 fs/exfat/fatent.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/exfat/fatent.c +1 -1
index a8b11e2ce43f1..a6728c3612899 100644
@@ -509,13 +509,13 @@ int exfat_alloc_cluster(struct inode *inode, unsigned int num_alloc,
 			}
 		}
 		p_chain->size++;
+		sbi->used_clusters++;
 
 		last_clu = new_clu;
 
 		if (p_chain->size == num_alloc) {
 done:
 			sbi->clu_srch_ptr = hint_clu;
-			sbi->used_clusters += p_chain->size;
 			mutex_unlock(&sbi->bitmap_lock);
 			return 0;
 		}
Signature · 1 line
2.53.0
author maintainer
#2300 lore raw

PATCH 2279/2651 exfat: take bitmap_lock at the start of exfat_alloc_cluster()

In reply to Greg Kroah-Hartman

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

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

From: Chi Zhiling <[email protected]>

[ Upstream commit 48acff2eedef7fecdfbd39be1b6f4463a9e43e3e ]

exfat_alloc_cluster() checks sbi->used_clusters against the total number of data clusters before acquiring sbi->bitmap_lock. A concurrent allocation can update sbi->used_clusters after the check but before the lock is acquired, making the check stale. This can allow the allocation to proceed even though there are not enough free clusters, causing it to fail partway through.

Acquire sbi->bitmap_lock before checking sbi->used_clusters so that the free-space check and subsequent cluster allocation are serialized with concurrent allocations.

Fixes f55c096f62f1 ("exfat: do not zero the extended part")
---
 fs/exfat/fatent.c | 17 ++++++++++-------
 1 file changed, 10 insertions(+), 7 deletions(-)
fs/exfat/fatent.c +10 -7
index a6728c3612899..3c8bdc131f6f3 100644
@@ -427,19 +427,22 @@ int exfat_alloc_cluster(struct inode *inode, unsigned int num_alloc,
 	struct super_block *sb = inode->i_sb;
 	struct exfat_sb_info *sbi = EXFAT_SB(sb);
 
+	mutex_lock(&sbi->bitmap_lock);
+
 	total_cnt = EXFAT_DATA_CLUSTER_COUNT(sbi);
 
 	if (unlikely(total_cnt < sbi->used_clusters)) {
 		exfat_fs_error_ratelimit(sb,
 			"%s: invalid used clusters(t:%u,u:%u)\n",
 			__func__, total_cnt, sbi->used_clusters);
-		return -EIO;
+		ret = -EIO;
+		goto unlock;
 	}
 
-	if (num_alloc > total_cnt - sbi->used_clusters)
-		return -ENOSPC;
-
-	mutex_lock(&sbi->bitmap_lock);
+	if (num_alloc > total_cnt - sbi->used_clusters) {
+		ret = -ENOSPC;
+		goto unlock;
+	}
 
 	hint_clu = p_chain->dir;
 	/* find new cluster */
@@ -516,8 +519,8 @@ int exfat_alloc_cluster(struct inode *inode, unsigned int num_alloc,
 		if (p_chain->size == num_alloc) {
 done:
 			sbi->clu_srch_ptr = hint_clu;
-			mutex_unlock(&sbi->bitmap_lock);
-			return 0;
+			ret = 0;
+			goto unlock;
 		}
 
 		hint_clu = new_clu + 1;
Signature · 1 line
2.53.0
author maintainer
#2301 lore raw

PATCH 2280/2651 exfat: clean stale bdev buffers of newly allocated clusters

In reply to Greg Kroah-Hartman

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

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

From: Nicolas Falesy <[email protected]>

[ Upstream commit 0550ac7f5f577e34e5fcf2bd7a51965f5c1b0194 ]

Directory entries are read and written through buffer_heads of the block device. Removing the entries of a directory dirties such a buffer. If the directory is then removed and its cluster is reused for file data before writeback, the stale buffer stays dirty in the block device mapping, and the next flush of the block device (fsync, syncfs or umount) writes it over the new file data. The file silently reads back with one sector replaced by the deleted directory entries.

This was harmless while file data went through exfat_get_block(), as __block_write_begin_int() and do_direct_IO() call clean_bdev_aliases() for newly allocated blocks. Since data I/O moved to iomap, nothing drops these buffers any more.

Clean the aliases in exfat_alloc_cluster(), once per contiguous run of allocated clusters. Doing it at allocation time covers every path that allocates clusters: buffered and direct writes, and also fallocate() and an extending truncate(), which allocate clusters before the data is written, so the later iomap mapping does not see them as new.

Tested on the exfat dev branch in a KVM guest with a reproducer that removes the entries of a directory, removes the directory and writes a file over its freed cluster: buffered with and without fsync, O_DIRECT, after fallocate(), after an extending ftruncate(), and with the freed cluster in the middle of a fragmented allocation. Without this patch every run corrupted the file (55/55); with it, none did (0/55). A churn test that creates, removes, preallocates and truncates directories and files, then runs fsck.exfat, is clean with and without the patch.

Fixes 82a81a7352bc ("exfat: add iomap buffered I/O support")
Fixes 867b9c96dc83 ("exfat: add iomap direct I/O support")
Assisted-by Claude-Opus-5.5
---
 fs/exfat/fatent.c | 27 +++++++++++++++++++++++++++
 1 file changed, 27 insertions(+)
fs/exfat/fatent.c +27 -0
index 3c8bdc131f6f3..9f4607fced7ff 100644
@@ -418,12 +418,28 @@ int exfat_zeroed_cluster(struct inode *dir, unsigned int clu)
 	return 0;
 }
 
+/*
+ * Newly allocated clusters may still have dirty buffer_heads in the block
+ * device mapping, e.g. the dentries of a directory that was just removed.
+ * File data does not go through those buffers, so drop them; otherwise a
+ * later flush of the block device writes them over the new data.
+ */
+static void exfat_clean_bdev_aliases(struct super_block *sb,
+				     unsigned int clu, unsigned int count)
+{
+	struct exfat_sb_info *sbi = EXFAT_SB(sb);
+
+	clean_bdev_aliases(sb->s_bdev, exfat_cluster_to_sector(sbi, clu),
+			   (sector_t)count << sbi->sect_per_clus_bits);
+}
+
 int exfat_alloc_cluster(struct inode *inode, unsigned int num_alloc,
 		struct exfat_chain *p_chain, bool sync_bmap, bool contig)
 {
 	int ret = -ENOSPC;
 	unsigned int total_cnt;
 	unsigned int hint_clu, new_clu, last_clu = EXFAT_EOF_CLUSTER;
+	unsigned int run_clu = EXFAT_EOF_CLUSTER, run_len = 0;
 	struct super_block *sb = inode->i_sb;
 	struct exfat_sb_info *sbi = EXFAT_SB(sb);
 
@@ -514,10 +530,21 @@ int exfat_alloc_cluster(struct inode *inode, unsigned int num_alloc,
 		p_chain->size++;
 		sbi->used_clusters++;
 
+		/* clean stale buffers once per contiguous run of clusters */
+		if (run_len && new_clu == run_clu + run_len) {
+			run_len++;
+		} else {
+			if (run_len)
+				exfat_clean_bdev_aliases(sb, run_clu, run_len);
+			run_clu = new_clu;
+			run_len = 1;
+		}
+
 		last_clu = new_clu;
 
 		if (p_chain->size == num_alloc) {
 done:
+			exfat_clean_bdev_aliases(sb, run_clu, run_len);
 			sbi->clu_srch_ptr = hint_clu;
 			ret = 0;
 			goto unlock;
Signature · 1 line
2.53.0
author maintainer
#2302 lore raw

PATCH 2281/2651 rust: workqueue: replace deprecated system_wq with system_{percpu,dfl}_wq

In reply to Greg Kroah-Hartman

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

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

From: Danilo Krummrich <[email protected]>

[ Upstream commit 10ff62c6bb0baf9c2f77f92d2bcdaf6566c31191 ]

system_wq is deprecated and triggers a runtime warning:

	[    0.857414] workqueue: work func ...WorkItemPointerKy0_E3runB7_ enqueued on deprecated workqueue. Use system_{percpu|dfl}_wq instead.

Replace system() with system_percpu() and system_dfl(), to match the previous behavior of the deprecated system() and convert doc examples and tests to system_dfl().

system_unbound_wq is deprecated in the same way, in favor of system_dfl_wq. Since system_unbound() has no users, just remove it as well.

---
 Documentation/rust/testing.rst                |  2 +-
 .../translations/zh_CN/rust/testing.rst       |  2 +-
 drivers/android/binder/process.rs             |  4 +-
 rust/kernel/sync/completion.rs                |  2 +-
 rust/kernel/sync/lock/spinlock.rs             |  2 +-
 rust/kernel/workqueue.rs                      | 52 ++++++++++---------
 6 files changed, 33 insertions(+), 31 deletions(-)
Documentation/rust/testing.rst +1 -1
index e3943aceceb94..73046523a9a27 100644
@@ -97,7 +97,7 @@ operator are also supported as usual, e.g.:
 
 	/// ```
 	/// # use kernel::{spawn_work_item, workqueue};
-	/// spawn_work_item!(workqueue::system(), || pr_info!("x\n"))?;
+	/// spawn_work_item!(workqueue::system_dfl(), || pr_info!("x\n"))?;
 	/// # Ok::<(), Error>(())
 	/// ```
 
Documentation/translations/zh_CN/rust/testing.rst +1 -1
index 6747d00129915..fdd88fa2fe40a 100644
@@ -93,7 +93,7 @@ KUnit 测试即文档测试
 
 	/// ```
 	/// # use kernel::{spawn_work_item, workqueue};
-	/// spawn_work_item!(workqueue::system(), || pr_info!("x\n"))?;
+	/// spawn_work_item!(workqueue::system_dfl(), || pr_info!("x\n"))?;
 	/// # Ok::<(), Error>(())
 	/// ```
 
drivers/android/binder/process.rs +2 -2
index 5372bfbd93b35..de5bca7f9fc74 100644
@@ -1728,7 +1728,7 @@ pub(crate) fn release(this: Arc<Process>, _file: &File) {
         if should_schedule {
             // Ignore failures to schedule to the workqueue. Those just mean that we're already
             // scheduled for execution.
-            let _ = workqueue::system().enqueue(this);
+            let _ = workqueue::system_percpu().enqueue(this);
         }
 
         drop(binderfs_file);
@@ -1745,7 +1745,7 @@ pub(crate) fn flush(this: ArcBorrow<'_, Process>) -> Result {
         if should_schedule {
             // Ignore failures to schedule to the workqueue. Those just mean that we're already
             // scheduled for execution.
-            let _ = workqueue::system().enqueue(Arc::from(this));
+            let _ = workqueue::system_percpu().enqueue(Arc::from(this));
         }
         Ok(())
     }
rust/kernel/sync/completion.rs +1 -1
index 35ff049ff0783..1771bfc0ade28 100644
@@ -38,7 +38,7 @@
 ///             done <- Completion::new(),
 ///         }), GFP_KERNEL)?;
 ///
-///         let _ = workqueue::system().enqueue(this.clone());
+///         let _ = workqueue::system_dfl().enqueue(this.clone());
 ///
 ///         Ok(this)
 ///     }
rust/kernel/sync/lock/spinlock.rs +1 -1
index aafc80125f591..92ad133262b62 100644
@@ -450,7 +450,7 @@ fn run(this: Arc<Self>) {
     fn spinlock_irq_condvar() -> Result {
         let testdata = Test::new()?;
 
-        let _ = workqueue::system().enqueue(testdata.clone());
+        let _ = workqueue::system_dfl().enqueue(testdata.clone());
 
         // Let the updater know when we're ready to wait
         let mut state = testdata.state.lock();
rust/kernel/workqueue.rs +27 -25

118 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#2303 lore raw

PATCH 2282/2651 ksmbd: fix iface_list use-after-free during server reset

In reply to Greg Kroah-Hartman

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

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

From: Henry Hu <[email protected]>

[ Upstream commit d34d38ab0c62fe4eb9e746420c554e6d0e6f54db ]

ksmbd_find_netdev_name_iface_list() walks iface_list for fsctl_query_iface_info_ioctl(), which holds RTNL. But during server reset, ksmbd_tcp_destroy() unlinks and frees the entries without RTNL, and queued SMB requests can still be running at that point. So an FSCTL_QUERY_NETWORK_INTERFACE_INFO request can therefore race with interface destruction and dereference a freed entry. With debug-only instrumentation to make the race deterministic, KASAN reports:

   BUG: KASAN: slab-use-after-free in
   ksmbd_find_netdev_name_iface_list

ksmbd_find_netdev_name_iface_list
fsctl_query_iface_info_ioctl
smb2_ioctl
handle_ksmbd_work

Freed by:
kfree
ksmbd_tcp_destroy
ksmbd_conn_transport_destroy
kill_server_store

The fix is to detach iface_list to a temporary list under RTNL, then drop RTNL before cleanup because the following cleanup may block and hold RTNL for a long time.

Fixes b2d99376c5d6 ("ksmbd: browse interfaces list on FSCTL_QUERY_INTERFACE_INFO IOCTL")
Assisted-by LLM
---
 fs/smb/server/transport_tcp.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
fs/smb/server/transport_tcp.c +6 -1
index af3b6a01862ba..7492aa08f9f31 100644
@@ -945,10 +945,15 @@ static void ksmbd_tcp_stop_listener(struct interface *iface)
 void ksmbd_tcp_destroy(void)
 {
 	struct interface *iface, *tmp;
+	LIST_HEAD(iface_list_to_free);
 
 	unregister_netdevice_notifier(&ksmbd_netdev_notifier);
 
-	list_for_each_entry_safe(iface, tmp, &iface_list, entry) {
+	rtnl_lock();
+	list_splice_init(&iface_list, &iface_list_to_free);
+	rtnl_unlock();
+
+	list_for_each_entry_safe(iface, tmp, &iface_list_to_free, entry) {
 		ksmbd_tcp_stop_listener(iface);
 		list_del(&iface->entry);
 		kfree(iface->name);
Signature · 1 line
2.53.0
author maintainer
#2304 lore raw

PATCH 2283/2651 ksmbd: fix link speed query in fsctl_query_iface_info_ioctl()

In reply to Greg Kroah-Hartman

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

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

From: Henry Hu <[email protected]>

[ Upstream commit 2bc1d25fc8597fa6cbf6b1ff92653881939a6436 ]

fsctl_query_iface_info_ioctl() used to call netdev->ethtool_ops->get_link_ksettings() directly and never checked the return value. If the callback fails, cmd.base.speed may be left uninitialized. Also, SPEED_UNKNOWN (-1) is treated as a numeric link speed and would be converted into a bogus link speed.

Use __ethtool_get_link_ksettings() to acquire the per-netdev ops lock when needed. Fall back to 1Gbps when the query fails, or when the reported speed is 0 or SPEED_UNKNOWN.

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
---
 fs/smb/server/smb2pdu.c | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)
fs/smb/server/smb2pdu.c +3 -4
index 1c8037c85de95..26dc8933e2a0f 100644
@@ -10683,6 +10683,7 @@ static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
 	struct sockaddr_storage_rsp *sockaddr_storage;
 	unsigned int flags;
 	unsigned long long speed;
+	struct ethtool_link_ksettings cmd;
 
 	rtnl_lock();
 	for_each_netdev(&init_net, netdev) {
@@ -10717,10 +10718,8 @@ static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
 		nii_rsp->Next = cpu_to_le32(152);
 		nii_rsp->Reserved = 0;
 
-		if (netdev->ethtool_ops->get_link_ksettings) {
-			struct ethtool_link_ksettings cmd;
-
-			netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
+		if (!__ethtool_get_link_ksettings(netdev, &cmd) &&
+		    cmd.base.speed && cmd.base.speed != SPEED_UNKNOWN) {
 			speed = cmd.base.speed;
 		} else {
 			ksmbd_debug(SMB, "%s %s\n", netdev->name,
Signature · 1 line
2.53.0
author maintainer
#2305 lore raw

PATCH 2284/2651 ksmbd: fix unlocked IPv6 addr_list walk in fsctl_query_iface_info_ioctl()

In reply to Greg Kroah-Hartman

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

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

From: Henry Hu <[email protected]>

[ Upstream commit a63bb4d91c784f63ad7c063717dff7920d8445be ]

fsctl_query_iface_info_ioctl() walks idev6->addr_list with a plain list_for_each_entry() while holding only rtnl_lock(). rtnl does not serialize all writers of this list: the DAD-failure path (addrconf_dad_failure -> ipv6_add_addr) can insert addresses without holding RTNL. It updates idev->addr_list with list_add_tail_rcu() under write_lock_bh(&idev->lock), so it can race with the unlocked walk.

addr_list is RCU managed, so walk it with list_for_each_entry_rcu() under rcu_read_lock(), matching the other lockless readers of the list.

---
 fs/smb/server/smb2pdu.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
fs/smb/server/smb2pdu.c +3 -1
index 26dc8933e2a0f..efc3723389c5a 100644
@@ -10761,13 +10761,15 @@ static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
 			if (!idev6)
 				continue;
 
-			list_for_each_entry(ifa, &idev6->addr_list, if_list) {
+			rcu_read_lock();
+			list_for_each_entry_rcu(ifa, &idev6->addr_list, if_list) {
 				if (ifa->flags & (IFA_F_TENTATIVE |
 							IFA_F_DEPRECATED))
 					continue;
 				memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
 				break;
 			}
+			rcu_read_unlock();
 			sockaddr_storage->addr6.ScopeId = 0;
 			nbytes += sizeof(struct network_interface_info_ioctl_rsp);
 		}
Signature · 1 line
2.53.0
author maintainer
#2306 lore raw

PATCH 2285/2651 ksmbd: fix invalid Next offset in interface info replies

In reply to Greg Kroah-Hartman

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

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

From: Henry Hu <[email protected]>

[ Upstream commit 2c50a4a5e75db55880eca43c035649cb51fcb52a ]

fsctl_query_iface_info_ioctl() assigns nii_rsp to the next output slot before checking whether the interface has an in_device or inet6_dev. If either lookup returns NULL, the loop continues without advancing nbytes, leaving nii_rsp pointing at an uncommitted slot. If no later entry is committed, clearing nii_rsp->Next updates that slot instead of the last returned entry, leaving the latter with a nonzero Next offset.

Fix this by using nbytes to locate the last committed entry and clear its Next field, but only when the response contains at least one entry.

---
 fs/smb/server/smb2pdu.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
fs/smb/server/smb2pdu.c +8 -2
index efc3723389c5a..9b97656d599b0 100644
@@ -10776,9 +10776,15 @@ static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
 	}
 	rtnl_unlock();
 
-	/* zero if this is last one */
-	if (nii_rsp)
+	/*
+	 * nii_rsp may point to an entry not included in nbytes if the IPv4
+	 * or IPv6 device lookup failed. Clear Next in the last returned entry.
+	 */
+	if (nbytes > 0) {
+		nii_rsp = (struct network_interface_info_ioctl_rsp *)
+			  &rsp->Buffer[nbytes - sizeof(*nii_rsp)];
 		nii_rsp->Next = 0;
+	}
 
 	rsp->PersistentFileId = SMB2_NO_FID;
 	rsp->VolatileFileId = SMB2_NO_FID;
Signature · 1 line
2.53.0
author maintainer
#2307 lore raw

PATCH 2286/2651 ksmbd: report IPv4 and IPv6 addresses independently in iface query

In reply to Greg Kroah-Hartman

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

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

From: Henry Hu <[email protected]>

[ Upstream commit bb0326a5806015fb7e5a6a721a50ff172c92c6e4 ]

fsctl_query_iface_info_ioctl() appends an entry before checking that a usable address was found, so it advertises unspecified-address
placeholders: an entry containing 0.0.0.0 when an in_device exists but has no primary IPv4 address, and an entry containing :: when an inet6_dev exists but its address list is empty or every address is tentative or deprecated.

The loop also couples IPv6 reporting to IPv4 success: when __in_dev_get_rtnl() returns NULL it continues to the next interface, skipping the IPv6 pass, so an interface without an in_device is dropped even if it has a usable IPv6 address.

Query IPv4 and IPv6 independently and append an entry only when an address is found. Factor out the common entry initialization and query the link speed once per interface instead of once per address family.

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
Assisted-by Codex:gpt-5.6-sol
---
 fs/smb/server/smb2pdu.c | 127 ++++++++++++++++++++++------------------
 1 file changed, 70 insertions(+), 57 deletions(-)
fs/smb/server/smb2pdu.c +70 -57
index 9b97656d599b0..dc53b1d3e5931 100644
@@ -10673,6 +10673,27 @@ static __be32 idev_ipv4_address(struct in_device *idev)
 	return addr;
 }
 
+static struct network_interface_info_ioctl_rsp *
+ksmbd_iface_entry_init(struct smb2_ioctl_rsp *rsp, int nbytes,
+		       struct net_device *netdev, unsigned long long speed)
+{
+	struct network_interface_info_ioctl_rsp *nii_rsp;
+
+	nii_rsp = (struct network_interface_info_ioctl_rsp *)&rsp->Buffer[nbytes];
+	nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
+	nii_rsp->Capability = 0;
+	if (netdev->real_num_tx_queues > 1)
+		nii_rsp->Capability |= RSS_CAPABLE;
+	if (ksmbd_rdma_capable_netdev(netdev))
+		nii_rsp->Capability |= RDMA_CAPABLE;
+	nii_rsp->Next = cpu_to_le32(152);
+	nii_rsp->Reserved = 0;
+	nii_rsp->LinkSpeed = cpu_to_le64(speed);
+	memset(nii_rsp->SockAddr_Storage, 0, 128);
+
+	return nii_rsp;
+}
+
 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
 					struct smb2_ioctl_rsp *rsp,
 					unsigned int out_buf_len)
@@ -10687,7 +10708,12 @@ static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
 
 	rtnl_lock();
 	for_each_netdev(&init_net, netdev) {
-		bool ipv4_set = false;
+		struct inet6_ifaddr *ifa;
+		struct inet6_dev *idev6;
+		struct in_device *idev;
+		struct in6_addr ip6 = { };
+		bool have_ip6 = false;
+		__be32 ip4 = 0;
 
 		if (netdev->type == ARPHRD_LOOPBACK)
 			continue;
@@ -10698,25 +10724,6 @@ static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
 		flags = netif_get_flags(netdev);
 		if (!(flags & IFF_RUNNING))
 			continue;
-ipv6_retry:
-		if (out_buf_len <
-		    nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
-			rtnl_unlock();
-			return -ENOSPC;
-		}
-
-		nii_rsp = (struct network_interface_info_ioctl_rsp *)
-				&rsp->Buffer[nbytes];
-		nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
-
-		nii_rsp->Capability = 0;
-		if (netdev->real_num_tx_queues > 1)
-			nii_rsp->Capability |= RSS_CAPABLE;
-		if (ksmbd_rdma_capable_netdev(netdev))
-			nii_rsp->Capability |= RDMA_CAPABLE;
-
-		nii_rsp->Next = cpu_to_le32(152);
-		nii_rsp->Reserved = 0;
 
 		if (!__ethtool_get_link_ksettings(netdev, &cmd) &&
 		    cmd.base.speed && cmd.base.speed != SPEED_UNKNOWN) {
@@ -10726,60 +10733,66 @@ static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
 				    "speed is unknown, defaulting to 1Gb/sec");
 			speed = SPEED_1000;
 		}
-
 		speed *= 1000000;
-		nii_rsp->LinkSpeed = cpu_to_le64(speed);
 
-		sockaddr_storage = (struct sockaddr_storage_rsp *)
-					nii_rsp->SockAddr_Storage;
-		memset(sockaddr_storage, 0, 128);
+		/*
+		 * Query IPv4 and IPv6 independently; emit an entry only when a
+		 * usable address exists, so an interface missing one family is
+		 * still reported for the other and 0.0.0.0 / :: placeholders are
+		 * never advertised.
+		 */
+		idev = __in_dev_get_rtnl(netdev);
+		if (idev)
+			ip4 = idev_ipv4_address(idev);
 
-		if (!ipv4_set) {
-			struct in_device *idev;
+		idev6 = __in6_dev_get(netdev);
+		if (idev6) {
+			rcu_read_lock();
+			list_for_each_entry_rcu(ifa, &idev6->addr_list, if_list) {
+				if (ifa->flags & (IFA_F_TENTATIVE | IFA_F_DEPRECATED))
+					continue;
+				memcpy(&ip6, ifa->addr.s6_addr, sizeof(ip6));
+				have_ip6 = true;
+				break;
+			}
+			rcu_read_unlock();
+		}
 
+		if (ip4) {
+			if (out_buf_len <
+			    nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
+				rtnl_unlock();
+				return -ENOSPC;
+			}
+
+			nii_rsp = ksmbd_iface_entry_init(rsp, nbytes, netdev, speed);
+			sockaddr_storage = (struct sockaddr_storage_rsp *)nii_rsp->SockAddr_Storage;
 			sockaddr_storage->Family = INTERNETWORK;
 			sockaddr_storage->addr4.Port = 0;
-
-			idev = __in_dev_get_rtnl(netdev);
-			if (!idev)
-				continue;
-			sockaddr_storage->addr4.IPv4Address =
-						idev_ipv4_address(idev);
+			sockaddr_storage->addr4.IPv4Address = ip4;
 			nbytes += sizeof(struct network_interface_info_ioctl_rsp);
-			ipv4_set = true;
-			goto ipv6_retry;
-		} else {
-			struct inet6_dev *idev6;
-			struct inet6_ifaddr *ifa;
-			__u8 *ipv6_addr = sockaddr_storage->addr6.IPv6Address;
+		}
+
+		if (have_ip6) {
+			if (out_buf_len <
+			    nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
+				rtnl_unlock();
+				return -ENOSPC;
+			}
 
+			nii_rsp = ksmbd_iface_entry_init(rsp, nbytes, netdev, speed);
+			sockaddr_storage = (struct sockaddr_storage_rsp *)nii_rsp->SockAddr_Storage;
 			sockaddr_storage->Family = INTERNETWORKV6;
 			sockaddr_storage->addr6.Port = 0;
 			sockaddr_storage->addr6.FlowInfo = 0;
-
-			idev6 = __in6_dev_get(netdev);
-			if (!idev6)
-				continue;
-
-			rcu_read_lock();
-			list_for_each_entry_rcu(ifa, &idev6->addr_list, if_list) {
-				if (ifa->flags & (IFA_F_TENTATIVE |
-							IFA_F_DEPRECATED))
-					continue;
-				memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
-				break;
-			}
-			rcu_read_unlock();
+			memcpy(sockaddr_storage->addr6.IPv6Address, ip6.s6_addr, 16);
 			sockaddr_storage->addr6.ScopeId = 0;
 			nbytes += sizeof(struct network_interface_info_ioctl_rsp);
 		}
 	}
 	rtnl_unlock();
 
-	/*
-	 * nii_rsp may point to an entry not included in nbytes if the IPv4
-	 * or IPv6 device lookup failed. Clear Next in the last returned entry.
-	 */
+	/* Clear Next of the last committed entry to terminate the list. */
 	if (nbytes > 0) {
 		nii_rsp = (struct network_interface_info_ioctl_rsp *)
 			  &rsp->Buffer[nbytes - sizeof(*nii_rsp)];
Signature · 1 line
2.53.0
author maintainer
#2308 lore raw

PATCH 2287/2651 ksmbd: fix AFP_AfpInfo header fields in synthesized xattr

In reply to Greg Kroah-Hartman

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

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

From: Gael Blivet <[email protected]>

[ Upstream commit d3ef5ae55a16d4b31859e7feadbb50a0cd38dfcc ]

smb2_set_stream_name_xattr() synthesizes a 60-byte AFP_AfpInfo xattr when a client opens a nonexistent one on a Time Machine share, so the probe is answered instead of failing with -EBADF. Its header does not match what clients write: ksmbd uses 0x00051607 and 0x00020000 for the first two fields and leaves the third zero.

The user.DosStream.AFP_AfpInfo:$DATA xattr a macOS client writes begins:

00000000: 4146 5000 0000 0100 0000 0000 0000 0080 AFP.............

Write those sixteen bytes: the signature, the version at offset 4 and the backup time at offset 12. The 60-byte length is already correct and the rest stays zeroed: a zero type and creator lets the client use the file extension for icon and type detection.

Fixes eaff8e924f60 ("ksmbd: synthesize empty AFP_AfpInfo xattr on first probe")
Assisted-by Claude:claude-opus-5
---
 fs/smb/server/smb2pdu.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
fs/smb/server/smb2pdu.c +3 -2
index dc53b1d3e5931..4f6cf8df4ae9f 100644
@@ -3468,8 +3468,9 @@ static noinline int smb2_set_stream_name_xattr(const struct path *path,
 			 * AAPL there too.
 			 */
 			static const u8 afpinfo_empty[60] = {
-				0x00, 0x05, 0x16, 0x07, /* magic  0x00051607 BE */
-				0x00, 0x02, 0x00, 0x00, /* version 0x00020000 BE */
+				'A', 'F', 'P', 0x00,	/* signature */
+				0x00, 0x00, 0x01, 0x00,	/* version */
+				[15] = 0x80,		/* backup time */
 			};
 			rc = ksmbd_vfs_setxattr(idmap, path, xattr_stream_name,
 						(void *)afpinfo_empty,
Signature · 1 line
2.53.0
author maintainer
#2309 lore raw

PATCH 2288/2651 ksmbd: print IPv6 client addresses correctly in procfs

In reply to Greg Kroah-Hartman

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

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

From: Gael Blivet <[email protected]>

[ Upstream commit cf0ef575a56993147f087d3f251fc2a04fdffbeb ]

conn->inet_addr and conn->inet6_addr share a union, and three procfs printers choose between them by testing whether inet_addr is zero. For an IPv6 peer that field aliases the first four bytes of the address, which are zero only for :: prefixed addresses, so a client with a global IPv6 address takes the IPv4 branch and is listed from those four bytes. A client at 2001:db8::1 is listed as 32.1.13.184.

IPv4 mapped addresses begin with zero bytes, so the listing is correct until a native IPv6 client connects.

Record the address family where the address is stored and select on that, in the client listing and in both session listings.

Fixes fe4dc5987d7d ("ksmbd: expose connection runtime state in procfs")
Assisted-by Claude:claude-opus-5
---
 fs/smb/server/connection.c        | 2 +-
 fs/smb/server/connection.h        | 3 +++
 fs/smb/server/mgmt/user_session.c | 4 ++--
 fs/smb/server/transport_tcp.c     | 1 +
 4 files changed, 7 insertions(+), 3 deletions(-)
fs/smb/server/connection.c +1 -1
index b519376ecc17b..d66fc0fbe5269 100644
@@ -114,7 +114,7 @@ static int proc_show_clients(struct seq_file *m, void *v)
 			sessions++;
 		rcu_read_unlock();
 #if IS_ENABLED(CONFIG_IPV6)
-		if (!conn->inet_addr)
+		if (conn->is_ipv6)
 			seq_printf(m, "client:\t%pI6c\n", &conn->inet6_addr);
 		else
 #endif
fs/smb/server/connection.h +3 -0
index a4f5a64b36b4e..8e0da44a1e0f6 100644
@@ -68,6 +68,9 @@ struct ksmbd_conn {
 		u8			inet6_addr[16];
 #endif
 	};
+#if IS_ENABLED(CONFIG_IPV6)
+	bool				is_ipv6;
+#endif
 	unsigned int			inet_hash;
 	char				*request_buf;
 	struct ksmbd_transport		*transport;
fs/smb/server/mgmt/user_session.c +2 -2
index d131809dd08ad..a18533bb4fe39 100644
@@ -153,7 +153,7 @@ static int show_proc_session(struct seq_file *m, void *v)
 		const char *name;
 
 #if IS_ENABLED(CONFIG_IPV6)
-		if (chan->conn->inet_addr)
+		if (!chan->conn->is_ipv6)
 			seq_printf(m, "client:\t%pI4\n",
 					&chan->conn->inet_addr);
 		else
@@ -256,7 +256,7 @@ static int show_proc_sessions(struct seq_file *m, void *v)
 			ksmbd_user_session_get(session);
 
 #if IS_ENABLED(CONFIG_IPV6)
-			if (!chan->conn->inet_addr)
+			if (chan->conn->is_ipv6)
 				seq_printf(m, "client:\t%pI6c\n", &chan->conn->inet6_addr);
 			else
 #endif
fs/smb/server/transport_tcp.c +1 -0
index 7492aa08f9f31..2c0e6b9abd5e9 100644
@@ -104,6 +104,7 @@ static struct tcp_transport *alloc_transport(struct socket *client_sk)
 	if (client_sk->sk->sk_family == AF_INET6) {
 		memcpy(&conn->inet6_addr, &client_sk->sk->sk_v6_daddr, 16);
 		conn->inet_hash = ipv6_addr_hash(&client_sk->sk->sk_v6_daddr);
+		conn->is_ipv6 = true;
 	} else {
 		conn->inet_addr = inet_sk(client_sk->sk)->inet_daddr;
 		conn->inet_hash = ipv4_addr_hash(inet_sk(client_sk->sk)->inet_daddr);
Signature · 1 line
2.53.0
author maintainer
#2310 lore raw

PATCH 2289/2651 smb/server: fix trailing period in generated short names

In reply to Greg Kroah-Hartman

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

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

From: ChenXiaoSong <[email protected]>

[ Upstream commit e8486c5cfbdd07811afa4196060bafbf78ccdae2 ]

Reproducer:

1. touch /mnt/file
2. smbinfo filealternatenameinfo /mnt/file
Alternate Name: FILE~9!.

See MS-FSCC 2.1.5.2.1. The base filename MUST be 1-8 characters in length and MUST NOT contain a "." period character.

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
---
 fs/smb/server/smb_common.c | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)
fs/smb/server/smb_common.c +1 -3
index 21ba0ce5abbf4..5ddefb5a7078c 100644
@@ -525,8 +525,6 @@ int ksmbd_populate_dot_dotdot_entries(struct ksmbd_work *work, int info_level,
  * @shortname:	destination short filename
  *
  * Return:	shortname length or 0 when source long name is '.' or '..'
- * TODO: Though this function conforms the restriction of 8.3 Filename spec,
- * but the result is different with Windows 7's one. need to check.
  */
 int ksmbd_extract_shortname(struct ksmbd_conn *conn, const char *longname,
 			    char *shortname)
@@ -590,7 +588,7 @@ int ksmbd_extract_shortname(struct ksmbd_conn *conn, const char *longname,
 	if (dot_present)
 		memcpy(out + baselen + 4, extension, 4);
 	else
-		out[baselen + 4] = '\0';
+		out[baselen + 3] = '\0';
 	smbConvertToUTF16((__le16 *)shortname, out, PATH_MAX,
 			  conn->local_nls, 0);
 	len = strlen(out) * 2;
Signature · 1 line
2.53.0
author maintainer
#2311 lore raw

PATCH 2290/2651 ksmbd: disconnect on invalid encryption transform flags

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit 0882f124ae329eefb66b00e63b9043f24c006b0e ]

MS-SMB2 3.3.5.2.1.1 requires the Flags/EncryptionAlgorithm field in an SMB2 transform header to be 0x0001. The server must disconnect the connection when it has any other value.

smb3_decrypt_req() currently ignores this field. A client with the session key can therefore send a correctly authenticated encrypted request with invalid flags and have it processed. Check the field before looking up the session key or decrypting the request. The caller aborts the connection when this check fails.

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
---
 fs/smb/server/smb2pdu.c | 6 ++++++
 1 file changed, 6 insertions(+)
fs/smb/server/smb2pdu.c +6 -0
index 4f6cf8df4ae9f..74b4e332317b7 100644
@@ -12644,6 +12644,12 @@ int smb3_decrypt_req(struct ksmbd_work *work)
 		return -ECONNABORTED;
 	}
 
+	if (tr_hdr->Flags != cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED)) {
+		pr_err_ratelimited("Invalid transform flags 0x%04x\n",
+				   le16_to_cpu(tr_hdr->Flags));
+		return -ECONNABORTED;
+	}
+
 	buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
 	original_msg_size = le32_to_cpu(tr_hdr->OriginalMessageSize);
 	if (buf_data_size < sizeof(struct smb2_compression_hdr) ||
Signature · 1 line
2.53.0
author maintainer
#2312 lore raw

PATCH 2291/2651 ksmbd: cache the resolved share path for durable reconnects

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit 2a90ba573d41efa82e075ba9ac532bb3ec0519c4 ]

A share configured as /a/link/b, with /a/link pointing to /real, is opened relative to share->vfs_path at /real/b. However, ksmbd_validate_name_reconnect() compares the file's d_path() result against the original /a/link/b string and rejects a valid reconnect.

Render share->vfs_path with d_path() after the existing kern_path() lookup and cache a copy in real_path along with its length. Use the resolved string for durable reconnect name validation. Keep path and path_sz as the configured spelling for existing consumers, including the volume serial calculation and path lookups.

Fixes c8efcc786146 ("ksmbd: add support for durable handles v1/v2")
---
 fs/smb/server/mgmt/share_config.c | 43 +++++++++++++++++++++++++++++--
 fs/smb/server/mgmt/share_config.h |  2 ++
 fs/smb/server/vfs_cache.c         | 12 +++++----
 3 files changed, 50 insertions(+), 7 deletions(-)
fs/smb/server/mgmt/share_config.c +41 -2
index cc9f18ede80df..f85134c38cdd1 100644
@@ -8,6 +8,7 @@
 #include <linux/slab.h>
 #include <linux/rwsem.h>
 #include <linux/parser.h>
+#include <linux/dcache.h>
 #include <linux/namei.h>
 #include <linux/fs_struct.h>
 #include <linux/sched.h>
@@ -108,6 +109,7 @@ static void kill_share(struct ksmbd_share_config *share)
 		path_put(&share->vfs_path);
 	kfree(share->name);
 	kfree(share->path);
+	kfree(share->real_path);
 	kfree(share);
 }
 
@@ -182,6 +184,43 @@ static int parse_veto_list(struct ksmbd_share_config *share,
 	return 0;
 }
 
+static int share_config_resolve_path(struct ksmbd_share_config *share)
+{
+	char *buf, *path;
+	int ret;
+
+	ret = kern_path(share->path, 0, &share->vfs_path);
+	if (ret)
+		return ret;
+
+	buf = kmalloc(PATH_MAX, KSMBD_DEFAULT_GFP);
+	if (!buf) {
+		ret = -ENOMEM;
+		goto out;
+	}
+
+	path = d_path(&share->vfs_path, buf, PATH_MAX);
+	if (IS_ERR(path)) {
+		ret = PTR_ERR(path);
+		goto out_buf;
+	}
+
+	path = kstrdup(path, KSMBD_DEFAULT_GFP);
+	if (!path) {
+		ret = -ENOMEM;
+		goto out_buf;
+	}
+
+	share->real_path = path;
+	share->real_path_sz = strlen(path);
+out_buf:
+	kfree(buf);
+out:
+	if (ret)
+		path_put(&share->vfs_path);
+	return ret;
+}
+
 static struct ksmbd_share_config *share_config_request(struct ksmbd_work *work,
 						       const char *name)
 {
@@ -272,12 +311,12 @@ static struct ksmbd_share_config *share_config_request(struct ksmbd_work *work,
 			}
 
 			scoped_with_init_fs()
-				ret = kern_path(share->path, 0, &share->vfs_path);
+				ret = share_config_resolve_path(share);
 			ksmbd_revert_fsids(work);
 			if (ret) {
 				ksmbd_debug(SMB, "failed to access '%s'\n",
 					    share->path);
-				/* Avoid put_path() */
+				/* No path reference is retained on failure. */
 				kfree(share->path);
 				share->path = NULL;
 			}
fs/smb/server/mgmt/share_config.h +2 -0
index d157545fe7d1d..91691b525907d 100644
@@ -16,8 +16,10 @@ struct ksmbd_work;
 struct ksmbd_share_config {
 	char			*name;
 	char			*path;
+	char			*real_path;
 
 	unsigned int		path_sz;
+	unsigned int		real_path_sz;
 	unsigned int		flags;
 	struct list_head	veto_list;
 
fs/smb/server/vfs_cache.c +7 -5
index 38196befa03a5..56f07914197c1 100644
@@ -1921,6 +1921,8 @@ void ksmbd_free_global_file_table(void)
 int ksmbd_validate_name_reconnect(struct ksmbd_share_config *share,
 				  struct ksmbd_file *fp, char *name)
 {
+	const char *share_path = share->real_path;
+	size_t share_path_sz = share->real_path_sz;
 	char *pathname, *ab_pathname;
 	int ret = 0;
 
@@ -1937,14 +1939,14 @@ int ksmbd_validate_name_reconnect(struct ksmbd_share_config *share,
 	if (name) {
 		size_t len = strlen(ab_pathname);
 
-		if (len == share->path_sz && !strncmp(ab_pathname, share->path, len)) {
+		if (len == share_path_sz && !strncmp(ab_pathname, share_path, len)) {
 			/* the durable fp is the share root itself */
 			if (name[0])
 				ret = -EINVAL;
-		} else if (len <= share->path_sz ||
-			   strncmp(ab_pathname, share->path, share->path_sz) ||
-			   ab_pathname[share->path_sz] != '/' ||
-			   strcmp(&ab_pathname[share->path_sz + 1], name)) {
+		} else if (len <= share_path_sz ||
+			   strncmp(ab_pathname, share_path, share_path_sz) ||
+			   ab_pathname[share_path_sz] != '/' ||
+			   strcmp(&ab_pathname[share_path_sz + 1], name)) {
 			ret = -EINVAL;
 		}
 		if (ret)
Signature · 1 line
2.53.0
author maintainer
#2313 lore raw

PATCH 2292/2651 ksmbd: fix durable reconnects for root shares

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit 25e36df831a47597c03c6239fbc71285e7d714c2 ]

When a share exports "/", ksmbd_validate_name_reconnect() expects another slash after the share path. For a file at /foo, this rejects the valid reconnect name "foo" even though the file is in the share.

Compare the requested name with the rendered file path after its leading slash when the resolved share root is "/". Keep the exact-root/empty-name check and reject rendered paths without an initial slash.

Fixes c8efcc786146 ("ksmbd: add support for durable handles v1/v2")
---
 fs/smb/server/vfs_cache.c | 4 ++++
 1 file changed, 4 insertions(+)
fs/smb/server/vfs_cache.c +4 -0
index 56f07914197c1..f00d4d81283a8 100644
@@ -1943,6 +1943,10 @@ int ksmbd_validate_name_reconnect(struct ksmbd_share_config *share,
 			/* the durable fp is the share root itself */
 			if (name[0])
 				ret = -EINVAL;
+		} else if (share_path_sz == 1 && share_path[0] == '/') {
+			if (ab_pathname[0] != '/' ||
+			    strcmp(ab_pathname + 1, name))
+				ret = -EINVAL;
 		} else if (len <= share_path_sz ||
 			   strncmp(ab_pathname, share_path, share_path_sz) ||
 			   ab_pathname[share_path_sz] != '/' ||
Signature · 1 line
2.53.0
author maintainer
#2314 lore raw

PATCH 2293/2651 smb: smbdirect: dont WARN on an unexpected receive opcode

In reply to Greg Kroah-Hartman

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

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

From: Stefan Metzmacher <[email protected]>

[ Upstream commit e8592dec2e935befe842f90f4044d210f59c4d30 ]

The receive completion handlers smbdirect_connection_recv_io_done(), smbdirect_accept_negotiate_recv_done() and smbdirect_connect_negotiate_recv_done() verify that the completion is a regular receive with WARN_ON_ONCE(wc->opcode != IB_WC_RECV).

But wc->opcode is controlled by the remote peer: a posted receive work request is consumed not only by an incoming SEND, but also by an RDMA Write with Immediate, which completes as IB_WC_RECV_RDMA_WITH_IMM. An unauthenticated peer can transmit such a message, even before the negotiate completes, so it reaches the accept/connect negotiate handlers as well. With panic_on_warn set this is a remote denial of service, and otherwise it still taints the kernel and spams the log for something a peer can trigger at will.

The opcode check itself was inherited from the original client and server recv_done() handlers (fs/smb/client/smbdirect.c and fs/smb/server/transport_rdma.c), where an unexpected opcode was simply logged and the connection was torn down. Only the WARN_ON_ONCE() was added on top during the socketization rework. Drop the WARN_ON_ONCE() and keep the existing graceful error path, which logs the unexpected opcode (unless the status is IB_WC_WR_FLUSH_ERR) and tears the connection down.

Fixes ea4151222a93 ("smb: smbdirect: introduce smbdirect_connection_recv_io_done()")
Fixes eb3ed1e9048c ("smb: smbdirect: introduce smbdirect_accept_connect_request()")
Fixes d1f187656797 ("smb: smbdirect: introduce smbdirect_connect[_sync]()")
Cc Namjae Jeon <[email protected]>
Cc Paulo Alcantara <[email protected]>
Cc Tom Talpey <[email protected]>
Assisted-by Claude:claude-opus-5-5
---
 fs/smb/smbdirect/accept.c     | 2 +-
 fs/smb/smbdirect/connect.c    | 2 +-
 fs/smb/smbdirect/connection.c | 2 +-
 3 files changed, 3 insertions(+), 3 deletions(-)
fs/smb/smbdirect/accept.c +1 -1
index e7e5eb75a5aea..85e37d11f43de 100644
@@ -234,7 +234,7 @@ static void smbdirect_accept_negotiate_recv_done(struct ib_cq *cq, struct ib_wc
 	struct smbdirect_socket *sc = recv_io->socket;
 	unsigned long flags;
 
-	if (unlikely(wc->status != IB_WC_SUCCESS || WARN_ON_ONCE(wc->opcode != IB_WC_RECV))) {
+	if (unlikely(wc->status != IB_WC_SUCCESS || wc->opcode != IB_WC_RECV)) {
 		if (wc->status != IB_WC_WR_FLUSH_ERR)
 			smbdirect_log_rdma_recv(sc, SMBDIRECT_LOG_ERR,
 				"wc->status=%s (%d) wc->opcode=%d\n",
fs/smb/smbdirect/connect.c +1 -1
index 34a3e72c38fbb..0d02f03063ac7 100644
@@ -581,7 +581,7 @@ static void smbdirect_connect_negotiate_recv_done(struct ib_cq *cq, struct ib_wc
 	struct smbdirect_socket *sc = recv_io->socket;
 	unsigned long flags;
 
-	if (unlikely(wc->status != IB_WC_SUCCESS || WARN_ON_ONCE(wc->opcode != IB_WC_RECV))) {
+	if (unlikely(wc->status != IB_WC_SUCCESS || wc->opcode != IB_WC_RECV)) {
 		if (wc->status != IB_WC_WR_FLUSH_ERR)
 			smbdirect_log_rdma_recv(sc, SMBDIRECT_LOG_ERR,
 				"wc->status=%s (%d) wc->opcode=%d\n",
fs/smb/smbdirect/connection.c +1 -1
index f48c857bda5a4..e6c7b343fe870 100644
@@ -1529,7 +1529,7 @@ void smbdirect_connection_recv_io_done(struct ib_cq *cq, struct ib_wc *wc)
 	u32 data_length;
 	u32 remaining_data_length;
 
-	if (unlikely(wc->status != IB_WC_SUCCESS || WARN_ON_ONCE(wc->opcode != IB_WC_RECV))) {
+	if (unlikely(wc->status != IB_WC_SUCCESS || wc->opcode != IB_WC_RECV)) {
 		if (wc->status != IB_WC_WR_FLUSH_ERR)
 			smbdirect_log_rdma_recv(sc, SMBDIRECT_LOG_ERR,
 				"wc->status=%s (%d) wc->opcode=%d\n",
Signature · 1 line
2.53.0
author maintainer
#2315 lore raw

PATCH 2294/2651 ksmbd: keep lease tables until their last lease is closed

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit 20e3068315423e6e493588dd94d462c8e7fd3a2e ]

Disconnecting one channel destroys the lease table for its ClientGuid, even when another channel still uses the same opens. A lease break ACK on the surviving channel can no longer find the lease. Detached durable opens also lose their lease lookup entries before reconnect or expiry.

Tie a client table to its lease entries instead of the connection which created it. Remove the table when its last lease is removed, and release any remaining entries at server shutdown. Do not destroy client tables from connection teardown or keep a connection reference in each table.

For a detached lease, collect break candidates using the table's ClientGuid directly. The existing notification retry path takes its own references on matching live connections.

Fixes 0626e6641f6b ("cifsd: add server handler for central processing and tranport layers")
---
 fs/smb/server/oplock.c | 46 +++++++++++++++++-------------------------
 fs/smb/server/oplock.h |  3 +--
 fs/smb/server/server.c |  3 +--
 3 files changed, 20 insertions(+), 32 deletions(-)
fs/smb/server/oplock.c +18 -28
index 313bf01ad3508..96b36b8329a66 100644
@@ -125,6 +125,12 @@ static void lease_add_table(struct lease *lease, struct lease_table *lb)
 	spin_unlock(&lb->lb_lock);
 }
 
+static void free_lease_table(struct lease_table *lb)
+{
+	kfree(lb);
+}
+
+/* The caller holds lease_list_lock for write. */
 static void lease_del_table(struct lease *lease)
 {
 	struct lease_table *lb = lease->l_lb;
@@ -143,6 +149,10 @@ static void lease_del_table(struct lease *lease)
 	spin_unlock(&lb->lb_lock);
 
 	lease_put(lease);
+	if (list_empty(&lb->lease_list)) {
+		list_del(&lb->l_entry);
+		free_lease_table(lb);
+	}
 }
 
 static struct lease_table *alloc_lease_table(struct oplock_info *opinfo)
@@ -155,21 +165,11 @@ static struct lease_table *alloc_lease_table(struct oplock_info *opinfo)
 
 	memcpy(lb->client_guid, opinfo->conn->ClientGUID,
 	       SMB2_CLIENT_GUID_SIZE);
-	lb->conn = ksmbd_conn_get(opinfo->conn);
 	INIT_LIST_HEAD(&lb->lease_list);
 	spin_lock_init(&lb->lb_lock);
 	return lb;
 }
 
-static void free_lease_table(struct lease_table *lb)
-{
-	if (!lb)
-		return;
-
-	ksmbd_conn_put(lb->conn);
-	kfree(lb);
-}
-
 static struct lease *alloc_lease(struct lease_ctx_info *lctx,
 				 struct ksmbd_inode *ci)
 {
@@ -927,8 +927,6 @@ static int smb2_break_collect_channels(struct oplock_info *opinfo,
 		if (lb) {
 			memcpy(guid, lb->client_guid, sizeof(guid));
 			have_guid = true;
-			if (lb->conn)
-				owner->conn = ksmbd_conn_get(lb->conn);
 		}
 		read_unlock(&lease_list_lock);
 	}
@@ -1495,25 +1493,17 @@ static void oplock_break_drain_none(struct list_head *head,
 	}
 }
 
-void destroy_lease_table(struct ksmbd_conn *conn)
+void destroy_lease_table(void)
 {
-	struct lease_table *lb, *lbtmp;
-	struct lease *lease, *ltmp;
+	struct lease_table *lb;
+	struct lease *lease;
 
 	write_lock(&lease_list_lock);
-	if (list_empty(&lease_table_list)) {
-		write_unlock(&lease_list_lock);
-		return;
-	}
-
-	list_for_each_entry_safe(lb, lbtmp, &lease_table_list, l_entry) {
-		if (conn && memcmp(lb->client_guid, conn->ClientGUID,
-				   SMB2_CLIENT_GUID_SIZE))
-			continue;
-		list_for_each_entry_safe(lease, ltmp, &lb->lease_list, l_entry)
-			lease_del_table(lease);
-		list_del(&lb->l_entry);
-		free_lease_table(lb);
+	while (!list_empty(&lease_table_list)) {
+		lb = list_first_entry(&lease_table_list, struct lease_table,
+				      l_entry);
+		lease = list_first_entry(&lb->lease_list, struct lease, l_entry);
+		lease_del_table(lease);
 	}
 	write_unlock(&lease_list_lock);
 }
fs/smb/server/oplock.h +1 -2
index e114e2148c30e..5ef05166e5020 100644
@@ -34,7 +34,6 @@ struct lease_ctx_info {
 
 struct lease_table {
 	char			client_guid[SMB2_CLIENT_GUID_SIZE];
-	struct ksmbd_conn	*conn;
 	struct list_head	lease_list;
 	struct list_head	l_entry;
 	spinlock_t		lb_lock;
@@ -122,7 +121,7 @@ struct oplock_info *lookup_lease_in_table(struct ksmbd_conn *conn,
 					  char *lease_key);
 int find_same_lease_key(struct ksmbd_conn *conn, struct ksmbd_inode *ci,
 			struct lease_ctx_info *lctx);
-void destroy_lease_table(struct ksmbd_conn *conn);
+void destroy_lease_table(void);
 void smb_send_parent_lease_break_noti(struct ksmbd_file *fp,
 				      struct lease_ctx_info *lctx);
 void smb_lazy_parent_lease_break_close(struct ksmbd_file *fp);
fs/smb/server/server.c +1 -2
index 0593094f5fd08..c836e75b4825c 100644
@@ -436,7 +436,6 @@ static int ksmbd_server_process_request(struct ksmbd_conn *conn)
 static int ksmbd_server_terminate_conn(struct ksmbd_conn *conn)
 {
 	ksmbd_conn_sessions_cleanup(conn);
-	destroy_lease_table(conn);
 	return 0;
 }
 
@@ -666,7 +665,7 @@ static int ksmbd_server_shutdown(void)
 	ksmbd_proc_cleanup();
 	ksmbd_crypto_destroy();
 	ksmbd_free_global_file_table();
-	destroy_lease_table(NULL);
+	destroy_lease_table();
 	ksmbd_work_pool_destroy();
 	ksmbd_exit_file_cache();
 	server_conf_free();
Signature · 1 line
2.53.0
author maintainer
#2316 lore raw

PATCH 2295/2651 ksmbd: inherit FileIds in related compound requests

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit 318cd7461a7facb9cd5f7a5d1580fd874440e035 ]

MS-SMB2 specifies that subsequent related operations use the FileId from the preceding operation. Track FileIds from handle-bearing requests so related requests that use the all-ones placeholder resolve to the inherited handle.

Return STATUS_INVALID_HANDLE when a related request refers to a FileId but the preceding operation neither contained nor generated one.

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
---
 fs/smb/server/ksmbd_work.h |   9 ++-
 fs/smb/server/server.c     |   5 +-
 fs/smb/server/smb2pdu.c    | 150 ++++++++++++++++++++++++++++---------
 fs/smb/server/smb2pdu.h    |   1 +
 4 files changed, 126 insertions(+), 39 deletions(-)
fs/smb/server/ksmbd_work.h +5 -4
index 6877f68381186..be98a2c3be770 100644
@@ -54,10 +54,7 @@ struct ksmbd_work {
 	/* Current cmd hdr in compound rsp buf*/
 	int                             curr_smb2_rsp_hdr_off;
 
-	/*
-	 * Current Local FID assigned compound response if SMB2 CREATE
-	 * command is present in compound request
-	 */
+	/* FileId generated or used by the previous operation in a compound. */
 	u64				compound_fid;
 	u64				compound_pfid;
 	u64				compound_sid;
@@ -95,6 +92,10 @@ struct ksmbd_work {
 	bool				owns_conn_ref:1;
 	bool                            need_invalidate_rkey:1;
 	bool				request_open_chseq_tracked:1;
+	/* The previous command carries a FileId or is a CREATE. */
+	bool				compound_fid_present:1;
+	/* A related command failed because there was no FileId to inherit. */
+	bool				compound_fid_missing:1;
 	bool				session_setup_reauth:1;
 
 	unsigned int                    remote_key;
fs/smb/server/server.c +4 -1
index c836e75b4825c..064f99427ca6f 100644
@@ -157,7 +157,10 @@ static int __process_request(struct ksmbd_work *work, struct ksmbd_conn *conn,
 		}
 	}
 
-	ret = cmds->proc(work);
+	if (smb2_check_compound_fid(work))
+		ret = -EBADF;
+	else
+		ret = cmds->proc(work);
 	if (conn->ops->inc_reqs) {
 		struct smb2_hdr *rsp = ksmbd_resp_buf_curr(work);
 
fs/smb/server/smb2pdu.c +116 -34

182 lines not on this page · raw message

fs/smb/server/smb2pdu.h +1 -0
index 20a5337459ab0..38270130d1444 100644
@@ -397,6 +397,7 @@ bool is_smb2_rsp(struct ksmbd_work *work);
 u16 get_smb2_cmd_val(struct ksmbd_work *work);
 void set_smb2_rsp_status(struct ksmbd_work *work, __le32 err);
 int init_smb2_rsp_hdr(struct ksmbd_work *work);
+bool smb2_check_compound_fid(struct ksmbd_work *work);
 int smb2_allocate_rsp_buf(struct ksmbd_work *work);
 bool is_chained_smb2_message(struct ksmbd_work *work);
 int init_smb2_neg_rsp(struct ksmbd_work *work);
Signature · 1 line
2.53.0
author maintainer
#2317 lore raw

PATCH 2296/2651 ksmbd: round SetAllocation to the advertised allocation unit

In reply to Greg Kroah-Hartman

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

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

From: DaeMyung Kang <[email protected]>

[ Upstream commit aad7d86a6651efefb2c0a4f02c86dfeff3c176a2 ]

SetAllocation rounds requests to 512-byte blocks, although FS_SIZE_INFORMATION advertises the filesystem's f_bsize as its allocation unit. For example, on a filesystem with a 4 KiB unit, a 1000-byte request can truncate an 8 KiB file to 1024 bytes instead of 4 KiB.

Round the request to the advertised unit and use the same result for the block-count decision, fallocate, truncate, and the size stored on the open handle. Validate the unit and rounded size before either operation. Use DIV_ROUND_UP_ULL() so the calculation works on 32-bit kernels.

This does not change the existing block-count decision for whether to call fallocate. In particular, success does not yet guarantee reservation of holes within the requested range on a sparse file.

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
---
 fs/smb/server/smb2pdu.c | 35 ++++++++++++++++++++---------------
 1 file changed, 20 insertions(+), 15 deletions(-)
fs/smb/server/smb2pdu.c +20 -15
index c380f82ed8796..81c8bc5033cdf 100644
@@ -8483,10 +8483,11 @@ static int set_file_allocation_info(struct ksmbd_work *work,
 	 * properly with any smb.conf option
 	 */
 
-	loff_t alloc_blks;
-	u64 alloc_size;
+	u64 alloc_size, target, alloc_blks;
+	u32 alloc_unit;
 	struct inode *inode;
 	struct kstat stat;
+	struct kstatfs stfs;
 	int rc;
 
 	if (!(fp->daccess & FILE_WRITE_DATA_LE))
@@ -8499,44 +8500,48 @@ static int set_file_allocation_info(struct ksmbd_work *work,
 			 AT_STATX_SYNC_AS_STAT);
 	if (rc)
 		return rc;
+	rc = vfs_statfs(&fp->filp->f_path, &stfs);
+	if (rc)
+		return rc;
 
 	/*
-	 * AllocationSize is fully client-controlled (the caller only
-	 * validates the fixed 8-byte buffer length). Reject values that
-	 * would overflow the "round up to 512-byte blocks" conversion
-	 * below instead of silently wrapping it to a tiny block count,
-	 * which would truncate the file to a size the client never
-	 * asked for.
+	 * Use the allocation unit advertised in FS_SIZE_INFORMATION.
+	 * Reject requests that overflow when rounded to a whole unit.
 	 */
 	alloc_size = le64_to_cpu(file_alloc_info->AllocationSize);
-	if (alloc_size > MAX_LFS_FILESIZE - 511)
+	if (stfs.f_bsize <= 0 || (u64)stfs.f_bsize > U32_MAX)
+		return -EINVAL;
+	alloc_unit = stfs.f_bsize;
+	if (alloc_size > MAX_LFS_FILESIZE - (alloc_unit - 1))
 		return -EINVAL;
 
-	alloc_blks = (alloc_size + 511) >> 9;
+	target = DIV_ROUND_UP_ULL(alloc_size, alloc_unit) * alloc_unit;
+	alloc_blks = DIV_ROUND_UP_ULL(target, 512);
 	inode = file_inode(fp->filp);
+	if (target > inode->i_sb->s_maxbytes)
+		return -EINVAL;
 
 	if (alloc_blks > stat.blocks) {
 		smb_break_all_levII_oplock(work, fp, 1);
-		rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
-				   alloc_blks * 512);
+		rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0, target);
 		if (rc && rc != -EOPNOTSUPP) {
 			pr_err("vfs_fallocate is failed : %d\n", rc);
 			return rc;
 		}
 	} else if (alloc_blks < stat.blocks &&
-		   alloc_blks * 512 <= i_size_read(inode)) {
+		   target <= i_size_read(inode)) {
 		/*
 		 * Truncate at or below EOF to discard excess allocation.
 		 * Truncating above EOF would extend the file on disk.
 		 */
-		rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
+		rc = ksmbd_vfs_truncate(work, fp, target);
 		if (rc) {
 			pr_err("truncate failed!, err %d\n", rc);
 			return rc;
 		}
 	}
 
-	fp->allocation_size = le64_to_cpu(file_alloc_info->AllocationSize);
+	fp->allocation_size = target;
 	fp->allocation_size_set = true;
 	return 0;
 }
Signature · 1 line
2.53.0
author maintainer
#2318 lore raw

PATCH 2297/2651 ksmbd: fix fd_limit accounting across durable reconnects

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit df5c868f6b80ca16c171cfac5e4e6c9be83ba4c2 ]

A disconnected durable handle keeps its ksmbd_file and the fd_limit reservation taken at its initial open. Reconnecting allocates another volatile ID and takes another reservation for the same file. Final close returns only one reservation, so repeated reconnects permanently reduce the server-wide open-file budget.

Move reservation into ksmbd_open_fd() and release it on every creation failure. Keep the reservation until final close, including while a durable handle is disconnected. Make ID allocation independent of fd_limit so reconnects neither consume nor return slots. This also avoids returning an unreserved slot when persistent ID allocation fails.

New opens continue to return -EMFILE when the budget is exhausted, keeping the existing STATUS_INSUFFICIENT_RESOURCES mapping.

Fixes c8efcc786146 ("ksmbd: add support for durable handles v1/v2")
---
 fs/smb/server/vfs_cache.c | 15 ++++++++-------
 1 file changed, 8 insertions(+), 7 deletions(-)
fs/smb/server/vfs_cache.c +8 -7
index f00d4d81283a8..c6999ed4e6d67 100644
@@ -1283,11 +1283,6 @@ static int __open_id(struct ksmbd_file_table *ft, struct ksmbd_file *fp,
 	u64			id = 0;
 	int			ret;
 
-	if (type == OPEN_ID_TYPE_VOLATILE_ID && fd_limit_depleted()) {
-		__open_id_set(fp, KSMBD_NO_FID, type);
-		return -EMFILE;
-	}
-
 	idr_preload(KSMBD_DEFAULT_GFP);
 	write_lock(&ft->lock);
 	ret = idr_alloc_cyclic(ft->idr, fp, KSMBD_START_FID, INT_MAX - 1,
@@ -1297,7 +1292,6 @@ static int __open_id(struct ksmbd_file_table *ft, struct ksmbd_file *fp,
 		ret = 0;
 	} else {
 		id = KSMBD_NO_FID;
-		fd_limit_close();
 	}
 
 	__open_id_set(fp, id, type);
@@ -1317,10 +1311,15 @@ struct ksmbd_file *ksmbd_open_fd(struct ksmbd_work *work, struct file *filp)
 	struct ksmbd_file *fp;
 	int ret;
 
+	/* Durable reconnects reuse the slot held for the lifetime of fp. */
+	if (fd_limit_depleted())
+		return ERR_PTR(-EMFILE);
+
 	fp = kmem_cache_zalloc(filp_cache, KSMBD_DEFAULT_GFP);
 	if (!fp) {
 		pr_err("Failed to allocate memory\n");
-		return ERR_PTR(-ENOMEM);
+		ret = -ENOMEM;
+		goto err_fd_limit;
 	}
 
 	INIT_LIST_HEAD(&fp->blocked_works);
@@ -1374,6 +1373,8 @@ struct ksmbd_file *ksmbd_open_fd(struct ksmbd_work *work, struct file *filp)
 	ksmbd_conn_put(fp->conn);
 	ksmbd_share_config_put(fp->share_conf);
 	kmem_cache_free(filp_cache, fp);
+err_fd_limit:
+	fd_limit_close();
 	return ERR_PTR(ret);
 }
 
Signature · 1 line
2.53.0
author maintainer
#2319 lore raw

PATCH 2298/2651 ksmbd: reject foreign RPC pipe handles on IPC$ read and write

In reply to Greg Kroah-Hartman

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

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

From: Mohammed Alquraini <[email protected]>

[ Upstream commit da25995071e5e0f3aa9a41160b00b2f833127b3e ]

RPC pipe handles on IPC$ are allocated from a single server-global IDA, and ksmbd.mountd looks a pipe up by handle alone, with no session information. smb2_read_pipe() and smb2_write_pipe() take the handle straight from the client request (VolatileFileId) and pass it to the daemon without checking that the requesting session opened it. An authenticated user can therefore issue an SMB2 READ or WRITE on IPC$ with another session's handle and receive that session's in-flight DCERPC response, or write attacker-chosen bytes into its pipe stream. A tree connect to IPC$, which every RPC client already has, is the only requirement.

Validate ownership before the transfer, the way the sibling pipe paths already do: under sess->rpc_lock, ksmbd_session_rpc_method() returns 0 for a handle the session did not open. smb2_get_info_file_pipe() and the FSCTL_PIPE_TRANSCEIVE ioctl already reject such handles; read and write were the remaining gap. Reject them with STATUS_FILE_CLOSED, as the ioctl path does.

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
Assisted-by LLM
---
 fs/smb/server/smb2pdu.c | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)
fs/smb/server/smb2pdu.c +20 -0
index 81c8bc5033cdf..8bd0800a48f7e 100644
@@ -8949,6 +8949,16 @@ static noinline int smb2_read_pipe(struct ksmbd_work *work)
 
 	id = req->VolatileFileId;
 
+	lockdep_assert_not_held(&work->sess->rpc_lock);
+	down_read(&work->sess->rpc_lock);
+	if (!ksmbd_session_rpc_method(work->sess, id)) {
+		up_read(&work->sess->rpc_lock);
+		rsp->hdr.Status = STATUS_FILE_CLOSED;
+		smb2_set_err_rsp(work);
+		return -ENOENT;
+	}
+	up_read(&work->sess->rpc_lock);
+
 	rpc_resp = ksmbd_rpc_read(work->sess, id);
 	if (rpc_resp) {
 		void *aux_payload_buf;
@@ -9579,6 +9589,16 @@ static noinline int smb2_write_pipe(struct ksmbd_work *work)
 		goto out;
 	}
 
+	lockdep_assert_not_held(&work->sess->rpc_lock);
+	down_read(&work->sess->rpc_lock);
+	if (!ksmbd_session_rpc_method(work->sess, id)) {
+		up_read(&work->sess->rpc_lock);
+		rsp->hdr.Status = STATUS_FILE_CLOSED;
+		smb2_set_err_rsp(work);
+		return -ENOENT;
+	}
+	up_read(&work->sess->rpc_lock);
+
 	data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
 			   data_offset);
 
Signature · 1 line
2.53.0
author maintainer
#2320 lore raw

PATCH 2299/2651 ksmbd: reject FILE_ATTRIBUTE_TEMPORARY on directories

In reply to Greg Kroah-Hartman

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

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

From: Michail Andreas Michalopoulos <[email protected]>

[ Upstream commit 8323aab48525b83f750e712f66e6e9387b550cf4 ]

Setting FILE_ATTRIBUTE_TEMPORARY on a directory with SMB2 SET_INFO (FileBasicInformation) succeeds: ksmbd keeps the attribute and, with "store dos attributes" enabled, also writes it to the DOS attribute xattr.

MS-FSA (FileBasicInformation) says the request must fail with STATUS_INVALID_PARAMETER when FILE_ATTRIBUTE_TEMPORARY is set on a directory, and Samba rejects it too. smbtorture's smb2.create.dosattr_tmp_dir checks this and fails against ksmbd.

Return -EINVAL, which is sent as STATUS_INVALID_PARAMETER, when a directory is asked to become TEMPORARY. Do the check before any timestamp is changed, so a rejected request leaves the open file and the inode unchanged.

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
Assisted-by LLM
---
 fs/smb/server/smb2pdu.c | 5 +++++
 1 file changed, 5 insertions(+)
fs/smb/server/smb2pdu.c +5 -0
index 8bd0800a48f7e..55aa09a07aed4 100644
@@ -8408,6 +8408,11 @@ static int set_file_basic_info(struct ksmbd_file *fp,
 	inode = file_inode(filp);
 	idmap = file_mnt_idmap(filp);
 
+	/* MS-FSA FileBasicInformation: a directory can't be marked TEMPORARY */
+	if (S_ISDIR(inode->i_mode) &&
+	    (file_info->Attributes & FILE_ATTRIBUTE_TEMPORARY_LE))
+		return -EINVAL;
+
 	if (file_info->CreationTime)
 		fp->create_time = le64_to_cpu(file_info->CreationTime);
 
Signature · 1 line
2.53.0
author maintainer
#2321 lore raw

PATCH 2300/2651 net: pse-pd: si3474: fix use-after-free in ancillary client error path

In reply to Greg Kroah-Hartman

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

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

From: Carlo Szelinsky <[email protected]>

[ Upstream commit 70c29b35fd87f87a7b8dad6eb8d55ce54a0d549a ]

If devm_add_action_or_reset() fails, it has already unregistered the ancillary I2C client, and the error message then reads that client's device. It can only fail with -ENOMEM, which is already reported, so drop the message.

Found by code inspection. Not reproduced.

Fixes a2317231df4b ("net: pse-pd: Add Si3474 PSE controller driver")
---
 drivers/net/pse-pd/si3474.c | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)
drivers/net/pse-pd/si3474.c +1 -3
index 1845b9c51cf7a..2f4f241a48af6 100644
@@ -516,10 +516,8 @@ static int si3474_i2c_probe(struct i2c_client *client)
 		return PTR_ERR(priv->client[1]);
 
 	ret = devm_add_action_or_reset(dev, si3474_ancillary_i2c_remove, priv->client[1]);
-	if (ret < 0) {
-		dev_err(&priv->client[1]->dev, "Cannot register remove callback\n");
+	if (ret)
 		return ret;
-	}
 
 	ret = i2c_smbus_read_byte_data(priv->client[1], VENDOR_IC_ID_REG);
 	if (ret < 0) {
Signature · 1 line
2.53.0
author maintainer
#2322 lore raw

PATCH 2301/2651 net: skbuff: dont copy alloc_cpu in skb header copies

In reply to Greg Kroah-Hartman

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

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

From: Carolina Jubran <[email protected]>

[ Upstream commit 78d4bd22ec9df490135303c00e190ac43d5c334a ]

Commit 68822bdf76f1 ("net: generalize skb freeing deferral to per-cpu lists") added alloc_cpu to struct sk_buff and placed it in the headers group copied by __copy_skb_header().

This is wrong for newly allocated skbs. For example, skb_segment() allocates a new skb and records the current CPU in alloc_cpu, but __copy_skb_header() overwrites it with the value from the original skb.

If the original skb was allocated on another CPU, the segment may later be treated as remotely allocated and unnecessarily deferred there when it is freed.

Move alloc_cpu out of the headers group so it is preserved across header copies. Copy it explicitly in skb_clone(), which allocates the skb object directly instead of going through __alloc_skb().

This was discovered while investigating a throughput regression with software IPsec. The load used 512 IPsec tunnels carrying traffic over VXLAN, with 512 parallel iperf3 flows and an MTU of 4500.

Before the fix:

16.09% queued_spin_lock_slowpath

             |
             --15.90%--_raw_spin_lock_irqsave
                       |
                       --9.37%--__slab_free
                                 kfree
                                 skb_release_data
                                 napi_consume_skb
                                 mlx5e_poll_tx_cq

After the fix:

6.84% queued_spin_lock_slowpath

             |
             --6.57%--_raw_spin_lock_irqsave
                      |
                      --5.00%--__slab_free
                                kfree
                                skb_release_data
                                napi_consume_skb
                                mlx5e_poll_tx_cq
---
 include/linux/skbuff.h | 4 ++--
 net/core/skbuff.c      | 2 +-
 2 files changed, 3 insertions(+), 3 deletions(-)
include/linux/skbuff.h +2 -2
index a3ff380d43f01..d6894f463bf43 100644
@@ -1036,8 +1036,6 @@ struct sk_buff {
 	__u16			tc_index;	/* traffic control index */
 #endif
 
-	u16			alloc_cpu;
-
 	union {
 		__wsum		csum;
 		struct {
@@ -1088,6 +1086,8 @@ struct sk_buff {
 
 	); /* end headers group */
 
+	u16			alloc_cpu;
+
 	/* These elements must be at the end, see alloc_skb() for details.  */
 	sk_buff_data_t		tail;
 	sk_buff_data_t		end;
net/core/skbuff.c +1 -1
index ea4c38dee19f5..0c1229c544d24 100644
@@ -1593,7 +1593,6 @@ static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
 #ifdef CONFIG_NET_RX_BUSY_POLL
 	CHECK_SKB_FIELD(napi_id);
 #endif
-	CHECK_SKB_FIELD(alloc_cpu);
 #ifdef CONFIG_XPS
 	CHECK_SKB_FIELD(sender_cpu);
 #endif
@@ -1625,6 +1624,7 @@ static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb)
 	C(pfmemalloc);
 	C(pp_recycle);
 	n->destructor = NULL;
+	C(alloc_cpu);
 	C(tail);
 	C(end);
 	C(head);
Signature · 1 line
2.53.0