Skip to contentSkip to conversation

5.10.275-rc1 review

PATCH In review Greg Kroah-Hartman 7 participants 1,855 messages Nov 18 – Nov 19 Page 6 of 14

Subsystems (7)
lore
Share & tools
lore
author maintainer
#684 lore raw

PATCH 679/1848 wifi: mac80211: reload TDLS header pointer after skb_linearize()

In reply to Greg Kroah-Hartman

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

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

From: Weigang He <[email protected]>

[ Upstream commit 35c5a5ea4418571997a7e7af3e7e8922b136f6e6 ]

ieee80211_process_tdls_channel_switch() sets tf = skb->data before it calls skb_linearize(), and reads tf->action_code afterwards.

ieee80211_rx_h_data() queues TDLS channel switch requests and responses to the interface after pulling only offsetof(struct ieee80211_tdls_data, u) bytes, so the skb can still be non-linear when the interface work handles it. Drivers that build paged RX skbs do this for every frame that does not fit into the skb head, e.g. iwlwifi (mvm), which is also the only mac80211 driver that sets NL80211_FEATURE_TDLS_CHANNEL_SWITCH. If the remaining data does not fit into the tailroom, skb_linearize() moves the data to a new head and frees the old one, and the action code is then read from freed memory. Depending on what that memory holds by then, the frame is handled as before or ends in the WARN_ON_ONCE() of the default case.

The frame only has to be a data frame with the TDLS ethertype from an authorized peer, e.g. relayed by the AP from another station in the BSS; the read happens before the sender is checked to be a TDLS peer.

Load tf after skb_linearize(), as the request and response handlers already do.

Found by static analysis tool CodeQL.

Fixes 8a4d32f30d11 ("mac80211: add TDLS channel-switch Rx flow")
Assisted-by LLM codeql
---
 net/mac80211/tdls.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
net/mac80211/tdls.c +2 -1
index 66e32f1d0a989..5605903ae7d18 100644
@@ -1924,7 +1924,7 @@ static void
 ieee80211_process_tdls_channel_switch(struct ieee80211_sub_if_data *sdata,
 				      struct sk_buff *skb)
 {
-	struct ieee80211_tdls_data *tf = (void *)skb->data;
+	struct ieee80211_tdls_data *tf;
 	struct wiphy *wiphy = sdata->local->hw.wiphy;
 
 	ASSERT_RTNL();
@@ -1940,6 +1940,7 @@ ieee80211_process_tdls_channel_switch(struct ieee80211_sub_if_data *sdata,
 	 * The packet/size was already validated by mac80211 Rx path, only look
 	 * at the action type.
 	 */
+	tf = (void *)skb->data;
 	switch (tf->action_code) {
 	case WLAN_TDLS_CHANNEL_SWITCH_REQUEST:
 		ieee80211_process_tdls_channel_switch_req(sdata, skb);
Signature · 1 line
2.53.0
author maintainer
#685 lore raw

PATCH 680/1848 wifi: rsi: Skip TX aggregation setup for non-QoS frames

In reply to Greg Kroah-Hartman

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

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

From: Alex Kazinsky <[email protected]>

[ Upstream commit 71f756a4c064b0312f46617c20893ecc17c332e4 ]

When transmitting a non-QoS unicast frame to a station in AP mode, rsi_core_xmit() assigns IEEE80211_NONQOS_TID (16) to tid. The station lookup succeeds, allowing tid to index start_tx_aggr[], which has only IEEE80211_NUM_TIDS (16) elements. This causes an out-of-bounds read and, if the value read is zero, an out-of-bounds write.

Only access the aggregation state for tids below IEEE80211_NUM_TIDS, excluding the non-QoS sentinel from TX aggregation setup.

Found by Linux Verification Center (linuxtesting.org) with SVACE.

Fixes 19844c0a9a19 ("rsi: data and managemet path changes for AP mode")
---
 drivers/net/wireless/rsi/rsi_91x_core.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/wireless/rsi/rsi_91x_core.c +1 -1
index b7fa03813da11..734e006caadb6 100644
@@ -458,7 +458,7 @@ void rsi_core_xmit(struct rsi_common *common, struct sk_buff *skb)
 			tx_params->sta_id = 0;
 		}
 
-		if (rsta) {
+		if (rsta && tid < IEEE80211_NUM_TIDS) {
 			/* Start aggregation if not done for this tid */
 			if (!rsta->start_tx_aggr[tid]) {
 				rsta->start_tx_aggr[tid] = true;
Signature · 1 line
2.53.0
author maintainer
#686 lore raw

PATCH 681/1848 wifi: cfg80211: fix out-of-bounds read in valid_rule()

In reply to Greg Kroah-Hartman

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

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

From: Zijing Yin <[email protected]>

[ Upstream commit 9d8ec0b5b5295bd23d979d1b2b905de25c36fff2 ]

valid_rule() validates a struct fwdb_rule from the regulatory database firmware file, but bounds checks only the first byte of the structure, the length field itself.

It then uses that length, which comes straight out of the file, to decide whether the optional fields are present, and reads rule->wmm_ptr at offset 18 of the 20-byte structure once the length claims 20 bytes or more.

A rule placed in the last bytes of the file therefore makes the parser read up to 19 bytes past the end of the firmware image. The image comes from vmalloc() in kernel_read_file(), so with the rule at the end of a page the read falls into the guard page and oopses, with no memory debugging enabled.

A length of at least offsetofend(max_bw) but below offsetofend(wmm_ptr) takes the other branch, so valid_rule() returns true having read nothing out of bounds, and the database is accepted. regdb_query_country() does not re-check the rule, and reads rule->start, rule->end, rule->max_bw and rule->cac_timeout off the end of the kmemdup()ed copy.

A malformed regulatory.db is parsed by cfg80211's own request_firmware_nowait() at init time, and on demand from user space through NL80211_CMD_RELOAD_REGDB, which needs CAP_NET_ADMIN but no wireless hardware. Both paths require write access to the firmware search path and CONFIG_CFG80211_REQUIRE_SIGNED_REGDB=n.

Bound the whole declared rule, not just its length field. The existing check on sizeof(rule->len) is still needed, since rule->len has to be shown to be inside the file before it can be read, so the new test goes after it. A rule reaching past the end of the file is now rejected, which fails the database rather than reading out of bounds. That also gives regdb_query_country() the bound it already assumes.

Fixes 230ebaa189af ("cfg80211: read wmm rules from regulatory database")
---
 net/wireless/reg.c | 3 +++
 1 file changed, 3 insertions(+)
net/wireless/reg.c +3 -0
index 6ab5d8971d10f..07490c7a25bed 100644
@@ -669,6 +669,9 @@ static bool valid_rule(const u8 *data, unsigned int size, u16 rule_ptr)
 	/* mandatory fields */
 	if (rule->len < offsetofend(struct fwdb_rule, max_bw))
 		return false;
+	/* the rule must lie entirely within the database */
+	if ((u8 *)rule + rule->len > data + size)
+		return false;
 	if (rule->len >= offsetofend(struct fwdb_rule, wmm_ptr)) {
 		u32 wmm_ptr = be16_to_cpu(rule->wmm_ptr) << 2;
 		struct fwdb_wmm_rule *wmm;
Signature · 1 line
2.53.0
author maintainer
#687 lore raw

PATCH 682/1848 drm/vc4: Publish the output fence outside of job_lock

In reply to Greg Kroah-Hartman

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

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

From: Maíra Canal <[email protected]>

[ Upstream commit 9ee552a42c3905b4547e83173d46413137ec329a ]

job_lock is taken by the V3D interrupt handler, so nesting an IRQ-unsafe lock under it creates an inversion. drm_syncobj_replace_fence() takes drm_syncobj::lock, which other paths acquire with interrupts enabled. For example, a thread interrupted while holding it blocks the handler on job_lock, and the handler can only make progress once the submit path releases job_lock, which it cannot do while waiting for drm_syncobj::lock.

This is reported by lockdep:

[  188.139076] ========================================================
[  188.139086] WARNING: possible irq lock inversion dependency detected
[  188.139096] 7.3.0-rc3-00067-gc4f3feeaf60f #67 Tainted: G         C
[  188.139108] --------------------------------------------------------
[  188.139116] swapper/0/0 just changed the state of lock:
[  188.139125] ffff0000054f8ff8 (&vc4->job_lock){-...}-{3:3}, at: vc4_irq+0xa8/0x28c [vc4]
[  188.139234] but this lock took another, HARDIRQ-unsafe lock in the past:
[  188.139242]  (&syncobj->lock){+.+.}-{3:3}
[  188.139256] and interrupts could create inverse lock ordering between them.
[  188.139267] other info that might help us debug this:
[  188.139275]  Possible interrupt unsafe locking scenario:
[  188.139284]        CPU0                    CPU1
[  188.139291]        ----                    ----
[  188.139299]   lock(&syncobj->lock);
[  188.139312]                                local_irq_disable();
[  188.139320]                                lock(&vc4->job_lock);
[  188.139335]                                lock(&syncobj->lock);
[  188.139350]   <Interrupt>
[  188.139358]     lock(&vc4->job_lock);
[  188.139372] *** DEADLOCK ***

Hand the fence over after job_lock is dropped. The job can complete and drop exec->fence in that window, so take a reference first and publish through the local pointer, as exec may already be gone.

---
 drivers/gpu/drm/vc4/vc4_gem.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
drivers/gpu/drm/vc4/vc4_gem.c +9 -1
index 82b413ae11ac9..d46357f73e74f 100644
@@ -689,8 +689,11 @@ vc4_queue_submit(struct drm_device *dev, struct vc4_exec_info *exec,
 	fence->seqno = exec->seqno;
 	exec->fence = &fence->base;
 
+	/* The job can complete and drop exec->fence as soon as job_lock is
+	 * released, so hold our own reference.
+	 */
 	if (out_sync)
-		drm_syncobj_replace_fence(out_sync, exec->fence);
+		dma_fence_get(&fence->base);
 
 	vc4_update_bo_seqnos(exec, seqno);
 
@@ -712,6 +715,11 @@ vc4_queue_submit(struct drm_device *dev, struct vc4_exec_info *exec,
 
 	spin_unlock_irqrestore(&vc4->job_lock, irqflags);
 
+	if (out_sync) {
+		drm_syncobj_replace_fence(out_sync, &fence->base);
+		dma_fence_put(&fence->base);
+	}
+
 	return 0;
 }
 
Signature · 1 line
2.53.0
author maintainer
#688 lore raw

PATCH 683/1848 9p/xen: validate the response size from the backend

In reply to Greg Kroah-Hartman

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

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

From: Yehyeong Lee <[email protected]>

[ Upstream commit 9b4cf60c6b739461c5b4ec9c52587da6b2608786 ]

p9_xen_response() takes the length of an incoming response from the ring -- the first field of the 9p header, which the Xen transport reuses as its framing header -- and uses it to advance the consumer index, but never checks that it is at least the header size or no larger than the number of bytes the backend has actually produced.

A malicious or buggy backend can post a response whose size is smaller than the header (for example 0). The consumer index then never advances, so the response work re-reads the same ring contents instead of making progress. In testing this raced with the teardown that the malformed reply triggers and dereferenced a freed p9_client:

9pfs 9pfs-0: Wrong req tag=ffff

  BUG: kernel NULL pointer dereference, address: 0000000000000060
  #PF: supervisor read access in kernel mode
  #PF: error_code(0x0000) - not-present page
  PGD 0 P4D 0
  Oops: Oops: 0000 [#1] SMP NOPTI
  CPU: 0 UID: 0 PID: 11 Comm: kworker/0:1 Not tainted 7.2.0-rc5 #6 PREEMPT(lazy)
  Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS rel-1.17.0-0-gb52ca86e094d-prebuilt.qemu.org 04/01/2014
  Workqueue: events p9_xen_response
  RIP: 0010:idr_find+0x4/0x10
  RSP: 0018:ffffbf5d80063de8 EFLAGS: 00010202
  RAX: 0000000000000001 RBX: ffffa229c21195a0 RCX: ffffa229c2400000
  RDX: ffffa229c11c2200 RSI: 000000000000ffff RDI: 0000000000000050
  RBP: 000000000000ffff R08: 3fffffffffffdfff R09: ffffffffffffffff
  R10: 3fffffffffffdfff R11: ffffffff87a60e80 R12: 0000000000000050
  R13: 0000000000000000 R14: 000000000000ffff R15: 0000000000100000
  FS:  0000000000000000(0000) GS:ffffa22a7661c000(0000) knlGS:0000000000000000
  CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
  CR2: 0000000000000060 CR3: 000000003ac34002 CR4: 0000000000770ef0
  PKRU: 55555554
  Call Trace:
   <TASK>
   p9_tag_lookup+0x2b/0x90
   p9_xen_response+0x17c/0x2e0
   process_one_work+0x16a/0x3a0
   worker_thread+0x172/0x2e0
   kthread+0xdd/0x110
   ret_from_fork+0x18b/0x240
   ret_from_fork_asm+0x1a/0x30
   </TASK>
  Modules linked in:
  CR2: 0000000000000060
  ---[ end trace 0000000000000000 ]---

Reject a response whose size is outside [sizeof(header), queued] before using it, matching the validation the backend already applies to incoming requests.

Fixes f66c72bea129 ("xen/9pfs: receive responses")

Message-ID: <[email protected]>

---
 net/9p/trans_xen.c | 8 ++++++++
 1 file changed, 8 insertions(+)
net/9p/trans_xen.c +8 -0
index 5ff1892edbf2e..ff81b323ea7b5 100644
@@ -222,6 +222,14 @@ static void p9_xen_response(struct work_struct *work)
 				     masked_prod, &masked_cons,
 				     XEN_9PFS_RING_SIZE(ring));
 
+		if (h.size < sizeof(h) ||
+		    h.size > xen_9pfs_queued(prod, cons,
+					     XEN_9PFS_RING_SIZE(ring))) {
+			dev_warn_ratelimited(&priv->dev->dev,
+					     "bad response size %u from backend\n", h.size);
+			break;
+		}
+
 		req = p9_tag_lookup(priv->client, h.tag);
 		if (!req || req->status != REQ_STATUS_SENT) {
 			dev_warn(&priv->dev->dev, "Wrong req tag=%x\n", h.tag);
Signature · 1 line
2.53.0
author maintainer
#689 lore raw

PATCH 684/1848 9p: dont decrement a server-owned zero nlink

In reply to Greg Kroah-Hartman

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

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

From: Yuanfu Xie <[email protected]>

[ Upstream commit 4e915aa8566173b44146bc46177c85afbe6bdf96 ]

A 9P2000.L server can report nlink=0 for a regular file that still exists. On a cache=loose or cache=fscache mount, lookup stores that value with set_nlink(). A later successful unlink calls v9fs_dec_count(), which still calls drop_nlink() for a non-directory. drop_nlink() warns, and the unsigned link count wraps to 4294967295. fstat() on a descriptor opened before the unlink shows 0 before and 4294967295 after.

The warning on the unpatched kernel, trimmed:

WARNING: fs/inode.c:408 at drop_nlink+0xac/0xd0, CPU#1: trigger/188
CPU: 1 UID: 0 PID: 188 Comm: trigger Tainted: G                 N  7.3.0-rc4-00537-ga3ff15db6820 #1 PREEMPT(lazy)
RIP: 0010:drop_nlink+0xac/0xd0
Call Trace:
 <TASK>
 v9fs_remove+0x529/0x750
 vfs_unlink+0x2f0/0xbd0
 filename_unlinkat+0x340/0x6c0
 __x64_sys_unlink+0x46/0x70
 do_syscall_64+0xe8/0x4f0
 entry_SYSCALL_64_after_hwframe+0x77/0x7f
 </TASK>
---[ end trace 0000000000000000 ]---

Directories whose cached nlink is at most 2 already skip this decrement, because the exported filesystem may not maintain nlink (commit ac89b2ef9b559). cache=none skips it as well (commit 574aa0b479947). cache=mmap does not take this path: it sets neither CACHE_META nor CACHE_LOOSE. A regular file on cache=loose or cache=fscache still does. Its count came from GETATTR and may already be zero, so skip the decrement when i_nlink is already 0.

Verified on 7.3-rc4-00537-ga3ff15db6820 with only this change. A server that advertises nlink=0 and accepts the unlink no longer warns, and the open descriptor stays at nlink 0. An honest server on the same mount still goes from 1 to 0. A rejected unlink leaves the count unchanged. cache=none is unchanged. With panic_on_warn the unpatched kernel panics on the warning; the patched kernel does not.

Fixes ac89b2ef9b559 ("9p: don't maintain dir i_nlink if the exported fs doesn't either")

Message-ID: <[email protected]>

---
 fs/9p/vfs_inode.c | 8 ++++++++
 1 file changed, 8 insertions(+)
fs/9p/vfs_inode.c +8 -0
index 74ecf2c9dcbd9..eb666ac84ea16 100644
@@ -521,6 +521,12 @@ static int v9fs_at_to_dotl_flags(int flags)
  * nothing and races with concurrent metadata fetches that may already
  * have observed the post-unlink value (nlink == 0).
  *
+ * The same applies to a regular file whose cached nlink has already been
+ * driven to zero by the server: in the cached modes the attributes come
+ * from GETATTR and are applied verbatim, so decrementing a link count the
+ * server does not maintain only trips the drop_nlink() WARN_ON and
+ * underflows i_nlink.
+ *
  * @inode: inode whose nlink is being dropped
  */
 static void v9fs_dec_count(struct inode *inode)
@@ -529,6 +535,8 @@ static void v9fs_dec_count(struct inode *inode)
 
 	if (v9ses->cache != CACHE_LOOSE && v9ses->cache != CACHE_FSCACHE)
 		return;
+	if (inode->i_nlink == 0)
+		return;
 	if (!S_ISDIR(inode->i_mode) || inode->i_nlink > 2)
 		drop_nlink(inode);
 }
Signature · 1 line
2.53.0
author maintainer
#690 lore raw

PATCH 685/1848 batman-adv: dat: initialize orig_node of unfilled candidate slots

In reply to Greg Kroah-Hartman

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

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

From: Sven Eckelmann <[email protected]>

[ Upstream commit 4eb19a389d74f06901b4cd6f24b996b2e84eaefc ]

batadv_dat_select_candidates() allocates the candidate array without zeroing it. batadv_choose_next_candidate() marks each slot as BATADV_DAT_CANDIDATE_NOT_FOUND but only sets orig_node when an eligible originator was found. In the following rounds, batadv_is_orig_node_eligible() compares res[j].orig_node of all previous slots against the evaluated originator. For slots without candidates, it reads uninitialized memory.

The orig_node has to be cleared together with the
BATADV_DAT_CANDIDATE_NOT_FOUND type.

Fixes 785ea1144182 ("batman-adv: Distributed ARP Table - create DHT helper functions")
---
 net/batman-adv/distributed-arp-table.c | 1 +
 1 file changed, 1 insertion(+)
net/batman-adv/distributed-arp-table.c +1 -0
index 6ff856a803dd1..a3af95b5f42db 100644
@@ -585,6 +585,7 @@ static void batadv_choose_next_candidate(struct batadv_priv *bat_priv,
 	 * NOT_FOUND
 	 */
 	cands[select].type = BATADV_DAT_CANDIDATE_NOT_FOUND;
+	cands[select].orig_node = NULL;
 
 	/* iterate over the originator list and find the node with the closest
 	 * dat_address which has not been selected yet
Signature · 1 line
2.53.0
author maintainer
#691 lore raw

PATCH 686/1848 batman-adv: fix skb leak when hard_iface is being released

In reply to Greg Kroah-Hartman

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

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

From: Sven Eckelmann <[email protected]>

[ Upstream commit 522e4aece2e96cacbb8a6ae1eec0d4c0dd6f4fed ]

batadv_batman_skb_recv() owns the skb it is given. When the hard_iface refcount already dropped to zero, the function jumped to err_out, which only returned NET_RX_DROP and skipped the kfree_skb() under err_free.

To avoid a leak, free the skb before returning in this case.

Fixes 4fe56e60ac1b ("batman-adv: Check hard_iface refcnt when receiving skb")
---
 net/batman-adv/main.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
net/batman-adv/main.c +4 -3
index c621f638561ef..860194a06e534 100644
@@ -502,8 +502,10 @@ int batadv_batman_skb_recv(struct sk_buff *skb, struct net_device *dev,
 	 * shut down otherwise the packet may trigger de-reference errors
 	 * further down in the receive path.
 	 */
-	if (!kref_get_unless_zero(&hard_iface->refcount))
-		goto err_out;
+	if (!kref_get_unless_zero(&hard_iface->refcount)) {
+		kfree_skb(skb);
+		return NET_RX_DROP;
+	}
 
 	skb = skb_share_check(skb, GFP_ATOMIC);
 
@@ -562,7 +564,6 @@ int batadv_batman_skb_recv(struct sk_buff *skb, struct net_device *dev,
 	kfree_skb(skb);
 err_put:
 	batadv_hardif_put(hard_iface);
-err_out:
 	return NET_RX_DROP;
 }
 
Signature · 1 line
2.53.0
author maintainer
#692 lore raw

PATCH 687/1848 sctp: account for chunk padding in sctp_init_cause()

In reply to Greg Kroah-Hartman

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

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

From: Masafumi Suzuki <[email protected]>

[ Upstream commit ed6c53b27be492643da2017c6f8e2732be5edf1a ]

sctp_init_cause() accepts a chunk when skb_tailroom() can hold the cause header and the payload. sctp_addto_chunk() then writes 0-3 bytes of padding before that header so the chunk stays 4-byte aligned. The check does not include the padding, and the following skb_put() calls skb_over_panic() from softirq.

Count the padding sctp_addto_chunk() is about to write. The cause length on the wire stays the header plus the payload.

Found by LLM inspection, triggered and tested the fix.

Fixes 8914f4bace3f ("sctp: add sctp_make_op_error_limited and reuse inner functions")
---
 net/sctp/sm_make_chunk.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)
net/sctp/sm_make_chunk.c +8 -1
index 3425554931a37..362c314fd48e9 100644
@@ -145,6 +145,7 @@ int sctp_init_cause(struct sctp_chunk *chunk, __be16 cause_code,
 		    size_t paylen)
 {
 	struct sctp_errhdr err;
+	int chunklen, padlen;
 	__u16 len;
 
 	/* Cause code constants are now defined in network order.  */
@@ -152,7 +153,13 @@ int sctp_init_cause(struct sctp_chunk *chunk, __be16 cause_code,
 	len = sizeof(err) + paylen;
 	err.length = htons(len);
 
-	if (skb_tailroom(chunk->skb) < len)
+	/* sctp_addto_chunk() pads the chunk up to a 4-byte boundary before
+	 * appending the cause, so account for that padding here as well.
+	 */
+	chunklen = ntohs(chunk->chunk_hdr->length);
+	padlen = SCTP_PAD4(chunklen) - chunklen;
+
+	if (skb_tailroom(chunk->skb) < padlen + len)
 		return -ENOSPC;
 
 	chunk->subh.err_hdr = sctp_addto_chunk(chunk, sizeof(err), &err);
Signature · 1 line
2.53.0
author maintainer
#693 lore raw

PATCH 688/1848 btrfs: sysfs: restore NOFS context on early return in btrfs_sysfs_add_block_group_type()

In reply to Greg Kroah-Hartman

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

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

From: guolingxing <[email protected]>

[ Upstream commit 4172be965c2ce887ebfb1117c634a68555be8c11 ]

btrfs_sysfs_add_block_group_type() sets up a NOFS context with memalloc_nofs_save() because kobject_add() performs GFP_KERNEL allocations deep in its call chain, and the function may be called while holding a transaction handle or a lock required for a transaction commit, where reclaim could deadlock.

Every other return path of this function calls memalloc_nofs_restore() except the early return taken when another thread has already created the kobject for the same raid index (this can happen when restriping). Taking that path leaves PF_MEMALLOC_NOFS set on the calling task, so all subsequent memory allocations performed by that task remain restricted to the NOFS scope, which may lead to unexpected allocation failures or deadlocks later on.

Restore the NOFS context before returning from that path.

Fixes 49ea112da0e6 ("btrfs: do not create raid sysfs entries under any locks")
---
 fs/btrfs/sysfs.c | 1 +
 1 file changed, 1 insertion(+)
fs/btrfs/sysfs.c +1 -0
index ecf190286377c..6fd7b531705e3 100644
@@ -1151,6 +1151,7 @@ void btrfs_sysfs_add_block_group_type(struct btrfs_block_group *cache)
 	if (space_info->block_group_kobjs[index]) {
 		spin_unlock(&space_info->lock);
 		kobject_put(&rkobj->kobj);
+		memalloc_nofs_restore(nofs_flag);
 		return;
 	} else {
 		space_info->block_group_kobjs[index] = &rkobj->kobj;
Signature · 1 line
2.53.0
author maintainer
#694 lore raw

PATCH 689/1848 scsi: target: Verify the iSCSI ISID is null-terminated

In reply to Greg Kroah-Hartman

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

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

From: Yuanhe Shu <[email protected]>

[ Upstream commit cdf4b87a18cb6a0ee26865cb1b7b5660a491d302 ]

iscsi_parse_pr_out_transport_id() returns the ISID of a FORMAT CODE 01b TransportID as a pointer into the PERSISTENT RESERVE OUT parameter list, lowercased in place and never null-terminated. spc4r37 Table 508 requires the field to be null-terminated, but a non-conforming initiator can omit the NULL; when the ISID ends at the end of the received buffer, the pointer is not a C string.

The registration code still consumes it as one: strcmp() in __core_scsi3_locate_pr_reg() and in the REGISTER AND MOVE path, and snprintf("%s") in __core_scsi3_do_alloc_registration(), which also reads its first 8 bytes unconditionally with get_unaligned_be64() - a NUL check does not bound that read.

When the parameter list spans more than one page, transport_kmap_data_sg() maps it with vmap(), and the over-read walks off the end of the mapping into the vmalloc() guard page and oopses. Reproduced with a PR OUT REGISTER + SPEC_I_PT parameter list of exactly 8192 bytes whose final TransportID carries a 12-byte ISID without a terminating NUL:

  BUG: unable to handle page fault for address: ffffc9000138c000
  RIP: 0010:strcmp+0xc/0x30
  Call Trace:
   __core_scsi3_locate_pr_reg+0xd3/0x120 [target_core_mod]
   core_scsi3_decode_spec_i_port+0x8fc/0x13a0 [target_core_mod]
   core_scsi3_emulate_pro_register+0x73c/0x900 [target_core_mod]
   ...
   iscsi_target_rx_thread+0xef/0x1d0 [iscsi_target_mod]

With a single-page parameter list the buffer is a kmap() direct mapping, so the over-read continues into the physically adjacent page instead of faulting. snprintf("%s") then copies whatever follows the ISID in memory into pr_reg_isid, and PR IN READ FULL STATUS reports the registration back to any initiator, turning the over-read into an info leak of kernel heap contents. Reproduced with a 4096-byte parameter list whose last TransportID ends at the end of the buffer with a 4-byte ISID and no NUL, interleaved with I/O to populate adjacent pages: the READ FULL STATUS response returned the ISID as "0xleak" followed by raw bytes that were not part of the parameter list. The snprintf() into pr_reg_isid[PR_REG_ISID_LEN] caps the echoed ISID at 15 characters, so at most 11 bytes past the buffer are leaked per command, but the PR OUT command is not rate limited.

Any initiator that can send PR OUT to an iSCSI-exported LUN can trigger either variant, including a guest via vhost-scsi.

Require 8 bytes to remain after the ",i,0x" separator, and a NUL inside the rest of the descriptor, before the ISID pointer is returned. REGISTER AND MOVE fails with TCM_INVALID_PARAMETER_LIST; on SPEC_I_PT no target port claims the malformed TransportID, and the command fails the same way.

Fixes d04a179085c2 ("scsi: target: Bound PR-OUT TransportID parsing to the received buffer")
Cc Bryam Vargas <[email protected]>
Cc John Garry <[email protected]>
Assisted-by LLM
Fixes c66ac9db8d4a ("[SCSI] target: Add LIO target core v4.0.0-rc6")
---
 drivers/target/target_core_fabric_lib.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
drivers/target/target_core_fabric_lib.c +10 -0
index 8deadabca8884..be92cd880d207 100644
@@ -370,6 +370,16 @@ static bool iscsi_parse_pr_out_transport_id(
 			pr_err("Missing ISID in iSCSI Initiator port TransportID\n");
 			return false;
 		}
+		/*
+		 * The registration code reads the ISID as a C string,
+		 * and its first 8 bytes with get_unaligned_be64(), so
+		 * require 8 bytes after the separator and a NUL inside
+		 * the rest of the descriptor.
+		 */
+		if (buf + tid_len - p < 8 || !memchr(p, '\0', buf + tid_len - p)) {
+			pr_err("Incomplete or unterminated ISID in iSCSI Initiator port TransportID\n");
+			return false;
+		}
 		*port_nexus_ptr = p;
 		/*
 		 * Go ahead and do the lower case conversion of the received
Signature · 1 line
2.53.0
author maintainer
#695 lore raw

PATCH 690/1848 ALSA: us122l: Add missing NULL check in usb_stream_hwdep_mmap()

In reply to Greg Kroah-Hartman

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

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

From: YuanZhe Liu <[email protected]>

[ Upstream commit f5d3eb483fed59fc0f3b059b8b6a32cedc922360 ]

usb_stream_hwdep_mmap() reads us122l->sk.s and dereferences it without checking for NULL. The stream object is released by usb_stream_free(), which is reached through us122l_stop() both when the device is disconnected and when us122l_start() fails, and it leaves us122l->sk.s set to NULL. The hwdep file stays usable after that, so a later mmap()

	KASAN: null-ptr-deref in range [0x0000000000000010-0x0000000000000017]
	RIP: 0010:usb_stream_hwdep_mmap+0x107/0x890 sound/usb/usx2y/us122l.c:182

crashes while reading s->read_size, which sits at offset 0x10.

That NULL is an expected state for this field: usb_stream_hwdep_vm_fault(), usb_stream_hwdep_poll(), usb_stream_hwdep_ioctl(), usb_stream_stop() and usb_stream_free() all test it before use. Only the mmap callback misses the check, so let it return -ENODEV, matching what the other hwdep mapping in usx2yhwdeppcm.c does when its shared buffer has not been allocated.

Fixes 030a07e441296c372f946cd4065b5d831d8dc40c ("ALSA: Add USB US122L driver")
---
 sound/usb/usx2y/us122l.c | 2 ++
 1 file changed, 2 insertions(+)
sound/usb/usx2y/us122l.c +2 -0
index af92ebaf6e998..0b86dfd5abf9e 100644
@@ -208,6 +208,8 @@ static int usb_stream_hwdep_mmap(struct snd_hwdep *hw,
 	offset = area->vm_pgoff << PAGE_SHIFT;
 	mutex_lock(&us122l->mutex);
 	s = us122l->sk.s;
+	if (!s)
+		return -ENODEV;
 	read = offset < s->read_size;
 	if (read) {
 		if (area->vm_flags & VM_WRITE) {
Signature · 1 line
2.53.0
author maintainer
#696 lore raw

PATCH 691/1848 ALSA: us122l: Fix NULL dereference at hwdep open and release

In reply to Greg Kroah-Hartman

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

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

From: YuanZhe Liu <[email protected]>

[ Upstream commit 820e0050866942b5498488496462d12c6ce1c7a9 ]

usb_stream_hwdep_open() and usb_stream_hwdep_release() pass the result of usb_ifnum_to_if() straight to usb_autopm_get_interface() and usb_autopm_put_interface(), without checking it for NULL.

usb_ifnum_to_if() returns NULL once the device is gone, since usb_disable_device() clears udev->actconfig on disconnect. The hwdep file can outlive the disconnect: the card is released with snd_card_free_when_closed(), so a process that keeps the character device open reaches the driver's release callback after the USB configuration has been dropped, and interface_to_usbdev() then dereferences the NULL interface at offsetof(struct device, parent). The open callback has the same problem when it races with the disconnect.

Check both lookups and fail the open with -ENODEV; in release, skip the runtime PM put when the interface is already gone and still run the rest of the per-file cleanup. Move the us122l->first bookkeeping after the checks so that a failed open no longer leaves a stale file pointer behind.

---
 sound/usb/usx2y/us122l.c | 25 +++++++++++++++++--------
 1 file changed, 17 insertions(+), 8 deletions(-)
sound/usb/usx2y/us122l.c +17 -8
index 0b86dfd5abf9e..ef837d5d8fa04 100644
@@ -153,20 +153,27 @@ static const struct vm_operations_struct usb_stream_hwdep_vm_ops = {
 static int usb_stream_hwdep_open(struct snd_hwdep *hw, struct file *file)
 {
 	struct us122l	*us122l = hw->private_data;
-	struct usb_interface *iface;
+	struct usb_interface *iface, *iface0 = NULL;
 
 	snd_printdd(KERN_DEBUG "%p %p\n", hw, file);
 	if (hw->used >= 2)
 		return -EBUSY;
 
-	if (!us122l->first)
-		us122l->first = file;
-
 	if (us122l->is_us144) {
-		iface = usb_ifnum_to_if(us122l->dev, 0);
-		usb_autopm_get_interface(iface);
+		iface0 = usb_ifnum_to_if(us122l->dev, 0);
+		if (!iface0)
+			return -ENODEV;
 	}
+
 	iface = usb_ifnum_to_if(us122l->dev, 1);
+	if (!iface)
+		return -ENODEV;
+
+	if (!us122l->first)
+		us122l->first = file;
+
+	if (iface0)
+		usb_autopm_get_interface(iface0);
 	usb_autopm_get_interface(iface);
 	return 0;
 }
@@ -180,10 +187,12 @@ static int usb_stream_hwdep_release(struct snd_hwdep *hw, struct file *file)
 
 	if (us122l->is_us144) {
 		iface = usb_ifnum_to_if(us122l->dev, 0);
-		usb_autopm_put_interface(iface);
+		if (iface)
+			usb_autopm_put_interface(iface);
 	}
 	iface = usb_ifnum_to_if(us122l->dev, 1);
-	usb_autopm_put_interface(iface);
+	if (iface)
+		usb_autopm_put_interface(iface);
 	if (us122l->first == file)
 		us122l->first = NULL;
 	mutex_lock(&us122l->mutex);
Signature · 1 line
2.53.0
author maintainer
#697 lore raw

PATCH 692/1848 ALSA: usx2y: Initialize idle URBs before submitting streams

In reply to Greg Kroah-Hartman

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

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

From: YuanZhe Liu <[email protected]>

[ Upstream commit ceb0d8c22473933099b46cec70639d0f1f7c68ad ]

usb_stream_start() submits the first two capture and playback URBs and only afterwards assigns sk->idle_inurb, sk->idle_outurb, sk->completed_inurb and sk->completed_outurb to the remaining two URBs of each direction.

A transfer can complete as soon as usb_submit_urb() has been called, so the completion handler i_capture_start() or i_playback_start() may run before those pointers are set. While the stream is still being synchronized (state below usb_stream_sync1), stream_start() then calls playback_prep_freqn(sk, sk->idle_outurb) with sk->idle_outurb still NULL, and the packet descriptors are written through that NULL pointer:

  Oops: general protection fault, probably for non-canonical address
  0xdffffc0000000018: 0000 [#1] SMP KASAN
  KASAN: null-ptr-deref in range [0x00000000000000c0-0x00000000000000c7]
  RIP: 0010:playback_prep_freqn+0x11c/0x4a0 sound/usb/usx2y/usb_stream.c:33
  Call Trace:
   <IRQ>
   stream_start+0x5dc/0x8d0 sound/usb/usx2y/usb_stream.c:596
   i_capture_start+0x3da/0x710 sound/usb/usx2y/usb_stream.c:654
   __usb_hcd_giveback_urb+0x238/0x550 drivers/usb/core/hcd.c:1657
   usb_giveback_urb_bh+0x20b/0x530 drivers/usb/core/hcd.c:1691
   tasklet_hi_action+0xa/0x20 kernel/softirq.c:994
   handle_softirqs+0x16f/0x440 kernel/softirq.c:645
   </IRQ>

The four URBs referenced by these pointers are allocated long before and do not depend on any transfer state, so assign them before the submit loop. Keeping the assignment inside the retry path also restores a well-defined URB rotation when the start frame mismatch handling kills and resubmits the streams.

Fixes 030a07e441296c372f946cd4065b5d831d8dc40c ("ALSA: Add USB US122L driver")
---
 sound/usb/usx2y/usb_stream.c | 9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)
sound/usb/usx2y/usb_stream.c +4 -5
index 9d0e44793896f..992eec233675d 100644
@@ -687,6 +687,10 @@ int usb_stream_start(struct usb_stream_kernel *sk)
 	s->sync_packet = -1;
 	s->inpacket_head = -1;
 	sk->iso_frame_balance = 0;
+	sk->idle_inurb = sk->inurb[USB_STREAM_NURBS - 2];
+	sk->idle_outurb = sk->outurb[USB_STREAM_NURBS - 2];
+	sk->completed_inurb = sk->inurb[USB_STREAM_NURBS - 1];
+	sk->completed_outurb = sk->outurb[USB_STREAM_NURBS - 1];
 	++try;
 	for (u = 0; u < 2; u++) {
 		struct urb *inurb = sk->inurb[u];
@@ -745,11 +749,6 @@ int usb_stream_start(struct usb_stream_kernel *sk)
 		return -EFAULT;
 	}
 
-	sk->idle_inurb = sk->inurb[USB_STREAM_NURBS - 2];
-	sk->idle_outurb = sk->outurb[USB_STREAM_NURBS - 2];
-	sk->completed_inurb = sk->inurb[USB_STREAM_NURBS - 1];
-	sk->completed_outurb = sk->outurb[USB_STREAM_NURBS - 1];
-
 /* wait, check */
 	{
 		int wait_ms = 3000;
Signature · 1 line
2.53.0
author maintainer
#698 lore raw

PATCH 693/1848 bpf: Fix skb_pull() BUG in __bpf_redirect_neigh()

In reply to Greg Kroah-Hartman

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

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

From: Jamal Hadi Salim <[email protected]>

[ Upstream commit 23503acb214cbefaf3945d05ab9667ff11ae3de9 ]

The issue:
This is a follow-up to the short link-layer header fixes from Eric. After vlan pop_eth, a privileged SCHED_ACT BPF program can call bpf_skb_change_head(skb, 1, 0) and then bpf_redirect_neigh().

__bpf_redirect_neigh() calls skb_pull(skb, sizeof(*ethh)) after checking only that mac_header < network_header. Nothing verifies that the MAC header is long enough, that it is linear, or that the IP header the redirect goes on to read is linear either.

A SCHED_ACT BPF program can do:

    bpf_skb_change_head(skb, 1, 0);
    bpf_redirect_neigh(lo, NULL, 0, 0);

after vlan pop_eth. The skb then has mac_len == 1 and only one byte of linear data; skb_pull(ETH_HLEN) trips the skb->len < skb->data_len BUG in __skb_pull():

kernel BUG at ./include/linux/skbuff.h:2839!
RIP: skb_pull+0x40/0x50
Call Trace: skb_do_redirect -> packet_xmit -> packet_sendmsg Kernel panic - not syncing: Fatal exception in interrupt

The v4 and v6 paths read ip_hdr() and ipv6_hdr() as soon as the MAC header is gone. On the AF_PACKET frame below that leaves headlen == 0 after the pull, so the network header sits at skb->tail and the route lookup reads ip4h->protocol, ip4h->saddr and ip4h->daddr past the linear area.

The Fix:
Use skb_network_offset(), which is the MAC header span, instead of skb->mac_len. mac_len is zero for locally generated tc egress and netkit packets, while the span still rejects the one-byte header produced by pop_eth + bpf_skb_change_head(skb, 1, 0). The single check also covers the mac_header >= network_header test it replaces.

Use pskb_may_pull() to make the Ethernet header linear before it is read or pulled, and to make the IP header linear in both the v4 and the v6 path before ip_hdr()/ipv6_hdr() is read. The header pointers are taken after the pull, since pskb_may_pull() may reallocate skb->head.

Conditions to recreate the bug:
On x86-64 with 4 KiB pages, enable CONFIG_PACKET, CONFIG_BPF_SYSCALL, CONFIG_NET_SCH_INGRESS, CONFIG_NET_CLS_MATCHALL, CONFIG_NET_ACT_VLAN and CONFIG_NET_ACT_BPF. Run as root with BPF loading, network administration and raw-packet privileges. Bring lo up and attach a SCHED_ACT program that calls bpf_skb_change_head(skb, 1, 0), then returns bpf_redirect_neigh(skb->ifindex, NULL, 0, 0):

ip link set lo up
tc qdisc add dev lo clsact
tc filter add dev lo egress matchall action vlan pop_eth pipe \
action bpf object-file neigh_chghead.o section action

Send an untagged ETH_P_IP frame of ETH_HLEN + 8192 bytes through an AF_PACKET/SOCK_RAW socket bound to lo, without PACKET_VNET_HDR or PACKET_QDISC_BYPASS. Use a unicast destination MAC. The sender's skb has a 14-byte linear Ethernet prefix and a fragmented payload; pop_eth removes that prefix and change_head restores only one linear byte. The unfixed neighbor redirect then tries to pull 14 bytes and BUGs.

Sending the same frame without pop_eth and change_head leaves the IP header in the frags, which is the route lookup reading past skb->tail.

---
 net/core/filter.c | 21 ++++++++++++++-------
 1 file changed, 14 insertions(+), 7 deletions(-)
net/core/filter.c +14 -7
index 1fc7affeb981d..1630692179566 100644
@@ -2257,9 +2257,13 @@ static int bpf_out_neigh_v6(struct net *net, struct sk_buff *skb,
 static int __bpf_redirect_neigh_v6(struct sk_buff *skb, struct net_device *dev,
 				   struct bpf_nh_params *nh)
 {
-	const struct ipv6hdr *ip6h = ipv6_hdr(skb);
 	struct net *net = dev_net(dev);
 	int err, ret = NET_XMIT_DROP;
+	const struct ipv6hdr *ip6h;
+
+	if (unlikely(!pskb_may_pull(skb, sizeof(*ip6h))))
+		goto out_drop;
+	ip6h = ipv6_hdr(skb);
 
 	if (!nh) {
 		struct dst_entry *dst;
@@ -2369,9 +2373,13 @@ static int bpf_out_neigh_v4(struct net *net, struct sk_buff *skb,
 static int __bpf_redirect_neigh_v4(struct sk_buff *skb, struct net_device *dev,
 				   struct bpf_nh_params *nh)
 {
-	const struct iphdr *ip4h = ip_hdr(skb);
 	struct net *net = dev_net(dev);
 	int err, ret = NET_XMIT_DROP;
+	const struct iphdr *ip4h;
+
+	if (unlikely(!pskb_may_pull(skb, sizeof(*ip4h))))
+		goto out_drop;
+	ip4h = ip_hdr(skb);
 
 	if (!nh) {
 		struct flowi4 fl4 = {
@@ -2421,15 +2429,14 @@ static int __bpf_redirect_neigh_v4(struct sk_buff *skb, struct net_device *dev,
 static int __bpf_redirect_neigh(struct sk_buff *skb, struct net_device *dev,
 				struct bpf_nh_params *nh)
 {
-	struct ethhdr *ethh = eth_hdr(skb);
-
-	if (unlikely(skb->mac_header >= skb->network_header))
+	if (unlikely(skb_network_offset(skb) < ETH_HLEN ||
+		     !pskb_may_pull(skb, ETH_HLEN)))
 		goto out;
 	bpf_push_mac_rcsum(skb);
-	if (is_multicast_ether_addr(ethh->h_dest))
+	if (is_multicast_ether_addr(eth_hdr(skb)->h_dest))
 		goto out;
 
-	skb_pull(skb, sizeof(*ethh));
+	skb_pull(skb, ETH_HLEN);
 	skb_unset_mac_header(skb);
 	skb_reset_network_header(skb);
 
Signature · 1 line
2.53.0
author maintainer
#699 lore raw

PATCH 694/1848 drm/i915/gem: Reset err for each fence entry

In reply to Greg Kroah-Hartman

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

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

From: Lu Yao <[email protected]>

[ Upstream commit 31643dc89818d9b65bf42ecb1c67c99b64146fba ]

If dma_fence_chain_find_seqno() failed once, 'err' will store val in the following loop. May causing returns '-EINVAL' even though that entry never called dma_fence_chain_find_seqno() at all.

Fixes 13149e8bafc4 ("drm/i915: add syncobj timeline support")
Cc <[email protected]> # v5.10+
(cherry picked from commit 4e9db08db75f55c920986ac929cfd82a4ee99f41)
---
 drivers/gpu/drm/i915/gem/i915_gem_execbuffer.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpu/drm/i915/gem/i915_gem_execbuffer.c +1 -1
index 031c77fec1a08..177e3f734239d 100644
@@ -2685,7 +2685,6 @@ add_timeline_fence_array(struct i915_execbuffer *eb,
 	u64 __user *user_values;
 	struct eb_fence *f;
 	u64 nfences;
-	int err = 0;
 
 	nfences = timeline_fences->fence_count;
 	if (!nfences)
@@ -2723,6 +2722,7 @@ add_timeline_fence_array(struct i915_execbuffer *eb,
 		struct drm_syncobj *syncobj;
 		struct dma_fence *fence = NULL;
 		u64 point;
+		int err = 0;
 
 		if (__copy_from_user(&user_fence,
 				     user_fences++,
Signature · 1 line
2.53.0
author maintainer
#700 lore raw

PATCH 695/1848 mm/mempolicy: charge shared policy nodes

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

[ Upstream commit 68b2aa37afa390f08de13bc0bac61a9ded3318bc ]

Any local user can bypass memory.max with mbind() on a tmpfs file, and allocate unbounded kernel memory.

mbind() sets a NUMA memory policy for a range of a mapping. If the mapping is of a shmem and friends, the kernel also stores the policy on the inode, in a tree with one entry per range of the file.

Each mbind() on a single page of a mapping can add one shared policy node (struct sp_node) and one struct mempolicy to that tree. They outlive the mapping and stay around until the inode is destroyed. The tree is not bounded by the file size, so the file can be empty.

Memory that user space can allocate must be charged to a memory cgroup. A slab cache does that for all of its objects if it is created with SLAB_ACCOUNT. numa_policy_init() creates the slab caches for both structs without SLAB_ACCOUNT, so they are not charged to any cgroup.

Reproduced with mbind() on single pages of an empty tmpfs file, from a cgroup with memory.max=8M: the global OOM killer killed tasks owned by root, and the machine panicked.

Fix this by creating both caches with SLAB_ACCOUNT. This change implies that mbind() can now fail when running into memcg limits. Further, the policy_cache also serves task and VMA policies, so they are similarly accounted now.

Note that per-file limits are not really helpful, as the user could simply use many files; having limits per user is tricky as well.

Fix generated by an LLM and submitted by Chris Mason in private.

---
 mm/mempolicy.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
mm/mempolicy.c +2 -2
index 6c98585f20dfe..c6c5682c334b0 100644
@@ -2788,11 +2788,11 @@ void __init numa_policy_init(void)
 
 	policy_cache = kmem_cache_create("numa_policy",
 					 sizeof(struct mempolicy),
-					 0, SLAB_PANIC, NULL);
+					 0, SLAB_PANIC | SLAB_ACCOUNT, NULL);
 
 	sn_cache = kmem_cache_create("shared_policy_node",
 				     sizeof(struct sp_node),
-				     0, SLAB_PANIC, NULL);
+				     0, SLAB_PANIC | SLAB_ACCOUNT, NULL);
 
 	for_each_node(nid) {
 		preferred_node_policy[nid] = (struct mempolicy) {
Signature · 1 line
2.53.0
author maintainer
#701 lore raw

PATCH 696/1848 mm/memfd: make f_pos accesses atomic

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 5426cd43a4d28f1041c9ca45955121b921f29548 ]

Commit 9c225f2655e3 ("vfs: atomic f_pos accesses as per POSIX") made read(), write() and lseek() on a shared open file description of a regular file serialize on ->f_pos_lock. The flag that asks for it, FMODE_ATOMIC_POS, is set in do_dentry_open(). A memfd is a regular file too, but its struct file comes from alloc_file_pseudo() and never passes through do_dentry_open(), so it does not get the flag:

CPU0 CPU1
write(memfd, "a", 1) write(memfd, "b", 1)

    pos = file->f_pos  (= 0)
                                        pos = file->f_pos  (= 0)
    vfs_write(..., &pos)
                                        vfs_write(..., &pos)
    file->f_pos = pos  (= 1)
                                        file->f_pos = pos  (= 1)

One of the two bytes is overwritten. Two threads writing 100000 bytes each, one at a time, to a memfd end up with a file that is far shorter than 200000 bytes, while the same program on a tmpfs file never loses a byte.

Set the flag when the memfd is created. As for any other regular file the lock is only taken if the file is reachable in more than one way, and nothing a memfd does in read or write waits for another operation on the same file. This cannot be done for all alloc_file_pseudo() files: anon inode files such as eventfd are S_IFREG as well, and a blocked read holding ->f_pos_lock would lock out the write that is supposed to wake it.

Fix generated by an LLM and sent by Josef Bacik in private.

---
 mm/memfd.c | 2 ++
 1 file changed, 2 insertions(+)
mm/memfd.c +2 -0
index 8ce796ca5bfa4..a0a0233cadeb4 100644
@@ -326,6 +326,8 @@ SYSCALL_DEFINE2(memfd_create,
 		goto err_fd;
 	}
 	file->f_mode |= FMODE_LSEEK | FMODE_PREAD | FMODE_PWRITE;
+	/* a regular file like any other: POSIX.1-2008/SUSv4 Section XSI 2.9.7 */
+	file->f_mode |= FMODE_ATOMIC_POS;
 	file->f_flags |= O_LARGEFILE;
 
 	if (flags & MFD_ALLOW_SEALING) {
Signature · 1 line
2.53.0
author maintainer
#702 lore raw

PATCH 697/1848 drm/v3d: Initialize timedout_batches when running a CSD job

In reply to Greg Kroah-Hartman

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

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

From: Jose Maria Casanova Crespo <[email protected]>

[ Upstream commit 0afdbdd5b1af729108de8f893d179c3b99eac29d ]

v3d_csd_job_timedout() decides whether a compute job made progress by comparing CSD_CURRENT_CFG4, the number of batches the dispatcher still has to start, against the value saved at the previous timeout. That saved value is never initialized, so it is zero on the first timeout.

On V3D 7.1.6 and later, CFG4 counts down to zero once the dispatcher has started the last batch, but the dispatch keeps running until the batches in flight complete. If the first timeout fires in that window, the handler sees no change and resets the GPU while the job is about to complete. For example, this happens with long dispatches that only keep a single supergroup in flight.

Initialize timedout_batches to the value programmed in CFG4 when the job is started. The register does not return to it once a batch has started:
it counts down to zero on V3D 7.1.6 and later (CFG4 holds the number of batches), and to 0xffffffff on V3D 4.2 (CFG4 holds the number of batches minus one).

---
 drivers/gpu/drm/v3d/v3d_sched.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/gpu/drm/v3d/v3d_sched.c +2 -0
index 310fefac46c2a..badc39d6f6210 100644
@@ -245,6 +245,8 @@ v3d_csd_job_run(struct drm_sched_job *sched_job)
 		dma_fence_put(job->base.irq_fence);
 	job->base.irq_fence = dma_fence_get(fence);
 
+	job->timedout_batches = job->args.cfg[4];
+
 	trace_v3d_submit_csd(dev, to_v3d_fence(fence)->seqno);
 
 	for (i = 1; i <= 6; i++)
Signature · 1 line
2.53.0
author maintainer
#703 lore raw

PATCH 698/1848 vringh: bound top-level re-entry into indirect tables

In reply to Greg Kroah-Hartman

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

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

From: Fang Xieyan <[email protected]>

[ Upstream commit f898439ace7f89922e853b43bcbfcd26ea2e0a98 ]

In __vringh_iov(), the F_INDIRECT branch descends into the indirect table and continues before the descriptor accounting runs. A top-level indirect descriptor is therefore never charged to count. If such a descriptor sets NEXT to point back at itself, returning from the indirect table resumes at the same top-level descriptor, which is again not counted, so the walk never makes forward progress.

Because count stays flat and indirect_count is reset to 0 on every return to the top-level table, neither bound in the loop check trips. A guest can spin the vringh worker at 100% CPU inside __vringh_iov(), an uninterruptible host DoS.

Move the descriptor accounting above the indirect switch so that a top-level indirect descriptor is charged one top-level traversal step before the walk descends into its table, bringing this re-entry under the existing vrh->vring.num bound. Each top-level descriptor is still charged at most one step and indirect_count still bounds a single table, so legitimate chains (including the multiple-indirect case in tools/virtio/vringh_test.c) stay within vring.num, while a cyclic indirect descriptor is now rejected with -ELOOP.

Fixes dbd29e075228 ("vringh: Fix loop descriptors check in the indirect cases")
Cc Xie Yongji <[email protected]>
Assisted-by Hawkeye:GLM-5.3-flash
Assisted-by Qoder:Qwen3.8-Max

Message-ID: <[email protected]>

---
 drivers/vhost/vringh.c | 22 +++++++++++-----------
 1 file changed, 11 insertions(+), 11 deletions(-)
drivers/vhost/vringh.c +11 -11
index 61fcef5a3b031..ba2c680b940a1 100644
@@ -306,6 +306,17 @@ __vringh_iov(struct vringh *vrh, u16 i,
 		if (unlikely(err))
 			goto fail;
 
+		if (up_next == -1)
+			count++;
+		else
+			indirect_count++;
+
+		if (count > vrh->vring.num || indirect_count > desc_max) {
+			vringh_bad("Descriptor loop in %p", descs);
+			err = -ELOOP;
+			goto fail;
+		}
+
 		if (unlikely(desc.flags &
 			     cpu_to_vringh16(vrh, VRING_DESC_F_INDIRECT))) {
 			u64 a = vringh64_to_cpu(vrh, desc.addr);
@@ -331,17 +342,6 @@ __vringh_iov(struct vringh *vrh, u16 i,
 			continue;
 		}
 
-		if (up_next == -1)
-			count++;
-		else
-			indirect_count++;
-
-		if (count > vrh->vring.num || indirect_count > desc_max) {
-			vringh_bad("Descriptor loop in %p", descs);
-			err = -ELOOP;
-			goto fail;
-		}
-
 		if (desc.flags & cpu_to_vringh16(vrh, VRING_DESC_F_WRITE))
 			iov = wiov;
 		else {
Signature · 1 line
2.53.0
author maintainer
#704 lore raw

PATCH 699/1848 vringh: reject empty / undersized indirect descriptor tables

In reply to Greg Kroah-Hartman

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

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

From: Fang Xieyan <[email protected]>

[ Upstream commit 60a792b97933a686316737838cd007d27963011e ]

move_to_indirect() validates an indirect descriptor table only with "len % sizeof(struct vring_desc)". A descriptor flagged VRING_DESC_F_INDIRECT with len == 0 passes that test, so *desc_max is set to 0 while *descs points at the empty table. __vringh_iov() then copies one struct vring_desc from descs[0] -- 16 bytes past the end of the table -- before the "indirect_count > desc_max" loop detection aborts the walk. The over-read value is discarded when the walk aborts and is never used to map anything, but the access itself is out of bounds.

Reject any len smaller than one descriptor, alongside the existing stride check, so an empty table is refused with -EINVAL and no descriptor is ever fetched from it.

Fixes f87d0fbb5798 ("vringh: host-side implementation of virtio rings.")
Assisted-by Hawkeye:GLM-5.3-flash
Assisted-by Qoder:Qwen3.8-Max

Message-ID: <[email protected]>

---
 drivers/vhost/vringh.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/vhost/vringh.c +3 -2
index ba2c680b940a1..d7096bd8e4c8d 100644
@@ -170,8 +170,9 @@ static int move_to_indirect(const struct vringh *vrh,
 	}
 
 	len = vringh32_to_cpu(vrh, desc->len);
-	if (unlikely(len % sizeof(struct vring_desc))) {
-		vringh_bad("Strange indirect len %u", desc->len);
+	if (unlikely(len < sizeof(struct vring_desc) ||
+		     len % sizeof(struct vring_desc))) {
+		vringh_bad("Invalid indirect len %u", desc->len);
 		return -EINVAL;
 	}
 
Signature · 1 line
2.53.0
author maintainer
#705 lore raw

PATCH 700/1848 hwmon: (corsair-cpro) Cache fan target only after a successful command

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit e2c26431b4e47892378582a414b4bbaa9edf1798 ]

set_target() updates the cached fan target before sending the command. If the command fails, subsequent fanN_target reads report the failed request instead of the previous value. For example, after successfully setting 1200 RPM, a rejected request for 1800 RPM returns an error but leaves fanN_target reporting 1800. A failed request also replaces -ENODATA when no target has been successfully set.

Update the target cache under the existing mutex only after send_usb_cmd() succeeds, as set_pwm() already does when invalidating the target. Preserve the previous cached value and return the original error on failure.

---
 drivers/hwmon/corsair-cpro.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/hwmon/corsair-cpro.c +2 -1
index 05bf1bbdc4c0a..06b48599fa660 100644
@@ -208,10 +208,11 @@ static int set_target(struct ccp_device *ccp, int channel, long val)
 	int ret;
 
 	val = clamp_val(val, 0, 0xFFFF);
-	ccp->target[channel] = val;
 
 	mutex_lock(&ccp->mutex);
 	ret = send_usb_cmd(ccp, CTL_SET_FAN_TARGET, channel, val >> 8, val);
+	if (!ret)
+		ccp->target[channel] = val;
 
 	mutex_unlock(&ccp->mutex);
 	return ret;
Signature · 1 line
2.53.0
author maintainer
#706 lore raw

PATCH 701/1848 hwmon: (lm87) Fix drvdata type confusion in vrm_show() and vrm_store()

In reply to Greg Kroah-Hartman

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

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

From: Guenter Roeck <[email protected]>

[ Upstream commit 5b51ff0887b9f88d042b92dd07fcdda4132f0ebc ]

When an LM87 or ADM1024 device is probed with VID support enabled, reading from or writing to the vrm sysfs attribute triggers a driver data type confusion in vrm_show() and vrm_store() in drivers/hwmon/lm87.c.

In lm87_probe(), the driver stores the struct lm87_data pointer on the I2C client via i2c_set_clientdata() and passes the struct i2c_client pointer as the drvdata argument to devm_hwmon_device_register_with_groups(), which attaches the attribute groups to the registered hwmon device with client as its driver_data. Unlike the other sysfs callbacks that retrieve client via dev_get_drvdata() and then obtain data via i2c_get_clientdata(), vrm_show() and vrm_store() assign dev_get_drvdata(dev) directly to struct lm87_data *. Dereferencing data->vrm therefore accesses the struct i2c_client instance at offsetof(struct lm87_data, vrm), causing vrm_show() to leak an unrelated byte from struct i2c_client to userspace and vrm_store() to corrupt a byte within struct i2c_client while failing to update the actual VRM value.

Fix the problem by assigning the return value from dev_get_drvdata(dev) to struct i2c_client *client and using i2c_get_clientdata() to get the actual client data.

Fixes 00a0c905ab4b ("hwmon: (lm87) Use hwmon to create the sysfs groups")
---
 drivers/hwmon/lm87.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
drivers/hwmon/lm87.c +5 -2
index b2d820125bb67..4c88e866fdd6f 100644
@@ -600,13 +600,16 @@ static DEVICE_ATTR_RO(cpu0_vid);
 static ssize_t vrm_show(struct device *dev, struct device_attribute *attr,
 			char *buf)
 {
-	struct lm87_data *data = dev_get_drvdata(dev);
+	struct i2c_client *client = dev_get_drvdata(dev);
+	struct lm87_data *data = i2c_get_clientdata(client);
+
 	return sprintf(buf, "%d\n", data->vrm);
 }
 static ssize_t vrm_store(struct device *dev, struct device_attribute *attr,
 			 const char *buf, size_t count)
 {
-	struct lm87_data *data = dev_get_drvdata(dev);
+	struct i2c_client *client = dev_get_drvdata(dev);
+	struct lm87_data *data = i2c_get_clientdata(client);
 	unsigned long val;
 	int err;
 
Signature · 1 line
2.53.0
author maintainer
#707 lore raw

PATCH 702/1848 hwmon: (nct6683) Fix incorrect struct cast in show_pwm() and store_pwm()

In reply to Greg Kroah-Hartman

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

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

From: Guenter Roeck <[email protected]>

[ Upstream commit c4a01c2a80b203ab5f80885f6994346fe217f19c ]

On big-endian architectures, reading or writing the pwm[1-8] sysfs attributes in the nct6683 hardware monitoring driver always redirects to channel 0 due to an incorrect struct downcast in show_pwm() and store_pwm().
The driver defines the PWM sysfs attributes using SENSOR_TEMPLATE(), which initializes them as struct sensor_device_attribute (where the index is a 32-bit int). However, the sysfs callbacks show_pwm() and store_pwm() incorrectly downcast the attribute to a struct sensor_device_attribute_2 (where the index is an 8-bit u8). Because both structs start with struct device_attribute, container_of() resolves to the same base address. On big-endian architectures, reading the 8-bit index field from the memory layout of a 32-bit int fetches the most significant byte (which is 0), rather than the intended channel number.
This type mismatch causes all PWM reads to return data for channel 0, and any writes intended to configure other channels will silently overwrite the duty cycle of PWM channel 0 instead.

Fix the type casts in show_pwm() and store_pwm() to solve the problem.

Fixes 41082d66bfd6 ("hwmon: Driver for NCT6683D")
---
 drivers/hwmon/nct6683.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/hwmon/nct6683.c +2 -2
index 2d299149f4d25..cdd45a5752a0f 100644
@@ -911,7 +911,7 @@ static ssize_t
 show_pwm(struct device *dev, struct device_attribute *attr, char *buf)
 {
 	struct nct6683_data *data = nct6683_update_device(dev);
-	struct sensor_device_attribute_2 *sattr = to_sensor_dev_attr_2(attr);
+	struct sensor_device_attribute *sattr = to_sensor_dev_attr(attr);
 	int index = sattr->index;
 
 	return sprintf(buf, "%d\n", data->pwm[index]);
@@ -921,7 +921,7 @@ static ssize_t
 store_pwm(struct device *dev, struct device_attribute *attr, const char *buf,
 	  size_t count)
 {
-	struct sensor_device_attribute_2 *sattr = to_sensor_dev_attr_2(attr);
+	struct sensor_device_attribute *sattr = to_sensor_dev_attr(attr);
 	struct nct6683_data *data = dev_get_drvdata(dev);
 	int index = sattr->index;
 	unsigned long val;
Signature · 1 line
2.53.0
author maintainer
#708 lore raw

PATCH 703/1848 KVM: x86/mmu: Conditionally resched when retrying gPTE walk on A/D update failure

In reply to Greg Kroah-Hartman

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

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

From: Sean Christopherson <[email protected]>

[ Upstream commit b2691b3a6cd230209736c89684dab90d939aa56b ]

Conditionally reschedule when retrying a guest PTE walk because the CMPXCHG to update A/D bits failed, e.g. because a different task/vCPU modified the relevant gPTEs. On kernels without involuntary preemption of some kind, a misbehaving guest can "capture" a pCPU effectively indefinitely and trigger soft lockups by continuously modifying its gPTEs such that the result of the walk is remains valid.

Fixes b3e4e63fd9ee ("KVM: MMU: Use cmpxchg for pte updates on walk_addr()")

Message-ID: <[email protected]>

---
 arch/x86/kvm/mmu/paging_tmpl.h | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)
arch/x86/kvm/mmu/paging_tmpl.h +10 -1
index c6daeeff1d9c9..3778070381a8b 100644
@@ -327,6 +327,13 @@ static int FNAME(walk_addr_generic)(struct guest_walker *walker,
 	gpa_t real_gpa;
 	gfn_t gfn;
 
+	/*
+	 * KVM might sleep/resched when retrying the walk if the updating A/D
+	 * fails because the gPTE changed between reading the gPTE and trying
+	 * the CMPXHG to set A/D bits.
+	 */
+	might_sleep();
+
 	trace_kvm_mmu_pagetable_walk(addr, access);
 retry_walk:
 	walker->level = mmu->root_level;
@@ -457,8 +464,10 @@ static int FNAME(walk_addr_generic)(struct guest_walker *walker,
 							addr, write_fault);
 		if (unlikely(ret < 0))
 			goto error;
-		else if (ret)
+		else if (ret) {
+			cond_resched();
 			goto retry_walk;
+		}
 	}
 
 	pgprintk("%s: pte %llx pte_access %x pt_access %x\n",
Signature · 1 line
2.53.0
author maintainer
#709 lore raw

PATCH 704/1848 KVM: nVMX: Process each host MSR entry at most once when unwinding failed VM-Entry

In reply to Greg Kroah-Hartman

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

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

From: Sean Christopherson <[email protected]>

[ Upstream commit c33ef9d334059f7cb167569ed7b4779752fe4425 ]

Add a missing "break" in the inner for-loop of the open coded mess that unwinds MSRs back to the pre-VM-Enter state when VMLAUNCH/VMRESUME VM-Fails due to a consistency check that is caught by hardware but missed by KVM. I.e. move on to the next MSR in the VM-Entry load list after performing a write using a value found in the VM-Exit load list. Processing *every* matching entry in the VM-Exit load list makes the processing quadratic, which is problematic if the load lists are full of MSRs that are expensive to emulate. E.g. writing APIC_BASE triggers kvm_recalculate_apic_map() and a whole pile of unnecessary work.

Functionally, arbitrarily restoring the value of the first matching entry is "fine", because none of this is architecturally correct: the load lists are never supposed to have been used in the first place. In practice, it's likely a moot point as no well-behaved VMM will have multiple, diverging entries in the load lists.

Fixes bd18bffca353 ("KVM: nVMX: restore host state in nested_vmx_vmexit for VMFail")
Cc David Woodhouse <[email protected]>

Message-ID: <[email protected]>

---
 arch/x86/kvm/vmx/nested.c | 1 +
 1 file changed, 1 insertion(+)
arch/x86/kvm/vmx/nested.c +1 -0
index 7c861d34f9c56..477d69bcd52aa 100644
@@ -4498,6 +4498,7 @@ static void nested_vmx_restore_host_state(struct kvm_vcpu *vcpu)
 					__func__, j, h.index, h.value);
 				goto vmabort;
 			}
+			break;
 		}
 	}
 
Signature · 1 line
2.53.0
author maintainer
#710 lore raw

PATCH 705/1848 openrisc: export __mulsi3 for modules

In reply to Greg Kroah-Hartman

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

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

From: Andrew Morton <[email protected]>

[ Upstream commit 8ff981aa283a0ce516c2dc65a48a185ed336c657 ]

OpenRISC configurations without hardware multiplication fail to build modules which contain compiler-generated calls to __mulsi3. The failure is widespread, affecting filesystems, drivers and KUnit tests at modpost.

When CONFIG_OPENRISC_HAVE_INST_MUL is disabled, the architecture Makefile passes -msoft-mul to GCC. The multiplication helper is supplied by the libgcc archive linked into vmlinux, but or32_ksyms.c does not export it. Built-in callers can therefore link while module callers cannot resolve the symbol.

Export __mulsi3 alongside the other compiler-generated helpers.

The omission predates 7c3f4d699f34 ("resource, kunit: stop selecting GET_FREE_REGION"), which the robot identified when reporting an additional failing module. It was already present in the initial OpenRISC export list.

Fixes 616257669e1a ("OpenRISC: Miscellaneous")
Cc Jonas Bonn <[email protected]>
Cc Stefan Kristiansson <[email protected]>
Cc Stafford Horne <[email protected]>
Cc Arnd Bergmann <[email protected]>
Cc Karl Mehltretter <[email protected]>
---
 arch/openrisc/kernel/or32_ksyms.c | 1 +
 1 file changed, 1 insertion(+)
arch/openrisc/kernel/or32_ksyms.c +1 -0
index 212e5f85004cc..c63d7f25bc575 100644
@@ -35,6 +35,7 @@ DECLARE_EXPORT(__divsi3);
 DECLARE_EXPORT(__umodsi3);
 DECLARE_EXPORT(__modsi3);
 DECLARE_EXPORT(__muldi3);
+DECLARE_EXPORT(__mulsi3);
 DECLARE_EXPORT(__ashrdi3);
 DECLARE_EXPORT(__ashldi3);
 DECLARE_EXPORT(__lshrdi3);
Signature · 1 line
2.53.0
author maintainer
#711 lore raw

PATCH 706/1848 ocfs2: find the xattr entry again after defragmenting a bucket

In reply to Greg Kroah-Hartman

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

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

From: Joseph Qi <[email protected]>

[ Upstream commit 9a40c050f58344615a0604701b5d299519833163 ]

ocfs2_xattr_set_entry_bucket() hands loc.xl_entry to ocfs2_xa_set() twice:
once for the bucket as it stands, and, if that reports -ENOSPC, once more after ocfs2_defrag_xattr_bucket() has packed the name/value pairs down.

Defragmenting ends by sorting the entry array on xe_name_hash. Buckets are kept sorted, so the sort only permutes entries that share a hash, but lib/sort.c is an unstable heapsort and it does permute them. loc.xl_entry is an address inside xh_entries[], so afterwards it denotes whichever entry landed in that slot rather than the one the search found.

The second ocfs2_xa_set() then works on the wrong entry. Nothing on that path compares the entry's name with xi->xi_name, so what happens depends on how the two entries compare in size: ocfs2_xa_reuse_entry() trips its BUG_ON() when the padded name sizes differ, and otherwise the new value is written into the neighbouring attribute's value slot while the attribute being set is left untouched. setxattr() reports success either way.

Remember the entry's hash before defragmenting and look the entry up again afterwards, the way ocfs2_xattr_bucket_find() does. An entry that cannot be found again means the bucket no longer holds what the search found, so fail with -EFSCORRUPTED rather than writing through the stale pointer.

Fixes 012255961c9e ("ocfs2: Enable xattr set in index btree")
Cc Heming Zhao <[email protected]>
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
---
 fs/ocfs2/xattr.c | 30 +++++++++++++++++++++++++++++-
 1 file changed, 29 insertions(+), 1 deletion(-)
fs/ocfs2/xattr.c +29 -1
index f82d37e87c860..f7c4cecd64024 100644
@@ -5581,13 +5581,18 @@ static int ocfs2_xattr_set_entry_bucket(struct inode *inode,
 					struct ocfs2_xattr_search *xs,
 					struct ocfs2_xattr_set_ctxt *ctxt)
 {
-	int ret;
+	int ret, found = 0;
+	u16 xe_index;
+	u32 name_hash;
 	struct ocfs2_xa_loc loc;
 
 	trace_ocfs2_xattr_set_entry_bucket(xi->xi_name);
 
 	ocfs2_init_xattr_bucket_xa_loc(&loc, xs->bucket,
 				       xs->not_found ? NULL : xs->here);
+	/* Defragmenting below may move this entry, so remember its hash. */
+	name_hash = loc.xl_entry ? le32_to_cpu(loc.xl_entry->xe_name_hash) : 0;
+
 	ret = ocfs2_xa_set(&loc, xi, ctxt);
 	if (!ret) {
 		xs->here = loc.xl_entry;
@@ -5606,6 +5611,29 @@ static int ocfs2_xattr_set_entry_bucket(struct inode *inode,
 		goto out;
 	}
 
+	/*
+	 * ocfs2_defrag_xattr_bucket() sorts the entries by name hash and
+	 * lib/sort.c is not stable, so entries sharing a hash may have traded
+	 * slots.  Look the entry up again before writing through it.
+	 */
+	if (loc.xl_entry) {
+		ret = ocfs2_find_xe_in_bucket(inode, xs->bucket,
+					      xi->xi_name_index, xi->xi_name,
+					      name_hash, &xe_index, &found);
+		if (ret) {
+			mlog_errno(ret);
+			goto out;
+		}
+		if (!found) {
+			mlog(ML_ERROR, "xattr entry not found in bucket %llu after defrag\n",
+			     (unsigned long long)bucket_blkno(xs->bucket));
+			ret = -EFSCORRUPTED;
+			goto out;
+		}
+		loc.xl_entry = &bucket_xh(xs->bucket)->xh_entries[xe_index];
+		xs->here = loc.xl_entry;
+	}
+
 	ret = ocfs2_xa_set(&loc, xi, ctxt);
 	if (!ret) {
 		xs->here = loc.xl_entry;
Signature · 1 line
2.53.0
author maintainer
#712 lore raw

PATCH 707/1848 ocfs2: find the xattr entry again after converting a block to a bucket

In reply to Greg Kroah-Hartman

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

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

From: Joseph Qi <[email protected]>

[ Upstream commit 9c191a7a44882487e291e09f095d2ae4d7cca146 ]

ocfs2_xattr_create_index_block() turns a non-indexed xattr block into a tree by copying it into a bucket, and the copy sorts the entries: a block holds them in insertion order, a bucket by name hash. ocfs2_xattr_update_xattr_search() nevertheless relocates the caller's search by the index the entry had in the block, so unless the two orders agreed it points at an unrelated entry, and nothing between there and the write compares that entry's name with the one being set.

Setting an xattr whose new value no longer fits the block arrives here with xs->not_found clear. The block gave up because ocfs2_xa_block_can_reuse() wants an exact namevalue size match, while ocfs2_xa_bucket_can_reuse() only wants an entry at least as large as the new one, so the bucket accepts a pair the block rejected and the update lands on whichever entry the sort left at that index. Equal padded name lengths get that other attribute's value replaced in place and its name left alone, so setxattr returns success while the attribute asked for keeps its old value. A longer one trips ocfs2_xa_reuse_entry()'s BUG_ON, and a shorter one is refused by the bucket as well, so ocfs2_xa_prepare_entry() wipes the entry and writes the new name over it, leaving xe_name_hash describing a name that is no longer there.

Find the entry again by the name being set, matching the type as well. The copy carries every entry and every name over unchanged, and (type, name) pairs are unique within a block, so the match is exact. The type matters because the handlers strip their prefix before calling ocfs2_xattr_set(), so user.foo and trusted.foo share a stored name, a stored length and a hash, and both can sit in the same block.

The name has to come from xi rather than from xs->here: a failed set can remove the entry xs->here names, and only the "growing" caller sets ctxt->set_abort, which is what stops the conversion. Scan every entry rather than narrowing on the hash the way ocfs2_find_xe_in_bucket() does, since an existing entry keeps the hash it was stored under, which a kernel that sign-extended the name bytes made different from the one computed now. An empty result means the entry did not survive the failed set and this has become an insert; leaving xs->here alone would keep it pointing into the block, which is rewritten as a tree root before the caller reads it again.

Fixes 012255961c9e ("ocfs2: Enable xattr set in index btree")
Cc Heming Zhao <[email protected]>
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
---
 fs/ocfs2/xattr.c | 54 +++++++++++++++++++++++++++++++++++++++---------
 1 file changed, 44 insertions(+), 10 deletions(-)
fs/ocfs2/xattr.c +44 -10
index f7c4cecd64024..4e71a6e24cf90 100644
@@ -262,6 +262,7 @@ static int ocfs2_xattr_tree_list_index_block(struct inode *inode,
 					size_t buffer_size);
 
 static int ocfs2_xattr_create_index_block(struct inode *inode,
+					  struct ocfs2_xattr_info *xi,
 					  struct ocfs2_xattr_search *xs,
 					  struct ocfs2_xattr_set_ctxt *ctxt);
 
@@ -3001,7 +3002,7 @@ static int ocfs2_xattr_block_set(struct inode *inode,
 		else if ((ret != -ENOSPC) || ctxt->set_abort)
 			goto end;
 		else {
-			ret = ocfs2_xattr_create_index_block(inode, xs, ctxt);
+			ret = ocfs2_xattr_create_index_block(inode, xi, xs, ctxt);
 			if (ret)
 				goto end;
 		}
@@ -4285,13 +4286,10 @@ static void ocfs2_cp_xattr_block_to_bucket(struct inode *inode,
  * real place of the xattr.
  */
 static void ocfs2_xattr_update_xattr_search(struct inode *inode,
-					    struct ocfs2_xattr_search *xs,
-					    struct buffer_head *old_bh)
+					    struct ocfs2_xattr_info *xi,
+					    struct ocfs2_xattr_search *xs)
 {
-	char *buf = old_bh->b_data;
-	struct ocfs2_xattr_block *old_xb = (struct ocfs2_xattr_block *)buf;
-	struct ocfs2_xattr_header *old_xh = &old_xb->xb_attrs.xb_header;
-	int i;
+	int i, count;
 
 	xs->header = bucket_xh(xs->bucket);
 	xs->base = bucket_block(xs->bucket, 0);
@@ -4300,11 +4298,47 @@ static void ocfs2_xattr_update_xattr_search(struct inode *inode,
 	if (xs->not_found)
 		return;
 
-	i = xs->here - old_xh->xh_entries;
-	xs->here = &xs->header->xh_entries[i];
+	/*
+	 * A block holds its entries in insertion order while a bucket holds
+	 * them by name hash, so ocfs2_cp_xattr_block_to_bucket() sorted the
+	 * copies and the index this entry had in the block no longer says
+	 * where it is.  It copied every entry and every name unchanged, and
+	 * (type, name) pairs are unique within a block, so find it again by
+	 * name.
+	 *
+	 * Search for the name being set, not for the name xs->here carries.
+	 * A failed set may have removed that entry, and ocfs2_xa_remove_entry()
+	 * then memmoves its successor into the slot.  Comparing every entry
+	 * rather than narrowing on the hash also finds an entry stored under
+	 * the legacy signed hash, which ocfs2_find_xe_in_bucket() would skip.
+	 */
+	count = le16_to_cpu(xs->header->xh_count);
+	for (i = 0; i < count; i++) {
+		struct ocfs2_xattr_entry *xe = &xs->header->xh_entries[i];
+
+		if (ocfs2_xattr_get_type(xe) != xi->xi_name_index)
+			continue;
+		if (xe->xe_name_len != xi->xi_name_len)
+			continue;
+		if (!memcmp(xs->base + le16_to_cpu(xe->xe_name_offset),
+			    xi->xi_name, xi->xi_name_len)) {
+			xs->here = xe;
+			return;
+		}
+	}
+
+	/*
+	 * The entry did not survive the failed set, so this has become an
+	 * insert.  Point xs->here back inside the bucket: it still refers to
+	 * the block being converted, which is about to be rewritten as a tree
+	 * root.
+	 */
+	xs->not_found = -ENODATA;
+	xs->here = xs->header->xh_entries;
 }
 
 static int ocfs2_xattr_create_index_block(struct inode *inode,
+					  struct ocfs2_xattr_info *xi,
 					  struct ocfs2_xattr_search *xs,
 					  struct ocfs2_xattr_set_ctxt *ctxt)
 {
@@ -4371,7 +4405,7 @@ static int ocfs2_xattr_create_index_block(struct inode *inode,
 	ocfs2_cp_xattr_block_to_bucket(inode, xb_bh, xs->bucket);
 	ocfs2_xattr_bucket_journal_dirty(handle, xs->bucket);
 
-	ocfs2_xattr_update_xattr_search(inode, xs, xb_bh);
+	ocfs2_xattr_update_xattr_search(inode, xi, xs);
 
 	/* Change from ocfs2_xattr_header to ocfs2_xattr_tree_root */
 	memset(&xb->xb_attrs, 0, inode->i_sb->s_blocksize -
Signature · 1 line
2.53.0
author maintainer
#713 lore raw

PATCH 708/1848 ocfs2: do not index before the entry array when dividing an empty bucket

In reply to Greg Kroah-Hartman

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

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

From: Joseph Qi <[email protected]>

[ Upstream commit 7133a0d0954c109f1764ebf8ab32d7e757a6c587 ]

ocfs2_divide_xattr_bucket() appends an empty bucket carrying a sentinel hash when the source bucket has no divide position, taking that hash from xh_entries[start - 1]. ocfs2_xattr_find_divide_pos() returns count when every entry shares one hash, and its loop does not run at all for count < 2, so an empty bucket comes back with start == count == 0 and the read is xh_entries[-1].

That is outside the __counted_by_le(xh_count) bounds of xh_entries[] and lands on the header, so the value picked up is
xh_count | xh_free_start << 16. One above it is written into the new bucket's xh_entries[0] and committed, which leaves a bucket whose first hash does not follow the bucket before it. ocfs2_xattr_bucket_find() binary searches on xh_entries[0], so the broken key hides the range the sentinel was meant to cover: getxattr() answers -ENODATA for an attribute that is stored, and an insert can go to the wrong bucket and leave two copies of a name. The cross cluster divide hands the same value back as a tree record's e_cpos, which then claims a hash range it does not cover.

Read xh_entries[0] instead. The branch is only reached when every entry shares one hash, so for a non-empty bucket it holds the same value, and for an empty one it is the slot that carries the bucket key.

An empty bucket reaches the divide from ocfs2_check_xattr_bucket_collision(), which reports no collision for one, through ocfs2_add_new_xattr_bucket() and ocfs2_extend_xattr_bucket(). It does not take a failed set to get
there: a divide that finds no position is itself what leaves an empty sentinel bucket behind, and a later extend can pick it as the target.

Fixes 80bcaf3469b8 ("ocfs2/xattr: Proper hash collision handle in bucket division")
Cc Heming Zhao <[email protected]>
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
---
 fs/ocfs2/xattr.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
fs/ocfs2/xattr.c +9 -1
index 4e71a6e24cf90..3303930f62ac9 100644
@@ -4758,7 +4758,15 @@ static int ocfs2_divide_xattr_bucket(struct inode *inode,
 	start = ocfs2_xattr_find_divide_pos(xh);
 
 	if (start == count) {
-		xe = &xh->xh_entries[start-1];
+		/*
+		 * start == count means every entry shares one hash, so the
+		 * first of them carries it too.  An empty bucket has no
+		 * entries[start - 1], but its entries[0] still carries the
+		 * bucket key: either the hash ocfs2_xa_remove_entry()
+		 * deliberately leaves behind, or the sentinel a previous
+		 * divide wrote.
+		 */
+		xe = &xh->xh_entries[0];
 
 		/*
 		 * initialized a new empty bucket here.
Signature · 1 line
2.53.0
author maintainer
#714 lore raw

PATCH 709/1848 ocfs2: do not read the entry array of an empty xattr block

In reply to Greg Kroah-Hartman

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

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

From: Joseph Qi <[email protected]>

[ Upstream commit cd7c3563a98fe8c984463d83772e518cb7e68356 ]

ocfs2_cp_xattr_block_to_bucket() sizes the name and value area it has to carry over from the block's last entry, so an empty block makes it read xh_entries[-1]. That lands on the header, where xe_name_offset overlaps xh_name_value_len, and block storage never maintains that field, so it reads as 0 and the copy runs from the header to the end of the block.

The bucket that comes out has xh_count 0 but a name_value_len of blocksize less the header, and a matching xh_free_start that claims those bytes are in use -- nearly the whole bucket with the common 4K block size -- while the last block of the bucket holds a copy of the old block's bytes. Nothing but a trace event reads xh_name_value_len, the copied bytes came from the same inode and were wiped before the entry was removed, and ocfs2_defrag_xattr_bucket() recomputes xh_free_start, so this corrupts the header rather than leaking anything.

Leave the bucket empty instead, carrying over the hash the block was keyed by, since ocfs2_add_new_xattr_bucket() and ocfs2_xattr_bucket_find() both read xh_entries[0] of an empty bucket. That read is the exception ocfs2_xa_remove_entry() documents rather than a new out of bounds access.

A block reaches the conversion empty when truncating an external value back fails partway through: the "reusing" and "overwriting" callers of ocfs2_xa_cleanup_value_truncate() remove the entry without setting ctxt->set_abort, so ocfs2_xattr_block_set() sees a plain -ENOSPC and converts. The "growing" caller does set it, and the block form makes a single attempt with no defragment and retry in between, so that is the only route here.

Fixes 012255961c9e ("ocfs2: Enable xattr set in index btree")
Cc Heming Zhao <[email protected]>
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
---
 fs/ocfs2/xattr.c |   15 +++++++++++++++
 1 file changed, 15 insertions(+)
fs/ocfs2/xattr.c +15 -0
@@ -4241,6 +4241,21 @@ static void ocfs2_cp_xattr_block_to_buck
 		memset(bucket_block(bucket, i), 0, blocksize);
 
 	/*
+	 * An empty block has no names or values to carry over, and the
+	 * xh_entries[count - 1] below would be xh_entries[-1].  Leave the
+	 * bucket empty, but carry over the hash ocfs2_xa_remove_entry() left
+	 * in the block's xh_entries[0] so that the bucket still holds the key
+	 * it is looked up by.
+	 */
+	if (!count) {
+		xh->xh_num_buckets = cpu_to_le16(1);
+		xh->xh_free_start = cpu_to_le16(OCFS2_XATTR_BUCKET_SIZE);
+		xh->xh_entries[0].xe_name_hash =
+			xb_xh->xh_entries[0].xe_name_hash;
+		return;
+	}
+
+	/*
 	 * Since the xe_name_offset is based on ocfs2_xattr_header,
 	 * there is a offset change corresponding to the change of
 	 * ocfs2_xattr_header's position.
author maintainer
#715 lore raw

PATCH 710/1848 fat: hold truncate_lock in fat_write_failed()

In reply to Greg Kroah-Hartman

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

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

From: Matheus Alves de Almeida <[email protected]>

[ Upstream commit 7b90009546f5d3f3ac9428040cd7ffbdfd60f2eb ]

The current fat_write_failed() implementation calls into fat_truncate_blocks() without holding truncate_lock.

A failed or short extending write racing with FIBMAP can spuriously make a FAT filesystem read-only. FIBMAP bounds its lookup by i_blocks, so it can walk allocated clusters beyond i_size while fat_write_failed() is removing them. If the chain is shortened during the walk, the mapper can report a bogus "request beyond EOF" error, triggering the default read-only error policy. Hold truncate_lock for write around the block cleanup to serialize it with _fat_bmap().

For comparison, fat_setattr() correctly holds truncate_lock during truncation:

	down_write(&MSDOS_I(inode)->truncate_lock);
	truncate_setsize(inode, attr->ia_size);
	fat_truncate_blocks(inode, attr->ia_size);
	up_write(&MSDOS_I(inode)->truncate_lock);

Make it so ->truncate_lock is held exclusive while truncating.

Fixes 16fab2015099 ("fat: permit to return phy block number by fibmap in fallocated region")
Fixes 459f6ed3b8c7 ("fat: convert to use the new truncate convention.")
Cc Pedro Falcato <[email protected]>
---
 fs/fat/inode.c | 2 ++
 1 file changed, 2 insertions(+)
fs/fat/inode.c +2 -0
index bab9b202b4966..4b5eca334b268 100644
@@ -221,7 +221,9 @@ static void fat_write_failed(struct address_space *mapping, loff_t to)
 
 	if (to > inode->i_size) {
 		truncate_pagecache(inode, inode->i_size);
+		down_write(&MSDOS_I(inode)->truncate_lock);
 		fat_truncate_blocks(inode, inode->i_size);
+		up_write(&MSDOS_I(inode)->truncate_lock);
 	}
 }
 
Signature · 1 line
2.53.0
author maintainer
#716 lore raw

PATCH 711/1848 ocfs2: keep locking_state within the cluster connection lifetime

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit 5bdef466851e39ba752634cbea68e5ea24ccfb24 ]

The locking_state reader calls ocfs2_dlm_lvb() through the selected cluster stack. Its debug-object reference keeps the tracking list alive, but does not keep that stack selected without a cluster connection.

DLM initialization publishes the file before establishing its connection, and DLM shutdown drops the connection while the file still exists. Both the mount error unwind in ocfs2_mount_volume() and ocfs2_dismount_volume() remove the debugfs subtree only after ocfs2_dlm_shutdown() has returned. Whenever the disconnect releases the last stack reference, which is the case for a failed mount and for any unmount without a pending hangup, a concurrent reader dereferences a NULL active_stack:

Mount error unwind Debugfs reader
------------------ --------------
ocfs2_mount_volume(): out_dlm

    ocfs2_dlm_shutdown()
      disconnect last cluster
        clear active_stack
                                      read locking_state
                                        ocfs2_dlm_seq_show()
                                          ocfs2_dlm_lvb()
                                            dereference active_stack

fill_super(): out_debugfs
remove debugfs subtree

Publish the debug files only after the connection and the mount lock resources are initialized, so a failed DLM initialization has no debug reference to drop. Remove them again in the common DLM shutdown helper before the connection is dropped: debugfs removal waits for readers that are inside the file operations, and the parent directory is still present at that point in every caller. This covers the mount error unwind, the ocfs2_fill_super() failures after a successful mount that dismount with mnt_err set, and unmounts whose disconnect releases the stack directly.

Only the relevant frames of the report are kept:

Oops: general protection fault, probably for non-canonical address 0xdffffc0000000001: 0000 [#1] SMP KASAN NOPTI
KASAN: null-ptr-deref in range [0x0000000000000008-0x000000000000000f]
RIP: 0010:ocfs2_dlm_lvb+0x38/0xf0
Call Trace:
 <TASK>
 ocfs2_dlm_seq_show+0x36a/0xb70
 seq_read_iter+0x480/0x1110
 seq_read+0x362/0x5a0
 full_proxy_read+0x11f/0x180
 vfs_read+0x1a0/0xc20
 ksys_read+0x111/0x200
 </TASK>
---
 fs/ocfs2/dlmglue.c | 18 +++++++++++++-----
 1 file changed, 13 insertions(+), 5 deletions(-)
fs/ocfs2/dlmglue.c +13 -5
index a8ec22045ccaa..63c5312a5ed58 100644
@@ -3330,6 +3330,14 @@ static void ocfs2_dlm_shutdown_debug(struct ocfs2_super *osb)
 {
 	struct ocfs2_dlm_debug *dlm_debug = osb->osb_dlm_debug;
 
+	/*
+	 * Drain the readers before the cluster stack goes away: the
+	 * locking_state reader resolves ocfs2_dlm_lvb() through the
+	 * stack. Every caller removes the parent directory later.
+	 */
+	debugfs_lookup_and_remove("locking_state", osb->osb_debug_root);
+	debugfs_lookup_and_remove("locking_filter", osb->osb_debug_root);
+
 	if (dlm_debug)
 		ocfs2_put_dlm_debug(dlm_debug);
 }
@@ -3344,8 +3352,6 @@ int ocfs2_dlm_init(struct ocfs2_super *osb)
 		goto local;
 	}
 
-	ocfs2_dlm_init_debug(osb);
-
 	/* launch downconvert thread */
 	osb->dc_task = kthread_run(ocfs2_downconvert_thread, osb, "ocfs2dc-%s",
 			osb->uuid_str);
@@ -3385,9 +3391,10 @@ int ocfs2_dlm_init(struct ocfs2_super *osb)
 	ocfs2_orphan_scan_lock_res_init(&osb->osb_orphan_scan.os_lockres, osb);
 
 	osb->cconn = conn;
+	if (conn)
+		ocfs2_dlm_init_debug(osb);
 bail:
 	if (status < 0) {
-		ocfs2_dlm_shutdown_debug(osb);
 		if (osb->dc_task)
 			kthread_stop(osb->dc_task);
 	}
@@ -3417,10 +3424,11 @@ void ocfs2_dlm_shutdown(struct ocfs2_super *osb,
 	ocfs2_lock_res_free(&osb->osb_orphan_scan.os_lockres);
 
 	if (osb->cconn) {
+		/* The disconnect below may release the selected stack. */
+		ocfs2_dlm_shutdown_debug(osb);
+
 		ocfs2_cluster_disconnect(osb->cconn, hangup_pending);
 		osb->cconn = NULL;
-
-		ocfs2_dlm_shutdown_debug(osb);
 	}
 }
 
Signature · 1 line
2.53.0
author maintainer
#717 lore raw

PATCH 712/1848 ocfs2/dlm: serialize migration MLE cleanup on failure

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit 61469249aab03799b0d3294b7a0cd25dd303017a ]

A migration MLE has a base reference for the mastering answer and an in-use reference held by dlm_migrate_lockres(). The finishing assertion consumes the base reference, but migration failure drops it again without checking whether the assertion already consumed it.

The target queues its migration worker before it acknowledges the ALL_DONE packet, so its finishing assertion can be handled while the sender still waits for the status. If the connection fails before the status arrives, dlm_send_one_lockres() returns an error for a migration that the target has already completed:

Old-master sender Finishing assertion
----------------- -------------------
publish MLE; take in-use reference
send ALL_DONE; wait for status
take lookup reference unlink MLE
put lookup and base references
send returns a connection error
put base reference again; free MLE
put in-use reference; access freed MLE

dlm_assert_master_handler() holds dlm->spinlock from the MLE lookup to the final puts, and it takes dlm->master_lock around the unlink and the puts. Decide under the same locks: if the MLE is already unhashed, the assertion consumed the base reference, so drop only the sender's in-use reference. Otherwise unlink it before consuming the base reference so a later assertion no longer finds it.

An assertion that got there first has also made the target the owner and cleared DLM_LOCK_RES_MIGRATING. Treating the attempt as failed at that point would leave the lockres owned by the target while this node still holds the other nodes' locks and refmap bits, so it could neither be purged nor migrated again. Finish our side as a completed migration does instead: drop those locks under res->spinlock if the target still owns the lockres, and recalculate its usage.

Use the same cleanup for the pre-send failure, the send failure and the target-death failure paths. The sender's in-use reference keeps the MLE alive until its final put outside the nested locks. Successful migration retains its existing in-use-only put.

A target that has died cannot assert after the sender has seen its death. The o2net node-down callback runs before the DLM one; it disconnects the node and flushes the workqueue that runs the message handlers, so an assertion already received has been handled by the time the DLM removes the node from the domain map. A node that leaves the domain cleanly sends its exit message only after its assertions have been answered.

Two windows of the hand-over itself are left as they are: the handler switches the owner and the sender drops the other nodes' locks moments later, and an assertion from a live target that arrives after the sender has given up still meets the owner check in the handler. Waiting for the target before giving up would only stretch the first window into the time in which recovery of the target can observe it.

KASAN report, only the relevant frames are kept:

BUG: KASAN: slab-use-after-free in dlm_put_mle_inuse+0xce/0xe0
Read of size 8 at addr ffff8881190e3c20 by task umount/593

Call Trace:
 <TASK>
 dlm_put_mle_inuse+0xce/0xe0
 dlm_migrate_lockres+0x16af/0x20d0
 dlm_empty_lockres+0x60a/0xbd0
 dlm_unregister_domain+0x53b/0x11d0
 o2cb_cluster_disconnect+0xa5/0x110
 ocfs2_cluster_disconnect+0x73/0xc0
 ocfs2_dlm_shutdown+0x311/0x440
 ocfs2_dismount_volume+0x696/0x940
 generic_shutdown_super+0x15f/0x490
 kill_block_super+0x40/0xa0
 deactivate_locked_super+0xae/0x120
 deactivate_super+0xa2/0xc0
 cleanup_mnt+0x217/0x450
 task_work_run+0x144/0x230
 </TASK>

Allocated by task 593:
 kmem_cache_alloc_noprof+0x20b/0x5c0
 dlm_migrate_lockres+0x20e/0x20d0
 dlm_empty_lockres+0x60a/0xbd0
 dlm_unregister_domain+0x53b/0x11d0
 o2cb_cluster_disconnect+0xa5/0x110
 ocfs2_cluster_disconnect+0x73/0xc0
 ocfs2_dlm_shutdown+0x311/0x440
 ocfs2_dismount_volume+0x696/0x940

Freed by task 593:
 kmem_cache_free+0x242/0x580
 __dlm_put_mle+0x4b2/0x660
 dlm_migrate_lockres+0x1690/0x20d0
 dlm_empty_lockres+0x60a/0xbd0
 dlm_unregister_domain+0x53b/0x11d0
 o2cb_cluster_disconnect+0xa5/0x110
 ocfs2_cluster_disconnect+0x73/0xc0
 ocfs2_dlm_shutdown+0x311/0x440

The buggy address belongs to the object at ffff8881190e3c00
 which belongs to the cache o2dlm_mle of size 480

The buggy address is located 32 bytes inside of
freed 480-byte region [ffff8881190e3c00, ffff8881190e3de0)

Fixes 6714d8e86bf4 ("[PATCH] OCFS2: The Second Oracle Cluster Filesystem")
Assisted-by LLM
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
Cc Heming Zhao <[email protected]>
Cc Jia-Ju Bai <[email protected]>
---
 fs/ocfs2/dlm/dlmmaster.c | 70 ++++++++++++++++++++++++++++++++++------
 1 file changed, 61 insertions(+), 9 deletions(-)
fs/ocfs2/dlm/dlmmaster.c +61 -9
index b5726e4942ce3..5b04aadc7ac99 100644
@@ -2539,6 +2539,52 @@ static int dlm_is_lockres_migratable(struct dlm_ctxt *dlm,
  */
 
 
+/*
+ * Drop the sender's references on a migration MLE after the attempt has
+ * failed. The finishing assert from the target may already have unlinked
+ * the MLE and consumed its base reference; decide under the locks the
+ * assert handler holds, and only drop the base reference while the MLE is
+ * still hashed. Returns true when the assert got there first: the target
+ * has become the master, so the caller must complete the migration.
+ */
+static bool dlm_put_migration_mle(struct dlm_ctxt *dlm,
+				  struct dlm_master_list_entry *mle)
+{
+	bool asserted;
+
+	spin_lock(&dlm->spinlock);
+	spin_lock(&dlm->master_lock);
+	__dlm_mle_detach_hb_events(dlm, mle);
+	asserted = hlist_unhashed(&mle->master_hash_node);
+	if (!asserted) {
+		__dlm_unlink_mle(dlm, mle);
+		__dlm_put_mle(mle);
+	}
+	spin_unlock(&dlm->master_lock);
+	spin_unlock(&dlm->spinlock);
+
+	dlm_put_mle_inuse(mle);
+	return asserted;
+}
+
+/*
+ * The finishing assert got there first: it switched the owner to the
+ * target and cleared DLM_LOCK_RES_MIGRATING. Drop the other nodes' locks
+ * as a completed migration does, unless recovery has taken the lockres
+ * over since, and let the usage be recalculated.
+ */
+static void dlm_migrate_lockres_asserted(struct dlm_ctxt *dlm,
+					 struct dlm_lock_resource *res,
+					 u8 target)
+{
+	spin_lock(&res->spinlock);
+	if (res->owner == target)
+		dlm_remove_nonlocal_locks(dlm, res);
+	spin_unlock(&res->spinlock);
+
+	dlm_lockres_calc_usage(dlm, res);
+}
+
 static int dlm_migrate_lockres(struct dlm_ctxt *dlm,
 			       struct dlm_lock_resource *res, u8 target)
 {
@@ -2623,9 +2669,10 @@ static int dlm_migrate_lockres(struct dlm_ctxt *dlm,
 
 	if (ret < 0) {
 		if (mle_added) {
-			dlm_mle_detach_hb_events(dlm, mle);
-			dlm_put_mle(mle);
-			dlm_put_mle_inuse(mle);
+			if (dlm_put_migration_mle(dlm, mle)) {
+				dlm_migrate_lockres_asserted(dlm, res, target);
+				ret = 0;
+			}
 		} else if (mle) {
 			kmem_cache_free(dlm_mle_cache, mle);
 			mle = NULL;
@@ -2654,9 +2701,11 @@ static int dlm_migrate_lockres(struct dlm_ctxt *dlm,
 		mlog(0, "migration to node %u failed with %d\n",
 		     target, ret);
 		/* migration failed, detach and clean up mle */
-		dlm_mle_detach_hb_events(dlm, mle);
-		dlm_put_mle(mle);
-		dlm_put_mle_inuse(mle);
+		if (dlm_put_migration_mle(dlm, mle)) {
+			dlm_migrate_lockres_asserted(dlm, res, target);
+			ret = 0;
+			goto leave;
+		}
 		spin_lock(&res->spinlock);
 		res->state &= ~DLM_LOCK_RES_MIGRATING;
 		wake = 1;
@@ -2700,9 +2749,12 @@ static int dlm_migrate_lockres(struct dlm_ctxt *dlm,
 				     res->lockname.name, target);
 				ret = -EINVAL;
 				/* migration failed, detach and clean up mle */
-				dlm_mle_detach_hb_events(dlm, mle);
-				dlm_put_mle(mle);
-				dlm_put_mle_inuse(mle);
+				if (dlm_put_migration_mle(dlm, mle)) {
+					dlm_migrate_lockres_asserted(dlm, res,
+								     target);
+					ret = 0;
+					goto leave;
+				}
 				spin_lock(&res->spinlock);
 				res->state &= ~DLM_LOCK_RES_MIGRATING;
 				wake = 1;
Signature · 1 line
2.53.0
author maintainer
#718 lore raw

PATCH 713/1848 ocfs2: stop recovery before shutting down local allocators

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit 126429e2f503ade63502978beb0c519066442250 ]

Recovery completion needs the local allocators until it has finished reclaiming a failed node's allocation window and truncate log. During unmount, quota recovery is stopped first, but that leaves recovery_state at OCFS2_REC_QUOTA_DISABLED. New non-quota recovery can still start.

ocfs2_truncate_log_shutdown() drains existing completion work and releases osb_tl_bh before ocfs2_recovery_exit() closes that publication path:

Unmount Recovery
------- --------
stop quota recovery; disable quotas truncate_log_shutdown()
flush existing completion work
recover another failed node
queue completion
flush local log; release buffer
complete_truncate_log_recovery()
use released osb_tl_bh
recovery_exit(): disable and drain

An extra buffer reference alone would still let completion append new records after the final truncate-log flush.

Split stopping and draining recovery from freeing its state. Stop all recovery producers and drain completion work before shutting down either local allocator. Keep recovery-state release at its existing later point, so its lifetime relative to other teardown users stays unchanged. The second stop at recovery_exit() is harmless once recovery is disabled.

KASAN report as below:

    BUG: KASAN: slab-use-after-free in ocfs2_truncate_log_needs_flush+0x23d/0x360
    Read of size 8 at addr ffff8881093711e8 by task kworker/u16:3/53

    CPU: 0 UID: 0 PID: 53 Comm: kworker/u16:3 Not tainted 7.3.0-rc4-next-20260921-pmb-ocfs2-functional-v1+ #1 PREEMPT(lazy)
    Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
    Workqueue: ocfs2_wq ocfs2_complete_recovery
    Call Trace:
     <TASK>
     dump_stack_lvl+0x93/0xd0
     print_report+0xce/0x630
     ? ocfs2_truncate_log_needs_flush+0x23d/0x360
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __virt_addr_valid+0x20e/0x420
     ? ocfs2_truncate_log_needs_flush+0x23d/0x360
     kasan_report+0xe0/0x110
     ? ocfs2_truncate_log_needs_flush+0x23d/0x360
     ocfs2_truncate_log_needs_flush+0x23d/0x360
     ? __pfx_ocfs2_truncate_log_needs_flush+0x10/0x10
     ? __pfx_down_write+0x10/0x10
     ocfs2_complete_truncate_log_recovery+0x315/0x780
     ? trace_hardirqs_on+0x18/0x160
     ? __pfx_ocfs2_complete_truncate_log_recovery+0x10/0x10
     ? ocfs2_complete_recovery+0x666/0x11b0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? kfree+0x308/0x580
     ocfs2_complete_recovery+0x676/0x11b0
     ? __pfx_ocfs2_complete_recovery+0x10/0x10
     ? reacquire_held_locks+0xdd/0x200
     ? process_one_work+0x7c8/0x1b40
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_acquire+0x190/0x300
     ? __pfx_autoremove_wake_function+0x10/0x10
     ? process_one_work+0x834/0x1b40
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_release+0xc8/0x290
     ? srso_alias_return_thunk+0x5/0xfbef5
     process_one_work+0x9a8/0x1b40
     ? __pfx_process_one_work+0x10/0x10
     ? lock_acquire+0x190/0x300
     ? lock_is_held_type+0x8f/0x100
     ? srso_alias_return_thunk+0x5/0xfbef5
     worker_thread+0x65c/0xe40
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __kthread_parkme+0x177/0x220
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx_worker_thread+0x10/0x10
     kthread+0x351/0x460
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx_kthread+0x10/0x10
     ret_from_fork+0x659/0x940
     ? __pfx_ret_from_fork+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __switch_to+0x74f/0xf70
     ? __pfx_kthread+0x10/0x10
     ret_from_fork_asm+0x1a/0x30
     </TASK>

    Allocated by task 538:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     __kasan_slab_alloc+0x89/0x90
     kmem_cache_alloc_noprof+0x20b/0x5c0
     alloc_buffer_head+0x26/0x120
     folio_alloc_buffers+0x122/0x1d0
     bdev_getblk+0x299/0x4f0
     ocfs2_read_blocks_sync+0x513/0xbc0
     ocfs2_iget+0x9cd/0x1a00
     ocfs2_get_system_file_inode+0x25e/0x7a0
     ocfs2_fill_super+0x1b05/0x3930
     get_tree_bdev_flags+0x35d/0x5f0
     vfs_get_tree+0x93/0x320
     fc_mount+0x1d/0x200
     path_mount+0x592/0x1e00
     __x64_sys_mount+0x24b/0x2d0
     do_syscall_64+0x114/0x620
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    Freed by task 553:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     kasan_save_free_info+0x3b/0x60
     __kasan_slab_free+0x5f/0x80
     kmem_cache_free+0x242/0x580
     free_buffer_head+0x4b/0xc0
     try_to_free_buffers+0x1dc/0x330
     ocfs2_truncate_log_shutdown+0x789/0x1290
     ocfs2_dismount_volume+0x1da/0x940
     generic_shutdown_super+0x15f/0x490
     kill_block_super+0x40/0xa0
     deactivate_locked_super+0xae/0x120
     deactivate_super+0xa2/0xc0
     cleanup_mnt+0x217/0x450
     task_work_run+0x144/0x230
     exit_to_user_mode_loop+0x17d/0x570
     do_syscall_64+0x4d1/0x620
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    The buggy address belongs to the object at ffff8881093711c0
     which belongs to the cache buffer_head of size 160
    The buggy address is located 40 bytes inside of
     freed 160-byte region [ffff8881093711c0, ffff888109371260)

    The buggy address belongs to the physical page:
    page: refcount:0 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x109371
    flags: 0x200000000000000(node=0|zone=2)
    page_type: f5(slab)
    raw: 0200000000000000 ffff8881008883c0 dead000000000100 dead000000000122
    raw: 0000000000000000 0000000000120012 00000000f5000000 0000000000000000
    page dumped because: kasan: bad access detected

    Memory state around the buggy address:
     ffff888109371080: 00 00 00 00 fc fc fc fc fc fc fc fc 00 00 00 00
     ffff888109371100: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    >ffff888109371180: fc fc fc fc fc fc fc fc fa fb fb fb fb fb fb fb
                                                              ^
     ffff888109371200: fb fb fb fb fb fb fb fb fb fb fb fb fc fc fc fc
     ffff888109371280: fc fc fc fc 00 00 00 00 00 00 00 00 00 00 00 00
    ==================================================================
---
 fs/ocfs2/journal.c | 15 ++++++++++++---
 fs/ocfs2/journal.h |  1 +
 fs/ocfs2/super.c   |  3 +++
 3 files changed, 16 insertions(+), 3 deletions(-)
fs/ocfs2/journal.c +12 -3
index 9809ae9debb54..da355eb757bac 100644
@@ -234,13 +234,22 @@ void ocfs2_recovery_disable_quota(struct ocfs2_super *osb)
 	ocfs2_recovery_disable(osb, OCFS2_REC_QUOTA_WANT_DISABLE);
 }
 
+/* Stop producers and drain completion work without freeing recovery state. */
+void ocfs2_recovery_stop(struct ocfs2_super *osb)
+{
+	ocfs2_recovery_disable(osb, OCFS2_REC_WANT_DISABLE);
+}
+
 void ocfs2_recovery_exit(struct ocfs2_super *osb)
 {
 	struct ocfs2_recovery_map *rm;
 
-	/* disable any new recovery threads and wait for any currently
-	 * running ones to exit. Do this before setting the vol_state. */
-	ocfs2_recovery_disable(osb, OCFS2_REC_WANT_DISABLE);
+	/*
+	 * Disable producers and drain work before freeing recovery state.
+	 * Do this before setting vol_state to VOLUME_DISMOUNTED: completion
+	 * work may still be waiting in __ocfs2_wait_on_mount().
+	 */
+	ocfs2_recovery_stop(osb);
 
 	/*
 	 * Now that recovery is shut down, and the osb is about to be
fs/ocfs2/journal.h +1 -0
index 4199d73bebf4d..dad955bd431bd 100644
@@ -149,6 +149,7 @@ void ocfs2_complete_recovery(struct work_struct *work);
 void ocfs2_wait_for_recovery(struct ocfs2_super *osb);
 
 int ocfs2_recovery_init(struct ocfs2_super *osb);
+void ocfs2_recovery_stop(struct ocfs2_super *osb);
 void ocfs2_recovery_exit(struct ocfs2_super *osb);
 void ocfs2_recovery_disable_quota(struct ocfs2_super *osb);
 
fs/ocfs2/super.c +3 -0
index 3cb235a196126..91a9b86389160 100644
@@ -1893,6 +1893,9 @@ static void ocfs2_dismount_volume(struct super_block *sb, int mnt_err)
 	/* Wait for worker to be done with the work structure in osb */
 	cancel_work_sync(&osb->dquot_drop_work);
 
+	/* Stop recovery producers before releasing their local allocators. */
+	ocfs2_recovery_stop(osb);
+
 	ocfs2_shutdown_local_alloc(osb);
 
 	ocfs2_truncate_log_shutdown(osb);
Signature · 1 line
2.53.0
author maintainer
#719 lore raw

PATCH 714/1848 ocfs2/cluster: unlink socket containers before releasing resources

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit 0988f0c0c7c908f0ff77fd8b90ce9918a1f41479 ]

A socket container's node and socket must remain alive while the container is on sock_containers. The debugfs formatter reads sc_node and sc_sock under o2net_debug_lock without taking their references, but sc_kref_release() releases both before taking that lock to unlink the container.

With CONFIG_DEBUG_FS enabled, a synchronous sender can retain its last socket-container reference after o2net_disconnect_node() has detached the connection and flushed o2net_wq. The caller runs outside that workqueue. After the sender removes its configfs dependency, node removal can proceed without waiting for the sender's final sc_put():

Sender (final sc_put) Configfs rmdir Debugfs reader
-------------------- -------------- --------------
o2nm_undepend_item()
Drop node item refs
o2nm_node_put()
[node can be freed]
sc_seq_show()
Lock debug lock Read sc_node->nd_name Unlock debug lock
sc_node = NULL
o2net_debug_del_sc()

The earlier socket release has a similar window. The container is still selectable while its socket has been released and sc_sock has not yet been cleared:

Sender (final sc_put) Debugfs reader
-------------------- --------------
sock_release(sc->sc_sock)
[socket can be freed]
sc_seq_show()
Lock debug lock Read sc_sock->sk fields Unlock debug lock
sc_sock = NULL
...
o2net_debug_del_sc()

Move o2net_debug_del_sc() before releasing either resource. Unlinking under the existing debug lock waits for an active formatter to finish and prevents later readers from selecting the container. This covers both socket fields and node fields, including nd_num in the stats formatter.

KASAN report as below:

    BUG: KASAN: slab-use-after-free in string+0x42b/0x470
    Read of size 1 at addr ffff88810f56fc90 by task python3/506

    CPU: 0 UID: 0 PID: 506 Comm: python3 Not tainted 7.3.0-rc4-next-20260921-pmb-ocfs2-functional-v1+ #1 PREEMPT(lazy)
    Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
    Call Trace:
     <TASK>
     dump_stack_lvl+0x93/0xd0
     print_report+0xce/0x630
     kasan_report+0xe0/0x110
     string+0x42b/0x470
     vsnprintf+0x330/0x1110
     seq_printf+0x1a8/0x260
     sc_seq_show+0x604/0x9f0
     seq_read_iter+0x480/0x1110
     seq_read+0x362/0x5a0
     full_proxy_read+0x11f/0x180
     vfs_read+0x1a0/0xc20
     ksys_read+0x111/0x200
     do_syscall_64+0x114/0x620
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

(User register dump omitted.)

     </TASK>

    Allocated by task 497:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     __kasan_kmalloc+0xaa/0xb0
     __kmalloc_cache_noprof+0x28d/0x610
     o2nm_node_group_make_item+0xea/0x1a0
     configfs_mkdir+0x762/0xca0
     vfs_mkdir+0x399/0x7e0
     filename_mkdirat+0x129/0x450
     __x64_sys_mkdir+0x70/0xa0
     do_syscall_64+0x114/0x620
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    Freed by task 505:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     kasan_save_free_info+0x3b/0x60
     __kasan_slab_free+0x5f/0x80
     kfree+0x308/0x580
     config_item_cleanup+0x14b/0x230
     config_item_put+0x79/0x90
     sc_put+0x454/0x6e0
     o2net_send_message_vec+0x63d/0x1560
     o2net_send_message+0xa6/0xe0
     validation_send_write+0x17f/0x1d0
     full_proxy_write+0x11f/0x180
     vfs_write+0x25a/0x1010
     ksys_write+0x111/0x200
     do_syscall_64+0x114/0x620
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    The buggy address belongs to the object at ffff88810f56fc00
     which belongs to the cache kmalloc-512 of size 512
    The buggy address is located 144 bytes inside of
     freed 512-byte region [ffff88810f56fc00, ffff88810f56fe00)

(Page and shadow-memory dumps omitted.)

---
 fs/ocfs2/cluster/tcp.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
fs/ocfs2/cluster/tcp.c +3 -2
index bd9a2eb244673..e02b32e91b048 100644
@@ -385,6 +385,9 @@ static void sc_kref_release(struct kref *kref)
 
 	sclog(sc, "releasing\n");
 
+	/* Unlink before freeing anything the debugfs readers dereference. */
+	o2net_debug_del_sc(sc);
+
 	if (sc->sc_sock) {
 		sock_release(sc->sc_sock);
 		sc->sc_sock = NULL;
@@ -394,8 +397,6 @@ static void sc_kref_release(struct kref *kref)
 	o2nm_node_put(sc->sc_node);
 	sc->sc_node = NULL;
 
-	o2net_debug_del_sc(sc);
-
 	if (sc->sc_page)
 		__free_page(sc->sc_page);
 	kfree(sc);
Signature · 1 line
2.53.0
author maintainer
#720 lore raw

PATCH 715/1848 ocfs2: wait for filecheck kobject release after a failed add

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit a25c02af29c3e95128e4343fceb4bdace8e480a0 ]

The filecheck kobject and its release completion are embedded in ocfs2_super, so the osb must outlive the kobject. On a failed kobject_init_and_add(), creation clears fs_fcheck and calls kobject_put(), but returns without waiting for the release callback.

With CONFIG_DEBUG_KOBJECT_RELEASE, the last put queues delayed cleanup. Mount failure can then free the containing osb before the embedded release timer expires:

Mount failure Delayed cleanup
------------- ---------------
ocfs2_filecheck_create_sysfs()
kobject_init_and_add() fails
fs_fcheck = NULL
kobject_put()
queue delayed release
return to mount error cleanup
ocfs2_dismount_volume()
remove_sysfs() skips the wait
kfree(osb)
expire embedded release timer
access freed osb

The normal removal path waits for fs_kobj_unregister, but it returns early when fs_fcheck is NULL. The failed-add path therefore leaves the delayed work and its completion in freed storage.

Wait for the existing release completion after the failed-add kobject_put(), before returning to mount error cleanup. This keeps the enclosing osb alive until the kobject has finished releasing, matching the normal teardown path.

KASAN report as below:

    BUG: KASAN: slab-use-after-free in __run_timers+0xa6d/0xa90
    Write of size 8 at addr ffff8881178a5658 by task swapper/0/0

    CPU: 0 UID: 0 PID: 0 Comm: swapper/0 Not tainted 7.3.0-rc4-next-20260921-pmb-ocfs2-functional-v1+ #1 PREEMPT(lazy)
    Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
    Call Trace:
     <IRQ>
     dump_stack_lvl+0x93/0xd0
     print_report+0xce/0x630
     ? __run_timers+0xa6d/0xa90
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __virt_addr_valid+0x20e/0x420
     ? __run_timers+0xa6d/0xa90
     kasan_report+0xe0/0x110
     ? __run_timers+0xa6d/0xa90
     __run_timers+0xa6d/0xa90
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx___run_timers+0x10/0x10
     ? __lock_acquire+0x5a3/0x2140
     ? __pfx_do_raw_spin_lock+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     timer_expire_remote+0xfa/0x160
     ? __pfx_timer_expire_remote+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? trace_hardirqs_on+0x18/0x160
     tmigr_handle_remote_up+0x4ba/0x9d0
     ? __pfx_tmigr_handle_remote_up+0x10/0x10
     ? tmigr_handle_remote+0x21a/0x340
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_release+0xc8/0x290
     ? __pfx_tmigr_handle_remote_up+0x10/0x10
     __walk_groups_from+0x5a/0x160
     tmigr_handle_remote+0x24f/0x340
     ? __pfx_tmigr_handle_remote+0x10/0x10
     ? lock_acquire+0x190/0x300
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_release+0xc8/0x290
     run_timer_softirq+0x222/0x270
     ? __pfx_run_timer_softirq+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lockdep_hardirqs_on_prepare+0xb8/0x1a0
     ? srso_alias_return_thunk+0x5/0xfbef5
     handle_softirqs+0x1fa/0x8d0
     ? __pfx_handle_softirqs+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? _raw_spin_unlock+0x23/0x40
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __hrtimer_rearm_deferred+0x1fb/0x5d0
     __irq_exit_rcu+0x113/0x1e0
     irq_exit_rcu+0xe/0x20
     sysvec_apic_timer_interrupt+0x6c/0x80
     </IRQ>
     <TASK>
     asm_sysvec_apic_timer_interrupt+0x1a/0x20
    RIP: 0010:pv_native_safe_halt+0xf/0x20
    Code: fa 18 01 e9 ee 37 ff fa 0f 1f 00 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 f3 0f 1e fa eb 07 0f 00 2d 23 c7 14 00 fb f4 <e9> c7 37 ff fa 66 2e 0f 1f 84 00 00 00 00 00 66 90 90 90 90 90 90
    RSP: 0018:ffffffff87c07cf8 EFLAGS: 00000206
    RAX: 0000000000045d0f RBX: ffffffff87c2d4c0 RCX: ffffffff86111e95
    RDX: 0000000000000000 RSI: 0000000000000000 RDI: ffffffff815b508e
    RBP: fffffbfff0f85a98 R08: 0000000000000001 R09: ffffed10310c68ba
    R10: ffff8881886345d3 R11: 0000000000000000 R12: 0000000000000001
    R13: 0000000000000000 R14: 1ffffffff0f80fa4 R15: dffffc0000000000
     ? ct_kernel_exit.constprop.0+0xc5/0xf0
     ? do_idle+0x3ae/0x650
     default_idle+0x9/0x10
     default_idle_call+0x6c/0xb0
     do_idle+0x3ae/0x650
     ? __pfx___schedule+0x10/0x10
     ? __pfx_do_idle+0x10/0x10
     ? rest_init+0x1cd/0x330
     ? srso_alias_return_thunk+0x5/0xfbef5
     cpu_startup_entry+0x54/0x60
     rest_init+0x1e1/0x330
     ? __pfx_acpi_read_bit_register+0x10/0x10
     ? __pfx_rest_init+0x10/0x10
     ? acpi_os_write_port+0x23/0xb0
     ? __pfx_kernel_init+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? acpi_ut_status_exit+0xd6/0x180
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? acpi_ut_status_exit+0xd6/0x180
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? acpi_enable_subsystem+0x2b0/0x4e0
     ? __pfx_x86_late_time_init+0x10/0x10
     start_kernel+0x417/0x4b0
     x86_64_start_reservations+0x18/0x30
     x86_64_start_kernel+0x111/0x120
     common_startup_64+0x13e/0x158
     </TASK>

    Allocated by task 494:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     __kasan_kmalloc+0xaa/0xb0
     __kmalloc_cache_noprof+0x28d/0x610
     ocfs2_initialize_super.isra.0+0xab/0x3070
     ocfs2_fill_super+0x801/0x3920
     get_tree_bdev_flags+0x35d/0x5f0
     vfs_get_tree+0x93/0x320
     fc_mount+0x1d/0x200
     path_mount+0x592/0x1e00
     __x64_sys_mount+0x24b/0x2d0
     do_syscall_64+0x114/0x620
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    Freed by task 494:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     kasan_save_free_info+0x3b/0x60
     __kasan_slab_free+0x5f/0x80
     kfree+0x308/0x580
     ocfs2_dismount_volume+0x43c/0x9b0
     ocfs2_fill_super+0x258f/0x3920
     get_tree_bdev_flags+0x35d/0x5f0
     vfs_get_tree+0x93/0x320
     fc_mount+0x1d/0x200
     path_mount+0x592/0x1e00
     __x64_sys_mount+0x24b/0x2d0
     do_syscall_64+0x114/0x620
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    The buggy address belongs to the object at ffff8881178a4000
     which belongs to the cache kmalloc-8k of size 8192
    The buggy address is located 5720 bytes inside of
     freed 8192-byte region [ffff8881178a4000, ffff8881178a6000)

    The buggy address belongs to the physical page:
    page: refcount:0 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x1178a0
    head: order:3 mapcount:0 entire_mapcount:0 nr_pages_mapped:0 pincount:0
    flags: 0x200000000000040(head|node=0|zone=2)
    page_type: f5(slab)
    raw: 0200000000000040 ffff888100043880 dead000000000122 0000000000000000
    raw: 0000000000000000 0000000000020002 00000000f5000000 0000000000000000
    head: 0200000000000040 ffff888100043880 dead000000000122 0000000000000000
    head: 0000000000000000 0000000000020002 00000000f5000000 0000000000000000
    head: 0200000000000003 fffffffffffffe01 00000000ffffffff 00000000ffffffff
    head: 0000000000000000 0000000000000000 00000000ffffffff 0000000000000000
    page dumped because: kasan: bad access detected

    Memory state around the buggy address:
     ffff8881178a5500: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
     ffff8881178a5580: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
    >ffff8881178a5600: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
                                                        ^
     ffff8881178a5680: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
     ffff8881178a5700: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
    ==================================================================
---
 fs/ocfs2/filecheck.c | 2 ++
 1 file changed, 2 insertions(+)
fs/ocfs2/filecheck.c +2 -0
index 3be84bac44c1e..24b5c6c3a1e2b 100644
@@ -190,6 +190,8 @@ int ocfs2_filecheck_create_sysfs(struct ocfs2_super *osb)
 		/* Mount failure still calls ocfs2_filecheck_remove_sysfs(). */
 		entry->fs_fcheck = NULL;
 		kobject_put(&entry->fs_kobj);
+		/* Keep ocfs2_super alive until the kobject is released. */
+		wait_for_completion(&entry->fs_kobj_unregister);
 		kfree(fcheck);
 		return ret;
 	}
Signature · 1 line
2.53.0
author maintainer
#721 lore raw

PATCH 716/1848 xfs: fix temporary cursor leak in btree shift corruption paths

In reply to Greg Kroah-Hartman

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

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

From: Jianyun Gao <[email protected]>

[ Upstream commit 2bbca049deeb1699cafd966cb2793fee576ee409 ]

In xfs_btree_lshift and xfs_btree_rshift, when XFS_IS_CORRUPT detects an invalid firstrec/lastrec result after xfs_btree_dup_cursor has successfully allocated a temporary cursor, the error path jumps to error0 which returns without freeing tcur. This leaks the cursor memory, the xfs_group reference, and the per-level buffer references held by the duplicated cursor. Jump to error1 instead, which calls xfs_btree_del_cursor(tcur, XFS_BTREE_ERROR) to properly release all resources.

Fixes 9eaead51bed95 ("[XFS] implement generic xfs_btree_rshift")
---
 fs/xfs/libxfs/xfs_btree.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/xfs/libxfs/xfs_btree.c +2 -2
index aaa59daa77d05..6cae1098f73e1 100644
@@ -2396,7 +2396,7 @@ xfs_btree_lshift(
 		i = xfs_btree_firstrec(tcur, level);
 		if (XFS_IS_CORRUPT(tcur->bc_mp, i != 1)) {
 			error = -EFSCORRUPTED;
-			goto error0;
+			goto error1;
 		}
 
 		error = xfs_btree_decrement(tcur, level, &i);
@@ -2566,7 +2566,7 @@ xfs_btree_rshift(
 	i = xfs_btree_lastrec(tcur, level);
 	if (XFS_IS_CORRUPT(tcur->bc_mp, i != 1)) {
 		error = -EFSCORRUPTED;
-		goto error0;
+		goto error1;
 	}
 
 	error = xfs_btree_increment(tcur, level, &i);
Signature · 1 line
2.53.0
author maintainer
#722 lore raw

PATCH 717/1848 net/sched: sch_qfq: prevent aggregate self-replacement

In reply to Greg Kroah-Hartman

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

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

From: Kyle Zeng <[email protected]>

[ Upstream commit 2e54b3e187300893688c2c7517894f5d96732e05 ]

qfq_change_class() snapshots the current aggregate settings while holding the qdisc tree lock, but drops the lock before selecting the destination aggregate. During that gap, qfq_enqueue() can move the class to an aggregate matching the requested settings.

When qfq_change_class() resumes, qfq_find_agg() then returns cl->agg. If it is a singleton, qfq_deact_rm_from_agg() frees the aggregate before qfq_add_to_agg() immediately accesses the same pointer, causing a use-after-free.

While holding the tree lock, skip the replacement when the destination is already the current aggregate. Any estimator replacement has already completed, so the class change can finish normally.

---
 net/sched/sch_qfq.c | 3 +++
 1 file changed, 3 insertions(+)
net/sched/sch_qfq.c +3 -0
index 1c38447b456a7..7092082b4a326 100644
@@ -520,11 +520,14 @@ static int qfq_change_class(struct Qdisc *sch, u32 classid, u32 parentid,
 		sch_tree_lock(sch);
 		qfq_init_agg(q, new_agg, lmax, weight);
 	}
+	if (existing && new_agg == cl->agg)
+		goto unlock;
 	if (existing)
 		qfq_deact_rm_from_agg(q, cl);
 	else
 		qdisc_class_hash_insert(&q->clhash, &cl->common);
 	qfq_add_to_agg(q, new_agg, cl);
+unlock:
 	sch_tree_unlock(sch);
 	qdisc_class_hash_grow(sch, &q->clhash);
 
Signature · 1 line
2.53.0
author maintainer
#723 lore raw

PATCH 718/1848 drm/bridge: nwl-dsi: Cleanup endpoint mux control selection

In reply to Greg Kroah-Hartman

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

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

From: Esben Haabendal <[email protected]>

[ Upstream commit 8dad0ebd822f54102aadc6ca4f0f8777112d175d ]

Using the endpoint define values makes it more clear that the argument to mux_control_try_select() must be valid state integers, and not something that looks like a boolean.

The endpoint value is kept, as it will be used in a following patch that changes behavior slightly based on which endpoint is selected.

---
 drivers/gpu/drm/bridge/nwl-dsi.c | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)
drivers/gpu/drm/bridge/nwl-dsi.c +6 -4
index b68d335981588..0b2dfdd5d3233 100644
@@ -116,6 +116,8 @@ struct nwl_dsi {
 	int error;
 
 	struct nwl_dsi_transfer *xfer;
+
+	unsigned int endpoint;
 };
 
 static const struct regmap_config nwl_dsi_regmap_config = {
@@ -1087,13 +1089,12 @@ static int nwl_dsi_parse_dt(struct nwl_dsi *dsi)
 static int nwl_dsi_select_input(struct nwl_dsi *dsi)
 {
 	struct device_node *remote;
-	u32 use_dcss = 1;
 	int ret;
 
 	remote = of_graph_get_remote_node(dsi->dev->of_node, 0,
 					  NWL_DSI_ENDPOINT_LCDIF);
 	if (remote) {
-		use_dcss = 0;
+		dsi->endpoint = NWL_DSI_ENDPOINT_LCDIF;
 	} else {
 		remote = of_graph_get_remote_node(dsi->dev->of_node, 0,
 						  NWL_DSI_ENDPOINT_DCSS);
@@ -1102,11 +1103,12 @@ static int nwl_dsi_select_input(struct nwl_dsi *dsi)
 				      "No valid input endpoint found\n");
 			return -EINVAL;
 		}
+		dsi->endpoint = NWL_DSI_ENDPOINT_DCSS;
 	}
 
 	DRM_DEV_INFO(dsi->dev, "Using %s as input source\n",
-		     (use_dcss) ? "DCSS" : "LCDIF");
-	ret = mux_control_try_select(dsi->mux, use_dcss);
+		     (dsi->endpoint == NWL_DSI_ENDPOINT_DCSS) ? "DCSS" : "LCDIF");
+	ret = mux_control_try_select(dsi->mux, dsi->endpoint);
 	if (ret < 0)
 		DRM_DEV_ERROR(dsi->dev, "Failed to select input: %d\n", ret);
 
Signature · 1 line
2.53.0
author maintainer
#724 lore raw

PATCH 719/1848 drm/bridge: nwl-dsi: Limit LCDIF specific sync override

In reply to Greg Kroah-Hartman

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

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

From: Esben Haabendal <[email protected]>

[ Upstream commit 54a88d9afcca66221d14f438d0960472984968ec ]

When using DCSS with NWL, overriding the mode flags to enforce active high sync is preventing the use of active low with downstream bridges, such as ti-sn65dsi83, which will not see such mode flags set by the panel.

Fixes 44cfc6233447 ("drm/bridge: Add NWL MIPI DSI host controller support")
---
 drivers/gpu/drm/bridge/nwl-dsi.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
drivers/gpu/drm/bridge/nwl-dsi.c +5 -2
index 0b2dfdd5d3233..f9b6b8a3f6e67 100644
@@ -831,10 +831,13 @@ static int nwl_dsi_bridge_atomic_check(struct drm_bridge *bridge,
 				       struct drm_connector_state *conn_state)
 {
 	struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
+	struct nwl_dsi *dsi = bridge_to_dsi(bridge);
 
 	/* At least LCDIF + NWL needs active high sync */
-	adjusted_mode->flags |= (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC);
-	adjusted_mode->flags &= ~(DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC);
+	if (dsi->endpoint == NWL_DSI_ENDPOINT_LCDIF) {
+		adjusted_mode->flags |= (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC);
+		adjusted_mode->flags &= ~(DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC);
+	}
 
 	/* Do a full modeset if crtc_state->active is changed to be true. */
 	if (crtc_state->active_changed && crtc_state->active)
Signature · 1 line
2.53.0
author maintainer
#725 lore raw

PATCH 720/1848 inotify: do not coalesce rename events

In reply to Greg Kroah-Hartman

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

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

From: Hungyu Lin <[email protected]>

[ Upstream commit 581230d2ec3c0380917d1255792508851e7c4627 ]

inotify compares the mask, watch descriptor and name when coalescing adjacent unread events, but ignores their rename cookies. Distinct IN_MOVED_FROM events can therefore be coalesced, losing the cookie needed to match a later IN_MOVED_TO event.

For example, watch two directories with IN_MOVE. Move an entry from the first directory into an unwatched directory, recreate it under the same name, then move it from the first directory into the second watched directory before reading the events. The second IN_MOVED_FROM is merged with the first, while the IN_MOVED_TO retains the second rename's cookie. Userspace can no longer pair the second rename's events.

The original inotify implementation compared cookies before coalescing. The fsnotify conversion lost this comparison. Do not coalesce IN_MOVED_FROM or IN_MOVED_TO events, which carry the identity of their respective renames. Leave coalescing of other event types unchanged.

---
 fs/notify/inotify/inotify_fsnotify.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/notify/inotify/inotify_fsnotify.c +1 -1
index 993375f0db673..ff0af29745a8c 100644
@@ -36,7 +36,7 @@ static bool event_compare(struct fsnotify_event *old_fsn,
 
 	old = INOTIFY_E(old_fsn);
 	new = INOTIFY_E(new_fsn);
-	if (old->mask & FS_IN_IGNORED)
+	if (old->mask & (FS_IN_IGNORED | FS_MOVE))
 		return false;
 	if ((old->mask == new->mask) &&
 	    (old->wd == new->wd) &&
Signature · 1 line
2.53.0
author maintainer
#726 lore raw

PATCH 721/1848 block: Return the soft block size for compat BLKBSZGET

In reply to Greg Kroah-Hartman

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

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

From: Hungyu Lin <[email protected]>

[ Upstream commit 57cd1a08717690e5ea01d7ac7a96bb33a2dca117 ]

BLKBSZGET returns the block device's soft block size, while BLKSSZGET returns its logical sector size. The compat BLKBSZGET_32 handler uses bdev_logical_block_size(), so it returns the wrong value when these sizes differ.

For example, on an x86_64 kernel a native query of a RAM or loop device with 512-byte logical sectors returns the initial soft block size of 4096 bytes, but an i386 process gets 512 bytes. This makes 32-bit blockdev --getbsz and the BSZ column of --report disagree with native queries, even without a preceding BLKBSZSET.

Use block_size() as the native handler and the pre-regression compat handler do, and correct the case comment to describe the soft size.

---
 block/ioctl.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
block/ioctl.c +2 -2
index 11e692741f17c..5212ef396c220 100644
@@ -692,8 +692,8 @@ long compat_blkdev_ioctl(struct file *file, unsigned cmd, unsigned long arg)
 		return compat_put_ulong(argp, size >> 9);
 
 	/* The data is compatible, but the command number is different */
-	case BLKBSZGET_32: /* get the logical block size (cf. BLKSSZGET) */
-		return put_int(argp, bdev_logical_block_size(bdev));
+	case BLKBSZGET_32: /* get the soft block size (cf. BLKSSZGET) */
+		return put_int(argp, block_size(bdev));
 	case BLKBSZSET_32:
 		return blkdev_bszset(bdev, mode, argp);
 	case BLKGETSIZE64_32:
Signature · 1 line
2.53.0
author maintainer
#727 lore raw

PATCH 722/1848 xfs: fix wrong compat fields in xfs_ioctl32_bstat_copyin()

In reply to Greg Kroah-Hartman

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

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

From: Reid Downing <[email protected]>

[ Upstream commit b7eb276a39b14e685c2fe578f8ac22fc48ff9e6c ]

bs_blocks and bs_xflags were both read from bstat32->bs_size. Read each one from its own field instead.

Fixes e94fc4a43e5c39 ("[XFS] Add compat handlers for swapext ioctl")
Cc [email protected] # v2.6.29
---
 fs/xfs/xfs_ioctl32.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/xfs/xfs_ioctl32.c +2 -2
index c1771e7281177..62d62c2a9fc07 100644
@@ -136,8 +136,8 @@ xfs_ioctl32_bstat_copyin(
 	    xfs_ioctl32_bstime_copyin(&bstat->bs_atime, &bstat32->bs_atime) ||
 	    xfs_ioctl32_bstime_copyin(&bstat->bs_mtime, &bstat32->bs_mtime) ||
 	    xfs_ioctl32_bstime_copyin(&bstat->bs_ctime, &bstat32->bs_ctime) ||
-	    get_user(bstat->bs_blocks,	&bstat32->bs_size)	||
-	    get_user(bstat->bs_xflags,	&bstat32->bs_size)	||
+	    get_user(bstat->bs_blocks,	&bstat32->bs_blocks)	||
+	    get_user(bstat->bs_xflags,	&bstat32->bs_xflags)	||
 	    get_user(bstat->bs_extsize,	&bstat32->bs_extsize)	||
 	    get_user(bstat->bs_extents,	&bstat32->bs_extents)	||
 	    get_user(bstat->bs_gen,	&bstat32->bs_gen)	||
Signature · 1 line
2.53.0
author maintainer
#728 lore raw

PATCH 723/1848 xfs: clamp a pNFS LAYOUTCOMMIT extent before computing its end

In reply to Greg Kroah-Hartman

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

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

From: Daejun Park <[email protected]>

[ Upstream commit d8c2bc88460f89e543ab3af622fc8f34c7011d71 ]

xfs_fs_commit_blocks() adds the client's length to the offset before it clamps the end to the file size. A large length wraps the sum and reaches xfs_iomap_write_unwritten() unclamped. With the previous two patches the LAYOUTCOMMIT then fails with -EIO and converts nothing.

Clamp the length first.

Fixes 527851124d10 ("xfs: implement pNFS export operations")
---
 fs/xfs/xfs_pnfs.c | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)
fs/xfs/xfs_pnfs.c +1 -3
index 053b99929f835..8b82249b48110 100644
@@ -250,9 +250,7 @@ xfs_fs_commit_blocks(
 		if (start > size)
 			continue;
 
-		end = start + maps[i].length;
-		if (end > size)
-			end = size;
+		end = start + min_t(u64, maps[i].length, size - start);
 
 		length = end - start;
 		if (!length)
Signature · 1 line
2.53.0
author maintainer
#729 lore raw

PATCH 724/1848 xfs: clamp the pNFS layout range to the maximum file size

In reply to Greg Kroah-Hartman

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

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

From: Daejun Park <[email protected]>

[ Upstream commit 29f3c1be4e554c9dbc66e13333034e0947477cb6 ]

xfs_fs_map_blocks() lets two bad layout ranges through. An offset of 2^63 or more is negative and passes "offset > limit". A length above the limit, such as NFS4_UINT64_MAX, wraps "offset > limit - length" and stays unclamped. With NFS4_UINT64_MAX, a read layout is built from an uninitialized mapping.

Reject a negative offset and one at the limit, and clamp the length. This needs "xfs: cap the block count of xfs_iomap_write_direct() at one extent".

---
 fs/xfs/xfs_pnfs.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
fs/xfs/xfs_pnfs.c +2 -3
index 8b82249b48110..e02a6b84c609c 100644
@@ -124,10 +124,9 @@ xfs_fs_map_blocks(
 	if (!write)
 		limit = max(limit, round_up(i_size_read(inode),
 				     inode->i_sb->s_blocksize));
-	if (offset > limit)
+	if (offset < 0 || offset >= limit)
 		goto out_unlock;
-	if (offset > limit - length)
-		length = limit - offset;
+	length = min_t(u64, length, limit - offset);
 
 	error = filemap_write_and_wait(inode->i_mapping);
 	if (error)
Signature · 1 line
2.53.0
author maintainer
#730 lore raw

PATCH 725/1848 can: isotp: check the return values of can_rx_register() in isotp_bind()

In reply to Greg Kroah-Hartman

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

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

From: Oliver Hartkopp <[email protected]>

[ Upstream commit 874f5f14cf626f72477071eff381c8485554250d ]

isotp_bind() ignores the return values of can_rx_register() for the RX and the echo receiver and binds the socket anyway. When a receiver can not be allocated, bind() succeeds without this receiver, so the socket does not receive frames or its transmissions time out. isotp_release() and isotp_notify() later try to remove the missing receiver, which triggers the "receive list entry not found" warning in can_rx_unregister().

As the device has been checked before and RTNL prevents a namespace change during bind(), only -ENOMEM can be returned here.

Check the return values and register the RX receiver as the last step. The echo receiver is registered first, as it only handles the socket's own echo frames and does nothing while no transmission is in progress. So a failed RX registration only needs to remove the echo receiver, and isotp_rcv() has never processed a frame for this socket.

Set so->ifindex before the registrations, so that a First Frame received before so->bound is set can be answered with a Flow Control frame and the RX timeout is started as usual. As the RX receiver is registered last, this can only happen for a bind() that succeeds. Reset so->ifindex when bind() fails.

Check IFF_UP only after the receivers have been registered, so that a bind() that fails on a down device does not report ENETDOWN. As bind() holds RTNL, the device state can not change in between.

Fixes e057dd3fc20f ("can: add ISO 15765-2:2016 transport protocol")
---
 net/can/isotp.c | 42 +++++++++++++++++++++++++++---------------
 1 file changed, 27 insertions(+), 15 deletions(-)
net/can/isotp.c +27 -15
index 01d5a4603663c..d06a99ce84135 100644
@@ -1482,7 +1482,6 @@ static int isotp_bind(struct socket *sock, struct sockaddr *uaddr, int len)
 	struct sock *sk = sock->sk;
 	struct isotp_sock *so = isotp_sk(sk);
 	struct net *net = sock_net(sk);
-	int ifindex;
 	struct net_device *dev;
 	canid_t tx_id = addr->can_addr.tp.tx_id;
 	canid_t rx_id = addr->can_addr.tp.rx_id;
@@ -1559,26 +1558,36 @@ static int isotp_bind(struct socket *sock, struct sockaddr *uaddr, int len)
 		err = -EINVAL;
 		goto out_put_dev;
 	}
-	if (!(dev->flags & IFF_UP))
-		notify_enetdown = 1;
 
-	ifindex = dev->ifindex;
-
-	if (isotp_register_rxid(so))
-		can_rx_register(net, dev, rx_id, SINGLE_MASK(rx_id),
-				isotp_rcv, sk, "isotp", sk);
+	/* switch to new settings */
+	so->ifindex = dev->ifindex;
+	so->rxid = rx_id;
+	so->txid = tx_id;
 
 	/* no consecutive frame echo skb in flight */
 	WRITE_ONCE(so->cfecho, 0);
 
-	/* register for echo skb's */
-	can_rx_register(net, dev, tx_id, SINGLE_MASK(tx_id),
-			isotp_rcv_echo, sk, "isotpe", sk);
+	/* register for echo skb's first (no echo traffic at this point) */
+	err = can_rx_register(net, dev, tx_id, SINGLE_MASK(tx_id),
+			      isotp_rcv_echo, sk, "isotpe", sk);
+	if (err)
+		goto out_put_dev;
+
+	if (isotp_register_rxid(so)) {
+		err = can_rx_register(net, dev, rx_id, SINGLE_MASK(rx_id),
+				      isotp_rcv, sk, "isotp", sk);
+		if (err) {
+			/* unregister echo skb subscription */
+			can_rx_unregister(net, dev, tx_id, SINGLE_MASK(tx_id),
+					  isotp_rcv_echo, sk);
+			goto out_put_dev;
+		}
+	}
+
+	/* report a down device only for a successful bind() */
+	if (!(dev->flags & IFF_UP))
+		notify_enetdown = 1;
 
-	/* switch to new settings */
-	so->ifindex = ifindex;
-	so->rxid = rx_id;
-	so->txid = tx_id;
 	so->bound = 1;
 
 	/* bind() ok -> hold a reference for so->dev so that isotp_release()
@@ -1589,6 +1598,9 @@ static int isotp_bind(struct socket *sock, struct sockaddr *uaddr, int len)
 	dev_hold(so->dev);
 
 out_put_dev:
+	if (err)
+		so->ifindex = 0; /* reset on failed bind() */
+
 	/* remove potential reference from dev_get_by_index() */
 	dev_put(dev);
 out:
Signature · 1 line
2.53.0
author maintainer
#731 lore raw

PATCH 726/1848 can: proc: reset pkg_stats atomics individually

In reply to Greg Kroah-Hartman

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

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

From: Runyu Xiao <[email protected]>

[ Upstream commit 12297f855bbd943847cb8893a3614caef5a9c2a8 ]

Commit 80b5f90158d1 ("can: statistics: use atomic access in hot path") converted several members of struct can_pkg_stats to atomic_long_t and updated the hot TX/RX and procfs read paths to use atomic_long_*() helpers. However, can_init_stats() still clears the whole struct with memset().

can_init_stats() is reached from can_stat_update() in timer context and also from the procfs reset path. Those paths can run while the TX/RX hot paths are concurrently updating rx_frames, tx_frames, matches and their *_delta counters. Hitting the whole-struct memset() in that window performs plain writes to fields that otherwise follow an atomic_long_t access contract, which can lose or mix live statistics updates.

This issue was found by source-level API-misuse analysis looking for whole-object resets left behind after atomic_long_t conversions, then manually audited on Linux v6.18.21.

Replace the whole-struct memset() with a helper that resets the atomic_long_t counters via atomic_long_set() and clears the derived scalar statistics explicitly. This preserves the existing reset semantics for scalar fields while restoring atomic access discipline for the live counters.

Build-tested by compiling net/can/proc.o on x86_64 netdev/main. Runtime-tested with a QEMU + vcan setup on Linux v6.18.21 by driving concurrent traffic and reset_stats reads, which reproduced inconsistent exported statistics before the fix.

[Hartkopp] can_stat_update() also read the *_delta counters at the beginning and cleared them with atomic_long_set() at the end. Increments from the hot path in between were lost for both the current and the next interval. Use atomic_long_xchg() to fetch and clear the *_delta counters in one atomic step instead.

On x86_64 atomic_long_set() is a plain store like memset(), so the memset() is an actual problem only on architectures with lock-based atomics (e.g. parisc). The inconsistencies seen on x86_64 come from the *_delta handling and from the stale snapshots, which are fixed in "can:
proc: skip stats calculation after reset in can_stat_update()". As before, the counters are reset one at a time and the derived scalar statistics use plain stores.

---
 net/can/proc.c | 39 +++++++++++++++++++++++++++++----------
 1 file changed, 29 insertions(+), 10 deletions(-)
net/can/proc.c +29 -10
index 550d46d1c60a4..d21f4eab1cba9 100644
@@ -76,16 +76,39 @@ static const char rx_list_name[][8] = {
  * af_can statistics stuff
  */
 
+static void can_reset_pkg_stats(struct can_pkg_stats *pkg_stats)
+{
+	atomic_long_set(&pkg_stats->rx_frames, 0);
+	atomic_long_set(&pkg_stats->tx_frames, 0);
+	atomic_long_set(&pkg_stats->matches, 0);
+
+	pkg_stats->total_rx_rate = 0;
+	pkg_stats->total_tx_rate = 0;
+	pkg_stats->total_rx_match_ratio = 0;
+
+	pkg_stats->current_rx_rate = 0;
+	pkg_stats->current_tx_rate = 0;
+	pkg_stats->current_rx_match_ratio = 0;
+
+	pkg_stats->max_rx_rate = 0;
+	pkg_stats->max_tx_rate = 0;
+	pkg_stats->max_rx_match_ratio = 0;
+
+	atomic_long_set(&pkg_stats->rx_frames_delta, 0);
+	atomic_long_set(&pkg_stats->tx_frames_delta, 0);
+	atomic_long_set(&pkg_stats->matches_delta, 0);
+}
+
 static void can_init_stats(struct net *net)
 {
 	struct can_pkg_stats *pkg_stats = net->can.pkg_stats;
 	struct can_rcv_lists_stats *rcv_lists_stats = net->can.rcv_lists_stats;
 	/*
-	 * This memset function is called from a timer context (when
+	 * This stats reset is called from a timer context (when
 	 * can_stattimer is active which is the default) OR in a process
 	 * context (reading the proc_fs when can_stattimer is disabled).
 	 */
-	memset(pkg_stats, 0, sizeof(struct can_pkg_stats));
+	can_reset_pkg_stats(pkg_stats);
 	pkg_stats->jiffies_init = jiffies;
 
 	rcv_lists_stats->stats_reset++;
@@ -125,9 +148,10 @@ void can_stat_update(struct timer_list *t)
 	long rx_frames = atomic_long_read(&pkg_stats->rx_frames);
 	long tx_frames = atomic_long_read(&pkg_stats->tx_frames);
 	long matches = atomic_long_read(&pkg_stats->matches);
-	long rx_frames_delta = atomic_long_read(&pkg_stats->rx_frames_delta);
-	long tx_frames_delta = atomic_long_read(&pkg_stats->tx_frames_delta);
-	long matches_delta = atomic_long_read(&pkg_stats->matches_delta);
+	/* fetch and clear values for 'current rate' calculation */
+	long rx_frames_delta = atomic_long_xchg(&pkg_stats->rx_frames_delta, 0);
+	long tx_frames_delta = atomic_long_xchg(&pkg_stats->tx_frames_delta, 0);
+	long matches_delta = atomic_long_xchg(&pkg_stats->matches_delta, 0);
 
 	/* restart counting in timer context on user request */
 	if (user_reset)
@@ -176,11 +200,6 @@ void can_stat_update(struct timer_list *t)
 	if (pkg_stats->max_rx_match_ratio < pkg_stats->current_rx_match_ratio)
 		pkg_stats->max_rx_match_ratio = pkg_stats->current_rx_match_ratio;
 
-	/* clear values for 'current rate' calculation */
-	atomic_long_set(&pkg_stats->tx_frames_delta, 0);
-	atomic_long_set(&pkg_stats->rx_frames_delta, 0);
-	atomic_long_set(&pkg_stats->matches_delta, 0);
-
 	/* restart timer (one second) */
 	mod_timer(&net->can.stattimer, round_jiffies(jiffies + HZ));
 }
Signature · 1 line
2.53.0
author maintainer
#732 lore raw

PATCH 727/1848 can: proc: skip stats calculation after reset in can_stat_update()

In reply to Greg Kroah-Hartman

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

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

From: Oliver Hartkopp <[email protected]>

[ Upstream commit 01b19ed9fa031a649f3dd103ebe6e0102602e542 ]

Commit 80b5f90158d1 ("can: statistics: use atomic access in hot path") introduced local snapshots of the statistics counters at the beginning of can_stat_update(). When can_init_stats() resets the statistics, these stale pre-reset snapshots are still used for the following total/current /max calculations and overwrite the freshly reset values. Additionally a jiffies tick between the snapshot and the reset could trigger a second can_init_stats() call.

Merge the reset conditions into a single check and skip the calculation for the current interval when the statistics have been reset.

Fixes 80b5f90158d1 ("can: statistics: use atomic access in hot path")
---
 net/can/proc.c | 30 ++++++++++++------------------
 1 file changed, 12 insertions(+), 18 deletions(-)
net/can/proc.c +12 -18
index d21f4eab1cba9..396a637054da4 100644
@@ -153,25 +153,18 @@ void can_stat_update(struct timer_list *t)
 	long tx_frames_delta = atomic_long_xchg(&pkg_stats->tx_frames_delta, 0);
 	long matches_delta = atomic_long_xchg(&pkg_stats->matches_delta, 0);
 
-	/* restart counting in timer context on user request */
-	if (user_reset)
-		can_init_stats(net);
-
-	/* restart counting on jiffies overflow */
-	if (j < pkg_stats->jiffies_init)
-		can_init_stats(net);
-
-	/* prevent overflow in calc_rate() */
-	if (rx_frames > (LONG_MAX / HZ))
-		can_init_stats(net);
-
-	/* prevent overflow in calc_rate() */
-	if (tx_frames > (LONG_MAX / HZ))
-		can_init_stats(net);
-
-	/* matches overflow - very improbable */
-	if (matches > (LONG_MAX / 100))
+	/*
+	 * Restart counting in timer context on user request, on jiffies
+	 * overflow or to prevent overflows in calc_rate() and in the
+	 * match ratio calculation. The local snapshots are stale after
+	 * the reset, so skip the calculation for this interval.
+	 */
+	if (user_reset || j < pkg_stats->jiffies_init ||
+	    rx_frames > (LONG_MAX / HZ) || tx_frames > (LONG_MAX / HZ) ||
+	    matches > (LONG_MAX / 100)) {
 		can_init_stats(net);
+		goto out;
+	}
 
 	/* calc total values */
 	if (rx_frames)
@@ -200,6 +193,7 @@ void can_stat_update(struct timer_list *t)
 	if (pkg_stats->max_rx_match_ratio < pkg_stats->current_rx_match_ratio)
 		pkg_stats->max_rx_match_ratio = pkg_stats->current_rx_match_ratio;
 
+out:
 	/* restart timer (one second) */
 	mod_timer(&net->can.stattimer, round_jiffies(jiffies + HZ));
 }
Signature · 1 line
2.53.0
author maintainer
#733 lore raw

PATCH 728/1848 can: peak_usb: pcan_usb_fd_decode_buf(): accept short uCAN end-of-list records

In reply to Greg Kroah-Hartman

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

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

From: Liu Changjie <[email protected]>

[ Upstream commit 2d4c272e816a5b784f1fc7899256f8826df34edb ]

A PCAN-USB FD v2 running firmware 3.2.0 sends a 16-byte status record followed by a four-byte zero-size end marker.

Since commit 93fcab2c6968 ("can: peak_usb: validate uCAN receive record lengths") these transfers cause repeated receive-buffer dumps while the interface is up.

This has been observed on Linux 7.2.11-arch1-1 with matching kernel headers:
- Classic CAN, 500 kbit/s: 25 decoder errors in 5 s before the fix; none in 15 s after.
- CAN FD, 500 kbit/s nominal and 2 Mbit/s data: 26 decoder errors in 5 s before the fix; none in 60 s after.
- Three additional down/up cycles: no decoder errors.

pcan_usb_fd_decode_buf() requires a complete 12-byte struct pucan_msg before checking the size field, so it rejects the end marker with -EBADMSG.

Check that the size field is present before testing for an end marker. Require the full header for nonzero-size records and keep the remaining record and payload length checks.

This patch was created with LLM assistance.

Fixes 93fcab2c6968 ("can: peak_usb: validate uCAN receive record lengths")
[mkl: copy additional info to commit message]
[mkl: convert Assisted-by: tag to prose]

---
Built and tested the original and patched peak_usb modules on Arch Linux 7.2.11-arch1-1 with matching kernel headers.

- Classic CAN, 500 kbit/s: 25 decoder errors in 5 s before the fix; none in 15 s after.
- CAN FD, 500 kbit/s nominal and 2 Mbit/s data: 26 decoder errors in 5 s before the fix; none in 60 s after.
- Three additional down/up cycles: no decoder errors.

USB captures during the patched tests contained 406 packets with short end markers. Neither receive-buffer dump recurred.

The CAN bus was disconnected; external TX/RX was not tested. One startup "can_change_state: oops, state did not change" message and an RX dropped count reaching 2 were observed during the patched tests. Their causes remain undetermined.

---
 drivers/net/can/usb/peak_usb/pcan_usb_fd.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
drivers/net/can/usb/peak_usb/pcan_usb_fd.c +6 -1
index 709bf603784fe..dccc00e08f012 100644
@@ -692,7 +692,7 @@ static int pcan_usb_fd_decode_buf(struct peak_usb_device *dev, struct urb *urb)
 		u16 rx_msg_type, rx_msg_size;
 		size_t rx_msg_min_size;
 
-		if (msg_end - msg_ptr < sizeof(*rx_msg)) {
+		if (msg_end - msg_ptr < sizeof(rx_msg->size)) {
 			err = -EBADMSG;
 			break;
 		}
@@ -703,6 +703,11 @@ static int pcan_usb_fd_decode_buf(struct peak_usb_device *dev, struct urb *urb)
 			break;
 		}
 
+		if (msg_end - msg_ptr < sizeof(*rx_msg)) {
+			err = -EBADMSG;
+			break;
+		}
+
 		rx_msg_size = le16_to_cpu(rx_msg->size);
 		rx_msg_type = le16_to_cpu(rx_msg->type);
 
Signature · 1 line
2.53.0
author maintainer
#734 lore raw

PATCH 729/1848 mm/gup: fix out-of-bounds write for nr_pages == 0 in GUP-fast

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

[ Upstream commit 1dfe4b276c23189394afb42d114ee8a54cc3aff2 ]

With nr_pages == 0, GUP-fast still enters its page table walk and can write past the caller's page array. The old end <= start check caught empty ranges, but was replaced with an overflow check.

Users such as OrangeFS can pass a zero page count derived from a userspace-supplied length. So let's return zero for nr_pages == 0 before starting the walk, just like GUP-slow.

Fix generated by an LLM and sent by Chris Mason in private.

---
 mm/gup.c | 3 +++
 1 file changed, 3 insertions(+)
mm/gup.c +3 -0
index 11307a8b20d58..e1fe283badf3b 100644
@@ -2743,6 +2743,9 @@ static int internal_get_user_pages_fast(unsigned long start,
 				       FOLL_FAST_ONLY)))
 		return -EINVAL;
 
+	if (unlikely(!nr_pages))
+		return 0;
+
 	if (gup_flags & FOLL_PIN)
 		atomic_set(&current->mm->has_pinned, 1);
 
Signature · 1 line
2.53.0
author maintainer
#735 lore raw

PATCH 730/1848 mm/mmu_gather: fix flushing ranges with 4 GiB or larger

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 64ae7959a1df8af8eec504e31df2ec9670424a4e ]

__tlb_adjust_range() takes the size of the range which has to be flushed as an unsigned int. Its callers, tlb_flush_{pte,pmd,pud,p4d}_range(), get and pass an unsigned long. Consequently, a range that is 4 GiB or larger gets truncated, possibly to 0.

On arm64 with hugetlb, a 64k kernel can have 16 GiB hugetlb folios mapped contiguously at the PMD level and flush them when unmapping, and a 16k kernel can flush 64 GiB PUDs through tlb_unshare_pmd_ptdesc(). So at least these two scenarios are affected.

Fix it by flushing the proper range instead of the truncated one by properly using "unsigned long" for range_size.

Fix generated by an LLM and sent by Josef Bacik in private.

Fixes b528e4b6405b ("mm/hugetlb: add tlb_remove_hugetlb_entry for handling hugetlb pages")
Fixes 8ce720d5bd91 ("mm/hugetlb: fix excessive IPI broadcasts when unsharing PMD tables using mmu_gather")
[ david: use two-tab indent, simplify description ]
---
 include/asm-generic/tlb.h | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
include/asm-generic/tlb.h +1 -2
index a80accdbcd255..b811f05d1e625 100644
@@ -322,8 +322,7 @@ struct mmu_gather {
 void tlb_flush_mmu(struct mmu_gather *tlb);
 
 static inline void __tlb_adjust_range(struct mmu_gather *tlb,
-				      unsigned long address,
-				      unsigned int range_size)
+		unsigned long address, unsigned long range_size)
 {
 	tlb->start = min(tlb->start, address);
 	tlb->end = max(tlb->end, address + range_size);
Signature · 1 line
2.53.0
author maintainer
#736 lore raw

PATCH 731/1848 mm/mmu_notifier: set ->mm only after mmgrab()

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

[ Upstream commit 5ad9e4b0f1104f5dbfb41125c34bb30ea6dc7a94 ]

Radeon uses a non-NULL notifier->mm to decide whether to call mmu_interval_notifier_remove() when freeing a buffer object. __mmu_interval_notifier_insert() sets ->mm before validating the range, so a wrapping userptr range can leave ->mm set after insertion fails. Cleanup then tries to remove an unregistered notifier for which no mm reference was acquired.

Set ->mm only after mmgrab(), once insertion can no longer fail. While we could fix radeon's code instead, setting ->mm on success only makes the code more robust.

Fix generated by an LLM and sent by Chris Mason in private.

---
 mm/mmu_notifier.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
mm/mmu_notifier.c +5 -2
index 9165ca619c8cf..b66b9ae21538f 100644
@@ -922,7 +922,6 @@ static int __mmu_interval_notifier_insert(
 	struct mmu_notifier_subscriptions *subscriptions, unsigned long start,
 	unsigned long length, const struct mmu_interval_notifier_ops *ops)
 {
-	interval_sub->mm = mm;
 	interval_sub->ops = ops;
 	RB_CLEAR_NODE(&interval_sub->interval_tree.rb);
 	interval_sub->interval_tree.start = start;
@@ -939,8 +938,12 @@ static int __mmu_interval_notifier_insert(
 	if (WARN_ON(atomic_read(&mm->mm_users) <= 0))
 		return -EINVAL;
 
-	/* pairs with mmdrop in mmu_interval_notifier_remove() */
+	/*
+	 * Pairs with mmdrop in mmu_interval_notifier_remove(). Drivers take a
+	 * non-NULL ->mm for "registered", so set it only with the reference.
+	 */
 	mmgrab(mm);
+	interval_sub->mm = mm;
 
 	/*
 	 * If some invalidate_range_start/end region is going on in parallel
Signature · 1 line
2.53.0
author maintainer
#737 lore raw

PATCH 732/1848 mm: fix unmap_mapping_range() beyond 4 GiB on 32-bit

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 7a81bc23dade8082187be6d9cc36e4be4b7207e2 ]

Commit 9eab0421fa94 ("mm: fix unmap_mapping_range high bits shift bug") made holebegin and holelen unsigned before they are shifted, by casting them to pgoff_t. That is an unsigned long: on a 32-bit kernel the cast cuts off the upper half of the two loff_t values, so a hole which begins at 4 GiB or beyond is taken for one in the first 4 GiB of the file.

truncate_pagecache() passes the new size of the file and asks for private COWed pages to be unmapped as well. If a file of 6 GiB is truncated to 5 GiB, everything from 1 GiB on is unmapped, and what a process has written to a private mapping of the range between 1 GiB and 5 GiB is
lost: it reads the contents of the file again.

Where the range has an end, the wrong range is unmapped instead of the right one. The page cache copes with that, as it unmaps every folio that it removes. The callers which only have unmap_mapping_range() to get rid of user mappings do not, for example drm_vma_node_unmap(), whose fake offsets reach beyond 4 GiB on 32-bit, and revoke_iomem() with physical addresses of more than 32 bits.

Cast to u64 instead. Nothing changes for 64-bit kernels.

Fix generated by an LLM and sent by Josef Bacik in private.

---
 mm/memory.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
mm/memory.c +2 -2
index 3ebf3f1da428b..403fcef10bdac 100644
@@ -3328,8 +3328,8 @@ void unmap_mapping_pages(struct address_space *mapping, pgoff_t start,
 void unmap_mapping_range(struct address_space *mapping,
 		loff_t const holebegin, loff_t const holelen, int even_cows)
 {
-	pgoff_t hba = (pgoff_t)(holebegin) >> PAGE_SHIFT;
-	pgoff_t hlen = ((pgoff_t)(holelen) + PAGE_SIZE - 1) >> PAGE_SHIFT;
+	pgoff_t hba = (u64)holebegin >> PAGE_SHIFT;
+	pgoff_t hlen = ((u64)holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
 
 	/* Check for overflow. */
 	if (sizeof(holelen) > sizeof(hlen)) {
Signature · 1 line
2.53.0
author maintainer
#738 lore raw

PATCH 733/1848 mm/ksm: reset the unstable trees of all nodes

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit 890e118e95bfc2aae4432ec2a95192d6f9193211 ]

Each full scan resets ksm_nr_node_ids unstable tree roots. Enabling merge_across_nodes resets this count to 1, even if per-node roots were previously allocated.

So when toggling "merge_across_nodes" 0 -> 1 -> 0, a scan that starts while the setting is 1 and continues after switching back to 0 can encounter stale unstable tree roots, resulting in UAF.

Only root is allowed to change "merge_across_nodes", and the documented sequence is: "merge_across_nodes setting can be changed only when there are no ksm shared pages in the system: set run 2 to unmerge pages first, then to 1 after changing merge_across_nodes, to remerge according to the new setting."

Let's fix it by tracking in ksm_nr_node_ids the actual number of allocated tree roots.

remove_all_stable_nodes() and ksm_check_stable_tree() will now scan more tree roots (skipping the empty ones), which is harmless.

---
 mm/ksm.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
mm/ksm.c +3 -3
index 94d17fb3f184f..466ca19997551 100644
@@ -282,6 +282,7 @@ static bool ksm_use_zero_pages __read_mostly;
 #ifdef CONFIG_NUMA
 /* Zeroed when merging across nodes is not allowed */
 static unsigned int ksm_merge_across_nodes = 1;
+/* Number of allocated stable and unstable tree roots. */
 static int ksm_nr_node_ids = 1;
 #else
 #define ksm_merge_across_nodes	1U
@@ -3063,14 +3064,13 @@ static ssize_t merge_across_nodes_store(struct kobject *kobj,
 			else {
 				root_stable_tree = buf;
 				root_unstable_tree = buf + nr_node_ids;
+				ksm_nr_node_ids = nr_node_ids;
 				/* Stable tree is empty but not the unstable */
 				root_unstable_tree[0] = one_unstable_tree[0];
 			}
 		}
-		if (!err) {
+		if (!err)
 			ksm_merge_across_nodes = knob;
-			ksm_nr_node_ids = knob ? 1 : nr_node_ids;
-		}
 	}
 	mutex_unlock(&ksm_thread_mutex);
 
Signature · 1 line
2.53.0
author maintainer
#739 lore raw

PATCH 734/1848 ipv6: fix device binding after failed datagram connect

In reply to Greg Kroah-Hartman

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

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

From: Xia Yan <[email protected]>

[ Upstream commit bc53aab4881adc134f495092034e9e7c0791d84c ]

__ip6_datagram_connect() can change sk_bound_dev_if when connecting to an address that needs a scope ID. If ip6_datagram_dst_update() fails, the old peer address and port are restored, but the new device binding is left behind.

A UDP socket can then keep reporting its original peer while sends and attempts to reconnect to that peer fail with ENETUNREACH. Replies to the socket are also dropped by the device match. The same problem occurs when a scoped multicast destination picks up np->mcast_oif.

Save the original binding before processing the scope and restore it along with the peer information on failure. This completes the rollback in commit 2f987a76a977 ("net: ipv6: keep sk status consistent after datagram connect failure") and preserves the new binding on success.

Found while reviewing scope-ID handling in __ip6_datagram_connect().

Confirmed by exchanging UDP traffic over ::1, then attempting a link-local connect with a nonexistent scope ifindex or a down interface. After that connect fails, the original peer is still reported but communication and reconnecting to it fail.

Tested before and after the fix in UML for three rounds, covering explicit scopes, multicast interface fallback, initially unconnected sockets and existing bindings. With the fix, the old binding and peer are retained, and traffic and reconnection to the original peer work. Also built on x86_64 with W=1 using adjusted allmodconfig and allyesconfig configurations, with no new warnings.

Fixes 2f987a76a977 ("net: ipv6: keep sk status consistent after datagram connect failure")
---
 net/ipv6/datagram.c | 4 ++++
 1 file changed, 4 insertions(+)
net/ipv6/datagram.c +4 -0
index 8f772274f0daa..b265930e74514 100644
@@ -141,6 +141,7 @@ int __ip6_datagram_connect(struct sock *sk, struct sockaddr *uaddr,
 	__be32			fl6_flowlabel = 0;
 	__be32			old_fl6_flowlabel;
 	__be16			old_dport;
+	int			old_bound_dev_if;
 	int			addr_type;
 	int			err;
 
@@ -211,6 +212,8 @@ int __ip6_datagram_connect(struct sock *sk, struct sockaddr *uaddr,
 		goto out;
 	}
 
+	old_bound_dev_if = sk->sk_bound_dev_if;
+
 	if (__ipv6_addr_needs_scope_id(addr_type)) {
 		if (addr_len >= sizeof(struct sockaddr_in6) &&
 		    usin->sin6_scope_id) {
@@ -253,6 +256,7 @@ int __ip6_datagram_connect(struct sock *sk, struct sockaddr *uaddr,
 		sk->sk_v6_daddr = old_daddr;
 		np->flow_label = old_fl6_flowlabel;
 		inet->inet_dport = old_dport;
+		WRITE_ONCE(sk->sk_bound_dev_if, old_bound_dev_if);
 		goto out;
 	}
 
Signature · 1 line
2.53.0
author maintainer
#740 lore raw

PATCH 735/1848 net/sched: clamp skb->queue_mapping before indexing the tx queue

In reply to Greg Kroah-Hartman

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

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

From: Jamal Hadi Salim <[email protected]>

[ Upstream commit f19f2b308beb158d0e6f6eb806ced636e4ebf6ce ]

This issue was caught by Sashiko (nipa). A producer-side path cap is already merged (ea4d4b5dddb5); this patch adds the matching consumer-side caps.

The issue:
The tx queue is picked and capped in netdev_core_pick_tx() before the __dev_xmit_skb() qdisc enqueue path. A tc BPF program running inside an egress qdisc (not clsact) can then change __sk_buff->queue_mapping; that store is never re-checked. bpf_convert_ctx_access() bounds it only by NO_QUEUE_MAPPING, not by the device's queue count.

Two consumers read the stale value:

- On dequeue, qdisc_restart() calls netdev_get_tx_queue(), which indexes dev->_tx[]. netdev_get_tx_queue() guards it with just a DEBUG_NET_WARN_ON_ONCE, so sch_direct_xmit() takes the out-of-bounds txq->_xmit_lock and writes txq->xmit_lock_owner past the end of the allocation on non-lltx devices such as ifb. Drivers that index their rings from skb_get_queue_mapping() (ex: ifb) go out of range the same way.

- On enqueue, taprio_enqueue() indexes q->qdiscs[] with the same value; the array is sized dev->num_tx_queues. A duplicating netem on a child qdisc clones the skb and re-enqueues the clone at the taprio root (qdisc_root_bh()) through a direct rootq->enqueue() call, so the value reaches taprio_enqueue() before any dequeue cap runs.

The Fix:
Cap the mapping at the consumers and write the capped value back, so the qdisc's _tx[] lookup, the taprio q->qdiscs[] lookup and any later driver read stay in range.

On the dequeue side the cap folds into the dequeue path instead of a separate walk over the returned list: dequeue_skb() caps the head, and each bulk helper caps the element it appends. For a qdisc that is not TCQ_F_ONETXQUEUE, netdev_cap_txqueue() logs a ratelimited notice and selects queue 0.

A TCQ_F_ONETXQUEUE qdisc is bound to a single tx queue: dequeue_skb() uses q->dev_queue for the frozen check, the BQL limit and the trace point, while qdisc_restart() transmits on the skb's queue. Capping an out-of-range mapping to queue 0 would therefore send a per-queue child's skb through a different queue than the one it was dequeued for. On mq, mqprio, taprio and htb offload children, a stopped queue 0 could then park the list in q->gso_skb, and the later wake would schedule queue 0's own child instead of this qdisc. Pin a TCQ_F_ONETXQUEUE mapping to the qdisc's own queue to keep the documented invariant.

The pin covers every mapping, not only an out-of-range one: an in-range mapping that a filter sets on one of those per-queue children is rewritten to the child's own queue, and this path does not call netdev_cap_txqueue(), so it logs no notice. On a single-queue device qdisc_create() sets TCQ_F_ONETXQUEUE, so the one-queue trigger described below also takes this branch and is corrected without a notice.

That also keeps a bulk list on one queue by construction: every element of a TCQ_F_ONETXQUEUE qdisc, including a follower changed by a filter, is pinned to q->dev_queue before it is appended. The fast bulk helper therefore needs no head comparison and no skb_bad_txq requeue; the slow helper, used only by non-ONETXQUEUE qdiscs, still compares and requeues a mismatched follower, where a wake on any queue reschedules q.

On the enqueue side taprio_enqueue() caps the mapping against real_num_tx_queues and writes it back before selecting q->qdiscs[queue], so a duplicating child cannot steer the clone out of the array.

Conditions to recreate the bug:
The dequeue path: load a SCHED_CLS or SCHED_ACT program that stores __sk_buff->queue_mapping (a tc BPF action is enough), attach it to a transmit qdisc (for example a matchall filter on a prio root), and send a packet. With a 1-queue device a store of 1 indexes one past dev->_tx[]. Under KASAN with panic_on_warn=1 the unfixed kernel faults with "BUG:

KASAN: slab-out-of-bounds in sch_direct_xmit". Loading the program needs

CAP_BPF/CAP_SYS_ADMIN, so the trigger is root.

The enqueue path: on a multi-queue device, install a software taprio root, graft a prio child with a duplicating netem on every class, and store an out-of-range queue_mapping from a matchall+bpf filter on the prio. The duplicate is re-enqueued at the taprio root and indexes q->qdiscs[] past dev->num_tx_queues; the unfixed kernel faults in taprio_enqueue_one(). Same CAP_BPF/CAP_SYS_ADMIN requirement.

---
 net/sched/sch_generic.c | 41 ++++++++++++++++++++++++++++++++++++-----
 net/sched/sch_taprio.c  |  5 +++++
 2 files changed, 41 insertions(+), 5 deletions(-)
net/sched/sch_generic.c +36 -5
index af066995f811a..ccb37a459f7f1 100644
@@ -67,9 +67,34 @@ static void qdisc_maybe_clear_missed(struct Qdisc *q,
 
 #define SKB_XOFF_MAGIC ((struct sk_buff *)1UL)
 
+/* Re-cap a stale queue_mapping; an ONETXQUEUE qdisc pins q->dev_queue. */
+static u16 qdisc_cap_skb_tx_queue(struct Qdisc *q, struct sk_buff *skb)
+{
+	u16 queue = skb_get_queue_mapping(skb);
+	struct net_device *dev = qdisc_dev(q);
+	u16 capped;
+
+	if (q->flags & TCQ_F_ONETXQUEUE)
+		capped = q->dev_queue - netdev_get_tx_queue(dev, 0);
+	else
+		capped = netdev_cap_txqueue(dev, queue);
+
+	if (unlikely(capped != queue))
+		skb_set_queue_mapping(skb, capped);
+
+	return capped;
+}
+
+static struct netdev_queue *skb_cap_tx_queue(struct Qdisc *q,
+					     struct sk_buff *skb)
+{
+	return netdev_get_tx_queue(qdisc_dev(q),
+				   qdisc_cap_skb_tx_queue(q, skb));
+}
+
 static inline struct sk_buff *__skb_dequeue_bad_txq(struct Qdisc *q)
 {
-	const struct netdev_queue *txq = q->dev_queue;
+	const struct netdev_queue *txq;
 	spinlock_t *lock = NULL;
 	struct sk_buff *skb;
 
@@ -81,7 +106,8 @@ static inline struct sk_buff *__skb_dequeue_bad_txq(struct Qdisc *q)
 	skb = skb_peek(&q->skb_bad_txq);
 	if (skb) {
 		/* check the reason of requeuing without tx lock first */
-		txq = skb_get_tx_queue(txq->dev, skb);
+		/* re-cap: real_num_tx_queues may have shrunk */
+		txq = skb_cap_tx_queue(q, skb);
 		if (!netif_xmit_frozen_or_stopped(txq)) {
 			skb = __skb_dequeue(&q->skb_bad_txq);
 			if (qdisc_is_percpu_stats(q)) {
@@ -192,6 +218,8 @@ static void try_bulk_dequeue_skb(struct Qdisc *q,
 		if (!nskb)
 			break;
 
+		/* Every element of an ONETXQUEUE qdisc is pinned to q->dev_queue. */
+		qdisc_cap_skb_tx_queue(q, nskb);
 		bytelimit -= nskb->len; /* covers GSO len */
 		skb->next = nskb;
 		skb = nskb;
@@ -209,7 +237,6 @@ static void try_bulk_dequeue_skb_slow(struct Qdisc *q,
 				      struct sk_buff *skb,
 				      int *packets)
 {
-	int mapping = skb_get_queue_mapping(skb);
 	struct sk_buff *nskb;
 	int cnt = 0;
 
@@ -217,7 +244,9 @@ static void try_bulk_dequeue_skb_slow(struct Qdisc *q,
 		nskb = q->dequeue(q);
 		if (!nskb)
 			break;
-		if (unlikely(skb_get_queue_mapping(nskb) != mapping)) {
+		/* A tc BPF store may have changed the mapping; cap it. */
+		if (unlikely(qdisc_cap_skb_tx_queue(q, nskb) !=
+			     skb_get_queue_mapping(skb))) {
 			qdisc_enqueue_skb_bad_txq(q, nskb);
 			break;
 		}
@@ -262,7 +291,7 @@ static struct sk_buff *dequeue_skb(struct Qdisc *q, bool *validate,
 		if (xfrm_offload(skb))
 			*validate = true;
 		/* check the reason of requeuing without tx lock first */
-		txq = skb_get_tx_queue(txq->dev, skb);
+		txq = skb_cap_tx_queue(q, skb);
 		if (!netif_xmit_frozen_or_stopped(txq)) {
 			skb = __skb_dequeue(&q->gso_skb);
 			if (qdisc_is_percpu_stats(q)) {
@@ -298,6 +327,8 @@ static struct sk_buff *dequeue_skb(struct Qdisc *q, bool *validate,
 	skb = q->dequeue(q);
 	if (skb) {
 bulk:
+		/* cap the head; the bulk helpers cap every appended element */
+		qdisc_cap_skb_tx_queue(q, skb);
 		if (qdisc_may_bulk(q))
 			try_bulk_dequeue_skb(q, skb, txq, packets, budget);
 		else
net/sched/sch_taprio.c +5 -0
index d0b25ab5ff9aa..bb12b35d7191d 100644
@@ -445,6 +445,11 @@ static int taprio_enqueue(struct sk_buff *skb, struct Qdisc *sch,
 	int queue;
 
 	queue = skb_get_queue_mapping(skb);
+	if (unlikely(queue >= qdisc_dev(sch)->real_num_tx_queues)) {
+		/* A tc BPF program may have stored an out-of-range mapping. */
+		queue = netdev_cap_txqueue(qdisc_dev(sch), queue);
+		skb_set_queue_mapping(skb, queue);
+	}
 
 	child = q->qdiscs[queue];
 	if (unlikely(!child))
Signature · 1 line
2.53.0
author maintainer
#741 lore raw

PATCH 736/1848 nvmet: dont return memory contents beyond valid data when reading ANA log page

In reply to Greg Kroah-Hartman

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

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

From: Ewan D. Milne <[email protected]>

[ Upstream commit 29b8758b4700357909f06705a0c48c7a60c556d5 ]

The host side does not know how much valid data will be returned by the target so it will typically provide a buffer larger than the amount of valid data in the ANA log page. The memory allocation used by the target does not guarantee that prior kernel memory contents will not be returned past the end of the valid page data. Fix this to ensure that the SGL is zeroed before copying the data.

Fixes 72efd25dcf4f ("nvmet: add minimal ANA support")
---
 drivers/nvme/target/admin-cmd.c | 9 +++++++++
 1 file changed, 9 insertions(+)
drivers/nvme/target/admin-cmd.c +9 -0
index 6a8274caa3bc7..835ff574f80b9 100644
@@ -254,6 +254,15 @@ static void nvmet_execute_get_log_page_ana(struct nvmet_req *req)
 	u16 ngrps = 0;
 	u16 status;
 
+	/*
+	 * The header and one descriptor per enabled group are the only bytes
+	 * written below; zero the whole transfer first so the unwritten tail
+	 * does not leak stale kernel memory to the host.
+	 */
+	status = nvmet_zero_sgl(req, 0, req->transfer_len);
+	if (status)
+		goto out;
+
 	status = NVME_SC_INTERNAL;
 	desc = kmalloc(sizeof(struct nvme_ana_group_desc) +
 			NVMET_MAX_NAMESPACES * sizeof(__le32), GFP_KERNEL);
Signature · 1 line
2.53.0
author maintainer
#742 lore raw

PATCH 737/1848 arm64: mm: validate /dev/mem mmap ranges without overflow

In reply to Greg Kroah-Hartman

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

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

From: Zhao Gongyi <[email protected]>

[ Upstream commit b0958b1397fb5ffdb995c0ccc74349841929c08d ]

An arm64 syzkaller reproducer creates a FUSE character device with major:minor 1:1, so opening it uses the /dev/mem file operations. It maps one page from offset 0xfffffffffffff000 at user address zero. The next openat() with a NULL pathname triggers a synchronous external abort (SEA, ESR 0x96000010) in strncpy_from_user() via do_getname(), panicking the kernel.

valid_mmap_phys_addr_range() checks the exclusive end by adding the mapping size to the starting address. For this offset, the sum wraps to zero and passes the PHYS_MASK test, allowing an out-of-range PFN to reach remap_pfn_range(). The inclusive-end overflow check in mmap_mem_prepare() does not catch it because the end is ULONG_MAX.

Reject starting PFNs outside PHYS_MASK and compare the inclusive length against the remaining physical range without overflowing. This also allows mappings that end exactly at PHYS_MASK, which the old check incorrectly rejects.

Fixes 1d18c47c735e ("arm64: MMU fault handling and page table management")
[[email protected]: changed the check to look more like __access_ok()]
---
 arch/arm64/mm/mmap.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
arch/arm64/mm/mmap.c +3 -1
index 3028bacbc4e9c..0e908fd345d7c 100644
@@ -45,7 +45,9 @@ int valid_phys_addr_range(phys_addr_t addr, size_t size)
  */
 int valid_mmap_phys_addr_range(unsigned long pfn, size_t size)
 {
-	return !(((pfn << PAGE_SHIFT) + size) & ~PHYS_MASK);
+	const phys_addr_t limit = PHYS_MASK + 1;
+
+	return size <= limit && pfn <= (limit - size) >> PAGE_SHIFT;
 }
 
 #ifdef CONFIG_STRICT_DEVMEM
Signature · 1 line
2.53.0
author maintainer
#743 lore raw

PATCH 738/1848 drm/nouveau/devinit/gf100-: try to avoid double-running vbios scripts

In reply to Greg Kroah-Hartman

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

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

From: Ilia Mirkin <[email protected]>

[ Upstream commit 2139cb633d48ebbbaec88d2e5a8ebe8e774df4fb ]

Turns out some VBIOSes don't actually set the bit in question in 2240c. Use the nv50-style detection to try avoiding running the vbios twice.

---
 .../drm/nouveau/nvkm/subdev/devinit/gf100.c   | 20 +++++++++++++++++++
 1 file changed, 20 insertions(+)
drivers/gpu/drm/nouveau/nvkm/subdev/devinit/gf100.c +20 -0
index 8b1b34c3ad262..686f788baa725 100644
@@ -27,6 +27,7 @@
 #include <subdev/bios/init.h>
 #include <subdev/bios/pll.h>
 #include <subdev/clk/pll.h>
+#include <subdev/vga.h>
 
 int
 gf100_devinit_pll_set(struct nvkm_devinit *init, u32 type, u32 freq)
@@ -102,6 +103,25 @@ gf100_devinit_preinit(struct nvkm_devinit *base)
 	 * can use it as a reliable way to know whether we should run devinit.
 	 */
 	base->post = ((nvkm_rd32(device, 0x2240c) & BIT(1)) == 0);
+
+	/*
+	 * However some VBIOS init sequences miss this bit. So fall back to
+	 * the nv50 method of checking if the bit is not set. Running the
+	 * VBIOS multiple times may have detrimental effects.
+	 */
+	if (base->post) {
+		u64 disable = nvkm_devinit_disable(base);
+		/* magic to detect whether or not x86 vbios code has
+		 * executed the devinit scripts to initialise the
+		 * board. only works if there's a display engine.
+		 */
+		if (!(disable & (1ULL << NVKM_ENGINE_DISP))) {
+			if (nvkm_rdvgac(device, 0, 0x00) ||
+			    nvkm_rdvgac(device, 0, 0x1a)) {
+				base->post = false;
+			}
+		}
+	}
 }
 
 static const struct nvkm_devinit_func
Signature · 1 line
2.53.0
author maintainer
#744 lore raw

PATCH 739/1848 ALSA: hda/realtek: Enable bass speakers on Alienware m17 R3

In reply to Greg Kroah-Hartman

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

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

From: Chris Simpson <[email protected]>

[ Upstream commit eb296114d5ba4d335a640dbbbbc9618fded0ffe7 ]

The Alienware m17 R3 (ALC289, PCI SSID 1028:09d1) has a second speaker pair, the bass speakers, on pin 0x17, which the BIOS leaves unconnected (0x411111f0). No PCI SSID quirk matches the machine, so it gets ALC269_FIXUP_DELL4_MIC_NO_PRESENCE from the fallback pin quirk table, and only the speakers on pin 0x14 play.

Use ALC289_FIXUP_DUAL_SPK, as on the Alienware x16 R2 and Dell XPS 15 9510/9520: it sets pin 0x17 up as a speaker on DAC 0x02, so one volume control covers both pairs, and chains to ALC269_FIXUP_DELL4_MIC_NO_PRESENCE, so the headset mic setup is unchanged.

Tested on an Alienware m17 R3 (BIOS 1.38.0), Linux 7.3 with this change
applied: the bass speakers play, and volume and mute cover both pairs, also after suspend and resume. Headphones and a headset mic were not tested.

I used Claude Code (Claude Opus 5.5) to find the unused pin, pick the existing fixup and write this patch and changelog; I did the listening tests myself.

---
 sound/pci/hda/patch_realtek.c | 1 +
 1 file changed, 1 insertion(+)
sound/pci/hda/patch_realtek.c +1 -0
index 25573c62e86d1..4edd1e022797d 100644
@@ -9170,6 +9170,7 @@ static const struct snd_pci_quirk alc269_fixup_tbl[] = {
 	SND_PCI_QUIRK(0x1028, 0x097e, "Dell Precision", ALC289_FIXUP_DUAL_SPK),
 	SND_PCI_QUIRK(0x1028, 0x098d, "Dell Precision", ALC233_FIXUP_ASUS_MIC_NO_PRESENCE),
 	SND_PCI_QUIRK(0x1028, 0x09bf, "Dell Precision", ALC233_FIXUP_ASUS_MIC_NO_PRESENCE),
+	SND_PCI_QUIRK(0x1028, 0x09d1, "Alienware m17 R3", ALC289_FIXUP_DUAL_SPK),
 	SND_PCI_QUIRK(0x1028, 0x0a2e, "Dell", ALC236_FIXUP_DELL_AIO_HEADSET_MIC),
 	SND_PCI_QUIRK(0x1028, 0x0a30, "Dell", ALC236_FIXUP_DELL_AIO_HEADSET_MIC),
 	SND_PCI_QUIRK(0x1028, 0x0a58, "Dell", ALC255_FIXUP_DELL_HEADSET_MIC),
Signature · 1 line
2.53.0
author maintainer
#745 lore raw

PATCH 740/1848 ALSA: cs46xx: Handle SCB creation failures before dereferencing

In reply to Greg Kroah-Hartman

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

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

From: Alex Kazinsky <[email protected]>

[ Upstream commit 023d3e1176202339cd94a3d732e3aec74e36ba22 ]

With CONFIG_PM_SLEEP enabled, cs46xx_dsp_create_scb() can return NULL if kmemdup() fails to allocate the SCB data saved for resume. cs46xx_dsp_scb_and_task_init() and _dsp_create_generic_scb() dereference the returned pointer without checking it, causing a NULL pointer dereference on allocation failure.

Check both return values before accessing the SCB descriptors. Return -ENOMEM when creating the null SCB fails and propagate NULL from _dsp_create_generic_scb().

Found by Linux Verification Center (linuxtesting.org) with SVACE static analysis tool.

Fixes 41116e926cb9 ("ALSA: cs46xx - Fix suspend/resume with new DSP")
---
 sound/pci/cs46xx/dsp_spos.c         | 2 ++
 sound/pci/cs46xx/dsp_spos_scb_lib.c | 3 ++-
 2 files changed, 4 insertions(+), 1 deletion(-)
sound/pci/cs46xx/dsp_spos.c +2 -0
index 5d7c38a0ac7be..1712fb7c0148c 100644
@@ -1109,6 +1109,8 @@ int cs46xx_dsp_scb_and_task_init (struct snd_cs46xx *chip)
 
 		null_scb.entry_point = null_algorithm->address;
 		ins->the_null_scb = cs46xx_dsp_create_scb(chip, "nullSCB", (u32 *)&null_scb, NULL_SCB_ADDR);
+		if (!ins->the_null_scb)
+			return -ENOMEM;
 		ins->the_null_scb->task_entry = null_algorithm;
 		ins->the_null_scb->sub_list_ptr = ins->the_null_scb;
 		ins->the_null_scb->next_scb_ptr = ins->the_null_scb;
sound/pci/cs46xx/dsp_spos_scb_lib.c +2 -1
index 1f90ca723f4df..af5c78e3fd200 100644
@@ -285,7 +285,8 @@ _dsp_create_generic_scb (struct snd_cs46xx *chip, char * name, u32 * scb_data, u
 	dev_dbg(chip->card->dev, "dsp_spos: creating SCB <%s>\n", name);
 
 	scb = cs46xx_dsp_create_scb(chip,name,scb_data,dest);
-
+	if (!scb)
+		return NULL;
 
 	scb->sub_list_ptr = ins->the_null_scb;
 	scb->next_scb_ptr = ins->the_null_scb;
Signature · 1 line
2.53.0
author maintainer
#746 lore raw

PATCH 741/1848 ALSA: line6: Reject capture buffers smaller than two packets

In reply to Greg Kroah-Hartman

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

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

From: Sinan Turunc <[email protected]>

[ Upstream commit db51425c9eb038a8e40e09b837afde015ae9e3ec ]

line6_capture_copy() splits the copy into the ALSA ring buffer once at the buffer end and wraps pos_done once, which is only correct when one packet holds at most buffer_size frames. The packet size comes from the device's endpoint, and the per-device hw structs allow 64-byte periods with periods_min 1, so a packet can be larger than the whole buffer. audio_in_callback() logs an oversized packet and then copies it anyway.

The packet size is known at probe time, so constrain SNDRV_PCM_HW_PARAM_BUFFER_BYTES in snd_line6_capture_open() to at least twice the larger of the two endpoints' packet sizes. Two rather than one, because pos_done advances by the packet and wraps once, so a buffer of exactly one packet leaves the position unchanged after every packet. hw_params then rejects a buffer that cannot hold two packets, and the single wrap is valid for every configuration that gets through. Keep a guard in line6_capture_copy() that drops an oversized packet with a ratelimited error, for the case that should no longer be reachable.

Reproduced on 7.3-rc7 with a USB/IP device presenting the GuitarPort interface layout and 1024-byte packets into a 128-byte buffer: ALSA logged "invalid position: pos = 224, buffer size = 32" and the driver logged "driver bug: len" on every following packet. With this patch a 1024-byte buffer is refused at hw_params, and a 2048-byte buffer streams for 30 s with no report and with the position moving inside the buffer.

---
 sound/usb/line6/capture.c | 29 +++++++++++++++++++++++++++++
 1 file changed, 29 insertions(+)
sound/usb/line6/capture.c +29 -0
index 970c9bdce0b21..e77ef16c792f0 100644
@@ -94,6 +94,18 @@ void line6_capture_copy(struct snd_line6_pcm *line6pcm, char *fbuf, int fsize)
 	if (runtime == NULL)
 		return;
 
+	/*
+	 * snd_line6_capture_open() constrains the buffer to hold at least
+	 * two packets, so this cannot happen for a conforming device. Drop
+	 * the packet rather than overrun the single wrap below.
+	 */
+	if (unlikely(frames > runtime->buffer_size)) {
+		dev_err_ratelimited(line6pcm->line6->ifcdev,
+				    "packet of %d frames exceeds %lu-frame buffer, dropping\n",
+				    frames, runtime->buffer_size);
+		return;
+	}
+
 	if (line6pcm->in.pos_done + frames > runtime->buffer_size) {
 		/*
 		   The transferred area goes over buffer boundary,
@@ -228,6 +240,23 @@ static int snd_line6_capture_open(struct snd_pcm_substream *substream)
 	if (err < 0)
 		return err;
 
+	/*
+	 * line6_capture_copy() wraps the ring buffer once per packet and
+	 * advances pos_done by the packet, which only works when the buffer
+	 * holds more than one packet: with exactly one, pos_done gains a
+	 * buffer and loses it again on every packet. The packet size comes
+	 * from the device, so bound the buffer by two packets here. The
+	 * impulse-response path copies a playback URB into this ring, so
+	 * take the larger of the two endpoints.
+	 */
+	err = snd_pcm_hw_constraint_minmax(runtime,
+					   SNDRV_PCM_HW_PARAM_BUFFER_BYTES,
+					   2 * max(line6pcm->max_packet_size_in,
+						   line6pcm->max_packet_size_out),
+					   UINT_MAX);
+	if (err < 0)
+		return err;
+
 	line6_pcm_acquire(line6pcm, LINE6_STREAM_CAPTURE_HELPER, false);
 
 	runtime->hw = line6pcm->properties->capture_hw;
Signature · 1 line
2.53.0
author maintainer
#747 lore raw

PATCH 742/1848 ALSA: caiaq: free the EP4 URB when input setup fails

In reply to Greg Kroah-Hartman

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

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

From: Wentao Liang <[email protected]>

[ Upstream commit d21746bafdb8e1a5fc9bdcb86f603d827a500a62 ]

The three controllers that use the EP4 input URB allocate it before checking the endpoint type and before registering the input device. On failure they jump to exit_free_idev, which clears cdev->input_dev but leaves cdev->ep4_in_urb set. The card teardown then calls snd_usb_caiaq_input_free(), which returns early because input_dev is NULL, so the URB is never freed.

Release the URB before dropping the input device on the error path.

Fixes 6da7a2aa899f ("ALSA: usb/caiaq: Add support for Traktor Kontrol X1")
Assisted-by DeepSeek-V4.1-Flash and OpenAI Codex
---
 sound/usb/caiaq/input.c | 2 ++
 1 file changed, 2 insertions(+)
sound/usb/caiaq/input.c +2 -0
index c12eeb9710002..6a5adb8d1e6a7 100644
@@ -830,6 +830,8 @@ int snd_usb_caiaq_input_init(struct snd_usb_caiaqdev *cdev)
 	return 0;
 
 exit_free_idev:
+	usb_free_urb(cdev->ep4_in_urb);
+	cdev->ep4_in_urb = NULL;
 	input_free_device(input);
 	cdev->input_dev = NULL;
 	return ret;
Signature · 1 line
2.53.0
author maintainer
#748 lore raw

PATCH 743/1848 ALSA: usx2y: Require a buffer of two URBs

In reply to Greg Kroah-Hartman

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

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

From: Sinan Turunc <[email protected]>

[ Upstream commit 4cbb826b3b36df6c275454287ba1df4564a5370b ]

usx2y_urb_capt_retire() wraps the ring buffer once per packet and usx2y_urb_play_prepare() once per URB of nr_of_packs() packets of up to 50 frames. Both assume that the data fits in the buffer, and the hw constraints only require about two 1 ms periods, so a packet larger than the buffer on capture, or a URB larger than the buffer on playback, violates that assumption.

Constrain SNDRV_PCM_HW_PARAM_BUFFER_SIZE in snd_usx2y_pcm_open() to at least two URBs, 2 * nr_of_packs() * 50 frames, for both directions. The bound is in frames and derived from the driver's own packet limit, so it does not read the endpoint, whose altsetting is only selected in prepare. Two URBs rather than one, because the position advances by a URB on playback and only moves when a URB is less than the whole buffer. Keep a guard in usx2y_urb_capt_retire() that drops a packet larger than the buffer, for the case the constraint makes unreachable.

With nrpacks above about 163 (S16_LE) or 109 (S24_3LE) the bound exceeds the 64 KiB buffer the substream preallocates (twice that with the preallocation raised to its 128 KiB maximum), so hw_params fails for those module settings. That is intended: the driver cannot be safe with a URB larger than half the largest buffer.

Reproduced on 7.3-rc7 with a USB/IP device presenting the US-122 interface layout and 1024-byte packets into a 512-byte capture buffer:

  BUG: KASAN: out-of-bounds in i_usx2y_urb_complete+0x1285/0x1ac0
  Read of size 18446744073709551104 at addr ffff88800e448800 by task vhci_rx/83

Tested on 7.3-rc7 with the same device, S16_LE at 44100 Hz, nrpacks 4, so the bound is 400 frames. A 128-frame capture buffer and a 200-frame playback buffer are refused at hw_params with EINVAL. A 400-frame buffer streams for 30 s in each direction with the position advancing inside the buffer and no KASAN report; the capture guard did not fire. The same 400-frame capture buffer with S24_3LE, which selects altsetting 2 in prepare, streams for 30 s with the same result.

---
 sound/usb/usx2y/usbusx2yaudio.c | 24 ++++++++++++++++++++++++
 1 file changed, 24 insertions(+)
sound/usb/usx2y/usbusx2yaudio.c +24 -0
index cb86c8e33ee1a..c4e621b74ca5a 100644
@@ -50,6 +50,18 @@ static int usx2y_urb_capt_retire(struct snd_usx2y_substream *subs)
 			snd_printd("0 == len ERROR!\n");
 			continue;
 		}
+		/*
+		 * snd_usx2y_pcm_open() constrains the buffer to hold at least
+		 * two URBs, so this cannot happen for a device that keeps its
+		 * packets at 50 frames. Drop the packet rather than exceed the
+		 * single wrap below.
+		 */
+		if (unlikely(len > runtime->buffer_size)) {
+			dev_err_ratelimited(&usx2y->dev->dev,
+					    "%s: packet of %i frames exceeds %lu-frame buffer, dropping\n",
+					    __func__, len, runtime->buffer_size);
+			continue;
+		}
 
 		/* copy a data chunk */
 		if ((hwptr_done + len) > runtime->buffer_size) {
@@ -886,6 +898,18 @@ static int snd_usx2y_pcm_open(struct snd_pcm_substream *substream)
 	runtime->private_data = subs;
 	subs->pcm_substream = substream;
 	snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_PERIOD_TIME, 1000, 200000);
+	/*
+	 * Capture wraps the ring buffer once per packet and playback once
+	 * per URB of nr_of_packs() packets of at most 50 frames (see
+	 * usx2y_urb_play_prepare()). Playback needs the buffer to hold more
+	 * than one URB and capture more than one packet; use the URB bound
+	 * for both, and two URBs rather than one, because the position only
+	 * advances when a URB is less than the whole buffer. The bound is in
+	 * frames and does not depend on the altsetting, which is selected
+	 * in prepare.
+	 */
+	snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_BUFFER_SIZE,
+				     2 * nr_of_packs() * 50, UINT_MAX);
 	return 0;
 }
 
Signature · 1 line
2.53.0
author maintainer
#749 lore raw

PATCH 744/1848 ALSA: usx2y: Guard the playback copy

In reply to Greg Kroah-Hartman

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

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

From: Sinan Turunc <[email protected]>

[ Upstream commit e2c6de52ffacb2c0f4076884ee3fdb744735a4cb ]

usx2y_urb_play_prepare() sums the packet lengths of a whole URB, copies that many frames with a single wrap, and sizes each playback packet from the capture packet's actual_length. Three things are unchecked: that the URB fits in the ring buffer, that a packet fits in the playback endpoint's maxpacksize, from which tmpbuf is allocated, and that actual_length is a whole number of frames. The ISO descriptors take the raw actual_length while transfer_buffer_length and the copies take count * stride, so a packet that is not a multiple of the stride makes the descriptors add up to more than the buffer, by up to stride - 1 bytes per packet.

Return -EPIPE, as the existing packet-size check does, when the URB is larger than the buffer or a packet is larger than maxpacksize, and size each descriptor from whole frames, so the descriptors add up to transfer_buffer_length and each stays within maxpacksize. The buffer case is prevented by the previous patch and this is the guard for it; the other two depend only on the device.

The first case is reachable on the unpatched driver with ordinary
packets: on 7.3-rc7, a USB/IP device presenting the US-122 interface layout and sending 48-frame packets, with a 100-frame playback buffer (two 50-frame periods, inside the stock constraints), KASAN reports:

  BUG: KASAN: out-of-bounds in i_usx2y_urb_complete+0x79b/0x1ac0
  Read of size 18446744073709551280 at addr ffff88800e6b02e0 by task vhci_rx/80

With both patches, the same device and a 200-frame playback buffer is refused at hw_params with EINVAL, and a 400-frame buffer plays for 30 s with the position advancing inside the buffer, no KASAN report and neither guard message. The maxpacksize check is not exercised: the emulated device reports the same wMaxPacketSize on both endpoints.

The descriptor case is visible with capture packets of 195 bytes at stride 4 (48 frames and 3 bytes): without this change the four descriptors add up to 780 bytes for 768 bytes of data, and USB/IP's completion check refuses the URB ("total length of iso packets 780 not equal to actual length of buffer 768", -EPROTO), after which the driver stops the streams. With this patch every descriptor is 192 bytes, the descriptors add up to the data in every URB for 30 s, the position advances inside the buffer and KASAN reports nothing. The 48-frame playback run above is unchanged.

---
 sound/usb/usx2y/usbusx2yaudio.c | 19 ++++++++++++++++++-
 1 file changed, 18 insertions(+), 1 deletion(-)
sound/usb/usx2y/usbusx2yaudio.c +18 -1
index c4e621b74ca5a..2bd2873bfbfaa 100644
@@ -116,14 +116,31 @@ static int usx2y_urb_play_prepare(struct snd_usx2y_substream *subs,
 			snd_printk(KERN_ERR "should not be here with counts=%i\n", counts);
 			return -EPIPE;
 		}
+		if (counts * usx2y->stride > subs->maxpacksize) {
+			dev_err_ratelimited(&usx2y->dev->dev,
+					    "%s: packet of %i bytes exceeds maxpacksize %u\n",
+					    __func__, counts * usx2y->stride,
+					    subs->maxpacksize);
+			return -EPIPE;
+		}
 		/* set up descriptor */
 		urb->iso_frame_desc[pack].offset = pack ?
 			urb->iso_frame_desc[pack - 1].offset +
 			urb->iso_frame_desc[pack - 1].length :
 			0;
-		urb->iso_frame_desc[pack].length = cap_urb->iso_frame_desc[pack].actual_length;
+		urb->iso_frame_desc[pack].length = counts * usx2y->stride;
 	}
 	if (atomic_read(&subs->state) >= STATE_PRERUNNING) {
+		/*
+		 * The copy below wraps once, which needs count <= buffer_size.
+		 * snd_usx2y_pcm_open() guarantees it; guard anyway.
+		 */
+		if (unlikely(count > runtime->buffer_size)) {
+			dev_err_ratelimited(&usx2y->dev->dev,
+					    "%s: URB of %i frames exceeds %lu-frame buffer, stopping\n",
+					    __func__, count, runtime->buffer_size);
+			return -EPIPE;
+		}
 		if (subs->hwptr + count > runtime->buffer_size) {
 			/* err, the transferred area goes over buffer boundary.
 			 * copy the data to the temp buffer.
Signature · 1 line
2.53.0
author maintainer
#750 lore raw

PATCH 745/1848 net/smc: dont spin in smc_rx_recvmsg() while a pipe holds spliced data

In reply to Greg Kroah-Hartman

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

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

From: Bryam Vargas <[email protected]>

[ Upstream commit 8288ba942cfd20621c05e16978b7c3da91513ae1 ]

While bytes spliced off the RMB are still in a pipe, recvmsg() waits for the pipe to release them before it copies the data behind them. The path to that wait skips the timeout and signal checks, and smc_rx_wait() returns at once on RCV_SHUTDOWN. With a signal pending, after SHUT_RD, or once the peer closes or shuts down writing, recvmsg() spins on a CPU until the pipe is drained, and SIGKILL cannot stop it. MSG_DONTWAIT and an expired SO_RCVTIMEO wait there too instead of returning -EAGAIN.

Check the timeout and signals before that wait, and end it when the pipe releases the data or the connection is killed, not on RCV_SHUTDOWN. A zero-length read returns 0 without waiting for the pipe; a non-blocking one returns -EAGAIN while poll() still reports the socket readable (splice() can still take those bytes). The wait sets SOCKWQ_ASYNC_WAITDATA like smc_rx_wait(), so a byte arriving behind the pipe raises no SIGIO on a reader already asleep for it, and a full barrier orders its wait queue entry before its read of splice_pending, so no wake is lost.

---
 net/smc/smc_rx.c | 39 ++++++++++++++++++++++++++++++++++++++-
 1 file changed, 38 insertions(+), 1 deletion(-)
net/smc/smc_rx.c +38 -1
index 343bdab3b5077..7ed5564851169 100644
@@ -226,6 +226,27 @@ int smc_rx_wait(struct smc_sock *smc, long *timeo, size_t peeked,
 	return rc;
 }
 
+/* Wait for the pipe to release the spliced data. Unlike smc_rx_wait()
+ * it does not end on shutdown or sk_err, the data is already in the
+ * RMB; smc_conn_kill() wakes it and the caller checks conn->killed.
+ */
+static void smc_rx_wait_splice(struct smc_sock *smc, long *timeo)
+{
+	DEFINE_WAIT_FUNC(wait, woken_wake_function);
+	struct smc_connection *conn = &smc->conn;
+	struct sock *sk = &smc->sk;
+
+	sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
+	add_wait_queue(sk_sleep(sk), &wait);
+	/* pairs with the smp_mb() in wq_has_sleeper(): the release drops
+	 * splice_pending, then looks for a sleeper
+	 */
+	smp_mb();
+	sk_wait_event(sk, timeo, !atomic_read(&conn->splice_pending), &wait);
+	remove_wait_queue(sk_sleep(sk), &wait);
+	sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
+}
+
 static int smc_rx_recv_urg(struct smc_sock *smc, struct msghdr *msg, int len,
 			   int flags)
 {
@@ -376,7 +397,23 @@ int smc_rx_recvmsg(struct smc_sock *smc, struct msghdr *msg,
 		/* could be just 1 byte, even after waiting on data above */
 		readable = smc_rx_data_available(conn, peeked_bytes);
 		splbytes = atomic_read(&conn->splice_pending);
-		if (!readable || (msg && splbytes)) {
+		if (msg && splbytes) {
+			/* a pipe holds bytes ahead of these; the copy path
+			 * skips the timeout and signal checks
+			 */
+			if (!read_remaining)
+				break;
+			if (!timeo || signal_pending(current)) {
+				if (!read_done)
+					read_done = timeo ?
+						    sock_intr_errno(timeo) :
+						    -EAGAIN;
+				break;
+			}
+			smc_rx_wait_splice(smc, &timeo);
+			continue;
+		}
+		if (!readable) {
 			if (splbytes)
 				func = smc_rx_data_available_and_no_splice_pend;
 			else
Signature · 1 line
2.53.0
author maintainer
#751 lore raw

PATCH 746/1848 net: count last skb of each sk_backlog pass in __release_sock()

In reply to Greg Kroah-Hartman

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

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

From: Ray Zhang <[email protected]>

[ Upstream commit c4e4056b21355356f6a95bcdf03a850edd9f49e7 ]

Running 500 concurrent TCPv6 streams (neper "tcp_stream -6 -T 1 -F 500") on a 2-core Cortex-A53 (CONFIG_PREEMPT_NONE=y, HZ=1000, LATENCY_WARN) triggers resched_latency_warn() in __release_sock():

  [ 3655.311821] sched: CPU 0 need_resched set for > 100006892 ns (100 ticks) without schedule
  [ 3655.311889] Call trace:
  ...
  [ 3655.311944]  resched_latency_warn+0x7c/0x88
  [ 3655.311958]  sched_tick+0x1c0/0x418
  ...
  [ 3655.312578]  net_rx_action+0x238/0x438
  ...
  [ 3655.312641]  do_softirq+0x4c/0x90
  [ 3655.312651]  __local_bh_enable_ip+0x84/0x90
  [ 3655.312663]  local_bh_enable+0x1c/0x28
  [ 3655.312674]  __dev_queue_xmit+0x4a8/0xb00
  ...
  [ 3655.312782]  tcp_v6_do_rcv+0x240/0x5f8
  [ 3655.312793]  __release_sock+0x9c/0x188
  [ 3655.312806]  release_sock+0x150/0x168
  [ 3655.312817]  tcp_sendmsg+0x4c/0x70

__release_sock() can loop past 100 ms without calling cond_resched():

- Each outer-loop pass drains sk_backlog, but "if (!skb) break;" runs before "++nb", so a pass of B skbs only adds B - 1 to nb (0 for 1 skb).
- With 500 TCPv6 streams and NAPI sharing two Cortex-A53 cores, runnable tasks keep TIF_NEED_RESCHED set on CPU 0.
- During spin_unlock_bh() and TX softirqs (__dev_queue_xmit() -> local_bh_enable()), tcp_add_backlog() coalesces arriving pure ACKs into a single tail skb.
- Repeated 1-skb passes never advance nb or call cond_resched(), triggering resched_latency_warn() after 100 ticks.

Restore the do-while loop and drop "if (!skb) break;" so every skb increments nb across passes and calls cond_resched() every 16 skbs.

Reproduced the issue and verified the fix on two 2-core Cortex-A53 hosts (CONFIG_PREEMPT_NONE=y, HZ=1000, LATENCY_WARN, latency_warn_once=0) with a userspace reproducer over /dev/net/tun:

- CPU 0 runs a TCPv6 sender and a second runnable task while CPU 1 writes pure ACKs to /dev/net/tun (~30k TCPBacklogCoalesce/run), sustaining 1-skb sk_backlog refills in __release_sock() for ~400 ms (ftrace).
- Before: CPU 0 stayed unscheduled in __release_sock(), hitting resched_latency_warn() 293 and 275 times on the two hosts (> 100.9 ms).
- After: cond_resched() yielded CPU 0 inside __release_sock(), with 0 resched_latency_warn() hits on both hosts.
- Also observed no regression with the workload from
commit 16c610162d1f ("net: call cond_resched() less often in __release_sock()"), "super_netperf 4 -H srv -T,10 -l 3000 &".

---
 net/core/sock.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)
net/core/sock.c +2 -4
index 7d645d85da9fd..6cf0b1a7c2a74 100644
@@ -2570,7 +2570,7 @@ void __release_sock(struct sock *sk)
 
 		spin_unlock_bh(&sk->sk_lock.slock);
 
-		while (1) {
+		do {
 			next = skb->next;
 			prefetch(next);
 			WARN_ON_ONCE(skb_dst_is_noref(skb));
@@ -2578,12 +2578,10 @@ void __release_sock(struct sock *sk)
 			sk_backlog_rcv(sk, skb);
 
 			skb = next;
-			if (!skb)
-				break;
 
 			if (!(++nb & 15))
 				cond_resched();
-		}
+		} while (skb);
 
 		spin_lock_bh(&sk->sk_lock.slock);
 	}
Signature · 1 line
2.53.0
author maintainer
#752 lore raw

PATCH 747/1848 net: ethernet: ti: am65-cpsw-nuss: Enable timestamping of unicast PTP packets

In reply to Greg Kroah-Hartman

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

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

From: James Clark <[email protected]>

[ Upstream commit 6887a8f98244ba4c0fbe2d2461b9b8f8a300e326 ]

On a BeagleY-AI (J722S), ptp4l as a unicast master (unicast_listen) logs "received DELAY_REQ without timestamp" for each unicast Delay_Req, and its port goes to FAULTY after "timed out while polling for tx timestamp" for the first unicast Sync.

am65_cpsw_nuss_hwtstamp_set() does not set the TS_UNI_EN bit (bit 24) of the port's TS_CTL_LTYPE2 register. According to the TRM (J722S TRM SPRUJB3D, 12.2.1.4.7.13.5.1 Ethernet Port Receive Event and 12.2.1.4.7.13.5.2 Ethernet Port Transmit Event), this bit must be set for the port to timestamp PTP event messages over UDP sent to a unicast address; without it, only messages sent to the PTP multicast addresses selected by the TS_107 and TS_129 to TS_132 bits are timestamped. TI's netcp_ethss driver for the Keystone 2 Ethernet switch, which has the same timestamping registers, always sets TS_UNI_EN.

Set TS_UNI_EN along with the other bits. With this change, ptp4l in the same setup gets timestamps for the unicast Delay_Req and Sync messages.

Fixes b1f66a5bee07 ("net: ethernet: ti: am65-cpsw-nuss: enable packet timestamping support")
---
 drivers/net/ethernet/ti/am65-cpsw-nuss.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/net/ethernet/ti/am65-cpsw-nuss.c +3 -1
index 6228faa1a8c3d..ecffb524116ca 100644
@@ -103,6 +103,7 @@
 #define AM65_CPSW_PN_TS_CTL_LTYPE2_TS_319	BIT(21)
 #define AM65_CPSW_PN_TS_CTL_LTYPE2_TS_320	BIT(22)
 #define AM65_CPSW_PN_TS_CTL_LTYPE2_TS_TTL_NONZERO BIT(23)
+#define AM65_CPSW_PN_TS_CTL_LTYPE2_TS_UNI_EN	BIT(24)
 
 /* The PTP event messages - Sync, Delay_Req, Pdelay_Req, and Pdelay_Resp. */
 #define AM65_CPSW_TS_EVENT_MSG_TYPE_BITS (BIT(0) | BIT(1) | BIT(2) | BIT(3))
@@ -1274,7 +1275,8 @@ static int am65_cpsw_nuss_hwtstamp_set(struct net_device *ndev,
 			 AM65_CPSW_PN_TS_CTL_LTYPE2_TS_132 |
 			 AM65_CPSW_PN_TS_CTL_LTYPE2_TS_319 |
 			 AM65_CPSW_PN_TS_CTL_LTYPE2_TS_320 |
-			 AM65_CPSW_PN_TS_CTL_LTYPE2_TS_TTL_NONZERO;
+			 AM65_CPSW_PN_TS_CTL_LTYPE2_TS_TTL_NONZERO |
+			 AM65_CPSW_PN_TS_CTL_LTYPE2_TS_UNI_EN;
 
 	ts_ctrl = AM65_CPSW_TS_EVENT_MSG_TYPE_BITS <<
 		  AM65_CPSW_PN_TS_CTL_MSG_TYPE_EN_SHIFT;
Signature · 1 line
2.53.0
author maintainer
#753 lore raw

PATCH 748/1848 drm/etnaviv: Flush the tile status cache through both the PE and BLT

In reply to Greg Kroah-Hartman

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

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

From: Christian Gmeiner <[email protected]>

[ Upstream commit c1a757f8df1363032623fa9b1baaba0dcf34de6d ]

Since commit f232d9ec029c ("drm/etnaviv: fix TS cache flushing on GPUs with BLT engine"), jobs on GPUs with a BLT engine use a BLT command to flush the tile status cache instead of TS_FLUSH_CACHE, which is broken on most of these GPUs.

GC7000 r6008/r6009 and GC8200 r6401 are the other way around:
TS_FLUSH_CACHE works, but the BLT command does not flush the cache. The vendor driver handles these GPUs using TS_FLUSH_CACHE, but the etnaviv kernel driver has no way to identify them.

As a result, dirty tile status cache lines survive the end of a job. They are written back by the next cache flush, using the page table of the job issuing it. If that job belongs to another process, the write goes to the wrong address space.

On GC7000 r6009 this causes MMU faults and GPU recoveries blamed on an innocent process. I see around 1100 per run of a multisample depth/stencil test running alongside two other GPU clients.

Emit both flushes at the end of every job on GPUs with a BLT engine. Whichever does not work on a given GPU is a no-op. Since dirty lines are only written back once, this costs one additional state load per job.

Fixes f232d9ec029c ("drm/etnaviv: fix TS cache flushing on GPUs with BLT engine")
---
 drivers/gpu/drm/etnaviv/etnaviv_buffer.c | 40 +++++++++++-------------
 1 file changed, 18 insertions(+), 22 deletions(-)
drivers/gpu/drm/etnaviv/etnaviv_buffer.c +18 -22
index 7d897aafb2a6a..baa76846ba5d9 100644
@@ -229,6 +229,17 @@ u16 etnaviv_buffer_config_pta(struct etnaviv_gpu *gpu, unsigned short id)
 	return buffer->user_size / 8;
 }
 
+static void etnaviv_cmd_flush_ts(struct etnaviv_cmdbuf *buffer, bool has_blt)
+{
+	CMD_LOAD_STATE(buffer, VIVS_TS_FLUSH_CACHE, VIVS_TS_FLUSH_CACHE_FLUSH);
+
+	if (has_blt) {
+		CMD_LOAD_STATE(buffer, VIVS_BLT_ENABLE, 0x1);
+		CMD_LOAD_STATE(buffer, VIVS_BLT_SET_COMMAND, 0x1);
+		CMD_LOAD_STATE(buffer, VIVS_BLT_ENABLE, 0x0);
+	}
+}
+
 void etnaviv_buffer_end(struct etnaviv_gpu *gpu)
 {
 	struct etnaviv_cmdbuf *buffer = &gpu->buffer;
@@ -252,7 +263,7 @@ void etnaviv_buffer_end(struct etnaviv_gpu *gpu)
 		unsigned int dwords = 7;
 
 		if (has_blt)
-			dwords += 10;
+			dwords += 11;
 
 		link_target = etnaviv_buffer_reserve(gpu, buffer, dwords);
 
@@ -265,16 +276,8 @@ void etnaviv_buffer_end(struct etnaviv_gpu *gpu)
 			CMD_LOAD_STATE(buffer, VIVS_BLT_ENABLE, 0x0);
 		}
 		CMD_LOAD_STATE(buffer, VIVS_GL_FLUSH_CACHE, flush);
-		if (gpu->exec_state == ETNA_PIPE_3D) {
-			if (has_blt) {
-				CMD_LOAD_STATE(buffer, VIVS_BLT_ENABLE, 0x1);
-				CMD_LOAD_STATE(buffer, VIVS_BLT_SET_COMMAND, 0x1);
-				CMD_LOAD_STATE(buffer, VIVS_BLT_ENABLE, 0x0);
-			} else {
-				CMD_LOAD_STATE(buffer, VIVS_TS_FLUSH_CACHE,
-					       VIVS_TS_FLUSH_CACHE_FLUSH);
-			}
-		}
+		if (gpu->exec_state == ETNA_PIPE_3D)
+			etnaviv_cmd_flush_ts(buffer, has_blt);
 		CMD_SEM(buffer, SYNC_RECIPIENT_FE, SYNC_RECIPIENT_PE);
 		CMD_STALL(buffer, SYNC_RECIPIENT_FE, SYNC_RECIPIENT_PE);
 		if (has_blt) {
@@ -461,12 +464,12 @@ void etnaviv_buffer_queue(struct etnaviv_gpu *gpu, u32 exec_state,
 	return_dwords = 7;
 
 	/*
-	 * When the BLT engine is present we need 6 more dwords in the return
+	 * When the BLT engine is present we need 7 more dwords in the return
 	 * target: 3 enable/flush/disable + 4 enable/semaphore stall/disable,
-	 * but we don't need the normal TS flush state.
+	 * on top of the normal TS flush state.
 	 */
 	if (has_blt)
-		return_dwords += 6;
+		return_dwords += 7;
 
 	return_target = etnaviv_buffer_reserve(gpu, buffer, return_dwords);
 	CMD_LINK(cmdbuf, return_dwords, return_target);
@@ -483,14 +486,7 @@ void etnaviv_buffer_queue(struct etnaviv_gpu *gpu, u32 exec_state,
 				       VIVS_GL_FLUSH_CACHE_DEPTH |
 				       VIVS_GL_FLUSH_CACHE_COLOR |
 				       VIVS_GL_FLUSH_CACHE_SHADER_L1);
-		if (has_blt) {
-			CMD_LOAD_STATE(buffer, VIVS_BLT_ENABLE, 0x1);
-			CMD_LOAD_STATE(buffer, VIVS_BLT_SET_COMMAND, 0x1);
-			CMD_LOAD_STATE(buffer, VIVS_BLT_ENABLE, 0x0);
-		} else {
-			CMD_LOAD_STATE(buffer, VIVS_TS_FLUSH_CACHE,
-					       VIVS_TS_FLUSH_CACHE_FLUSH);
-		}
+		etnaviv_cmd_flush_ts(buffer, has_blt);
 	}
 	CMD_SEM(buffer, SYNC_RECIPIENT_FE, SYNC_RECIPIENT_PE);
 	CMD_STALL(buffer, SYNC_RECIPIENT_FE, SYNC_RECIPIENT_PE);
Signature · 1 line
2.53.0
author maintainer
#754 lore raw

PATCH 749/1848 udf: dont let the extent type hide an exhausted free-space table extent

In reply to Greg Kroah-Hartman

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

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

From: Matthias Goergens <[email protected]>

[ Upstream commit da582d84fcf5f2f0c1d7760e1a899ca7cedb80fc ]

udf_table_new_block() takes the first block of the free-space table extent closest to the goal. It keeps that extent's type and length together in goal_elen, subtracts one block, and deletes the extent only if goal_elen then reaches zero. UDF 2.60 section 2.3.7.1 requires the free-space extents of an Unallocated Space Entry to be of type 1 (allocated but not recorded), and mkudffs writes them that way. For such an extent the type bits keep goal_elen non-zero, so taking its last block leaves a type-1 extent of length zero behind, starting at the block after the extent, which is in use.

The next allocation that picks this empty extent returns that in-use block. Subtracting a block from 0x40000000 then borrows from the type bits, and the extent becomes type 0 with a length of 2^30 - blocksize:
about a gigabyte of "free" space overlapping live metadata, the other table extents and whatever lies behind the partition. From then on blocks are handed out twice, or past the end of the partition.

Extents that udf_table_free_blocks() adds are type 0, where the check works, so only tables written by mkudffs or by another implementation are affected. Nothing more than filling such a filesystem is needed:
on a fresh 1 MiB "mkudffs --space=unalloctable" image, creating empty files until the partition is full writes file entries over the reserve volume descriptor sequence and the backup anchor, and df then reports a negative amount of used space.

On syzbot's images the same double allocation is what the two reports below trip over. In the first, ftruncate() extends a new file with enough hole extents to need a chain of allocation extent descriptors; one AED is placed on another inode's file entry, and a later one is placed on the block of the AED currently being filled, which udf_setup_indirect_aext() zeroes, so __udf_add_aext() finds lengthAllocDescs out of step with its cursor. In the second, an AED is placed past the end of the device, sb_getblk() fails, and the error path of udf_do_extend_file() calls udf_truncate_extents() on an extent list that no longer covers i_size.

Keep the type separately from the length, as udf_table_prealloc_blocks() already does.

---
 fs/udf/balloc.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
fs/udf/balloc.c +5 -3
index e8e3e291ef819..0bbe86da3d133 100644
@@ -580,7 +580,7 @@ static udf_pblk_t udf_table_new_block(struct super_block *sb,
 	uint32_t elen, goal_elen = 0;
 	struct kernel_lb_addr eloc, goal_eloc;
 	struct extent_position epos, goal_epos;
-	int8_t etype;
+	int8_t etype, goal_etype = 0;
 	struct udf_inode_info *iinfo = UDF_I(table);
 
 	*err = -ENOSPC;
@@ -628,7 +628,8 @@ static udf_pblk_t udf_table_new_block(struct super_block *sb,
 			goal_epos.block = epos.block;
 			goal_epos.offset = epos.offset - adsize;
 			goal_eloc = eloc;
-			goal_elen = (etype << 30) | elen;
+			goal_elen = elen;
+			goal_etype = etype;
 		}
 	}
 
@@ -650,7 +651,8 @@ static udf_pblk_t udf_table_new_block(struct super_block *sb,
 	goal_elen -= sb->s_blocksize;
 
 	if (goal_elen)
-		udf_write_aext(table, &goal_epos, &goal_eloc, goal_elen, 1);
+		udf_write_aext(table, &goal_epos, &goal_eloc,
+			       (goal_etype << 30) | goal_elen, 1);
 	else
 		udf_delete_aext(table, goal_epos);
 	brelse(goal_epos.bh);
Signature · 1 line
2.53.0
author maintainer
#755 lore raw

PATCH 750/1848 MIPS: mm: Fix the cache error vector jump for XKPHYS kernels

In reply to Greg Kroah-Hartman

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

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

From: Imre Kaloz <[email protected]>

[ Upstream commit 30b76362f80d39d80f1197c88b284d9fa7952356 ]

except_vec2_generic jumps to cache_parity_error with a j, which cannot leave the vector's 256MB region. An XKPHYS kernel such as IP30's, linked at 512MB, is outside it, so the j targets an unbacked address and its speculative fetch raises bus errors on unrelated fetches. Jump to the handler's uncached XKPHYS address instead.

Fixes 7505576d1c1a ("MIPS: add support for SGI Octane (IP30)")
---
 arch/mips/mm/cex-gen.S | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)
arch/mips/mm/cex-gen.S +16 -0
index 45dff5cd4b8e7..b4c027b0421dc 100644
@@ -8,6 +8,7 @@
  *
  * Cache error handler
  */
+#include <asm/addrspace.h>
 #include <asm/asm.h>
 #include <asm/regdef.h>
 #include <asm/mipsregs.h>
@@ -37,6 +38,21 @@
 	nop
 	nop
 
+#if defined(CONFIG_64BIT) && VMLINUX_LOAD_ADDRESS >= XKPHYS && \
+    VMLINUX_LOAD_ADDRESS < XKSEG
+	/*
+	 * An XKPHYS kernel may lie outside the 256MB region a j from the
+	 * vector reaches, so jump to the handler's uncached XKPHYS address.
+	 */
+	PTR_LA	k0, cache_parity_error
+	PTR_LI	k1, TO_PHYS_MASK
+	and	k0, k0, k1
+	PTR_LI	k1, UNCAC_BASE
+	or	k0, k0, k1
+	jr	k0
+	nop
+#else
 	j	cache_parity_error
 	nop
+#endif
 	END(except_vec2_generic)
Signature · 1 line
2.53.0
author maintainer
#756 lore raw

PATCH 751/1848 MIPS: sgi-ip32: Mask MACE PCI interrupts in CRIME only

In reply to Greg Kroah-Hartman

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

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

From: Imre Kaloz <[email protected]>

[ Upstream commit 4e65c502b8975e7c3c3d84aba59cd04af1dd6b8a ]

Masking PCI interrupts in the MACE PCI control register overwrites the error and arbitration enables set at init, and a read-modify-write can hang CRIME 1.1 machines under DMA load. Enable the slot interrupts once and mask them in CRIME.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
---
 arch/mips/pci/pci-ip32.c      |  7 ++++--
 arch/mips/sgi-ip32/ip32-irq.c | 45 +++--------------------------------
 2 files changed, 8 insertions(+), 44 deletions(-)
arch/mips/pci/pci-ip32.c +5 -2
index 7ae89d0c70990..30aca6f76563d 100644
@@ -125,10 +125,13 @@ static int __init mace_init(void)
 {
 	PCIBIOS_MIN_IO = 0x1000;
 
-	/* Clear any outstanding errors and enable interrupts */
+	/*
+	 * Clear any outstanding errors and enable interrupts.  PCI interrupts
+	 * are masked in CRIME, so the per-slot enables stay on.
+	 */
 	mace->pci.error_addr = 0;
 	mace->pci.error = 0;
-	mace->pci.control = 0xff008500;
+	mace->pci.control = 0xff0085ff;
 
 	printk("MACE PCI rev %d\n", mace->pci.rev);
 
arch/mips/sgi-ip32/ip32-irq.c +3 -42

69 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#757 lore raw

PATCH 752/1848 MIPS: sgi-ip32: Leave MACE PCI control alone in config accesses

In reply to Greg Kroah-Hartman

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

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

From: Imre Kaloz <[email protected]>

[ Upstream commit a55a7df2cf788234850d9053ecc25a5470175929 ]

mace_pci_read_config() clears the master abort interrupt enable in the MACE PCI control register around each config read. A register read followed by two register writes can hang CRIME 1.1 under DMA load.

Ack master aborts in the error register instead, and follow every write with a read so back-to-back accesses cannot form that sequence.

Fixes c990081bf87b ("[MIPS] Fix IP32 breakage")
---
 arch/mips/pci/ops-mace.c | 26 +++++++++++++++++++-------
 arch/mips/pci/pci-ip32.c |  2 ++
 2 files changed, 21 insertions(+), 7 deletions(-)
arch/mips/pci/ops-mace.c +19 -7
index 951d8070fb486..8827e5f2ea460 100644
@@ -35,15 +35,27 @@ static inline int mkaddr(struct pci_bus *bus, unsigned int devfn,
 		(reg & 0xfc);
 }
 
+/*
+ * On CRIME 1.1, a MACE PCI register read followed by two register writes
+ * can hang the machine under DMA load, so every register write in this
+ * file is followed by a read.  Config cycles to empty slots end in a
+ * master abort; ack it with interrupts still off so the bridge error
+ * interrupt does not report it.
+ */
+static void mace_pci_ack_abort(void)
+{
+	u32 error = mace->pci.error;
+
+	if (error & MACEPCI_ERROR_MASTER_ABORT) {
+		mace->pci.error = error & ~MACEPCI_ERROR_MASTER_ABORT;
+		mace->pci.error;
+	}
+}
 
 static int
 mace_pci_read_config(struct pci_bus *bus, unsigned int devfn,
 		     int reg, int size, u32 *val)
 {
-	u32 control = mace->pci.control;
-
-	/* disable master aborts interrupts during config read */
-	mace->pci.control = control & ~MACEPCI_CONTROL_MAR_INT;
 	mace->pci.config_addr = mkaddr(bus, devfn, reg);
 	switch (size) {
 	case 1:
@@ -56,9 +68,7 @@ mace_pci_read_config(struct pci_bus *bus, unsigned int devfn,
 		*val = mace->pci.config_data.l;
 		break;
 	}
-	/* ack possible master abort */
-	mace->pci.error &= ~MACEPCI_ERROR_MASTER_ABORT;
-	mace->pci.control = control;
+	mace_pci_ack_abort();
 	/*
 	 * someone forgot to set the ultra bit for the onboard
 	 * scsi chips; we fake it here
@@ -77,6 +87,7 @@ mace_pci_write_config(struct pci_bus *bus, unsigned int devfn,
 		      int reg, int size, u32 val)
 {
 	mace->pci.config_addr = mkaddr(bus, devfn, reg);
+	mace->pci.error;
 	switch (size) {
 	case 1:
 		mace->pci.config_data.b[(reg & 3) ^ 3] = val;
@@ -88,6 +99,7 @@ mace_pci_write_config(struct pci_bus *bus, unsigned int devfn,
 		mace->pci.config_data.l = val;
 		break;
 	}
+	mace_pci_ack_abort();
 
 	DPRINTK("write%d: reg=%08x,val=%02x\n", size * 8, reg, val);
 
arch/mips/pci/pci-ip32.c +2 -0
index 30aca6f76563d..41ec8453c865d 100644
@@ -77,6 +77,8 @@ static irqreturn_t macepci_error(int irq, void *dev)
 	}
 
 	mace->pci.error = flags;
+	/* follow the write with a read, see mace_pci_ack_abort() */
+	mace->pci.error;
 
 	return IRQ_HANDLED;
 }
Signature · 1 line
2.53.0
author maintainer
#758 lore raw

PATCH 753/1848 nvmet: bound the traddr and trsvcid configfs writes

In reply to Greg Kroah-Hartman

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

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

From: Shao Mingyin <[email protected]>

[ Upstream commit cf399d4abbeddc317f8160a79fefb4016c469862 ]

nvmet_addr_traddr_store() and nvmet_addr_trsvcid_store() reject a write only when count is larger than NVMF_TRADDR_SIZE (256) respectively NVMF_TRSVCID_SIZE (32). A write of exactly that many characters is accepted, and the following

	sscanf(page, "%s\n", port->disc_addr.traddr)

has no field width. configfs terminates the buffer at page[count], so the scan writes 256 characters plus the trailing NUL, i.e. 257 bytes, into traddr[256]. The extra byte lands in the following tsas field of the discovery log entry, silently clearing the first TSAS byte (the RDMA queue type, or the TLS section type for TCP). trsvcid has the same off-by-one with a 32-byte write; there the extra byte lands in the reserved bytes that follow trsvcid.

Limit the scans to one byte less than the destination arrays. The count checks can stay as they are so that a normal newline-terminated write is still accepted.

Fixes 9ba2a5cb8896 ("nvmet: filter newlines from user input")
---
 drivers/nvme/target/configfs.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/nvme/target/configfs.c +2 -2
index 55057d34a4e99..beef58d9d011e 100644
@@ -141,7 +141,7 @@ static ssize_t nvmet_addr_traddr_store(struct config_item *item,
 	if (nvmet_is_port_enabled(port, __func__))
 		return -EACCES;
 
-	if (sscanf(page, "%s\n", port->disc_addr.traddr) != 1)
+	if (sscanf(page, "%255s", port->disc_addr.traddr) != 1)
 		return -EINVAL;
 	return count;
 }
@@ -215,7 +215,7 @@ static ssize_t nvmet_addr_trsvcid_store(struct config_item *item,
 	if (nvmet_is_port_enabled(port, __func__))
 		return -EACCES;
 
-	if (sscanf(page, "%s\n", port->disc_addr.trsvcid) != 1)
+	if (sscanf(page, "%31s", port->disc_addr.trsvcid) != 1)
 		return -EINVAL;
 	return count;
 }
Signature · 1 line
2.53.0
author maintainer
#759 lore raw

PATCH 754/1848 x86/nmi: Ignore negative NMI handler durations

In reply to Greg Kroah-Hartman

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

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

From: Breno Leitao <[email protected]>

[ Upstream commit ade63af6cfb7b3ca19ced28730fd6461e8d1d410 ]

I am seeing NMI handlers in the Meta fleet reported as running for about 584 years. Over 30 days, 11 AMD and Intel machines logged 637 such lines, for example:

AMD EPYC 9D25 (family 0x1a, model 0x11, stepping 0x0):

  [ 1650.616627] INFO: NMI handler (nmi_cpu_backtrace_handler.llvm.9643156322683129580) took too long to run: 18446744073709.551 msecs

Intel Xeon Platinum 8321HC (family 0x6, model 0x55, stepping 0xb):

  [360448.230129] INFO: NMI handler (perf_event_nmi_handler) took too long to run: 18446744071018.936 msecs

Intel Xeon D-2191A (family 0x6, model 0x55, stepping 0x4):

  [81787.188959] INFO: NMI handler (ghes_notify_nmi) took too long to run: 18446744073709.545 msecs

nmi_handle() times each handler with two sched_clock() reads. When the second read is lower than the first, the u64 subtraction wraps, and nmi_check_duration() treats the result as a duration. In the three examples, the clock went back by less than 1 us, by 2.7 s and by about 6 us.

The wrapped value is also stored in action->max_duration. Every later real duration is smaller, so the handler is never reported again until the next boot.

Whatever makes the clock read lower, a negative difference is not a duration, so return before it is stored or reported. A clock that steps forward is not covered, since that cannot be told from a real stall.

A backwards clock is still worth knowing about, so print the size of the step once per boot. This uses pr_warn_once() rather than WARN, as a stack trace says nothing about the clock and panic_on_warn machines should not go down for it.

Fixes 2ab00456ea8a ("x86: Warn when NMI handlers take large amounts of time")
---
 arch/x86/kernel/nmi.c | 8 ++++++++
 1 file changed, 8 insertions(+)
arch/x86/kernel/nmi.c +8 -0
index 09997eee7b6fe..8990e4efe414b 100644
@@ -109,6 +109,14 @@ static void nmi_check_duration(struct nmiaction *action, u64 duration)
 {
 	int remainder_ns, decimal_msecs;
 
+	/* sched_clock() went backwards? */
+	if ((s64)duration < 0) {
+		pr_warn_once("NMI handler (%ps): sched_clock() went backwards by %lld ns on CPU%d\n",
+			     action->handler, -(s64)duration,
+			     smp_processor_id());
+		return;
+	}
+
 	if (duration < nmi_longest_ns || duration < action->max_duration)
 		return;
 
Signature · 1 line
2.53.0
author maintainer
#760 lore raw

PATCH 755/1848 x86/boot: Fix off-by-one error in sme_clear_pgd()

In reply to Greg Kroah-Hartman

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

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

From: Thorsten Blum <[email protected]>

[ Upstream commit cb319926808b1cca522d2087a13205e840beb45b ]

The mapping helpers __sme_map_range_pmd() and __sme_map_range_pte(), and therefore sme_encrypt_kernel(), use exclusive end addresses and stop before vaddr reaches vaddr_end.

However, sme_clear_pgd() treats vaddr_end as inclusive when calculating the last PGD entry to clear. If vaddr_end is PGD-aligned, the first PGD entry outside the range is cleared too.

Use vaddr_end - 1 to calculate the last PGD entry within the range.

---
 arch/x86/mm/mem_encrypt_identity.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/x86/mm/mem_encrypt_identity.c +1 -1
index 5ec47af786ddb..7899448d46fe2 100644
@@ -102,7 +102,7 @@ static void __init sme_clear_pgd(struct sme_populate_pgd_data *ppd)
 	pgd_t *pgd_p;
 
 	pgd_start = ppd->vaddr & PGDIR_MASK;
-	pgd_end = ppd->vaddr_end & PGDIR_MASK;
+	pgd_end = (ppd->vaddr_end - 1) & PGDIR_MASK;
 
 	pgd_size = (((pgd_end - pgd_start) / PGDIR_SIZE) + 1) * sizeof(pgd_t);
 
Signature · 1 line
2.53.0
author maintainer
#761 lore raw

PATCH 756/1848 ata: libata-pmp: disable the SEMB port on Marvell 88SM9705

In reply to Greg Kroah-Hartman

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

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

From: Marco Ziliani <[email protected]>

[ Upstream commit 6b67cdb463b006e57f15e3fe4ea03b00f0ac9ee5 ]

The Marvell 88SM9705 is a 1-to-5 SATA port multiplier with one additional SEMB (SATA Enclosure Management Bridge) port [1]. Ports 0-4 are device ports and port 5 is the SEMB. The number of fan-out ports in GSCR[2] is 6 when the SEMB is enabled and 5 when it is not, so on boards without the SEMB there is no link 5 and this quirk does nothing. That includes the common 8-port PCIe cards that pair an 88SE9215 with an 88SM9705, which report 5 ports.

The SEMB port never answers SRST. libata probes it like a device port, and every EH round on the PMP ends in a retry loop that lasts about a minute before EH gives up, then starts over:

ata19.15: Port Multiplier 1.2, 0x1b4b:0x9705 r160, 6 ports, feat 0x1/0x1f ata19.05: hard resetting link
ata19.05: failed to resume link (SControl 0)
ata19.05: softreset failed (1st FIS failed)
ata19.05: hard resetting link
...
ata20.05: reset failed, giving up

Disk discovery waits for this, including disks on other controllers.

libata.force only partly works around it. The "disable" horkage only takes effect after IDENTIFY, which the SEMB link never reaches. "norst" on port 5 stops the retry loop, but the disks still come up about a minute later than with this change (see below).

Treat port 5 the same way as port 4 of the Marvell 88SM4140 and mark the link ATA_LFLAG_DISABLED.

Tested on a Synology DX1222 expansion unit (four 88SM9705 r160 behind a Marvell 88SE9235, passed through to a KVM guest, 6 disks), 7.4-rc1 with and without this change, one boot each:

                                    softreset  reset failed,  last disk
                                    failed     giving up      attached
  7.4-rc1, no libata.force          60         12             197 s
  7.4-rc1, libata.force=N.05:norst   0          0              70 s
  7.4-rc1 + this patch, no force     0          0              11 s

The problem was first found on a Synology DX1215 with the same chain, where this change brought the disks up after about 20 s instead of about 200 s, including a disk on a separate AHCI controller.

Each PMP still logs one "failed to resume link (SControl 0)" for port 5 at probe time.

---
 drivers/ata/libata-pmp.c | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
drivers/ata/libata-pmp.c +14 -0
index 452baa43d77ef..5fa06708eb6a0 100644
@@ -471,6 +471,20 @@ static void sata_pmp_quirks(struct ata_port *ap)
 			if (link->pmp == 4)
 				link->flags |= ATA_LFLAG_DISABLED;
 		}
+	} else if (vendor == 0x1b4b && devid == 0x9705) {
+		/*
+		 * Marvell 88SM9705 quirks
+		 *
+		 * 1-to-5 PMP with an extra SEMB port.  It reports 6 ports and
+		 * port 5 is the SEMB, which never answers SRST: EH spends about
+		 * a minute per round retrying it, and disk discovery waits for
+		 * that.  Seen behind a Marvell 88SE9235 in the Synology DX1215
+		 * and DX1222.
+		 */
+		ata_for_each_link(link, ap, EDGE) {
+			if (link->pmp == 5)
+				link->flags |= ATA_LFLAG_DISABLED;
+		}
 	}
 }
 
Signature · 1 line
2.53.0
author maintainer
#762 lore raw

PATCH 757/1848 can: raw: fix receiver memory leak

In reply to Greg Kroah-Hartman

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

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

From: Ziyang Xuan <[email protected]>

commit ee8b94c8510ce64afe0b87ef548d23e00915fb10 upstream.

Got kmemleak errors with the following ltp can_filter testcase:

for ((i=1; i<=100; i++))
do

        ./can_filter &
        sleep 0.1

done

==============================================================

[<00000000db4a4943>] can_rx_register+0x147/0x360 [can]
[<00000000a289549d>] raw_setsockopt+0x5ef/0x853 [can_raw]
[<000000006d3d9ebd>] __sys_setsockopt+0x173/0x2c0
[<00000000407dbfec>] __x64_sys_setsockopt+0x61/0x70
[<00000000fd468496>] do_syscall_64+0x33/0x40
[<00000000b7e47d51>] entry_SYSCALL_64_after_hwframe+0x61/0xc6

It's a bug in the concurrent scenario of unregister_netdevice_many() and raw_release() as following:

cpu0 cpu1
unregister_netdevice_many(can_dev)
unlist_netdevice(can_dev) // dev_get_by_index() return NULL after this net_set_todo(can_dev)

						raw_release(can_socket)
						  dev = dev_get_by_index(, ro->ifindex); // dev == NULL
						  if (dev) { // receivers in dev_rcv_lists not free because dev is NULL
						    raw_disable_allfilters(, dev, );
						    dev_put(dev);
						  }
						  ...
						  ro->bound = 0;
						  ...

call_netdevice_notifiers(NETDEV_UNREGISTER, )
raw_notify(, NETDEV_UNREGISTER, )
if (ro->bound) // invalid because ro->bound has been set 0
raw_disable_allfilters(, dev, ); // receivers in dev_rcv_lists will never be freed

Add a net_device pointer member in struct raw_sock to record bound can_dev, and use rtnl_lock to serialize raw_socket members between raw_bind(), raw_release(), raw_setsockopt() and raw_notify(). Use ro->dev to decide whether to free receivers in dev_rcv_lists.

Stable-dep-of: 962947b69589 ("can: replace ARPHRD_CAN type checks with can_get_ml_priv()") [ backport to 5.10: Adapt the raw_release() context as
free_percpu(ro->uniq) has already been moved out of raw_release() in
this tree. ]

---
 net/can/raw.c | 57 ++++++++++++++++++++++-----------------------------
 1 file changed, 24 insertions(+), 33 deletions(-)
net/can/raw.c +24 -33
index 8bbbd9092e3a3..7df3086e9f910 100644
@@ -83,6 +83,7 @@ struct raw_sock {
 	struct sock sk;
 	int bound;
 	int ifindex;
+	struct net_device *dev;
 	struct list_head notifier;
 	int loopback;
 	int recv_own_msgs;
@@ -275,7 +276,7 @@ static void raw_notify(struct raw_sock *ro, unsigned long msg,
 	if (!net_eq(dev_net(dev), sock_net(sk)))
 		return;
 
-	if (ro->ifindex != dev->ifindex)
+	if (ro->dev != dev)
 		return;
 
 	switch (msg) {
@@ -290,6 +291,7 @@ static void raw_notify(struct raw_sock *ro, unsigned long msg,
 
 		ro->ifindex = 0;
 		ro->bound = 0;
+		ro->dev = NULL;
 		ro->count = 0;
 		release_sock(sk);
 
@@ -343,6 +345,7 @@ static int raw_init(struct sock *sk)
 
 	ro->bound            = 0;
 	ro->ifindex          = 0;
+	ro->dev              = NULL;
 
 	/* set default filter to single entry dfilter */
 	ro->dfilter.can_id   = 0;
@@ -392,19 +395,13 @@ static int raw_release(struct socket *sock)
 
 	lock_sock(sk);
 
+	rtnl_lock();
 	/* remove current filters & unregister */
 	if (ro->bound) {
-		if (ro->ifindex) {
-			struct net_device *dev;
-
-			dev = dev_get_by_index(sock_net(sk), ro->ifindex);
-			if (dev) {
-				raw_disable_allfilters(dev_net(dev), dev, sk);
-				dev_put(dev);
-			}
-		} else {
+		if (ro->dev)
+			raw_disable_allfilters(dev_net(ro->dev), ro->dev, sk);
+		else
 			raw_disable_allfilters(sock_net(sk), NULL, sk);
-		}
 	}
 
 	if (ro->count > 1)
@@ -412,7 +409,9 @@ static int raw_release(struct socket *sock)
 
 	ro->ifindex = 0;
 	ro->bound = 0;
+	ro->dev = NULL;
 	ro->count = 0;
+	rtnl_unlock();
 
 	sock_orphan(sk);
 	sock->sk = NULL;
@@ -428,6 +427,7 @@ static int raw_bind(struct socket *sock, struct sockaddr *uaddr, int len)
 	struct sockaddr_can *addr = (struct sockaddr_can *)uaddr;
 	struct sock *sk = sock->sk;
 	struct raw_sock *ro = raw_sk(sk);
+	struct net_device *dev = NULL;
 	int ifindex;
 	int err = 0;
 	int notify_enetdown = 0;
@@ -437,14 +437,13 @@ static int raw_bind(struct socket *sock, struct sockaddr *uaddr, int len)
 	if (addr->can_family != AF_CAN)
 		return -EINVAL;
 
+	rtnl_lock();
 	lock_sock(sk);
 
 	if (ro->bound && addr->can_ifindex == ro->ifindex)
 		goto out;
 
 	if (addr->can_ifindex) {
-		struct net_device *dev;
-
 		dev = dev_get_by_index(sock_net(sk), addr->can_ifindex);
 		if (!dev) {
 			err = -ENODEV;
@@ -473,26 +472,20 @@ static int raw_bind(struct socket *sock, struct sockaddr *uaddr, int len)
 	if (!err) {
 		if (ro->bound) {
 			/* unregister old filters */
-			if (ro->ifindex) {
-				struct net_device *dev;
-
-				dev = dev_get_by_index(sock_net(sk),
-						       ro->ifindex);
-				if (dev) {
-					raw_disable_allfilters(dev_net(dev),
-							       dev, sk);
-					dev_put(dev);
-				}
-			} else {
+			if (ro->dev)
+				raw_disable_allfilters(dev_net(ro->dev),
+						       ro->dev, sk);
+			else
 				raw_disable_allfilters(sock_net(sk), NULL, sk);
-			}
 		}
 		ro->ifindex = ifindex;
 		ro->bound = 1;
+		ro->dev = dev;
 	}
 
  out:
 	release_sock(sk);
+	rtnl_unlock();
 
 	if (notify_enetdown) {
 		sk->sk_err = ENETDOWN;
@@ -558,9 +551,9 @@ static int raw_setsockopt(struct socket *sock, int level, int optname,
 		rtnl_lock();
 		lock_sock(sk);
 
-		if (ro->bound && ro->ifindex) {
-			dev = dev_get_by_index(sock_net(sk), ro->ifindex);
-			if (!dev) {
+		dev = ro->dev;
+		if (ro->bound && dev) {
+			if (dev->reg_state != NETREG_REGISTERED) {
 				if (count > 1)
 					kfree(filter);
 				err = -ENODEV;
@@ -601,7 +594,6 @@ static int raw_setsockopt(struct socket *sock, int level, int optname,
 		ro->count  = count;
 
  out_fil:
-		dev_put(dev);
 		release_sock(sk);
 		rtnl_unlock();
 
@@ -619,9 +611,9 @@ static int raw_setsockopt(struct socket *sock, int level, int optname,
 		rtnl_lock();
 		lock_sock(sk);
 
-		if (ro->bound && ro->ifindex) {
-			dev = dev_get_by_index(sock_net(sk), ro->ifindex);
-			if (!dev) {
+		dev = ro->dev;
+		if (ro->bound && dev) {
+			if (dev->reg_state != NETREG_REGISTERED) {
 				err = -ENODEV;
 				goto out_err;
 			}
@@ -645,7 +637,6 @@ static int raw_setsockopt(struct socket *sock, int level, int optname,
 		ro->err_mask = err_mask;
 
  out_err:
-		dev_put(dev);
 		release_sock(sk);
 		rtnl_unlock();
 
Signature · 1 line
2.53.0
author maintainer
#763 lore raw

PATCH 758/1848 can: raw: fix lockdep issue in raw_release()

In reply to Greg Kroah-Hartman

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

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

From: Eric Dumazet <[email protected]>

commit 11c9027c983e9e4b408ee5613b6504d24ebd85be upstream.

syzbot complained about a lockdep issue [1]

Since raw_bind() and raw_setsockopt() first get RTNL
before locking the socket, we must adopt the same order in raw_release()

[1]
WARNING: possible circular locking dependency detected 6.5.0-rc1-syzkaller-00192-g78adb4bcf99e #0 Not tainted
------------------------------------------------------
syz-executor.0/14110 is trying to acquire lock:
ffff88804e4b6130 (sk_lock-AF_CAN){+.+.}-{0:0}, at: lock_sock include/net/sock.h:1708 [inline] ffff88804e4b6130 (sk_lock-AF_CAN){+.+.}-{0:0}, at: raw_bind+0xb1/0xab0 net/can/raw.c:435

but task is already holding lock:
ffffffff8e3df368 (rtnl_mutex){+.+.}-{3:3}, at: raw_bind+0xa7/0xab0 net/can/raw.c:434

which lock already depends on the new lock.

the existing dependency chain (in reverse order) is:

-> #1 (rtnl_mutex){+.+.}-{3:3}:

__mutex_lock_common kernel/locking/mutex.c:603 [inline]
__mutex_lock+0x181/0x1340 kernel/locking/mutex.c:747
raw_release+0x1c6/0x9b0 net/can/raw.c:391
__sock_release+0xcd/0x290 net/socket.c:654
sock_close+0x1c/0x20 net/socket.c:1386
__fput+0x3fd/0xac0 fs/file_table.c:384
task_work_run+0x14d/0x240 kernel/task_work.c:179
resume_user_mode_work include/linux/resume_user_mode.h:49 [inline]
exit_to_user_mode_loop kernel/entry/common.c:171 [inline]
exit_to_user_mode_prepare+0x210/0x240 kernel/entry/common.c:204
__syscall_exit_to_user_mode_work kernel/entry/common.c:286 [inline]
syscall_exit_to_user_mode+0x1d/0x50 kernel/entry/common.c:297
do_syscall_64+0x44/0xb0 arch/x86/entry/common.c:86
entry_SYSCALL_64_after_hwframe+0x63/0xcd

-> #0 (sk_lock-AF_CAN){+.+.}-{0:0}:

check_prev_add kernel/locking/lockdep.c:3142 [inline]
check_prevs_add kernel/locking/lockdep.c:3261 [inline]
validate_chain kernel/locking/lockdep.c:3876 [inline]
__lock_acquire+0x2e3d/0x5de0 kernel/locking/lockdep.c:5144
lock_acquire kernel/locking/lockdep.c:5761 [inline]
lock_acquire+0x1ae/0x510 kernel/locking/lockdep.c:5726
lock_sock_nested+0x3a/0xf0 net/core/sock.c:3492
lock_sock include/net/sock.h:1708 [inline]
raw_bind+0xb1/0xab0 net/can/raw.c:435
__sys_bind+0x1ec/0x220 net/socket.c:1792
__do_sys_bind net/socket.c:1803 [inline]
__se_sys_bind net/socket.c:1801 [inline]
__x64_sys_bind+0x72/0xb0 net/socket.c:1801
do_syscall_x64 arch/x86/entry/common.c:50 [inline]
do_syscall_64+0x38/0xb0 arch/x86/entry/common.c:80
entry_SYSCALL_64_after_hwframe+0x63/0xcd

other info that might help us debug this:

Possible unsafe locking scenario:

CPU0 CPU1
---- ----

lock(rtnl_mutex);
        lock(sk_lock-AF_CAN);
        lock(rtnl_mutex);

lock(sk_lock-AF_CAN);

*** DEADLOCK ***

1 lock held by syz-executor.0/14110:

stack backtrace:
CPU: 0 PID: 14110 Comm: syz-executor.0 Not tainted 6.5.0-rc1-syzkaller-00192-g78adb4bcf99e #0
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 07/03/2023
Call Trace:
<TASK>
__dump_stack lib/dump_stack.c:88 [inline]
dump_stack_lvl+0xd9/0x1b0 lib/dump_stack.c:106
check_noncircular+0x311/0x3f0 kernel/locking/lockdep.c:2195
check_prev_add kernel/locking/lockdep.c:3142 [inline]
check_prevs_add kernel/locking/lockdep.c:3261 [inline]
validate_chain kernel/locking/lockdep.c:3876 [inline]
__lock_acquire+0x2e3d/0x5de0 kernel/locking/lockdep.c:5144
lock_acquire kernel/locking/lockdep.c:5761 [inline]
lock_acquire+0x1ae/0x510 kernel/locking/lockdep.c:5726
lock_sock_nested+0x3a/0xf0 net/core/sock.c:3492
lock_sock include/net/sock.h:1708 [inline]
raw_bind+0xb1/0xab0 net/can/raw.c:435
__sys_bind+0x1ec/0x220 net/socket.c:1792
__do_sys_bind net/socket.c:1803 [inline]
__se_sys_bind net/socket.c:1801 [inline]
__x64_sys_bind+0x72/0xb0 net/socket.c:1801
do_syscall_x64 arch/x86/entry/common.c:50 [inline]
do_syscall_64+0x38/0xb0 arch/x86/entry/common.c:80
entry_SYSCALL_64_after_hwframe+0x63/0xcd
RIP: 0033:0x7fd89007cb29
Code: 28 00 00 00 75 05 48 83 c4 28 c3 e8 e1 20 00 00 90 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 b0 ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007fd890d2a0c8 EFLAGS: 00000246 ORIG_RAX: 0000000000000031
RAX: ffffffffffffffda RBX: 00007fd89019bf80 RCX: 00007fd89007cb29
RDX: 0000000000000010 RSI: 0000000020000040 RDI: 0000000000000003
RBP: 00007fd8900c847a R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000
R13: 000000000000000b R14: 00007fd89019bf80 R15: 00007ffebf8124f8
</TASK>
Fixes ee8b94c8510c ("can: raw: fix receiver memory leak")
Cc Ziyang Xuan <[email protected]>
Cc Oliver Hartkopp <[email protected]>
Cc Marc Kleine-Budde <[email protected]>

Stable-dep-of: 962947b69589 ("can: replace ARPHRD_CAN type checks with can_get_ml_priv()") [ backport to 5.10: Adapt the raw_release() context as
free_percpu(ro->uniq) has already been moved out of raw_release() in
this tree. ]

---
 net/can/raw.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
net/can/raw.c +3 -2
index 7df3086e9f910..c9513dca8fc96 100644
@@ -393,9 +393,9 @@ static int raw_release(struct socket *sock)
 	list_del(&ro->notifier);
 	spin_unlock(&raw_notifier_lock);
 
+	rtnl_lock();
 	lock_sock(sk);
 
-	rtnl_lock();
 	/* remove current filters & unregister */
 	if (ro->bound) {
 		if (ro->dev)
@@ -411,12 +411,13 @@ static int raw_release(struct socket *sock)
 	ro->bound = 0;
 	ro->dev = NULL;
 	ro->count = 0;
-	rtnl_unlock();
 
 	sock_orphan(sk);
 	sock->sk = NULL;
 
 	release_sock(sk);
+	rtnl_unlock();
+
 	sock_put(sk);
 
 	return 0;
Signature · 1 line
2.53.0
author maintainer
#764 lore raw

PATCH 759/1848 can: raw: add missing refcount for memory leak fix

In reply to Greg Kroah-Hartman

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

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

From: Oliver Hartkopp <[email protected]>

commit c275a176e4b69868576e543409927ae75e3a3288 upstream.

Commit ee8b94c8510c ("can: raw: fix receiver memory leak") introduced a new reference to the CAN netdevice that has assigned CAN filters. But this new ro->dev reference did not maintain its own refcount which lead to another KASAN use-after-free splat found by Eric Dumazet.

This patch ensures a proper refcount for the CAN nedevice.

Fixes ee8b94c8510c ("can: raw: fix receiver memory leak")
Cc Ziyang Xuan <[email protected]>

Stable-dep-of: 962947b69589 ("can: replace ARPHRD_CAN type checks with can_get_ml_priv()") [ backport to 5.10: Use dev_hold()/dev_put() as in the 5.15-stable
backport, as this tree has no netdevice reference tracker. ]

---
 net/can/raw.c | 34 +++++++++++++++++++++++++---------
 1 file changed, 25 insertions(+), 9 deletions(-)
net/can/raw.c +25 -9
index c9513dca8fc96..3e2822707ed8d 100644
@@ -283,8 +283,10 @@ static void raw_notify(struct raw_sock *ro, unsigned long msg,
 	case NETDEV_UNREGISTER:
 		lock_sock(sk);
 		/* remove current filters & unregister */
-		if (ro->bound)
+		if (ro->bound) {
 			raw_disable_allfilters(dev_net(dev), dev, sk);
+			dev_put(dev);
+		}
 
 		if (ro->count > 1)
 			kfree(ro->filter);
@@ -398,10 +400,12 @@ static int raw_release(struct socket *sock)
 
 	/* remove current filters & unregister */
 	if (ro->bound) {
-		if (ro->dev)
+		if (ro->dev) {
 			raw_disable_allfilters(dev_net(ro->dev), ro->dev, sk);
-		else
+			dev_put(ro->dev);
+		} else {
 			raw_disable_allfilters(sock_net(sk), NULL, sk);
+		}
 	}
 
 	if (ro->count > 1)
@@ -451,10 +455,10 @@ static int raw_bind(struct socket *sock, struct sockaddr *uaddr, int len)
 			goto out;
 		}
 		if (dev->type != ARPHRD_CAN) {
-			dev_put(dev);
 			err = -ENODEV;
-			goto out;
+			goto out_put_dev;
 		}
+
 		if (!(dev->flags & IFF_UP))
 			notify_enetdown = 1;
 
@@ -462,7 +466,9 @@ static int raw_bind(struct socket *sock, struct sockaddr *uaddr, int len)
 
 		/* filters set by default/setsockopt */
 		err = raw_enable_allfilters(sock_net(sk), dev, sk);
-		dev_put(dev);
+		if (err)
+			goto out_put_dev;
+
 	} else {
 		ifindex = 0;
 
@@ -473,18 +479,28 @@ static int raw_bind(struct socket *sock, struct sockaddr *uaddr, int len)
 	if (!err) {
 		if (ro->bound) {
 			/* unregister old filters */
-			if (ro->dev)
+			if (ro->dev) {
 				raw_disable_allfilters(dev_net(ro->dev),
 						       ro->dev, sk);
-			else
+				/* drop reference to old ro->dev */
+				dev_put(ro->dev);
+			} else {
 				raw_disable_allfilters(sock_net(sk), NULL, sk);
+			}
 		}
 		ro->ifindex = ifindex;
 		ro->bound = 1;
+		/* bind() ok -> hold a reference for new ro->dev */
 		ro->dev = dev;
+		if (ro->dev)
+			dev_hold(ro->dev);
 	}
 
- out:
+out_put_dev:
+	/* remove potential reference from dev_get_by_index() */
+	if (dev)
+		dev_put(dev);
+out:
 	release_sock(sk);
 	rtnl_unlock();
 
Signature · 1 line
2.53.0
author maintainer
#765 lore raw

PATCH 760/1848 can: replace ARPHRD_CAN type checks with can_get_ml_priv()

In reply to Greg Kroah-Hartman

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

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

From: Oliver Hartkopp <[email protected]>

commit 962947b69589881167054bae5accc8abfd5aa4b6 upstream.

Commit 4e096a18867a ("net: introduce CAN specific pointer in the struct net_device") introduced an explicit way to assign the midlayer private pointer (dev->ml_priv) to named users like ML_PRIV_CAN. A valid pointer returned by can_get_ml_priv() therefore identifies a real CAN device.

The referenced commit only converted the j1939 and proc code to this check, while the other parts of the CAN subsystem still rely on dev->type == ARPHRD_CAN.

The TUNSETLINK ioctl allows a down TUN/TAP device to set its hardware type to ARPHRD_CAN while dev->ml_priv remains NULL. Such a repurposed netdevice passes the ARPHRD_CAN checks.

Commit 8aa59e355949 ("can: af_can: fix NULL pointer dereference in can_rx_register()") already made can_rx_register() reject such devices. But can_rx_unregister() still only checks dev->type and dereferences the NULL ml_priv when it walks the receive lists of the device.

CAN_ISOTP reaches this path: isotp_bind() ignores the return values of can_rx_register() and binds the socket anyway. When the socket is released or the device is unregistered, isotp_release() and isotp_notify() remove the filters that have never been registered and trigger the NULL pointer dereference in can_rx_unregister(). This only requires owning a TUN/TAP device or CAP_NET_ADMIN in an unprivileged user namespace.

Convert the remaining ARPHRD_CAN checks in af_can, bcm, gw, isotp and raw to can_get_ml_priv().

Fixes 4e096a18867a ("net: introduce CAN specific pointer in the struct net_device")
Cc Oleksij Rempel <[email protected]>

[ backport to 5.10: This tree has no can_skb_ext, so only the ARPHRD_CAN
check is removed from the conditions in can_rcv() and canfd_rcv(). There is no canxl_rcv() in this tree. Add the <linux/can/can-ml.h> include to raw.c, which upstream got with commit faba5860fcf9 ("can:

  raw: instantly reject disabled CAN frames"). ]
---
 net/can/af_can.c | 10 +++++-----
 net/can/bcm.c    |  7 ++++---
 net/can/gw.c     |  7 ++++---
 net/can/isotp.c  |  5 +++--
 net/can/raw.c    |  5 +++--
 5 files changed, 19 insertions(+), 15 deletions(-)
net/can/af_can.c +5 -5
index 05066662279d9..8131992809bb3 100644
@@ -225,7 +225,7 @@ int can_send(struct sk_buff *skb, int loop)
 		goto inval_skb;
 	}
 
-	if (unlikely(skb->dev->type != ARPHRD_CAN)) {
+	if (unlikely(!can_get_ml_priv(skb->dev))) {
 		err = -EPERM;
 		goto inval_skb;
 	}
@@ -452,7 +452,7 @@ int can_rx_register(struct net *net, struct net_device *dev, canid_t can_id,
 
 	/* insert new receiver  (dev,canid,mask) -> (func,data) */
 
-	if (dev && (dev->type != ARPHRD_CAN || !can_get_ml_priv(dev)))
+	if (dev && !can_get_ml_priv(dev))
 		return -ENODEV;
 
 	if (dev && !net_eq(net, dev_net(dev)))
@@ -519,7 +519,7 @@ void can_rx_unregister(struct net *net, struct net_device *dev, canid_t can_id,
 	struct can_rcv_lists_stats *rcv_lists_stats = net->can.rcv_lists_stats;
 	struct can_dev_rcv_lists *dev_rcv_lists;
 
-	if (dev && dev->type != ARPHRD_CAN)
+	if (dev && !can_get_ml_priv(dev))
 		return;
 
 	if (dev && !net_eq(net, dev_net(dev)))
@@ -687,7 +687,7 @@ static int can_rcv(struct sk_buff *skb, struct net_device *dev,
 {
 	struct canfd_frame *cfd = (struct canfd_frame *)skb->data;
 
-	if (unlikely(dev->type != ARPHRD_CAN || !can_get_ml_priv(dev) || skb->len != CAN_MTU)) {
+	if (unlikely(!can_get_ml_priv(dev) || skb->len != CAN_MTU)) {
 		pr_warn_once("PF_CAN: dropped non conform CAN skbuff: dev type %d, len %d\n",
 			     dev->type, skb->len);
 		goto free_skb;
@@ -713,7 +713,7 @@ static int canfd_rcv(struct sk_buff *skb, struct net_device *dev,
 {
 	struct canfd_frame *cfd = (struct canfd_frame *)skb->data;
 
-	if (unlikely(dev->type != ARPHRD_CAN || !can_get_ml_priv(dev) || skb->len != CANFD_MTU)) {
+	if (unlikely(!can_get_ml_priv(dev) || skb->len != CANFD_MTU)) {
 		pr_warn_once("PF_CAN: dropped non conform CAN FD skbuff: dev type %d, len %d\n",
 			     dev->type, skb->len);
 		goto free_skb;
net/can/bcm.c +4 -3
index f655764aae83e..99abdd11f1077 100644
@@ -54,6 +54,7 @@
 #include <linux/if_arp.h>
 #include <linux/skbuff.h>
 #include <linux/can.h>
+#include <linux/can/can-ml.h>
 #include <linux/can/core.h>
 #include <linux/can/skb.h>
 #include <linux/can/bcm.h>
@@ -1663,7 +1664,7 @@ static int bcm_sendmsg(struct socket *sock, struct msghdr *msg, size_t size)
 				goto out_release;
 			}
 
-			if (dev->type != ARPHRD_CAN) {
+			if (!can_get_ml_priv(dev)) {
 				dev_put(dev);
 				ret = -ENODEV;
 				goto out_release;
@@ -1811,7 +1812,7 @@ static int bcm_notifier(struct notifier_block *nb, unsigned long msg,
 {
 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
 
-	if (dev->type != ARPHRD_CAN)
+	if (!can_get_ml_priv(dev))
 		return NOTIFY_DONE;
 	if (msg != NETDEV_UNREGISTER && msg != NETDEV_DOWN)
 		return NOTIFY_DONE;
@@ -1967,7 +1968,7 @@ static int bcm_connect(struct socket *sock, struct sockaddr *uaddr, int len,
 			ret = -ENODEV;
 			goto fail;
 		}
-		if (dev->type != ARPHRD_CAN) {
+		if (!can_get_ml_priv(dev)) {
 			dev_put(dev);
 			ret = -ENODEV;
 			goto fail;
net/can/gw.c +4 -3
index c6efa4830ce99..55605135ca584 100644
@@ -52,6 +52,7 @@
 #include <linux/if_arp.h>
 #include <linux/skbuff.h>
 #include <linux/can.h>
+#include <linux/can/can-ml.h>
 #include <linux/can/core.h>
 #include <linux/can/skb.h>
 #include <linux/can/gw.h>
@@ -541,7 +542,7 @@ static int cgw_notifier(struct notifier_block *nb,
 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
 	struct net *net = dev_net(dev);
 
-	if (dev->type != ARPHRD_CAN)
+	if (!can_get_ml_priv(dev))
 		return NOTIFY_DONE;
 
 	if (msg == NETDEV_UNREGISTER) {
@@ -1092,7 +1093,7 @@ static int cgw_create_job(struct sk_buff *skb,  struct nlmsghdr *nlh,
 	if (!gwj->src.dev)
 		goto out;
 
-	if (gwj->src.dev->type != ARPHRD_CAN)
+	if (!can_get_ml_priv(gwj->src.dev))
 		goto out;
 
 	gwj->dst.dev = __dev_get_by_index(net, gwj->ccgw.dst_idx);
@@ -1100,7 +1101,7 @@ static int cgw_create_job(struct sk_buff *skb,  struct nlmsghdr *nlh,
 	if (!gwj->dst.dev)
 		goto out;
 
-	if (gwj->dst.dev->type != ARPHRD_CAN)
+	if (!can_get_ml_priv(gwj->dst.dev))
 		goto out;
 
 	ASSERT_RTNL();
net/can/isotp.c +3 -2
index d06a99ce84135..e4542fdf8431d 100644
@@ -65,6 +65,7 @@
 #include <linux/if_arp.h>
 #include <linux/skbuff.h>
 #include <linux/can.h>
+#include <linux/can/can-ml.h>
 #include <linux/can/core.h>
 #include <linux/can/skb.h>
 #include <linux/can/isotp.h>
@@ -1550,7 +1551,7 @@ static int isotp_bind(struct socket *sock, struct sockaddr *uaddr, int len)
 		err = -ENODEV;
 		goto out;
 	}
-	if (dev->type != ARPHRD_CAN) {
+	if (!can_get_ml_priv(dev)) {
 		err = -ENODEV;
 		goto out_put_dev;
 	}
@@ -1850,7 +1851,7 @@ static int isotp_notifier(struct notifier_block *nb, unsigned long msg,
 {
 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
 
-	if (dev->type != ARPHRD_CAN)
+	if (!can_get_ml_priv(dev))
 		return NOTIFY_DONE;
 	if (msg != NETDEV_UNREGISTER && msg != NETDEV_DOWN)
 		return NOTIFY_DONE;
net/can/raw.c +3 -2
index 3e2822707ed8d..293e79aadd32d 100644
@@ -49,6 +49,7 @@
 #include <linux/if_arp.h>
 #include <linux/skbuff.h>
 #include <linux/can.h>
+#include <linux/can/can-ml.h>
 #include <linux/can/core.h>
 #include <linux/can/skb.h>
 #include <linux/can/raw.h>
@@ -315,7 +316,7 @@ static int raw_notifier(struct notifier_block *nb, unsigned long msg,
 {
 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
 
-	if (dev->type != ARPHRD_CAN)
+	if (!can_get_ml_priv(dev))
 		return NOTIFY_DONE;
 	if (msg != NETDEV_UNREGISTER && msg != NETDEV_DOWN)
 		return NOTIFY_DONE;
@@ -454,7 +455,7 @@ static int raw_bind(struct socket *sock, struct sockaddr *uaddr, int len)
 			err = -ENODEV;
 			goto out;
 		}
-		if (dev->type != ARPHRD_CAN) {
+		if (!can_get_ml_priv(dev)) {
 			err = -ENODEV;
 			goto out_put_dev;
 		}
Signature · 1 line
2.53.0
author maintainer
#766 lore raw

PATCH 761/1848 can: protect the receive lists with a per-device lock

In reply to Greg Kroah-Hartman

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

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

From: Oliver Hartkopp <[email protected]>

commit 0f3ad9ab40e3dad06d5c0693806e07935ceedbc3 upstream.

The receive lists of a CAN device are located in the device's can_ml_priv and travel with the device when it is moved to another network namespace. But they are protected by the per-netns rcvlists_lock. So can_rx_unregister() needs dev_net(dev) to pick the right lock and silently returns when the passed namespace does not match dev_net(dev) anymore.

isotp_release() and bcm_release() leave their notifier list before they take any lock that serializes against the netdev notifier, which runs under RTNL. When the bound device is moved to another namespace in this window, the notifier skips the socket and the release path has to remove the filters itself. isotp_release() passes the socket's namespace, which does not match dev_net(dev) anymore. bcm_rx_unreg() passes dev_net(dev), which can_rx_unregister() reads again for its check, so a namespace change between both reads makes the check fail as well. In both cases can_rx_unregister() silently returns. As can_rx_register() stores rcv->sk without a reference, the remaining receivers point to the freed socket (isotp) or the freed op (bcm):

  BUG: KASAN: use-after-free in isotp_rcv+0x1570/0x24d0
  Read of size 1 at addr ffff888118130552 by task isotp_ns_uaf/578
   can_rcv_filter+0x4af/0x8c0
   can_receive+0x28d/0x3c0
   can_rcv+0x2a9/0x310
   __netif_receive_skb_one_core+0x21a/0x260
   process_backlog+0x210/0x760

Besides this, the lists of a device are protected by the rcvlists_lock of the namespace that is passed in. Callers which pass dev_net(dev) read it at different times, so the same lists may be modified under the locks of different namespaces while the device is moved.

Taking RTNL in these release paths is no option: raw_bind(), raw_setsockopt() and raw_release() already hold RTNL while adding and removing up to CAN_RAW_FILTER_MAX filters per socket, which unprivileged users can trigger repeatedly and which makes RTNL a global bottleneck.

Instead fix the root cause and add a spinlock to struct can_dev_rcv_lists, which protects the receive lists of a CAN device or the 'any' CAN device lists of a namespace. It is initialized in can_set_ml_priv(), which is used by all CAN network devices. With this, can_rx_unregister() finds the subscription independently of the current namespace of the device. The protocols keep the device valid with their tracked references. The per-netns rcvlists_lock only protects the receive list statistics anymore, and CAN_RAW, CAN_BCM and CAN_ISOTP pass the namespace that has been used for can_rx_register().

So isotp_release() and bcm_release() now remove their filters correctly without RTNL, and raw_release(), raw_setsockopt(), raw_bind() and isotp_bind() do not need RTNL anymore and add and remove their filters under lock_sock(). To serialize bind() with NETDEV_UNREGISTER, bind() publishes the device inside the RCU section of its lookup, and raw_notify() and isotp_notify() recheck the bound device under lock_sock(). As RTNL does not keep NETDEV_DOWN out of bind() anymore, bind() checks IFF_UP after publishing the bound device, with a barrier pair against raw_notify() and isotp_notify(), so a down transition during bind() is still reported with ENETDOWN.

Fixes 20bab8b88baa ("can: isotp: fix use-after-free race with concurrent NETDEV_UNREGISTER")
Fixes 8e8cda6d737d ("can: initial support for network namespaces")

[ backport to 5.10: Adapt the can_pernet_init() context to kzalloc() as
this tree has no kzalloc_obj(). so->dev and ro->dev hold untracked references with dev_hold() in this tree. raw_setsockopt() has no raw_setsockopt_locked() split from commit 1e5185c09058 ("can: raw: add locking for raw flags bitfield") in this tree, so remove the RTNL locking from the CAN_RAW_FILTER and CAN_RAW_ERR_FILTER cases directly. Keep the NULL check for dev_put() in raw_bind() and use sock_net(sk) in raw_release(). dev->reg_state is a bitfield in this tree, so it is read without READ_ONCE(). Use sk->sk_error_report() as this tree has no sk_error_report() helper. ]

---
 include/linux/can/can-ml.h |   3 ++
 include/net/netns/can.h    |   2 +-
 net/can/af_can.c           |  39 +++++++++-----
 net/can/bcm.c              |  43 +++++----------
 net/can/isotp.c            |  89 +++++++++++++++++++------------
 net/can/raw.c              | 106 +++++++++++++++++++++++++------------
 6 files changed, 166 insertions(+), 116 deletions(-)
include/linux/can/can-ml.h +3 -0
index 8afa92d15a664..f10444c6115f2 100644
@@ -45,6 +45,7 @@
 #include <linux/can.h>
 #include <linux/list.h>
 #include <linux/netdevice.h>
+#include <linux/spinlock.h>
 
 #define CAN_SFF_RCV_ARRAY_SZ (1 << CAN_SFF_ID_BITS)
 #define CAN_EFF_RCV_HASH_BITS 10
@@ -53,6 +54,7 @@
 enum { RX_ERR, RX_ALL, RX_FIL, RX_INV, RX_MAX };
 
 struct can_dev_rcv_lists {
+	spinlock_t lock; /* protects the receive lists and entries */
 	struct hlist_head rx[RX_MAX];
 	struct hlist_head rx_sff[CAN_SFF_RCV_ARRAY_SZ];
 	struct hlist_head rx_eff[CAN_EFF_RCV_ARRAY_SZ];
@@ -74,6 +76,7 @@ static inline struct can_ml_priv *can_get_ml_priv(struct net_device *dev)
 static inline void can_set_ml_priv(struct net_device *dev,
 				   struct can_ml_priv *ml_priv)
 {
+	spin_lock_init(&ml_priv->dev_rcv_lists.lock);
 	netdev_set_ml_priv(dev, ml_priv, ML_PRIV_CAN);
 }
 
include/net/netns/can.h +1 -1
index 52fbd8291a962..720d0f4141a2c 100644
@@ -28,7 +28,7 @@ struct netns_can {
 
 	/* receive filters subscribed for 'all' CAN devices */
 	struct can_dev_rcv_lists *rx_alldev_list;
-	spinlock_t rcvlists_lock;
+	spinlock_t rcvlists_lock; /* protects the rcv_entries(_max) stats */
 	struct timer_list stattimer; /* timer for statistics update */
 	struct can_pkg_stats *pkg_stats;
 	struct can_rcv_lists_stats *rcv_lists_stats;
net/can/af_can.c +25 -14
index 8131992809bb3..75d51a646456a 100644
@@ -462,9 +462,10 @@ int can_rx_register(struct net *net, struct net_device *dev, canid_t can_id,
 	if (!rcv)
 		return -ENOMEM;
 
-	spin_lock_bh(&net->can.rcvlists_lock);
-
 	dev_rcv_lists = can_dev_rcv_lists_find(net, dev);
+
+	spin_lock_bh(&dev_rcv_lists->lock);
+
 	rcv_list = can_rcv_list_find(&can_id, &mask, dev_rcv_lists);
 
 	rcv->can_id = can_id;
@@ -478,6 +479,9 @@ int can_rx_register(struct net *net, struct net_device *dev, canid_t can_id,
 	hlist_add_head_rcu(&rcv->list, rcv_list);
 	dev_rcv_lists->entries++;
 
+	spin_unlock_bh(&dev_rcv_lists->lock);
+
+	spin_lock_bh(&net->can.rcvlists_lock);
 	rcv_lists_stats->rcv_entries++;
 	rcv_lists_stats->rcv_entries_max = max(rcv_lists_stats->rcv_entries_max,
 					       rcv_lists_stats->rcv_entries);
@@ -509,6 +513,14 @@ static void can_rx_delete_receiver(struct rcu_head *rp)
  *
  * Description:
  *  Removes subscription entry depending on given (subscription) values.
+ *  The receive lists of a CAN device are protected by a per-device lock,
+ *  so the subscription is found even when the device has been moved to
+ *  another network namespace after can_rx_register(). The caller has to
+ *  ensure that @dev stays valid, e.g. by holding a reference to @dev or
+ *  RTNL. @net should be the namespace that has been used for
+ *  can_rx_register(). It selects the 'any' CAN device lists for
+ *  @dev == NULL and is otherwise only used for the receive list
+ *  statistics, which become imprecise when another namespace is passed.
  */
 void can_rx_unregister(struct net *net, struct net_device *dev, canid_t can_id,
 		       canid_t mask, void (*func)(struct sk_buff *, void *),
@@ -522,12 +534,10 @@ void can_rx_unregister(struct net *net, struct net_device *dev, canid_t can_id,
 	if (dev && !can_get_ml_priv(dev))
 		return;
 
-	if (dev && !net_eq(net, dev_net(dev)))
-		return;
+	dev_rcv_lists = can_dev_rcv_lists_find(net, dev);
 
-	spin_lock_bh(&net->can.rcvlists_lock);
+	spin_lock_bh(&dev_rcv_lists->lock);
 
-	dev_rcv_lists = can_dev_rcv_lists_find(net, dev);
 	rcv_list = can_rcv_list_find(&can_id, &mask, dev_rcv_lists);
 
 	/* Search the receiver list for the item to delete.  This should
@@ -547,26 +557,26 @@ void can_rx_unregister(struct net *net, struct net_device *dev, canid_t can_id,
 	 * a warning here.
 	 */
 	if (!rcv) {
+		spin_unlock_bh(&dev_rcv_lists->lock);
 		pr_warn("can: receive list entry not found for dev %s, id %03X, mask %03X\n",
 			DNAME(dev), can_id, mask);
-		goto out;
+		return;
 	}
 
 	hlist_del_rcu(&rcv->list);
 	dev_rcv_lists->entries--;
 
+	spin_unlock_bh(&dev_rcv_lists->lock);
+
+	spin_lock_bh(&net->can.rcvlists_lock);
 	if (rcv_lists_stats->rcv_entries > 0)
 		rcv_lists_stats->rcv_entries--;
-
- out:
 	spin_unlock_bh(&net->can.rcvlists_lock);
 
 	/* schedule the receiver item for deletion */
-	if (rcv) {
-		if (rcv->sk)
-			sock_hold(rcv->sk);
-		call_rcu(&rcv->rcu, can_rx_delete_receiver);
-	}
+	if (rcv->sk)
+		sock_hold(rcv->sk);
+	call_rcu(&rcv->rcu, can_rx_delete_receiver);
 }
 EXPORT_SYMBOL(can_rx_unregister);
 
@@ -804,6 +814,7 @@ static int can_pernet_init(struct net *net)
 		kzalloc(sizeof(*net->can.rx_alldev_list), GFP_KERNEL);
 	if (!net->can.rx_alldev_list)
 		goto out;
+	spin_lock_init(&net->can.rx_alldev_list->lock);
 	net->can.pkg_stats = kzalloc(sizeof(*net->can.pkg_stats), GFP_KERNEL);
 	if (!net->can.pkg_stats)
 		goto out_free_rx_alldev_list;
net/can/bcm.c +12 -31

75 lines not on this page · raw message

net/can/isotp.c +54 -35

186 lines not on this page · raw message

net/can/raw.c +71 -35

248 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#767 lore raw

PATCH 762/1848 ceph: clamp the inline data length in ceph_fill_inline_data()

In reply to Greg Kroah-Hartman

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

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

From: Guanglei Zhu <[email protected]>

[ Upstream commit 9c1d14d3b66b3e1dd96ee664c0dd2548f2b77a52 ]

The MDS decides how much inline data to attach to a reply, and the client parses inline_len without any upper bound: ceph_decode_need() only verifies that the message actually carries that many bytes. ceph_fill_inline_data() then copies the data into a single page with no length check, so a malicious or buggy MDS returning more inline data than the page can hold writes past its end.

Clamp the length to PAGE_SIZE so both callers, handle_cap_grant() and fill_inode(), are covered.

Fixes 31c542a199d7 ("ceph: add inline data to pagecache")
[ Adapted for 5.10.y: folio_size()/memcpy_to_folio() → PAGE_SIZE and the page API; this tree has no pr_warn_ratelimited_client(), so the warning is dropped. ]
---
 fs/ceph/addr.c | 3 +++
 1 file changed, 3 insertions(+)
fs/ceph/addr.c +3 -0
index 4e247e65bd070..bb9f13aa892c5 100644
@@ -1717,6 +1717,9 @@ void ceph_fill_inline_data(struct inode *inode, struct page *locked_page,
 	dout("fill_inline_data %p %llx.%llx len %zu locked_page %p\n",
 	     inode, ceph_vinop(inode), len, locked_page);
 
+	if (len > PAGE_SIZE)
+		len = PAGE_SIZE;
+
 	if (len > 0) {
 		void *kaddr = kmap_atomic(page);
 		memcpy(kaddr, data, len);
Signature · 1 line
2.53.0
author maintainer
#768 lore raw

PATCH 763/1848 arm64: sdei: Run the event handler on the kernel vectors

In reply to Greg Kroah-Hartman

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

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

From: Kiryl Shutsemau (Meta) <[email protected]>

[ Upstream commit 9bf6ee7952c7ee151c30e0fffcfc61b58127c899 ]

With KPTI, VBAR_EL1 holds the trampoline vectors from the return to EL0 until the next exception from EL0 maps the kernel and installs the kernel vectors. The trampoline vectors only handle exceptions from EL0; their current-EL half is zero-filled.

An SDEI event is dispatched regardless of PSTATE.DAIF, so it lands there whenever the CPU is in user space. The SDEI entry trampoline maps the kernel but leaves VBAR_EL1 alone. An exception taken by the handler then executes the zeros, takes an undefined instruction exception to the same vector, and loops there forever. The event never completes and the CPU is lost; RCU stall reports are the first sign of it.

RAS notifications land in user space whenever a task consumes the error, and NMI backtraces land wherever the CPU happens to be. The GHES handler takes no exception on its own, but any exception in the handler path does it: a WARN, a kprobe hit, or a fault fixed up by a _nofault() accessor.

Install the kernel vectors in __sdei_handler() when VBAR_EL1 holds the trampoline vectors, and restore it before returning to firmware. The switch covers irqentry_nmi_enter() and irqentry_nmi_exit() too, as Usama Arif pointed out: their tracepoints and context tracking WARNs can take an exception as well.

The IRQ-like resume into user space must still go through the trampoline to map the kernel. do_sdei_event() takes the interrupted VBAR_EL1 and keeps basing the resume address on it.

Fixes 79e9aa59dc29 ("arm64: sdei: Add trampoline code for remapping the kernel")
[[email protected]: use raw_cpu_read() for this_cpu_vector]

[ kas: 5.10 has __sdei_handler() in sdei.c around a static
_sdei_handler(); pass vbar to that ]

---
 arch/arm64/kernel/sdei.c | 27 ++++++++++++++++++++++++---
 1 file changed, 24 insertions(+), 3 deletions(-)
arch/arm64/kernel/sdei.c +24 -3
index 0083f5afa51db..36e4a95ae980b 100644
@@ -17,6 +17,7 @@
 #include <asm/sections.h>
 #include <asm/stacktrace.h>
 #include <asm/sysreg.h>
+#include <asm/vectors.h>
 #include <asm/vmap_stack.h>
 
 unsigned long sdei_exit_mode;
@@ -162,16 +163,18 @@ unsigned long sdei_arch_get_entry_point(int conduit)
  *  SDEI_EV_HANDLED -  success, return to the interrupted context.
  *  SDEI_EV_FAILED  -  failure, return this error code to firmare.
  *  virtual-address -  success, return to this address.
+ *
+ * vbar is the interrupted context's VBAR_EL1, for the IRQ-like resume.
  */
 static __kprobes unsigned long _sdei_handler(struct pt_regs *regs,
-					     struct sdei_registered_event *arg)
+					     struct sdei_registered_event *arg,
+					     unsigned long vbar)
 {
 	u32 mode;
 	int i, err = 0;
 	int clobbered_registers = 4;
 	u64 elr = read_sysreg(elr_el1);
 	u32 kernel_mode = read_sysreg(CurrentEL) | 1;	/* +SPSel */
-	unsigned long vbar = read_sysreg(vbar_el1);
 
 	if (arm64_kernel_unmapped_at_el0())
 		clobbered_registers++;
@@ -230,13 +233,31 @@ static __kprobes unsigned long _sdei_handler(struct pt_regs *regs,
 asmlinkage noinstr unsigned long
 __sdei_handler(struct pt_regs *regs, struct sdei_registered_event *arg)
 {
+	unsigned long vbar;
 	unsigned long ret;
 
+	/*
+	 * With KPTI, VBAR_EL1 holds the trampoline vectors from the return to
+	 * EL0 until the next exception from EL0 maps the kernel. They only
+	 * handle exceptions from EL0: an exception taken here would run their
+	 * empty current-EL half and never come back. Switch to the kernel
+	 * vectors. The IRQ-like resume keeps using the interrupted VBAR, so it
+	 * still goes through the trampoline.
+	 */
+	vbar = read_sysreg(vbar_el1);
+	if (arm64_kernel_unmapped_at_el0() &&
+	    vbar == (unsigned long)raw_cpu_read(this_cpu_vector)) {
+		write_sysreg((unsigned long)vectors, vbar_el1);
+		isb();
+	}
+
 	arm64_enter_nmi(regs);
 
-	ret = _sdei_handler(regs, arg);
+	ret = _sdei_handler(regs, arg, vbar);
 
 	arm64_exit_nmi(regs);
 
+	write_sysreg(vbar, vbar_el1);
+
 	return ret;
 }
Signature · 1 line
2.53.0
author maintainer
#769 lore raw

PATCH 764/1848 arm64: sdei: Preserve the interrupted contexts exception registers

In reply to Greg Kroah-Hartman

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

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

From: Kiryl Shutsemau (Meta) <[email protected]>

[ Upstream commit 58c1eb84e97701c583605ba2fd553b69afba2245 ]

An SDEI event is dispatched by firmware regardless of PSTATE.DAIF, so it can interrupt the kernel where the exception registers are live:

- exception entry, before kernel_entry has saved ELR_EL1/SPSR_EL1 and before the C handler has read ESR_EL1/FAR_EL1;
- exception return, after kernel_exit has loaded ELR_EL1/SPSR_EL1 and before the ERET.

An IRQ or pseudo-NMI cannot arrive there with PSTATE.I set. Firmware saves only x0-x17, PC and PSTATE around an SDEI event, so a synchronous exception taken by the handler overwrites the interrupted context's ELR, SPSR, ESR and FAR. do_sdei_event() only notices that ELR changed, and warns.

The interrupted context then carries on with the handler's state. A task interrupted on its way into the kernel can be sent SIGILL for the handler's kernel data abort. A task interrupted on its way back to user space ERETs to EL1, at the handler's fixup address, with user registers loaded.

With SDEI delivering NMI backtraces, this happens in normal operation. The handler runs show_regs(), which reads through possibly-NULL pointers with the _nofault() accessors. print_worker_info() faults this way for a kworker that is not running a work item, and a single sysrq-l warned once per such kworker.

Save ELR, SPSR, ESR and FAR in __sdei_handler() before irqentry_nmi_enter(), which can take an exception too, and restore them after irqentry_nmi_exit().

Once they are restored, a nested exception is harmless if its handler is safe in NMI context. That holds for EL1 data aborts on translation, permission and access-flag faults, which never take the mmap lock in NMI context, and for BRK. Warn once, with the syndrome, about any other exception class.

Fixes f5df26961853 ("arm64: kernel: Add arch-specific SDEI entry code and CPU masking")

[ kas: 5.10 has __sdei_handler() in sdei.c around a static
_sdei_handler(); open-code the fault type check ]

---
 arch/arm64/kernel/sdei.c | 76 ++++++++++++++++++++++++++++++++++------
 1 file changed, 66 insertions(+), 10 deletions(-)
arch/arm64/kernel/sdei.c +66 -10
index 36e4a95ae980b..118dbb7e85e83 100644
@@ -158,6 +158,33 @@ unsigned long sdei_arch_get_entry_point(int conduit)
 
 }
 
+/*
+ * Exceptions an SDEI handler may take without harm once __sdei_handler() has
+ * restored the interrupted context's exception registers. Their handlers are
+ * safe in NMI context:
+ *  - EL1 data aborts on translation, permission and access-flag faults:
+ *    faulthandler_disabled() is true in NMI context, so do_page_fault() never
+ *    takes the mmap lock. This covers the _nofault() accessors used by the
+ *    generic dump_stack()/show_regs() code (e.g. print_worker_info()).
+ *  - BRK: kprobes, WARN/BUG, kCFI and UBSAN traps, all NMI-capable.
+ * Anything else taken at EL1 is fatal on its own, or unexpected here.
+ */
+static bool sdei_nested_exception_ok(unsigned long esr)
+{
+	unsigned long fsc_type = esr & ESR_ELx_FSC_TYPE;
+
+	switch (ESR_ELx_EC(esr)) {
+	case ESR_ELx_EC_DABT_CUR:
+		return fsc_type == ESR_ELx_FSC_FAULT ||
+		       fsc_type == ESR_ELx_FSC_PERM ||
+		       fsc_type == ESR_ELx_FSC_ACCESS;
+	case ESR_ELx_EC_BRK64:
+		return true;
+	default:
+		return false;
+	}
+}
+
 /*
  * __sdei_handler() returns one of:
  *  SDEI_EV_HANDLED -  success, return to the interrupted context.
@@ -174,6 +201,7 @@ static __kprobes unsigned long _sdei_handler(struct pt_regs *regs,
 	int i, err = 0;
 	int clobbered_registers = 4;
 	u64 elr = read_sysreg(elr_el1);
+	u64 nested_elr, nested_esr, nested_far;
 	u32 kernel_mode = read_sysreg(CurrentEL) | 1;	/* +SPSel */
 
 	if (arm64_kernel_unmapped_at_el0())
@@ -192,18 +220,27 @@ static __kprobes unsigned long _sdei_handler(struct pt_regs *regs,
 	__uaccess_enable_hw_pan();
 
 	err = sdei_event_handler(regs, arg);
-	if (err)
-		return SDEI_EV_FAILED;
 
-	if (elr != read_sysreg(elr_el1)) {
-		/*
-		 * We took a synchronous exception from the SDEI handler.
-		 * This could deadlock, and if you interrupt KVM it will
-		 * hyp-panic instead.
-		 */
-		pr_warn("unsafe: exception during handler\n");
+	/*
+	 * A synchronous exception taken by the handler has overwritten the
+	 * exception registers; __sdei_handler() puts them back. Only the last
+	 * one's syndrome survives; report it if it is not one known to be
+	 * harmless.
+	 *
+	 * If the event interrupted a KVM world switch, VBAR points at the KVM
+	 * hyp vectors and any such exception is a hyp panic instead.
+	 */
+	nested_elr = read_sysreg(elr_el1);
+	nested_esr = read_sysreg(esr_el1);
+	nested_far = read_sysreg(far_el1);
+	if (nested_elr != elr && !sdei_nested_exception_ok(nested_esr)) {
+		pr_warn_once("unexpected exception during handler: ESR %#llx FAR %#llx near %pS\n",
+			     nested_esr, nested_far, (void *)nested_elr);
 	}
 
+	if (err)
+		return SDEI_EV_FAILED;
+
 	mode = regs->pstate & (PSR_MODE32_BIT | PSR_MODE_MASK);
 
 	/*
@@ -233,9 +270,20 @@ static __kprobes unsigned long _sdei_handler(struct pt_regs *regs,
 asmlinkage noinstr unsigned long
 __sdei_handler(struct pt_regs *regs, struct sdei_registered_event *arg)
 {
-	unsigned long vbar;
+	unsigned long elr, spsr, esr, far, vbar;
 	unsigned long ret;
 
+	/*
+	 * Nothing saved the interrupted context's exception registers on the
+	 * way in, and it may be in the middle of exception entry or return
+	 * (SDEI ignores DAIF). Save them before anything can take an exception
+	 * and overwrite them.
+	 */
+	elr = read_sysreg(elr_el1);
+	spsr = read_sysreg(spsr_el1);
+	esr = read_sysreg(esr_el1);
+	far = read_sysreg(far_el1);
+
 	/*
 	 * With KPTI, VBAR_EL1 holds the trampoline vectors from the return to
 	 * EL0 until the next exception from EL0 maps the kernel. They only
@@ -257,6 +305,14 @@ __sdei_handler(struct pt_regs *regs, struct sdei_registered_event *arg)
 
 	arm64_exit_nmi(regs);
 
+	/*
+	 * Put them back unconditionally. An unchanged ELR does not rule out a
+	 * nested exception: one may have returned to the same address.
+	 */
+	write_sysreg(elr, elr_el1);
+	write_sysreg(spsr, spsr_el1);
+	write_sysreg(esr, esr_el1);
+	write_sysreg(far, far_el1);
 	write_sysreg(vbar, vbar_el1);
 
 	return ret;
Signature · 1 line
2.53.0
author maintainer
#770 lore raw

PATCH 765/1848 microblaze: Use simple memset implementation from lib/string.c

In reply to Greg Kroah-Hartman

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

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

From: Michal Simek <[email protected]>

[ Upstream commit 8f0f265e6cf5b6d99a5a5d01b36985bc1131183e ]

On microblaze systems which are not using OPT_LIB_FUNCTION only simple memset is used. This function is already implemented in lib/string.c that's why it should be used instead.
This change is done in respect of issue fixed by commit 33d0f96ffd73 ("lib/string.c: Use freestanding environment") where gcc-10.x moved -ftree-loop-distribute-patterns optimization is to O2 optimization level. This optimization causes GCC to convert the while loop in memset.c into a call to memset. So This optimization is transforming a loop in a memset/memcpy into a call to the function itself. This makes the memset implementation as recursive.

Based on fix above -ffreestanding was used and it needs to be used on Microblaze too but the patch is not adding this flag it removes simple implementation to cause that generic implementation is used where this flag is already setup.

---
 arch/microblaze/include/asm/string.h |  2 ++
 arch/microblaze/lib/memset.c         | 20 ++------------------
 2 files changed, 4 insertions(+), 18 deletions(-)
arch/microblaze/include/asm/string.h +2 -0
index 34071a848b6a2..dbdb9eb4a733c 100644
@@ -8,7 +8,9 @@
 
 #ifdef __KERNEL__
 
+#ifdef CONFIG_OPT_LIB_FUNCTION
 #define __HAVE_ARCH_MEMSET
+#endif
 #define __HAVE_ARCH_MEMCPY
 #define __HAVE_ARCH_MEMMOVE
 
arch/microblaze/lib/memset.c +2 -18
index 04ea72c8a81dd..8810a89de851f 100644
@@ -30,22 +30,7 @@
 #include <linux/compiler.h>
 #include <linux/string.h>
 
-#ifdef __HAVE_ARCH_MEMSET
-#ifndef CONFIG_OPT_LIB_FUNCTION
-void *memset(void *v_src, int c, __kernel_size_t n)
-{
-	char *src = v_src;
-
-	/* Truncate c to 8 bits */
-	c = (c & 0xFF);
-
-	/* Simple, byte oriented memset or the rest of count. */
-	while (n--)
-		*src++ = c;
-
-	return v_src;
-}
-#else /* CONFIG_OPT_LIB_FUNCTION */
+#ifdef CONFIG_OPT_LIB_FUNCTION
 void *memset(void *v_src, int c, __kernel_size_t n)
 {
 	char *src = v_src;
@@ -92,6 +77,5 @@ void *memset(void *v_src, int c, __kernel_size_t n)
 
 	return v_src;
 }
-#endif /* CONFIG_OPT_LIB_FUNCTION */
 EXPORT_SYMBOL(memset);
-#endif /* __HAVE_ARCH_MEMSET */
+#endif /* CONFIG_OPT_LIB_FUNCTION */
Signature · 1 line
2.53.0
author maintainer
#771 lore raw

PATCH 766/1848 microblaze: Do loop unrolling for optimized memset implementation

In reply to Greg Kroah-Hartman

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

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

From: Michal Simek <[email protected]>

[ Upstream commit 95fee37be45f443a8a322ee7f6f78167b73f2abc ]

Align implementation with memcpy and memmove where also remaining bytes are copied via final switch case instead of using simple implementations which loop. But this alignment has much stronger reason and definitely aligning implementation is not the key point here. It is just good to have in mind that the same technique is used already there.

In GCC 10, now -ftree-loop-distribute-patterns optimization is on at O2. This optimization causes GCC to convert the while loop in memset.c into a call to memset.
So this optimization is transforming a loop in a memset/memcpy into a call to the function itself. This makes the memset implementation as recursive. "-freestanding" option will disable the built-in library function but it has been added in generic library implementation.

In default microblaze kernel defconfig we have CONFIG_OPT_LIB_FUNCTION enabled so it will always pick optimized version of memset which is target specific so we are replacing the while() loop with switch case to avoid recursive memset call.

Issue with freestanding was already discussed in connection to commit 33d0f96ffd73 ("lib/string.c: Use freestanding environment") and also this is topic in glibc and gcc.
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56888
http://patchwork.ozlabs.org/project/glibc/patch/[email protected]/

---
 arch/microblaze/lib/memset.c | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)
arch/microblaze/lib/memset.c +12 -1
index 8810a89de851f..9a62a1f0fc1d9 100644
@@ -72,8 +72,19 @@ void *memset(void *v_src, int c, __kernel_size_t n)
 	}
 
 	/* Simple, byte oriented memset or the rest of count. */
-	while (n--)
+	switch (n) {
+	case 3:
 		*src++ = c;
+		fallthrough;
+	case 2:
+		*src++ = c;
+		fallthrough;
+	case 1:
+		*src++ = c;
+		break;
+	default:
+		break;
+	}
 
 	return v_src;
 }
Signature · 1 line
2.53.0
author maintainer
#772 lore raw

PATCH 767/1848 microblaze: restore the ABI argument home area below pt_regs (PTO)

In reply to Greg Kroah-Hartman

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

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

From: Ramin Moussavi <[email protected]>

commit c35d40a3efd2e575ef51a761e983f2bf7113be6c upstream.

The MicroBlaze ABI has the caller reserve stack space for the arguments it passes in registers: REG_PARM_STACK_SPACE is 24 and OUTGOING_REG_PARM_STACK_SPACE is 1 in the gcc backend, so a callee may write to [caller_sp + 4, caller_sp + 28). The kernel calls C functions from entry.S with r1 pointing at pt_regs, handing the callee license to spill its incoming arguments over the saved registers -- the syscall dispatch is the worst case, where the first argument slot is PT_R1, the saved user stack pointer.

This was latent until GCC 15: since 3b9b8d6cfdf5 ("ira: Scale save/restore costs of callee save registers with block frequency") the allocator prefers spilling incoming arguments over copying them into callee-saved registers, and a kernel built with gcc >= 15 (without the TARGET_CALLEE_SAVE_COST workaround some distributions carry) corrupts PT_R1 on the first syscall: init takes SIGSEGV and the kernel panics.

The kernel had exactly this reservation until 2011:
commit 6e83557c38b4 ("microblaze: Remove r0_ram pointer and PTO alignment") removed STATE_SAVE_ARG_SPACE and with it the PTO offset, as part of cleaning up what was thought to be copied-from-v850 leftovers. Restore
it: the frame is STATE_SAVE_SIZE = PT_SIZE + PTO, r1 stays at the frame base through every asm-to-C call, and the saved registers are reached at r1 + PTO + PT_*. PTO is 28 rather than the historic 24, which was one word short: FIRST_PARM_OFFSET is 4 and REG_PARM_STACK_SPACE is 24, so the area spans [sp+4, sp+28) and needs 28 bytes. With 24 the last argument slot overlapped pt_regs' r0 -- harmless only because r0 is the constant-zero register. STACK_BOUNDARY is 32 bits, so 28 needs no further rounding.

Two places deliberately keep their mainline addressing. hw_exception_handler.S needs no offset change: its real-mode handler saves into the standalone pt_pool_space buffer rather than a stack frame, and _unaligned_data_exception works through a pointer to pt_regs in r7, where plain PT_* offsets are already right. And the user-SP reload after popping the frame keeps PT_R1 - PT_SIZE because PTO cancels there: (PTO + PT_R1) - (PT_SIZE + PTO) = PT_R1 - PT_SIZE. Both are exactly as the pre-2011 code had them.

The instruction count is unchanged -- the same instructions with different immediates, no per-call reservation and no trampolines. The cost is 28 bytes more kernel stack per saved frame.

Fixes 6e83557c38b4 ("microblaze: Remove r0_ram pointer and PTO alignment")
Assisted-by Claude:claude-opus-5
---
 arch/microblaze/include/asm/entry.h           |  13 +
 arch/microblaze/include/asm/processor.h       |   2 +-
 arch/microblaze/kernel/entry.S                | 277 +++++++++---------
 arch/microblaze/kernel/hw_exception_handler.S |   5 +
 arch/microblaze/kernel/process.c              |   5 +-
 5 files changed, 163 insertions(+), 139 deletions(-)
arch/microblaze/include/asm/entry.h +13 -0
index 6c42bed411662..74c5a99a37f8c 100644
@@ -21,6 +21,19 @@
 
 #define PER_CPU(var) var
 
+/*
+ * The MicroBlaze ABI has the caller reserve an argument home area:
+ * REG_PARM_STACK_SPACE is 24 and OUTGOING_REG_PARM_STACK_SPACE is 1, so a
+ * callee may write to [caller_sp + 4, caller_sp + 28).  The kernel calls C
+ * with r1 at the frame base, so reserve that area below pt_regs and reach
+ * the saved registers through PTO.  This restores what 6e83557c38b4
+ * ("microblaze: Remove r0_ram pointer and PTO alignment") removed; the old
+ * value of 24 was one word short and left the last argument slot
+ * overlapping pt_regs' r0.
+ */
+#define PTO			28
+#define STATE_SAVE_SIZE		(PT_SIZE + PTO)
+
 # ifndef __ASSEMBLY__
 DECLARE_PER_CPU(unsigned int, KSP); /* Saved kernel stack pointer */
 DECLARE_PER_CPU(unsigned int, KM); /* Kernel/user mode */
arch/microblaze/include/asm/processor.h +1 -1
index 1ff5a82b76b63..08c2b5ccafbb5 100644
@@ -114,7 +114,7 @@ unsigned long get_wchan(struct task_struct *p);
 #  define task_regs(task) ((struct pt_regs *)task_tos(task) - 1)
 
 #  define task_pt_regs_plus_args(tsk) \
-	((void *)task_pt_regs(tsk))
+	(((void *)task_pt_regs(tsk)) - PTO)
 
 #  define task_sp(task)	(task_regs(task)->r1)
 #  define task_pc(task)	(task_regs(task)->pc)
arch/microblaze/kernel/entry.S +141 -136

535 lines not on this page · raw message

arch/microblaze/kernel/hw_exception_handler.S +5 -0
index 54411de22fa6c..9d6cc7f520cc0 100644
@@ -326,6 +326,11 @@ _hw_exception_handler:
 #ifndef CONFIG_MMU
 	addik	r1, r1, -(EX_HANDLER_STACK_SIZ); /* Create stack frame */
 #else
+	/*
+	 * This handler saves into the static pt_pool_space buffer, not into a
+	 * stack frame, so the plain PT_* offsets are right here -- do not add
+	 * the PTO of entry.S's frames.
+	 */
 	swi	r1, r0, TOPHYS(pt_pool_space + PT_R1); /* GET_SP */
 	/* Save date to kernel memory. Here is the problem
 	 * when you came from user space */
arch/microblaze/kernel/process.c +3 -2
index ee000ae17e395..1d859d123f912 100644
@@ -20,6 +20,7 @@
 #include <linux/ptrace.h>
 #include <linux/uaccess.h> /* for USER_DS macros */
 #include <asm/cacheflush.h>
+#include <asm/entry.h>
 
 void show_regs(struct pt_regs *regs)
 {
@@ -64,7 +65,7 @@ int copy_thread(unsigned long clone_flags, unsigned long usp, unsigned long arg,
 		 * the registers. That's OK for a brand new thread.*/
 		memset(childregs, 0, sizeof(struct pt_regs));
 		memset(&ti->cpu_context, 0, sizeof(struct cpu_context));
-		ti->cpu_context.r1  = (unsigned long)childregs;
+		ti->cpu_context.r1  = (unsigned long)childregs - PTO;
 		ti->cpu_context.r20 = (unsigned long)usp; /* fn */
 		ti->cpu_context.r19 = (unsigned long)arg;
 		childregs->pt_mode = 1;
@@ -80,7 +81,7 @@ int copy_thread(unsigned long clone_flags, unsigned long usp, unsigned long arg,
 		childregs->r1 = usp;
 
 	memset(&ti->cpu_context, 0, sizeof(struct cpu_context));
-	ti->cpu_context.r1 = (unsigned long)childregs;
+	ti->cpu_context.r1 = (unsigned long)childregs - PTO;
 #ifndef CONFIG_MMU
 	ti->cpu_context.msr = (unsigned long)childregs->msr;
 #else
Signature · 1 line
2.53.0
author maintainer
#773 lore raw

PATCH 768/1848 HID: wacom: Advertise SW_MUTE_DEVICE capability prior to registration

In reply to Greg Kroah-Hartman

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

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

From: Lee Jones <[email protected]>

[ Upstream commit ba16e5ffbaa10fde960918d69af5e49f2b3fdd5e ]

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

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

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

Fixes d2ec58aee8b1 ("HID: wacom: generic: support generic touch switch")

[Lee: Retain devm_add_action() error handling and adapt context around
is_soft_touch_switch and wacom_initialize_battery()]

---
 drivers/hid/wacom_sys.c | 86 ++++++++++++++++++++++++++++++++++-------
 drivers/hid/wacom_wac.c |  5 +++
 2 files changed, 77 insertions(+), 14 deletions(-)
drivers/hid/wacom_sys.c +72 -14
index f418efa868ee9..e5d12683f5784 100644
@@ -924,6 +924,9 @@ static int wacom_add_shared_data(struct hid_device *hdev)
 
 	wacom_wac->shared = &data->shared;
 
+	if (wacom_wac->has_mute_touch_switch)
+		WRITE_ONCE(wacom_wac->shared->has_mute_touch_switch, true);
+
 	retval = devm_add_action(&hdev->dev, wacom_remove_shared_data, wacom);
 	if (retval) {
 		mutex_unlock(&wacom_udev_list_lock);
@@ -931,11 +934,6 @@ static int wacom_add_shared_data(struct hid_device *hdev)
 		return retval;
 	}
 
-	if (wacom_wac->features.device_type & WACOM_DEVICETYPE_TOUCH)
-		wacom_wac->shared->touch = hdev;
-	else if (wacom_wac->features.device_type & WACOM_DEVICETYPE_PEN)
-		wacom_wac->shared->pen = hdev;
-
 out:
 	mutex_unlock(&wacom_udev_list_lock);
 	return retval;
@@ -2336,22 +2334,76 @@ static void wacom_release_resources(struct wacom *wacom)
 
 static void wacom_set_shared_values(struct wacom_wac *wacom_wac)
 {
+	struct wacom *wacom = container_of(wacom_wac, struct wacom, wacom_wac);
+
+	guard(mutex)(&wacom_udev_list_lock);
+
+	if (wacom_wac->has_mute_touch_switch) {
+		WRITE_ONCE(wacom_wac->shared->has_mute_touch_switch, true);
+		wacom_wac->shared->is_touch_on = true;
+	}
+
 	if (wacom_wac->features.device_type & WACOM_DEVICETYPE_TOUCH) {
 		wacom_wac->shared->type = wacom_wac->features.type;
 		wacom_wac->shared->touch_input = wacom_wac->touch_input;
+		wacom_wac->shared->touch = wacom->hdev;
+	} else if (wacom_wac->features.device_type & WACOM_DEVICETYPE_PEN) {
+		/* Pairs with smp_load_acquire() in wacom_sibling_pending() */
+		smp_store_release(&wacom_wac->shared->pen, wacom->hdev);
 	}
+}
 
-	if (wacom_wac->has_mute_touch_switch) {
-		wacom_wac->shared->has_mute_touch_switch = true;
-		wacom_wac->shared->is_touch_on = true;
-	}
+static bool wacom_sibling_pending(struct wacom *wacom)
+{
+	const struct wacom_features *features = &wacom->wacom_wac.features;
+	struct hid_device *hdev = wacom->hdev;
+	struct usb_interface *sibling_intf;
+	int ifnum;
 
-	if (wacom_wac->shared->has_mute_touch_switch &&
-	    wacom_wac->shared->touch_input) {
-		set_bit(EV_SW, wacom_wac->shared->touch_input->evbit);
-		input_set_capability(wacom_wac->shared->touch_input, EV_SW,
-				     SW_MUTE_DEVICE);
+	if (features->type != HID_GENERIC ||
+	    !(features->device_type & WACOM_DEVICETYPE_TOUCH))
+		return false;
+
+	if (wacom->wacom_wac.shared) {
+		/* Pairs with smp_store_release() in wacom_set_shared_values() */
+		if (smp_load_acquire(&wacom->wacom_wac.shared->pen))
+			return false;
 	}
+
+	if (!hid_is_usb(hdev) || !wacom->usbdev || !wacom->intf ||
+	    !wacom->intf->cur_altsetting)
+		return false;
+
+	ifnum = wacom->intf->cur_altsetting->desc.bInterfaceNumber;
+
+	/*
+	 * On composite Wacom devices, the Pen interface is always interface 0.
+	 * If the Touch interface is interface 0, there is no sibling Pen
+	 * interface on this device (standalone touch device).
+	 */
+	if (ifnum == 0)
+		return false;
+
+	/* Look for the sibling Pen interface at interface 0 */
+	sibling_intf = usb_ifnum_to_if(wacom->usbdev, 0);
+	if (!sibling_intf || !sibling_intf->cur_altsetting)
+		return false;
+
+	if (sibling_intf->cur_altsetting->desc.bInterfaceClass !=
+	    USB_INTERFACE_CLASS_HID)
+		return false;
+
+	if (sibling_intf->cur_altsetting->desc.bInterfaceSubClass == 1 &&
+	    (sibling_intf->cur_altsetting->desc.bInterfaceProtocol == 1 ||
+	     sibling_intf->cur_altsetting->desc.bInterfaceProtocol == 2))
+		return false;
+
+	/*
+	 * Interface 0 is a candidate HID interface on this composite device
+	 * whose probe has not completed yet (shared->pen is NULL). Defer until
+	 * interface 0 finishes probing and registers shared values.
+	 */
+	return true;
 }
 
 static int wacom_parse_and_register(struct wacom *wacom, bool wireless)
@@ -2427,6 +2479,11 @@ static int wacom_parse_and_register(struct wacom *wacom, bool wireless)
 	if (error)
 		goto fail;
 
+	if (wacom_sibling_pending(wacom)) {
+		error = -EPROBE_DEFER;
+		goto fail;
+	}
+
 	if (!(features->device_type & WACOM_DEVICETYPE_WL_MONITOR) &&
 	     (features->quirks & WACOM_QUIRK_BATTERY)) {
 		error = wacom_initialize_battery(wacom);
@@ -2491,6 +2548,7 @@ static int wacom_parse_and_register(struct wacom *wacom, bool wireless)
 
 fail_hw_stop:
 	hid_hw_stop(hdev);
+	cancel_delayed_work_sync(&wacom->init_work);
 fail:
 	wacom_release_resources(wacom);
 	return error;
drivers/hid/wacom_wac.c +5 -0
index f74da953d78f2..8804bc2cba32d 100644
@@ -3882,6 +3882,11 @@ int wacom_setup_touch_input_capabilities(struct input_dev *input_dev,
 
 	if (features->type == HID_GENERIC) {
 		hid_dbg(hdev, "generic touch setup\n");
+		if (wacom_wac->has_mute_touch_switch ||
+		    (wacom_wac->shared && READ_ONCE(wacom_wac->shared->has_mute_touch_switch))) {
+			input_set_capability(input_dev, EV_SW, SW_MUTE_DEVICE);
+			wacom_wac->has_mute_touch_switch = true;
+		}
 		/* setup has already been done */
 		return 0;
 	}
Signature · 1 line
2.53.0
author maintainer
#774 lore raw

PATCH 769/1848 HID: wacom: Fix Use-After-Free in wacom_intuos_pad

In reply to Greg Kroah-Hartman

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

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

From: Lee Jones <[email protected]>

[ Upstream commit ef32877368a7013c060ef6bd03a30b6da2fe0c41 ]

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

Resolve this by introducing RCU protection for the touch_input pointer:

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

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

Fixes 961794a00eab ("Input: wacom - add reporting of SW_MUTE_DEVICE events")

[Lee: Use explicit mutex_lock()/mutex_unlock() in wacom_remove_shared_data()
for -std=gnu89 compatibility and adapt to res_wacom]

---
 drivers/hid/wacom_sys.c | 18 +++++++++++++-----
 drivers/hid/wacom_wac.c | 36 ++++++++++++++++++------------------
 drivers/hid/wacom_wac.h |  2 +-
 3 files changed, 32 insertions(+), 24 deletions(-)
drivers/hid/wacom_sys.c +13 -5
index e5d12683f5784..94e12c56e040a 100644
@@ -885,10 +885,16 @@ static void wacom_remove_shared_data(void *res)
 		data = container_of(wacom_wac->shared, struct wacom_hdev_data,
 				    shared);
 
-		if (wacom_wac->shared->touch == res_wacom->hdev)
+		mutex_lock(&wacom_udev_list_lock);
+		if (wacom_wac->shared->touch == res_wacom->hdev) {
 			wacom_wac->shared->touch = NULL;
-		else if (wacom_wac->shared->pen == res_wacom->hdev)
+			rcu_assign_pointer(wacom_wac->shared->touch_input, NULL);
+		} else if (wacom_wac->shared->pen == res_wacom->hdev) {
 			wacom_wac->shared->pen = NULL;
+		}
+		mutex_unlock(&wacom_udev_list_lock);
+
+		synchronize_rcu();
 
 		if (kref_put_mutex(&data->kref, wacom_release_shared_data, &wacom_udev_list_lock))
 			mutex_unlock(&wacom_udev_list_lock);
@@ -2344,9 +2350,11 @@ static void wacom_set_shared_values(struct wacom_wac *wacom_wac)
 	}
 
 	if (wacom_wac->features.device_type & WACOM_DEVICETYPE_TOUCH) {
-		wacom_wac->shared->type = wacom_wac->features.type;
-		wacom_wac->shared->touch_input = wacom_wac->touch_input;
-		wacom_wac->shared->touch = wacom->hdev;
+		if (wacom_wac->shared->touch == wacom->hdev || !wacom_wac->shared->touch) {
+			wacom_wac->shared->type = wacom_wac->features.type;
+			wacom_wac->shared->touch = wacom->hdev;
+			rcu_assign_pointer(wacom_wac->shared->touch_input, wacom_wac->touch_input);
+		}
 	} else if (wacom_wac->features.device_type & WACOM_DEVICETYPE_PEN) {
 		/* Pairs with smp_load_acquire() in wacom_sibling_pending() */
 		smp_store_release(&wacom_wac->shared->pen, wacom->hdev);
drivers/hid/wacom_wac.c +18 -18
index 8804bc2cba32d..059572ea05097 100644
@@ -510,6 +510,18 @@ static void wacom_intuos_schedule_prox_event(struct wacom_wac *wacom_wac)
 	}
 }
 
+static void wacom_report_touch_mute(struct wacom_wac *wacom_wac, bool mute)
+{
+	struct input_dev *touch_input;
+
+	guard(rcu)();
+	touch_input = rcu_dereference(wacom_wac->shared->touch_input);
+	if (touch_input) {
+		input_report_switch(touch_input, SW_MUTE_DEVICE, mute);
+		input_sync(touch_input);
+	}
+}
+
 static int wacom_intuos_pad(struct wacom_wac *wacom)
 {
 	struct wacom_features *features = &wacom->features;
@@ -650,12 +662,8 @@ static int wacom_intuos_pad(struct wacom_wac *wacom)
 	input_report_key(input, KEY_CONTROLPANEL, menu);
 	input_report_key(input, KEY_INFO, info);
 
-	if (wacom->shared && wacom->shared->touch_input) {
-		input_report_switch(wacom->shared->touch_input,
-				    SW_MUTE_DEVICE,
-				    !wacom->shared->is_touch_on);
-		input_sync(wacom->shared->touch_input);
-	}
+	if (wacom->shared)
+		wacom_report_touch_mute(wacom, !wacom->shared->is_touch_on);
 
 	input_report_abs(input, ABS_RX, strip1);
 	input_report_abs(input, ABS_RY, strip2);
@@ -2191,7 +2199,7 @@ static void wacom_wac_pad_event(struct hid_device *hdev, struct hid_field *field
 	 */
 	if ((equivalent_usage == WACOM_HID_WD_MUTE_DEVICE) ||
 	   (equivalent_usage == WACOM_HID_WD_TOUCHONOFF)) {
-		if (wacom_wac->shared->touch_input) {
+		if (wacom_wac->shared) {
 			bool *is_touch_on = &wacom_wac->shared->is_touch_on;
 
 			if (equivalent_usage == WACOM_HID_WD_MUTE_DEVICE && value)
@@ -2199,9 +2207,7 @@ static void wacom_wac_pad_event(struct hid_device *hdev, struct hid_field *field
 			else if (equivalent_usage == WACOM_HID_WD_TOUCHONOFF)
 				*is_touch_on = value;
 
-			input_report_switch(wacom_wac->shared->touch_input,
-					    SW_MUTE_DEVICE, !(*is_touch_on));
-			input_sync(wacom_wac->shared->touch_input);
+			wacom_report_touch_mute(wacom_wac, !(*is_touch_on));
 		}
 		return;
 	}
@@ -3292,11 +3298,8 @@ static int wacom_wireless_irq(struct wacom_wac *wacom, size_t len)
 
 		if ((wacom->shared->type == INTUOSHT ||
 		    wacom->shared->type == INTUOSHT2) &&
-		    wacom->shared->touch_input &&
 		    wacom->shared->touch_max) {
-			input_report_switch(wacom->shared->touch_input,
-					SW_MUTE_DEVICE, data[5] & 0x40);
-			input_sync(wacom->shared->touch_input);
+			wacom_report_touch_mute(wacom, data[5] & 0x40);
 		}
 
 		pid = get_unaligned_be16(&data[6]);
@@ -3331,11 +3334,8 @@ static int wacom_status_irq(struct wacom_wac *wacom_wac, size_t len)
 
 	if ((features->type == INTUOSHT ||
 	    features->type == INTUOSHT2) &&
-	    wacom_wac->shared->touch_input &&
 	    features->touch_max) {
-		input_report_switch(wacom_wac->shared->touch_input,
-				    SW_MUTE_DEVICE, data[8] & 0x40);
-		input_sync(wacom_wac->shared->touch_input);
+		wacom_report_touch_mute(wacom_wac, data[8] & 0x40);
 	}
 
 	if (data[9] & 0x02) { /* wireless module is attached */
drivers/hid/wacom_wac.h +1 -1
index 0de34c13e7a10..957247e6ba1c9 100644
@@ -286,7 +286,7 @@ struct wacom_shared {
 	/* for wireless device to access USB interfaces */
 	unsigned touch_max;
 	int type;
-	struct input_dev *touch_input;
+	struct input_dev __rcu *touch_input;
 	struct hid_device *pen;
 	struct hid_device *touch;
 	bool has_mute_touch_switch;
Signature · 1 line
2.53.0
author maintainer
#775 lore raw

PATCH 770/1848 HID: wacom: Fix Use-After-Free in wacom_bamboo_pad

In reply to Greg Kroah-Hartman

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

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

From: Lee Jones <[email protected]>

[ Upstream commit 3a523ecf9ac3fdd33f5eb31c43937ee44135395b ]

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

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

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

Fixes 8c97a765467c ("HID: wacom: add full support of the Wacom Bamboo PAD")

[Lee: Use explicit lock/unlock calls and top-of-block declarations in
wacom_remove_shared_data() and wacom_bamboo_pad_pen_event() for -std=gnu89 compatibility, and adapt to res_wacom]

---
 drivers/hid/wacom_sys.c | 40 ++++++++++++++++++++++++++--------------
 drivers/hid/wacom_wac.c | 14 +++++++-------
 drivers/hid/wacom_wac.h |  4 ++--
 3 files changed, 35 insertions(+), 23 deletions(-)
drivers/hid/wacom_sys.c +26 -14
index 94e12c56e040a..465d075d16f90 100644
@@ -882,15 +882,22 @@ static void wacom_remove_shared_data(void *res)
 	struct wacom_wac *wacom_wac = &res_wacom->wacom_wac;
 
 	if (wacom_wac->shared) {
+		struct hid_device *touch, *pen;
+
 		data = container_of(wacom_wac->shared, struct wacom_hdev_data,
 				    shared);
 
 		mutex_lock(&wacom_udev_list_lock);
-		if (wacom_wac->shared->touch == res_wacom->hdev) {
-			wacom_wac->shared->touch = NULL;
+		touch = rcu_dereference_protected(wacom_wac->shared->touch,
+						  lockdep_is_held(&wacom_udev_list_lock));
+		pen = rcu_dereference_protected(wacom_wac->shared->pen,
+						lockdep_is_held(&wacom_udev_list_lock));
+
+		if (touch == res_wacom->hdev) {
+			rcu_assign_pointer(wacom_wac->shared->touch, NULL);
 			rcu_assign_pointer(wacom_wac->shared->touch_input, NULL);
-		} else if (wacom_wac->shared->pen == res_wacom->hdev) {
-			wacom_wac->shared->pen = NULL;
+		} else if (pen == res_wacom->hdev) {
+			rcu_assign_pointer(wacom_wac->shared->pen, NULL);
 		}
 		mutex_unlock(&wacom_udev_list_lock);
 
@@ -2350,14 +2357,17 @@ static void wacom_set_shared_values(struct wacom_wac *wacom_wac)
 	}
 
 	if (wacom_wac->features.device_type & WACOM_DEVICETYPE_TOUCH) {
-		if (wacom_wac->shared->touch == wacom->hdev || !wacom_wac->shared->touch) {
+		struct hid_device *touch =
+			rcu_dereference_protected(wacom_wac->shared->touch,
+						  lockdep_is_held(&wacom_udev_list_lock));
+
+		if (touch == wacom->hdev || !touch) {
 			wacom_wac->shared->type = wacom_wac->features.type;
-			wacom_wac->shared->touch = wacom->hdev;
+			rcu_assign_pointer(wacom_wac->shared->touch, wacom->hdev);
 			rcu_assign_pointer(wacom_wac->shared->touch_input, wacom_wac->touch_input);
 		}
 	} else if (wacom_wac->features.device_type & WACOM_DEVICETYPE_PEN) {
-		/* Pairs with smp_load_acquire() in wacom_sibling_pending() */
-		smp_store_release(&wacom_wac->shared->pen, wacom->hdev);
+		rcu_assign_pointer(wacom_wac->shared->pen, wacom->hdev);
 	}
 }
 
@@ -2373,8 +2383,7 @@ static bool wacom_sibling_pending(struct wacom *wacom)
 		return false;
 
 	if (wacom->wacom_wac.shared) {
-		/* Pairs with smp_store_release() in wacom_set_shared_values() */
-		if (smp_load_acquire(&wacom->wacom_wac.shared->pen))
+		if (rcu_access_pointer(wacom->wacom_wac.shared->pen))
 			return false;
 	}
 
@@ -2844,16 +2853,19 @@ static void wacom_mode_change_work(struct work_struct *work)
 	bool is_direct = wacom->wacom_wac.is_direct_mode;
 	int error = 0;
 
-	if (shared->pen) {
-		wacom1 = hid_get_drvdata(shared->pen);
+	struct hid_device *pen = rcu_access_pointer(shared->pen);
+	struct hid_device *touch = rcu_access_pointer(shared->touch);
+
+	if (pen) {
+		wacom1 = hid_get_drvdata(pen);
 		wacom_release_resources(wacom1);
 		hid_hw_stop(wacom1->hdev);
 		wacom1->wacom_wac.has_mode_change = true;
 		wacom1->wacom_wac.is_direct_mode = is_direct;
 	}
 
-	if (shared->touch) {
-		wacom2 = hid_get_drvdata(shared->touch);
+	if (touch) {
+		wacom2 = hid_get_drvdata(touch);
 		wacom_release_resources(wacom2);
 		hid_hw_stop(wacom2->hdev);
 		wacom2->wacom_wac.has_mode_change = true;
drivers/hid/wacom_wac.c +7 -7
index 059572ea05097..4c7ad9dc543e5 100644
@@ -3203,6 +3203,7 @@ static int wacom_bpt_irq(struct wacom_wac *wacom, size_t len)
 static void wacom_bamboo_pad_pen_event(struct wacom_wac *wacom,
 		unsigned char *data)
 {
+	struct hid_device *pen;
 	unsigned char prefix;
 
 	/*
@@ -3215,13 +3216,12 @@ static void wacom_bamboo_pad_pen_event(struct wacom_wac *wacom,
 	prefix = data[0];
 	data[0] = WACOM_REPORT_BPAD_PEN;
 
-	/*
-	 * actually reroute the event.
-	 * No need to check if wacom->shared->pen is valid, hid_input_report()
-	 * will check for us.
-	 */
-	hid_input_report(wacom->shared->pen, HID_INPUT_REPORT, data,
-			 WACOM_PKGLEN_PENABLED, 1);
+	rcu_read_lock();
+	pen = rcu_dereference(wacom->shared->pen);
+	if (pen)
+		hid_input_report(pen, HID_INPUT_REPORT, data,
+				 WACOM_PKGLEN_PENABLED, 1);
+	rcu_read_unlock();
 
 	data[0] = prefix;
 }
drivers/hid/wacom_wac.h +2 -2
index 957247e6ba1c9..56d54ac53b3da 100644
@@ -287,8 +287,8 @@ struct wacom_shared {
 	unsigned touch_max;
 	int type;
 	struct input_dev __rcu *touch_input;
-	struct hid_device *pen;
-	struct hid_device *touch;
+	struct hid_device __rcu *pen;
+	struct hid_device __rcu *touch;
 	bool has_mute_touch_switch;
 	bool is_touch_on;
 };
Signature · 1 line
2.53.0
author maintainer
#776 lore raw

PATCH 771/1848 HID: wacom: Write shared touch initial status only once

In reply to Greg Kroah-Hartman

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

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

From: Ping Cheng <[email protected]>

[ Upstream commit cae3031c691dff0be61a26bc64e31a6939010d5c ]

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

Fixes ba16e5ffbaa1 ("HID: wacom: Advertise SW_MUTE_DEVICE capability prior to registration")

[Lee: Resolve context conflict around is_soft_touch_switch in
wacom_set_shared_values()]

---
 drivers/hid/wacom_sys.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/hid/wacom_sys.c +1 -1
index 465d075d16f90..ad570af507458 100644
@@ -2353,7 +2353,7 @@ static void wacom_set_shared_values(struct wacom_wac *wacom_wac)
 
 	if (wacom_wac->has_mute_touch_switch) {
 		WRITE_ONCE(wacom_wac->shared->has_mute_touch_switch, true);
-		wacom_wac->shared->is_touch_on = true;
+		WRITE_ONCE(wacom_wac->shared->is_touch_on, true);
 	}
 
 	if (wacom_wac->features.device_type & WACOM_DEVICETYPE_TOUCH) {
Signature · 1 line
2.53.0
author maintainer
#777 lore raw

PATCH 772/1848 HID: wacom: Setup SW_MUTE_DEVICE according to the order of input registration

In reply to Greg Kroah-Hartman

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

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

From: Ping Cheng <[email protected]>

[ Upstream commit 97ce491bcef2d231b8d51cee8e579183319a5ba4 ]

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

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

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

PATCH 773/1848 vxlan: Stop rejecting dynamic FDB entries with a nexthop ID

In reply to Greg Kroah-Hartman

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

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

From: Ido Schimmel <[email protected]>

[ Upstream commit 7308ef8b4a6779a39f68d053c19b53a5c584a663 ]

Commit 98fc57d16744 ("vxlan: reject dynamic fdb entries that reference a nexthop id") started rejecting FDB entries that point to FDB nexthops unless they are configured as "permanent" or "static". The intent was to prevent such entries from being aged out by vxlan_cleanup(), which runs without RTNL and can therefore race with other VXLAN devices that modify the same per-nexthop FDB list.

However, FRR installs remote MACs that are behind a multihomed Ethernet Segment (EVPN-MH) as dynamic FDB entries that point to an FDB nexthop group. Since the above commit, these entries are rejected and traffic towards the corresponding MACs is flooded to all the remote VTEPs.

These entries are also marked as externally learned ("extern_learn") and are therefore skipped by vxlan_cleanup(), but exempting externally learned entries from the checks is not enough: vxlan_cleanup() reads the state and flags of an entry without the hash lock, so an entry that is concurrently changed from dynamic and externally learned to static can still be aged out.

Instead, remove the checks added by the above commit and make vxlan_cleanup() skip FDB entries that point to FDB nexthops. Such entries can only be configured from user space, cannot be learned and cannot roam, so there is no reason to age them out. The nexthop pointer of an FDB entry is set before the entry is linked and is only cleared after it was unlinked and an RCU grace period has passed, so it can be checked without the hash lock.

Adjust the test cases added by the above commit and add a test case that checks that dynamic FDB entries that point to FDB nexthops are not aged out. Without the fix:

 # ./fib_nexthops.sh -t "ipv4_fdb_grp_fcnal ipv6_fdb_grp_fcnal"

IPv4 fdb groups functional
--------------------------
[...]

 TEST: Fdb mac add with nexthop group and dynamic state              [FAIL]
 TEST: Fdb mac add with nexthop group and extern_learn               [FAIL]
 TEST: Fdb mac without nexthop group aged out                        [ OK ]
 TEST: Fdb mac with nexthop group not aged out                       [FAIL]

[...]

IPv6 fdb groups functional
--------------------------
[...]

 TEST: Fdb mac add with nexthop group and dynamic state              [FAIL]
 TEST: Fdb mac add with nexthop group and extern_learn               [FAIL]
 TEST: Fdb mac without nexthop group aged out                        [ OK ]
 TEST: Fdb mac with nexthop group not aged out                       [FAIL]

[...]

Tests passed: 44
Tests failed: 6
Tests skipped: 0

With the fix:

 # ./fib_nexthops.sh -t "ipv4_fdb_grp_fcnal ipv6_fdb_grp_fcnal"

IPv4 fdb groups functional
--------------------------
[...]

 TEST: Fdb mac add with nexthop group and dynamic state              [ OK ]
 TEST: Fdb mac add with nexthop group and extern_learn               [ OK ]
 TEST: Fdb mac without nexthop group aged out                        [ OK ]
 TEST: Fdb mac with nexthop group not aged out                       [ OK ]

[...]

IPv6 fdb groups functional
--------------------------
[...]

 TEST: Fdb mac add with nexthop group and dynamic state              [ OK ]
 TEST: Fdb mac add with nexthop group and extern_learn               [ OK ]
 TEST: Fdb mac without nexthop group aged out                        [ OK ]
 TEST: Fdb mac with nexthop group not aged out                       [ OK ]

[...]

Tests passed: 50
Tests failed: 0
Tests skipped: 0

Fixes 1274e1cc4226 ("vxlan: ecmp support for mac fdb entries")
Fixes 98fc57d16744 ("vxlan: reject dynamic fdb entries that reference a nexthop id")

[ idosch: fixed a small conflict in vxlan_fdb_add(), adjusted the
vxlan_cleanup() hunk to the per-bucket FDB iteration in this tree and open-coded the wait in fdb_entry_aged() since slowwait() is not available to fib_nexthops.sh in this tree ]

---
 drivers/net/vxlan/vxlan_core.c              | 14 ++-----
 tools/testing/selftests/net/fib_nexthops.sh | 46 +++++++++++++++------
 2 files changed, 37 insertions(+), 23 deletions(-)
drivers/net/vxlan/vxlan_core.c +3 -11
index f10bbdc1b8260..7c2b826f01aa5 100644
@@ -1069,12 +1069,6 @@ static int vxlan_fdb_update_existing(struct vxlan_dev *vxlan,
 		return -EOPNOTSUPP;
 	}
 
-	if (rcu_access_pointer(f->nh) &&
-	    !(state & (NUD_PERMANENT | NUD_NOARP))) {
-		NL_SET_ERR_MSG(extack, "Cannot make a nexthop fdb dynamic");
-		return -EOPNOTSUPP;
-	}
-
 	/* Do not allow an externally learned entry to take over an entry added
 	 * by the user.
 	 */
@@ -1327,11 +1321,6 @@ static int vxlan_fdb_add(struct ndmsg *ndm, struct nlattr *tb[],
 	if (err)
 		return err;
 
-	if (nhid && !(ndm->ndm_state & (NUD_PERMANENT | NUD_NOARP))) {
-		NL_SET_ERR_MSG(extack, "A nexthop fdb cannot be dynamic");
-		return -EINVAL;
-	}
-
 	if (vxlan->default_dst.remote_ip.sa.sa_family != ip.sa.sa_family)
 		return -EAFNOSUPPORT;
 
@@ -3030,6 +3019,9 @@ static void vxlan_cleanup(struct timer_list *t)
 			if (f->flags & NTF_EXT_LEARNED)
 				continue;
 
+			if (rcu_access_pointer(f->nh))
+				continue;
+
 			timeout = READ_ONCE(f->used) + vxlan->cfg.age_interval * HZ;
 			if (time_before_eq(timeout, jiffies)) {
 				netdev_dbg(vxlan->dev,
tools/testing/selftests/net/fib_nexthops.sh +34 -12

68 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#779 lore raw

PATCH 774/1848 can: raw, isotp: copy socket options outside of lock_sock()

In reply to Greg Kroah-Hartman

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

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

From: Oliver Hartkopp <[email protected]>

commit 43c973a0887d3d7b2ee0a446603c97bf0f38c58e upstream.

The CAN_RAW and CAN_ISOTP specific socket options are copied from and to user space while holding lock_sock(). A copy that faults or stalls, e.g. on a userfaultfd or FUSE backed mapping, holds lock_sock() for its whole duration.

raw_notify() and isotp_notify() take lock_sock() of a socket that is bound to the vanishing device while holding RTNL. As the CAN_RAW options can also be changed on a bound socket, a stalled copy can block RTNL on an unregistration or namespace change of the bound device. Before "can: protect the receive lists with a per-device lock", raw_setsockopt() even held RTNL itself during the copy. CAN_ISOTP only copies its options for unbound sockets, which isotp_notify() skips without taking lock_sock().

Keep the user space copies out of the locked sections: Check the option name and length and copy the option values, including the CAN_RAW_FILTER filters, to kernel memory before lock_sock(). raw_setsockopt_locked() and isotp_setsockopt_locked() get the copied values directly and drop their now redundant length checks and copies. As a side effect, a failing copy can not leave partially overwritten options behind anymore. In raw_getsockopt() duplicate the filters under lock_sock() and copy them to user space after release_sock().

As the option name and length are now checked before lock_sock(), the order of the checks in isotp_setsockopt() and accordingly the order of the returned error values changes. This is in line with POSIX, which does not define an order in which multiple error conditions are detected and reported.

The generic SOL_SOCKET options in sk_setsockopt() are not affected by this patch.

Fixes c18ce101f2e4 ("[CAN]: Add raw protocol")
Fixes 1e5185c09058 ("can: raw: add locking for raw flags bitfield")
Cc [email protected] # depends on "can: protect the receive lists with a per-device lock"

[ backport to 5.10: This tree has no raw_setsockopt_locked() from commit
1e5185c09058 ("can: raw: add locking for raw flags bitfield"). raw_setsockopt() already copies all option values from user space before lock_sock() here, so only the raw_getsockopt() and isotp parts apply. raw_getsockopt() uses copy_to_user() instead of the getsockopt_iter interface and truncates the filter list to the user space buffer size in this tree. Keep that behaviour, duplicate the filters under lock_sock() and copy them with copy_to_user() after release_sock(). ]

---
 net/can/isotp.c | 100 +++++++++++++++++++++++++++---------------------
 net/can/raw.c   |  17 ++++++--
 2 files changed, 71 insertions(+), 46 deletions(-)
net/can/isotp.c +57 -43
index 2d230cefbb3fa..d4239b4976322 100644
@@ -1642,8 +1642,8 @@ static int isotp_getname(struct socket *sock, struct sockaddr *uaddr, int peer)
 	return ISOTP_MIN_NAMELEN;
 }
 
-static int isotp_setsockopt_locked(struct socket *sock, int level, int optname,
-			    sockptr_t optval, unsigned int optlen)
+static int isotp_setsockopt_locked(struct socket *sock, int optname,
+				   const void *val)
 {
 	struct sock *sk = sock->sk;
 	struct isotp_sock *so = isotp_sk(sk);
@@ -1654,11 +1654,7 @@ static int isotp_setsockopt_locked(struct socket *sock, int level, int optname,
 
 	switch (optname) {
 	case CAN_ISOTP_OPTS:
-		if (optlen != sizeof(struct can_isotp_options))
-			return -EINVAL;
-
-		if (copy_from_sockptr(&so->opt, optval, optlen))
-			return -EFAULT;
+		memcpy(&so->opt, val, sizeof(so->opt));
 
 		/* no separate rx_ext_address is given => use ext_address */
 		if (!(so->opt.flags & CAN_ISOTP_RX_EXT_ADDR))
@@ -1683,55 +1679,37 @@ static int isotp_setsockopt_locked(struct socket *sock, int level, int optname,
 		break;
 
 	case CAN_ISOTP_RECV_FC:
-		if (optlen != sizeof(struct can_isotp_fc_options))
-			return -EINVAL;
-
-		if (copy_from_sockptr(&so->rxfc, optval, optlen))
-			return -EFAULT;
+		memcpy(&so->rxfc, val, sizeof(so->rxfc));
 		break;
 
 	case CAN_ISOTP_TX_STMIN:
-		if (optlen != sizeof(u32))
-			return -EINVAL;
-
-		if (copy_from_sockptr(&so->force_tx_stmin, optval, optlen))
-			return -EFAULT;
+		so->force_tx_stmin = *(const u32 *)val;
 		break;
 
 	case CAN_ISOTP_RX_STMIN:
-		if (optlen != sizeof(u32))
-			return -EINVAL;
-
-		if (copy_from_sockptr(&so->force_rx_stmin, optval, optlen))
-			return -EFAULT;
+		so->force_rx_stmin = *(const u32 *)val;
 		break;
 
-	case CAN_ISOTP_LL_OPTS:
-		if (optlen == sizeof(struct can_isotp_ll_options)) {
-			struct can_isotp_ll_options ll;
-
-			if (copy_from_sockptr(&ll, optval, optlen))
-				return -EFAULT;
+	case CAN_ISOTP_LL_OPTS: {
+		const struct can_isotp_ll_options *ll = val;
 
-			/* check for correct ISO 11898-1 DLC data length */
-			if (ll.tx_dl != padlen(ll.tx_dl))
-				return -EINVAL;
+		/* check for correct ISO 11898-1 DLC data length */
+		if (ll->tx_dl != padlen(ll->tx_dl))
+			return -EINVAL;
 
-			if (ll.mtu != CAN_MTU && ll.mtu != CANFD_MTU)
-				return -EINVAL;
+		if (ll->mtu != CAN_MTU && ll->mtu != CANFD_MTU)
+			return -EINVAL;
 
-			if (ll.mtu == CAN_MTU &&
-			    (ll.tx_dl > CAN_MAX_DLEN || ll.tx_flags != 0))
-				return -EINVAL;
+		if (ll->mtu == CAN_MTU &&
+		    (ll->tx_dl > CAN_MAX_DLEN || ll->tx_flags != 0))
+			return -EINVAL;
 
-			memcpy(&so->ll, &ll, sizeof(ll));
+		memcpy(&so->ll, ll, sizeof(*ll));
 
-			/* set ll_dl for tx path to similar place as for rx */
-			so->tx.ll_dl = ll.tx_dl;
-		} else {
-			return -EINVAL;
-		}
+		/* set ll_dl for tx path to similar place as for rx */
+		so->tx.ll_dl = ll->tx_dl;
 		break;
+	}
 
 	default:
 		ret = -ENOPROTOOPT;
@@ -1745,13 +1723,49 @@ static int isotp_setsockopt(struct socket *sock, int level, int optname,
 
 {
 	struct sock *sk = sock->sk;
+	union {
+		struct can_isotp_options opt;
+		struct can_isotp_fc_options rxfc;
+		struct can_isotp_ll_options ll;
+		u32 stmin;
+	} val;
+	unsigned int size;
 	int ret;
 
 	if (level != SOL_CAN_ISOTP)
 		return -EINVAL;
 
+	/* copy the option values from user space before lock_sock() */
+	switch (optname) {
+	case CAN_ISOTP_OPTS:
+		size = sizeof(val.opt);
+		break;
+
+	case CAN_ISOTP_RECV_FC:
+		size = sizeof(val.rxfc);
+		break;
+
+	case CAN_ISOTP_TX_STMIN:
+	case CAN_ISOTP_RX_STMIN:
+		size = sizeof(val.stmin);
+		break;
+
+	case CAN_ISOTP_LL_OPTS:
+		size = sizeof(val.ll);
+		break;
+
+	default:
+		return -ENOPROTOOPT;
+	}
+
+	if (optlen != size)
+		return -EINVAL;
+
+	if (copy_from_sockptr(&val, optval, size))
+		return -EFAULT;
+
 	lock_sock(sk);
-	ret = isotp_setsockopt_locked(sock, level, optname, optval, optlen);
+	ret = isotp_setsockopt_locked(sock, optname, &val);
 	release_sock(sk);
 	return ret;
 }
net/can/raw.c +14 -3
index 262277783cc15..723495f2c6fca 100644
@@ -755,23 +755,34 @@ static int raw_getsockopt(struct socket *sock, int level, int optname,
 		return -EINVAL;
 
 	switch (optname) {
-	case CAN_RAW_FILTER:
+	case CAN_RAW_FILTER: {
+		struct can_filter *filter = NULL;
+
 		lock_sock(sk);
 		if (ro->count > 0) {
 			int fsize = ro->count * sizeof(struct can_filter);
 
 			if (len > fsize)
 				len = fsize;
-			if (copy_to_user(optval, ro->filter, len))
-				err = -EFAULT;
+			/* copy to user space after release_sock() */
+			filter = kmemdup(ro->filter, len, GFP_KERNEL);
+			if (!filter)
+				err = -ENOMEM;
 		} else {
 			len = 0;
 		}
 		release_sock(sk);
 
+		if (filter) {
+			if (copy_to_user(optval, filter, len))
+				err = -EFAULT;
+			kfree(filter);
+		}
+
 		if (!err)
 			err = put_user(len, optlen);
 		return err;
+	}
 
 	case CAN_RAW_ERR_FILTER:
 		if (len > sizeof(can_err_mask_t))
Signature · 1 line
2.53.0
author maintainer
#780 lore raw

PATCH 775/1848 ata: libata-scsi: reject data-in commands with a data-out buffer

In reply to Greg Kroah-Hartman

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

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

From: Zhao Gongyi <[email protected]>

[ Upstream commit a4845f077415ef32fe672c841e2fc58ae9e28273 ]

SG_IO can submit a data-in SCSI command with DMA_TO_DEVICE. The scatterlist can then contain pages pinned without write access. ata_scsi_rbuf_fill() writes simulated replies to that scatterlist; in the reported case, the copy tried to write the shared zero page and faulted in the kernel.

The same mismatch can affect SG_IO commands translated by libata. ZBC IN and GET PHYSICAL ELEMENT STATUS completion handlers can modify the receive buffer even if the drive aborts the command. For ATAPI, the successful INQUIRY completion also rewrites the buffer in atapi_fixup_inquiry().

Reject these mismatched commands before the buffer is written or the command is issued. Report ABORTED COMMAND / DATA IN BUFFER ERROR because the CDB itself can be valid; the supplied transfer direction is wrong.

Backport notes: Use the older five-argument ata_scsi_set_sense() interface and spell DATA IN BUFFER ERROR as ASC/ASCQ 0x4b/0x0a. The older ata_scsi_rbuf_fill() takes struct ata_scsi_args; get the device and command from args, and reject before copying. In 5.10, reject before ata_scsi_rbuf_get(), since its matching ata_scsi_rbuf_put() copies the simulated reply to the buffer.

---
 drivers/ata/libata-scsi.c | 25 +++++++++++++++++++++++++
 1 file changed, 25 insertions(+)
drivers/ata/libata-scsi.c +25 -0
index 77f121266b636..d3791425b9335 100644
@@ -1764,6 +1764,18 @@ static int ata_scsi_translate(struct ata_device *dev, struct scsi_cmnd *cmd,
 	if (xlat_func(qc))
 		goto done;
 
+	/*
+	 * A data-out request may contain pages pinned without write access.
+	 * Reject a translated data-in command before issuing it, since its
+	 * completion handler may write to the buffer even if the device fails.
+	 */
+	if (unlikely(cmd->sc_data_direction == DMA_TO_DEVICE &&
+		     ata_is_data(qc->tf.protocol) &&
+		     !(qc->tf.flags & ATA_TFLAG_WRITE))) {
+		ata_scsi_set_sense(dev, cmd, ABORTED_COMMAND, 0x4b, 0x0a);
+		goto done;
+	}
+
 	return ata_scsi_qc_issue(ap, qc);
 
 done:
@@ -1849,6 +1861,12 @@ static void ata_scsi_rbuf_fill(struct ata_scsi_args *args,
 	struct scsi_cmnd *cmd = args->cmd;
 	unsigned long flags;
 
+	/* A data-out request may contain pages pinned without write access. */
+	if (cmd->sc_data_direction == DMA_TO_DEVICE) {
+		ata_scsi_set_sense(args->dev, cmd, ABORTED_COMMAND, 0x4b, 0x0a);
+		return;
+	}
+
 	rbuf = ata_scsi_rbuf_get(cmd, false, &flags);
 	rc = actor(args, rbuf);
 	ata_scsi_rbuf_put(cmd, rc == 0, &flags);
@@ -2674,6 +2692,13 @@ static unsigned int atapi_xlat(struct ata_queued_cmd *qc)
 
 	qc->complete_fn = atapi_qc_complete;
 
+	/* atapi_fixup_inquiry() writes to the buffer on successful completion. */
+	if (scmd->sc_data_direction == DMA_TO_DEVICE &&
+	    scmd->cmnd[0] == INQUIRY) {
+		ata_scsi_set_sense(dev, scmd, ABORTED_COMMAND, 0x4b, 0x0a);
+		return 1;
+	}
+
 	qc->tf.flags |= ATA_TFLAG_ISADDR | ATA_TFLAG_DEVICE;
 	if (scmd->sc_data_direction == DMA_TO_DEVICE) {
 		qc->tf.flags |= ATA_TFLAG_WRITE;
Signature · 1 line
2.53.0
author maintainer
#781 lore raw

PATCH 776/1848 can: dev: can_fill_info(): dont wake up controller if interface is down

In reply to Greg Kroah-Hartman

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

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

From: ChunYuZhiQiang <[email protected]>

commit 75332c410c8190d61499001c5516af977ca426c3 upstream.

If the interface is down, the CAN controller might be powered down and its clocks gated. Don't call do_get_berr_counter() to read the bus error counters if the interface is down, and adjust can_get_size() to match.

This removes one trigger for a synchronous external abort seen on i.MX8QXP when "ip link show" is run on a flexcan interface that was never brought up. The underlying cause is platform-specific: on i.MX8QXP the CAN clocks are gated through the SCU LPCG and the subsystem shares the IMX_SC_R_CAN_0 power domain, and there is a window after pm_runtime_resume_and_get() returns where the clock has not reached the module yet. This patch avoids the netlink query path while the interface is down, but does not root-cause the LPCG window itself.

As a result, IFLA_CAN_BERR_COUNTER is no longer reported for down interfaces. Userspace must treat the attribute as optional.

The issue was triggered on an i.MX8QXP board by running "ip link show" without ever bringing the interface up:

    Internal error: synchronous external abort: 0000000096000210

    pc : flexcan_read_le+0x0/0x18
    lr : flexcan_get_berr_counter+0x4c/0x8c
    Call trace:
     flexcan_read_le+0x0/0x18
     flexcan_get_berr_counter+0x4c/0x8c
     can_fill_info+0x1f8/0x434
     rtnl_fill_ifinfo+0x8fc/0xbb4
     rtnl_dump_ifinfo+0x364/0x448

This is the same class of problem fixed for m_can in commit 91a55c72a821 ("can: m_can: m_can_get_berr_counter(): don't wake up controller if interface is down").

Note: in 5.10 the netlink code still lives in drivers/net/can/dev/dev.c, so this is a manual backport, not a cherry-pick.

Fixes ec56acfef2af1 ("can: flexcan: flexcan_get_berr_counter(): switch on clocks before accessing ecr register")
---
 drivers/net/can/dev/dev.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/net/can/dev/dev.c +2 -2
index b5e79d63d59b5..30d45805f29df 100644
@@ -1141,7 +1141,7 @@ static size_t can_get_size(const struct net_device *dev)
 	size += nla_total_size(sizeof(u32));			/* IFLA_CAN_STATE */
 	size += nla_total_size(sizeof(struct can_ctrlmode));	/* IFLA_CAN_CTRLMODE */
 	size += nla_total_size(sizeof(u32));			/* IFLA_CAN_RESTART_MS */
-	if (priv->do_get_berr_counter)				/* IFLA_CAN_BERR_COUNTER */
+	if (priv->do_get_berr_counter && netif_running(dev))	/* IFLA_CAN_BERR_COUNTER */
 		size += nla_total_size(sizeof(struct can_berr_counter));
 	if (priv->data_bittiming.bitrate)			/* IFLA_CAN_DATA_BITTIMING */
 		size += nla_total_size(sizeof(struct can_bittiming));
@@ -1186,7 +1186,7 @@ static int can_fill_info(struct sk_buff *skb, const struct net_device *dev)
 	    nla_put(skb, IFLA_CAN_CTRLMODE, sizeof(cm), &cm) ||
 	    nla_put_u32(skb, IFLA_CAN_RESTART_MS, priv->restart_ms) ||
 
-	    (priv->do_get_berr_counter &&
+	    (priv->do_get_berr_counter && netif_running(dev) &&
 	     !priv->do_get_berr_counter(dev, &bec) &&
 	     nla_put(skb, IFLA_CAN_BERR_COUNTER, sizeof(bec), &bec)) ||
 
Signature · 1 line
2.53.0
author maintainer
#782 lore raw

PATCH 777/1848 tracing/histograms: Verify event_call identity when updating synth_event refcount

In reply to Greg Kroah-Hartman

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

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

From: Lee Jones <[email protected]>

[ Upstream commit 3403d9bb27ebc3572bd048620746b4414e073bf9 ]

In event_hist_trigger_parse() and hist_unreg_all(), the histogram registration and unregistration paths look up find_synth_event() using trace_event_name(file->event_call) and adjust se->ref if a match is found.

Because find_synth_event() only compares the event basename, registering or removing a histogram on a non-synthetic trace event whose basename matches a synthetic event erroneously modifies the synthetic event's reference count. If a histogram is registered on the non-synthetic event before the synthetic event is created and removed afterwards, se->ref is decremented without a matching increment, allowing the synthetic event to be freed while an active histogram action still holds a pointer to it.

Introduce find_synth_event_call() to verify that &se->call matches file->event_call before adjusting se->ref.

Fixes 4b147936fa50 ("tracing: Add support for 'synthetic' events")
[Lee: Context conflict in event_hist_trigger_func() - no functional change]
---
 kernel/trace/trace_events_hist.c  | 11 +++--------
 kernel/trace/trace_events_synth.c | 10 ++++++++++
 kernel/trace/trace_synth.h        |  1 +
 3 files changed, 14 insertions(+), 8 deletions(-)
kernel/trace/trace_events_hist.c +3 -8
index f36b793147f8e..7c3c8cfb873c1 100644
@@ -5666,7 +5666,6 @@ static void hist_unreg_all(struct trace_event_file *file)
 	struct event_trigger_data *test, *n;
 	struct hist_trigger_data *hist_data;
 	struct synth_event *se;
-	const char *se_name;
 
 	lockdep_assert_held(&event_mutex);
 
@@ -5679,8 +5678,7 @@ static void hist_unreg_all(struct trace_event_file *file)
 			list_del_rcu(&test->list);
 			trace_event_trigger_enable_disable(file, 0);
 
-			se_name = trace_event_name(file->event_call);
-			se = find_synth_event(se_name);
+			se = find_synth_event_call(file->event_call);
 			if (se)
 				se->ref--;
 
@@ -5703,7 +5701,6 @@ static int event_hist_trigger_func(struct event_command *cmd_ops,
 	struct event_trigger_ops *trigger_ops;
 	struct hist_trigger_data *hist_data;
 	struct synth_event *se;
-	const char *se_name;
 	bool remove = false;
 	char *trigger, *p;
 	int ret = 0;
@@ -5800,8 +5797,7 @@ static int event_hist_trigger_func(struct event_command *cmd_ops,
 		}
 
 		cmd_ops->unreg(glob+1, trigger_ops, trigger_data, file);
-		se_name = trace_event_name(file->event_call);
-		se = find_synth_event(se_name);
+		se = find_synth_event_call(file->event_call);
 		if (se)
 			se->ref--;
 		ret = 0;
@@ -5842,8 +5838,7 @@ static int event_hist_trigger_func(struct event_command *cmd_ops,
 	if (ret)
 		goto out_unreg;
 
-	se_name = trace_event_name(file->event_call);
-	se = find_synth_event(se_name);
+	se = find_synth_event_call(file->event_call);
 	if (se)
 		se->ref++;
 	/* Just return zero, not the number of registered triggers */
kernel/trace/trace_events_synth.c +10 -0
index b126af59e61c3..e7867d02a9e92 100644
@@ -821,6 +821,16 @@ struct synth_event *find_synth_event(const char *name)
 	return NULL;
 }
 
+struct synth_event *find_synth_event_call(struct trace_event_call *call)
+{
+	struct synth_event *se;
+	const char *name;
+
+	name = trace_event_name(call);
+	se = find_synth_event(name);
+	return se && &se->call == call ? se : NULL;
+}
+
 static struct trace_event_fields synth_event_fields_array[] = {
 	{ .type = TRACE_FUNCTION_TYPE,
 	  .define_fields = synth_event_define_fields },
kernel/trace/trace_synth.h +1 -0
index 077c748a8b3a6..87320dab449a8 100644
@@ -37,5 +37,6 @@ struct synth_event {
 };
 
 extern struct synth_event *find_synth_event(const char *name);
+extern struct synth_event *find_synth_event_call(struct trace_event_call *call);
 
 #endif /* __TRACE_SYNTH_H */
Signature · 1 line
2.53.0
author maintainer
#783 lore raw

PATCH 778/1848 media: uvcvideo: Disable autosuspend for Insta360 Link

In reply to Greg Kroah-Hartman

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

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

From: Ricardo Ribalda <[email protected]>

[ Upstream commit 3de6df64f92d8633eb51a5e957ffc43ebdb2156e ]

When the device suspends, it keeps power-cycling.

The user notices it because the LED constanct oscillate between blue (ready) and no LED (off).

<6>[95202.128542] usb 3-3-port4: attempt power cycle
<6>[95206.070120] usb 3-3.4: new high-speed USB device number 49 using xhci_hcd
<6>[95206.212027] usb 3-3.4: New USB device found, idVendor=2e1a, idProduct=4c01, bcdDevice= 2.00
<6>[95206.212044] usb 3-3.4: New USB device strings: Mfr=1, Product=2, SerialNumber=<Serial: 1>
<6>[95206.212050] usb 3-3.4: Product: Insta360 Link
<6>[95206.212075] usb 3-3.4: Manufacturer: Amba
<7>[95206.214862] usb 3-3.4: GPIO lookup for consumer privacy
<7>[95206.214866] usb 3-3.4: using lookup tables for GPIO lookup
<7>[95206.214869] usb 3-3.4: No GPIO consumer privacy found
<6>[95206.214871] usb 3-3.4: Found UVC 1.10 device Insta360 Link (2e1a:4c01)
<3>[95206.217113] usb 3-3.4: Failed to query (GET_INFO) UVC control 14 on unit 1: -32 (exp. 1).
<3>[95206.217733] usb 3-3.4: Failed to query (GET_INFO) UVC control 16 on unit 1: -32 (exp. 1).
<4>[95206.223544] usb 3-3.4: Warning! Unlikely big volume range (=32767), cval->res is probably wrong.
<4>[95206.223554] usb 3-3.4: [9] FU [Mic Capture Volume] ch = 1, val = -32768/-1/1
<6>[95210.698990] usb 3-3.4: USB disconnect, device number 49
<6>[95211.963090] usb 3-3.4: new high-speed USB device number 50 using xhci_hcd
<6>[95212.657061] usb 3-3.4: new full-speed USB device number 51 using xhci_hcd
<3>[95212.783119] usb 3-3.4: device descriptor read/64, error -32
<3>[95213.015076] usb 3-3.4: device descriptor read/64, error -32
<6>[95213.120358] usb 3-3-port4: attempt power cycle

Bus 001 Device 009: ID 2e1a:4c01 Amba Insta360 Link Device Descriptor:
bLength 18
bDescriptorType 1
bcdUSB 2.00
bDeviceClass 239 Miscellaneous Device
bDeviceSubClass 2
bDeviceProtocol 1 Interface Association
bMaxPacketSize0 64
idVendor 0x2e1a
idProduct 0x4c01
bcdDevice 2.00

  iManufacturer           1 Amba
  iProduct                2 Insta360 Link
  iSerial                 0
  bNumConfigurations      1
---
 drivers/media/usb/uvc/uvc_driver.c | 14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)
drivers/media/usb/uvc/uvc_driver.c +13 -1
index c2adc6854c540..e2dab556ec996 100644
@@ -2373,8 +2373,11 @@ static int uvc_probe(struct usb_interface *intf,
 			"supported.\n", ret);
 	}
 
+	if (!(dev->quirks & UVC_QUIRK_DISABLE_AUTOSUSPEND))
+		usb_enable_autosuspend(udev);
+
 	uvc_trace(UVC_TRACE_PROBE, "UVC device initialized.\n");
-	usb_enable_autosuspend(udev);
+
 	return 0;
 
 error:
@@ -3057,6 +3060,15 @@ static const struct usb_device_id uvc_ids[] = {
 	  .bInterfaceSubClass	= 1,
 	  .bInterfaceProtocol	= 0,
 	  .driver_info		= UVC_INFO_QUIRK(UVC_QUIRK_FORCE_BPP) },
+	/* Insta360 Link */
+	{ .match_flags		= USB_DEVICE_ID_MATCH_DEVICE
+				| USB_DEVICE_ID_MATCH_INT_INFO,
+	  .idVendor		= 0x2e1a,
+	  .idProduct		= 0x4c01,
+	  .bInterfaceClass	= USB_CLASS_VIDEO,
+	  .bInterfaceSubClass	= 1,
+	  .bInterfaceProtocol	= 0,
+	  .driver_info		= UVC_INFO_QUIRK(UVC_QUIRK_DISABLE_AUTOSUSPEND) },
 	/* Intel RealSense D4M */
 	{ .match_flags		= USB_DEVICE_ID_MATCH_DEVICE
 				| USB_DEVICE_ID_MATCH_INT_INFO,
Signature · 1 line
2.53.0
author maintainer
#784 lore raw

PATCH 779/1848 media: uvcvideo: Add autosuspend quirk for AVerMedia Live Gamer HD 2

In reply to Greg Kroah-Hartman

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

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

From: Ricardo Ribalda <[email protected]>

[ Upstream commit b79251c881bb39f70c6f6fb30ad5d454b78c9f4a ]

A user has reported that this device gets stuck in a loop where every few seconds it will turn off and turn back on, causing audio devices to disappear and reappear, its LED to flash, spamming dmesg, etc. This only happens when not in use; everything is fine when the video device is actually being used.

They also reported that using the AUTOSUSPEND quirk via module parameters fixes the issue.

Add the device to the quirk list.

ID 07ca:1570 AVerMedia Technologies, Inc. AVerMedia USB Device Negotiated speed: High Speed (480Mbps)
Device Descriptor:
bLength 18
bDescriptorType 1
bcdUSB 2.10
bDeviceClass 239 Miscellaneous Device
bDeviceSubClass 2 [unknown]
bDeviceProtocol 1 Interface Association
bMaxPacketSize0 64
idVendor 0x07ca AVerMedia Technologies, Inc.
idProduct 0x1570 AVerMedia USB Device
bcdDevice 1.00

   iManufacturer           6 AVerMedia
   iProduct                7 AVerMedia USB Device
   iSerial                 3 53106326013650
   bNumConfigurations      1

Configuration Descriptor:
bLength 9
bDescriptorType 2
wTotalLength 0x01d6
bNumInterfaces 4
bConfigurationValue 1
iConfiguration 0
bmAttributes 0xa0
(Bus Powered)
Remote Wakeup
MaxPower 150mA
Interface Association:
bLength 8
bDescriptorType 11
bFirstInterface 0
bInterfaceCount 2
bFunctionClass 14 Video
bFunctionSubClass 3 Video Interface Collection
bFunctionProtocol 0
iFunction 8 AVerMedia Live Gamer HD 2
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 0
bAlternateSetting 0
bNumEndpoints 0
bInterfaceClass 14 Video
bInterfaceSubClass 1 Video Control
bInterfaceProtocol 0
iInterface 8 AVerMedia Live Gamer HD 2
VideoControl Interface Descriptor:
bLength 13
bDescriptorType 36
bDescriptorSubtype 1 (HEADER)
bcdUVC 1.00
wTotalLength 0x004d
dwClockFrequency 120.000000MHz
bInCollection 1
baInterfaceNr( 0) 1
VideoControl Interface Descriptor:
bLength 18
bDescriptorType 36
bDescriptorSubtype 2 (INPUT_TERMINAL)
bTerminalID 1
wTerminalType 0x0201 Camera Sensor
bAssocTerminal 0
iTerminal 0
wObjectiveFocalLengthMin 0
wObjectiveFocalLengthMax 0
wOcularFocalLength 0
bControlSize 3
bmControls 0x00000000
VideoControl Interface Descriptor:
bLength 11
bDescriptorType 36
bDescriptorSubtype 5 (PROCESSING_UNIT)
Warning: Descriptor too short
bUnitID 3
bSourceID 1
wMaxMultiplier 0
bControlSize 2
bmControls 0x0000000f
Brightness
Contrast
Hue
Saturation
iProcessing 0
bmVideoStandards 0x09
None
SECAM - 625/50
VideoControl Interface Descriptor:
bLength 9
bDescriptorType 36
bDescriptorSubtype 3 (OUTPUT_TERMINAL)
bTerminalID 2
wTerminalType 0x0101 USB Streaming
bAssocTerminal 0
bSourceID 4
iTerminal 0
VideoControl Interface Descriptor:
bLength 28
bDescriptorType 36
bDescriptorSubtype 6 (EXTENSION_UNIT)
bUnitID 4
guidExtensionCode {c66d125b-0480-0844-8c26-b8363a84de63}
bNumControls 17
bNrInPins 1
baSourceID( 0) 3
bControlSize 3
bmControls( 0) 0x07
bmControls( 1) 0xfe
bmControls( 2) 0x01
iExtension 0
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 1
bAlternateSetting 0
bNumEndpoints 0
bInterfaceClass 14 Video
bInterfaceSubClass 2 Video Streaming
bInterfaceProtocol 0
iInterface 8 AVerMedia Live Gamer HD 2
VideoStreaming Interface Descriptor:
bLength 14
bDescriptorType 36
bDescriptorSubtype 1 (INPUT_HEADER)
bNumFormats 1
wTotalLength 0x00bd
bEndpointAddress 0x89 EP 9 IN
bmInfo 0
bTerminalLink 2
bStillCaptureMethod 0
bTriggerSupport 0
bTriggerUsage 0
bControlSize 1
bmaControls( 0) 0
VideoStreaming Interface Descriptor:
bLength 11
bDescriptorType 36
bDescriptorSubtype 6 (FORMAT_MJPEG)
bFormatIndex 1
bNumFrameDescriptors 5
bFlags 0
Fixed-size samples: No
bDefaultFrameIndex 1
bAspectRatioX 0
bAspectRatioY 0
bmInterlaceFlags 0x00
Interlaced stream or variable: No
Fields per frame: 1 fields
Field 1 first: No
Field pattern: Field 1 only
bCopyProtect 0
VideoStreaming Interface Descriptor:
bLength 34
bDescriptorType 36
bDescriptorSubtype 7 (FRAME_MJPEG)
bFrameIndex 1
bmCapabilities 0x00
Still image unsupported
wWidth 640
wHeight 480
dwMinBitRate 294617088
dwMaxBitRate 294912000
dwMaxVideoFrameBufferSize 614400
dwDefaultFrameInterval 166833
bFrameIntervalType 2
dwFrameInterval( 0) 166666
dwFrameInterval( 1) 166833
VideoStreaming Interface Descriptor:
bLength 34
bDescriptorType 36
bDescriptorSubtype 7 (FRAME_MJPEG)
bFrameIndex 2
bmCapabilities 0x00
Still image unsupported
wWidth 720
wHeight 480
dwMinBitRate 331444224
dwMaxBitRate 331776000
dwMaxVideoFrameBufferSize 691200
dwDefaultFrameInterval 166833
bFrameIntervalType 2
dwFrameInterval( 0) 166666
dwFrameInterval( 1) 166833
VideoStreaming Interface Descriptor:
bLength 30
bDescriptorType 36
bDescriptorSubtype 7 (FRAME_MJPEG)
bFrameIndex 3
bmCapabilities 0x00
Still image unsupported
wWidth 720
wHeight 576
dwMinBitRate 331776000
dwMaxBitRate 331776000
dwMaxVideoFrameBufferSize 829440
dwDefaultFrameInterval 200000
bFrameIntervalType 1
dwFrameInterval( 0) 200000
VideoStreaming Interface Descriptor:
bLength 38
bDescriptorType 36
bDescriptorSubtype 7 (FRAME_MJPEG)
bFrameIndex 4
bmCapabilities 0x00
Still image unsupported
wWidth 1280
wHeight 720
dwMinBitRate 737280000
dwMaxBitRate 884736000
dwMaxVideoFrameBufferSize 1843200
dwDefaultFrameInterval 166666
bFrameIntervalType 3
dwFrameInterval( 0) 166666
dwFrameInterval( 1) 166833
dwFrameInterval( 2) 200000
VideoStreaming Interface Descriptor:
bLength 46
bDescriptorType 36
bDescriptorSubtype 7 (FRAME_MJPEG)
bFrameIndex 5
bmCapabilities 0x00
Still image unsupported
wWidth 1920
wHeight 1080
dwMinBitRate 994332672
dwMaxBitRate 1990656000
dwMaxVideoFrameBufferSize 4147200
dwDefaultFrameInterval 166666
bFrameIntervalType 5
dwFrameInterval( 0) 166666
dwFrameInterval( 1) 166833
dwFrameInterval( 2) 200000
dwFrameInterval( 3) 333333
dwFrameInterval( 4) 333667
VideoStreaming Interface Descriptor:
bLength 6
bDescriptorType 36
bDescriptorSubtype 13 (COLORFORMAT)
bColorPrimaries 1 (BT.709,sRGB)
bTransferCharacteristics 1 (BT.709)
bMatrixCoefficients 4 (SMPTE 170M (BT.601))
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 1
bAlternateSetting 1
bNumEndpoints 1
bInterfaceClass 14 Video
bInterfaceSubClass 2 Video Streaming
bInterfaceProtocol 0
iInterface 8 AVerMedia Live Gamer HD 2
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x89 EP 9 IN
bmAttributes 5
Transfer Type Isochronous
Synch Type Asynchronous
Usage Type Data
wMaxPacketSize 0x1400 3x 1024 bytes
bInterval 1
Interface Association:
bLength 8
bDescriptorType 11
bFirstInterface 2
bInterfaceCount 2
bFunctionClass 1 Audio
bFunctionSubClass 2 Streaming
bFunctionProtocol 0
iFunction 9 AVerMedia Live Gamer HD 2
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 2
bAlternateSetting 0
bNumEndpoints 0
bInterfaceClass 1 Audio
bInterfaceSubClass 1 Control Device
bInterfaceProtocol 0
iInterface 9 AVerMedia Live Gamer HD 2
AudioControl Interface Descriptor:
bLength 9
bDescriptorType 36
bDescriptorSubtype 1 (HEADER)
bcdADC 1.00
wTotalLength 0x003a
bInCollection 1
baInterfaceNr(0) 3
AudioControl Interface Descriptor:
bLength 12
bDescriptorType 36
bDescriptorSubtype 2 (INPUT_TERMINAL)
bTerminalID 1
wTerminalType 0x0602 Digital Audio Interface
bAssocTerminal 0
bNrChannels 1
wChannelConfig 0x0000
iChannelNames 0
iTerminal 0
AudioControl Interface Descriptor:
bLength 12
bDescriptorType 36
bDescriptorSubtype 2 (INPUT_TERMINAL)
bTerminalID 5
wTerminalType 0x0603 Line Connector
bAssocTerminal 0
bNrChannels 1
wChannelConfig 0x0000
iChannelNames 0
iTerminal 0
AudioControl Interface Descriptor:
bLength 9
bDescriptorType 36
bDescriptorSubtype 3 (OUTPUT_TERMINAL)
bTerminalID 2
wTerminalType 0x0101 USB Streaming
bAssocTerminal 0
bSourceID 3
iTerminal 0
AudioControl Interface Descriptor:
bLength 8
bDescriptorType 36
bDescriptorSubtype 6 (FEATURE_UNIT)
bUnitID 3
bSourceID 4
bControlSize 1
bmaControls(0) 0x01
Mute Control
iFeature 0
AudioControl Interface Descriptor:
bLength 8
bDescriptorType 36
bDescriptorSubtype 5 (SELECTOR_UNIT)
bUnitID 4
bNrInPins 2
baSourceID(0) 1
baSourceID(1) 5
iSelector 0
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 3
bAlternateSetting 0
bNumEndpoints 0
bInterfaceClass 1 Audio
bInterfaceSubClass 2 Streaming
bInterfaceProtocol 0
iInterface 9 AVerMedia Live Gamer HD 2
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 3
bAlternateSetting 1
bNumEndpoints 1
bInterfaceClass 1 Audio
bInterfaceSubClass 2 Streaming
bInterfaceProtocol 0
iInterface 9 AVerMedia Live Gamer HD 2
AudioStreaming Interface Descriptor:
bLength 7
bDescriptorType 36
bDescriptorSubtype 1 (AS_GENERAL)
bTerminalLink 2
bDelay 1 frames
wFormatTag 0x0001 PCM
AudioStreaming Interface Descriptor:
bLength 11
bDescriptorType 36
bDescriptorSubtype 2 (FORMAT_TYPE)
bFormatType 1 (FORMAT_TYPE_I)
bNrChannels 2
bSubframeSize 2
bBitResolution 16
bSamFreqType 1 Discrete
tSamFreq[ 0] 48000
Endpoint Descriptor:
bLength 9
bDescriptorType 5
bEndpointAddress 0x8a EP 10 IN
bmAttributes 5
Transfer Type Isochronous
Synch Type Asynchronous
Usage Type Data
wMaxPacketSize 0x00c0 1x 192 bytes
bInterval 4
bRefresh 0
bSynchAddress 0
AudioStreaming Endpoint Descriptor:
bLength 7
bDescriptorType 37
bDescriptorSubtype 1 (EP_GENERAL)
bmAttributes 0x01
Sampling Frequency
bLockDelayUnits 0 Undefined
wLockDelay 0x0000
Binary Object Store Descriptor:
bLength 5
bDescriptorType 15
wTotalLength 0x0016
bNumDeviceCaps 2
USB 2.0 Extension Device Capability:
bLength 7
bDescriptorType 16
bDevCapabilityType 2
bmAttributes 0x00000006
BESL Link Power Management (LPM) Supported
SuperSpeed USB Device Capability:
bLength 10
bDescriptorType 16
bDevCapabilityType 3
bmAttributes 0x00
wSpeedsSupported 0x000e
Device can operate at Full Speed (12Mbps)
Device can operate at High Speed (480Mbps) Device can operate at SuperSpeed (5Gbps)
bFunctionalitySupport 1
Lowest fully-functional device speed is Full Speed (12Mbps)
bU1DevExitLat 4 micro seconds
bU2DevExitLat 4 micro seconds
Device Status: 0x0000
(Bus Powered)

---
 drivers/media/usb/uvc/uvc_driver.c | 9 +++++++++
 1 file changed, 9 insertions(+)
drivers/media/usb/uvc/uvc_driver.c +9 -0
index e2dab556ec996..663f07f9ca018 100644
@@ -2787,6 +2787,15 @@ static const struct usb_device_id uvc_ids[] = {
 	  .bInterfaceSubClass	= 1,
 	  .bInterfaceProtocol	= 0,
 	  .driver_info		= (kernel_ulong_t)&uvc_quirk_fix_bandwidth },
+	/* AVerMedia Live Gamer HD 2 capture card */
+	{ .match_flags		= USB_DEVICE_ID_MATCH_DEVICE
+				| USB_DEVICE_ID_MATCH_INT_INFO,
+	  .idVendor		= 0x07ca,
+	  .idProduct		= 0x1570,
+	  .bInterfaceClass	= USB_CLASS_VIDEO,
+	  .bInterfaceSubClass	= 1,
+	  .bInterfaceProtocol	= 0,
+	  .driver_info		= UVC_INFO_QUIRK(UVC_QUIRK_DISABLE_AUTOSUSPEND) },
 	/* ViMicro Vega */
 	{ .match_flags		= USB_DEVICE_ID_MATCH_DEVICE
 				| USB_DEVICE_ID_MATCH_INT_INFO,
Signature · 1 line
2.53.0
author maintainer
#785 lore raw

PATCH 780/1848 media: uvcvideo: Force UVC version to 1.0a for 1bcf:0b40

In reply to Greg Kroah-Hartman

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

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

From: Laurent Pinchart <[email protected]>

[ Upstream commit b400b6f28af040d55b4eb397ea7b8ece368c6b12 ]

The Shenzhen Aoni Electronic Co.,Ltd 2K FHD camera reports a UVC 1.10 version, but implements UVC 1.0a as shown by the UVC probe control being 26 bytes long. Force the UVC version for that device.

---
 drivers/media/usb/uvc/uvc_driver.c | 17 +++++++++++++++++
 drivers/media/usb/uvc/uvcvideo.h   |  1 +
 2 files changed, 18 insertions(+)
drivers/media/usb/uvc/uvc_driver.c +17 -0
index 663f07f9ca018..d070711b4f2d3 100644
@@ -2342,6 +2342,12 @@ static int uvc_probe(struct usb_interface *intf,
 			"linux-uvc-devel mailing list.\n");
 	}
 
+	if (dev->info->uvc_version) {
+		dev->uvc_version = dev->info->uvc_version;
+		uvc_printk(KERN_INFO, "Forcing UVC version to %u.%02x\n",
+			   dev->uvc_version >> 8, dev->uvc_version & 0xff);
+	}
+
 	/* Register the V4L2 device. */
 	if (v4l2_device_register(&intf->dev, &dev->vdev) < 0)
 		goto error;
@@ -3023,6 +3029,17 @@ static const struct usb_device_id uvc_ids[] = {
 	  .bInterfaceSubClass	= 1,
 	  .bInterfaceProtocol	= 0,
 	  .driver_info		= (kernel_ulong_t)&uvc_quirk_probe_minmax },
+	/* Shenzhen Aoni Electronic Co.,Ltd 2K FHD camera */
+	{ .match_flags		= USB_DEVICE_ID_MATCH_DEVICE
+				| USB_DEVICE_ID_MATCH_INT_INFO,
+	  .idVendor		= 0x1bcf,
+	  .idProduct		= 0x0b40,
+	  .bInterfaceClass	= USB_CLASS_VIDEO,
+	  .bInterfaceSubClass	= 1,
+	  .bInterfaceProtocol	= 0,
+	  .driver_info		= (kernel_ulong_t)&(const struct uvc_device_info){
+		.uvc_version = 0x010a,
+	  } },
 	/* SiGma Micro USB Web Camera */
 	{ .match_flags		= USB_DEVICE_ID_MATCH_DEVICE
 				| USB_DEVICE_ID_MATCH_INT_INFO,
drivers/media/usb/uvc/uvcvideo.h +1 -0
index 4a1ff08453d77..184ff2c10560a 100644
@@ -654,6 +654,7 @@ static inline u32 uvc_urb_index(const struct uvc_urb *uvc_urb)
 struct uvc_device_info {
 	u32	quirks;
 	u32	meta_format;
+	u16	uvc_version;
 };
 
 struct uvc_device {
Signature · 1 line
2.53.0
author maintainer
#786 lore raw

PATCH 781/1848 media: uvcvideo: Force UVC version for Avermedia GC515

In reply to Greg Kroah-Hartman

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

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

From: Ricardo Ribalda <[email protected]>

[ Upstream commit 65444446f0c595c0e250368cde88735b59ccc446 ]

The device announces itself as UVC 1.5, but it only accepts UVC 1.1 controls.

The camera can probably be handled by the automatic uvc_version handler, but it is more correct to add a quirk and keep some tracking of what vendors are more or less compliant. Also it might be more robust if we introduce more UVC version-dependent code.

Bus 003 Device 021: ID 07ca:1515 AVerMedia Technologies, Inc. X'tra Go GC515 Negotiated speed: High Speed (480Mbps)
Device Descriptor:
bLength 18
bDescriptorType 1
bcdUSB 2.00
bDeviceClass 239 Miscellaneous Device
bDeviceSubClass 2 [unknown]
bDeviceProtocol 1 Interface Association
bMaxPacketSize0 64
idVendor 0x07ca AVerMedia Technologies, Inc.
idProduct 0x1515 X'tra Go GC515
bcdDevice 0.10

  iManufacturer           1 AVerMedia
  iProduct                2 X'tra Go GC515
  iSerial                 3 5313180000221
  bNumConfigurations      1

Configuration Descriptor:
bLength 9
bDescriptorType 2
wTotalLength 0x03fd
bNumInterfaces 4
bConfigurationValue 1
iConfiguration 0
bmAttributes 0xc0
Self Powered
MaxPower 500mA
Interface Association:
bLength 8
bDescriptorType 11
bFirstInterface 0
bInterfaceCount 2
bFunctionClass 14 Video
bFunctionSubClass 3 Video Interface Collection
bFunctionProtocol 0
iFunction 0
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 0
bAlternateSetting 0
bNumEndpoints 1
bInterfaceClass 14 Video
bInterfaceSubClass 1 Video Control
bInterfaceProtocol 1
iInterface 0
VideoControl Interface Descriptor:
bLength 13
bDescriptorType 36
bDescriptorSubtype 1 (HEADER)
bcdUVC 1.50
wTotalLength 0x0059
dwClockFrequency 30.000000MHz
bInCollection 1
baInterfaceNr( 0) 1
VideoControl Interface Descriptor:
bLength 18
bDescriptorType 36
bDescriptorSubtype 2 (INPUT_TERMINAL)
bTerminalID 1
wTerminalType 0x0201 Camera Sensor
bAssocTerminal 0
iTerminal 0
wObjectiveFocalLengthMin 0
wObjectiveFocalLengthMax 0
wOcularFocalLength 0
bControlSize 3
bmControls 0x00000000
VideoControl Interface Descriptor:
bLength 9
bDescriptorType 36
bDescriptorSubtype 3 (OUTPUT_TERMINAL)
bTerminalID 2
wTerminalType 0x0101 USB Streaming
bAssocTerminal 0
bSourceID 4
iTerminal 0
VideoControl Interface Descriptor:
bLength 7
bDescriptorType 36
bDescriptorSubtype 4 (SELECTOR_UNIT)
bUnitID 3
bNrInPins 1
baSource( 0) 1
iSelector 0
VideoControl Interface Descriptor:
bLength 13
bDescriptorType 36
bDescriptorSubtype 5 (PROCESSING_UNIT)
bUnitID 4
bSourceID 3
wMaxMultiplier 0
bControlSize 3
bmControls 0x00000000
iProcessing 0
bmVideoStandards 0x00
VideoControl Interface Descriptor:
bLength 29
bDescriptorType 36
bDescriptorSubtype 6 (EXTENSION_UNIT)
bUnitID 5
guidExtensionCode {55be8e1c-2fdb-4f7a-bd8d-b9b1108d20c3}
bNumControls 24
bNrInPins 1
baSourceID( 0) 4
bControlSize 4
bmControls( 0) 0xff
bmControls( 1) 0xff
bmControls( 2) 0xff
bmControls( 3) 0x00
iExtension 0
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x85 EP 5 IN
bmAttributes 3
Transfer Type Interrupt
Synch Type None
Usage Type Data
wMaxPacketSize 0x0040 1x 64 bytes
bInterval 1
VideoControl Endpoint Descriptor:
bLength 5
bDescriptorType 37
bDescriptorSubtype 3 (EP_INTERRUPT)
wMaxTransferSize 64
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 1
bAlternateSetting 0
bNumEndpoints 1
bInterfaceClass 14 Video
bInterfaceSubClass 2 Video Streaming
bInterfaceProtocol 1
iInterface 0
VideoStreaming Interface Descriptor:
bLength 16
bDescriptorType 36
bDescriptorSubtype 1 (INPUT_HEADER)
bNumFormats 3
wTotalLength 0x0303
bEndpointAddress 0x81 EP 1 IN
bmInfo 0
bTerminalLink 2
bStillCaptureMethod 1
bTriggerSupport 0
bTriggerUsage 0
bControlSize 1
bmaControls( 0) 4
bmaControls( 1) 4
bmaControls( 2) 0
VideoStreaming Interface Descriptor:
bLength 28
bDescriptorType 36
bDescriptorSubtype 16 (FORMAT_FRAME_BASED)
bFormatIndex 1
bNumFrameDescriptors 8
guidFormat {34363248-0000-0010-8000-00aa00389b71}
bBitsPerPixel 24
bDefaultFrameIndex 1
bAspectRatioX 0
bAspectRatioY 0
bmInterlaceFlags 0x00
Interlaced stream or variable: No
Fields per frame: 2 fields
Field 1 first: No
Field pattern: Field 1 only
bCopyProtect 1
bVariableSize 1
VideoStreaming Interface Descriptor:
bLength 62
bDescriptorType 36
bDescriptorSubtype 17 (FRAME_FRAME_BASED)
bFrameIndex 1
bmCapabilities 0x01
Still image supported
wWidth 1920
wHeight 1080
dwMinBitRate 33554432
dwMaxBitRate 268435456
dwDefaultFrameInterval 166666
bFrameIntervalType 9
dwBytesPerLine 0
dwFrameInterval( 0) 83333
dwFrameInterval( 1) 83416
dwFrameInterval( 2) 166666
dwFrameInterval( 3) 166833
dwFrameInterval( 4) 200000
dwFrameInterval( 5) 333333
dwFrameInterval( 6) 333667
dwFrameInterval( 7) 400000
dwFrameInterval( 8) 416666
VideoStreaming Interface Descriptor:
bLength 42
bDescriptorType 36
bDescriptorSubtype 17 (FRAME_FRAME_BASED)
bFrameIndex 2
bmCapabilities 0x01
Still image supported
wWidth 3840
wHeight 2160
dwMinBitRate 33554432
dwMaxBitRate 268435456
dwDefaultFrameInterval 333333
bFrameIntervalType 4
dwBytesPerLine 0
dwFrameInterval( 0) 333333
dwFrameInterval( 1) 333667
dwFrameInterval( 2) 400000
dwFrameInterval( 3) 416666
VideoStreaming Interface Descriptor:
bLength 34
bDescriptorType 36
bDescriptorSubtype 17 (FRAME_FRAME_BASED)
bFrameIndex 3
bmCapabilities 0x01
Still image supported
wWidth 2560
wHeight 1440
dwMinBitRate 33554432
dwMaxBitRate 268435456
dwDefaultFrameInterval 166666
bFrameIntervalType 2
dwBytesPerLine 0
dwFrameInterval( 0) 166666
dwFrameInterval( 1) 166833
VideoStreaming Interface Descriptor:
bLength 34
bDescriptorType 36
bDescriptorSubtype 17 (FRAME_FRAME_BASED)
bFrameIndex 4
bmCapabilities 0x01
Still image supported
wWidth 1280
wHeight 800
dwMinBitRate 33554432
dwMaxBitRate 268435456
dwDefaultFrameInterval 166666
bFrameIntervalType 2
dwBytesPerLine 0
dwFrameInterval( 0) 166666
dwFrameInterval( 1) 166833
VideoStreaming Interface Descriptor:
bLength 38
bDescriptorType 36
bDescriptorSubtype 17 (FRAME_FRAME_BASED)
bFrameIndex 5
bmCapabilities 0x01
Still image supported
wWidth 1280
wHeight 720
dwMinBitRate 33554432
dwMaxBitRate 268435456
dwDefaultFrameInterval 166666
bFrameIntervalType 3
dwBytesPerLine 0
dwFrameInterval( 0) 166666
dwFrameInterval( 1) 166833
dwFrameInterval( 2) 200000
VideoStreaming Interface Descriptor:
bLength 34
bDescriptorType 36
bDescriptorSubtype 17 (FRAME_FRAME_BASED)
bFrameIndex 6
bmCapabilities 0x01
Still image supported
wWidth 720
wHeight 576
dwMinBitRate 33554432
dwMaxBitRate 268435456
dwDefaultFrameInterval 200000
bFrameIntervalType 2
dwBytesPerLine 0
dwFrameInterval( 0) 200000
dwFrameInterval( 1) 400000
VideoStreaming Interface Descriptor:
bLength 42
bDescriptorType 36
bDescriptorSubtype 17 (FRAME_FRAME_BASED)
bFrameIndex 7
bmCapabilities 0x01
Still image supported
wWidth 720
wHeight 480
dwMinBitRate 33554432
dwMaxBitRate 268435456
dwDefaultFrameInterval 166666
bFrameIntervalType 4
dwBytesPerLine 0
dwFrameInterval( 0) 166666
dwFrameInterval( 1) 166833
dwFrameInterval( 2) 333333
dwFrameInterval( 3) 333667
VideoStreaming Interface Descriptor:
bLength 34
bDescriptorType 36
bDescriptorSubtype 17 (FRAME_FRAME_BASED)
bFrameIndex 8
bmCapabilities 0x01
Still image supported
wWidth 640
wHeight 480
dwMinBitRate 33554432
dwMaxBitRate 268435456
dwDefaultFrameInterval 166666
bFrameIntervalType 2
dwBytesPerLine 0
dwFrameInterval( 0) 166666
dwFrameInterval( 1) 166833
VideoStreaming Interface Descriptor:
bLength 6
bDescriptorType 36
bDescriptorSubtype 13 (COLORFORMAT)
bColorPrimaries 0 (Unspecified)
bTransferCharacteristics 0 (Unspecified)
bMatrixCoefficients 0 (Unspecified)
VideoStreaming Interface Descriptor:
bLength 28
bDescriptorType 36
bDescriptorSubtype 16 (FORMAT_FRAME_BASED)
bFormatIndex 2
bNumFrameDescriptors 8
guidFormat {43564548-0000-0010-8000-00aa00389b71}
bBitsPerPixel 24
bDefaultFrameIndex 1
bAspectRatioX 0
bAspectRatioY 0
bmInterlaceFlags 0x00
Interlaced stream or variable: No
Fields per frame: 2 fields
Field 1 first: No
Field pattern: Field 1 only
bCopyProtect 1
bVariableSize 1
VideoStreaming Interface Descriptor:
bLength 62
bDescriptorType 36
bDescriptorSubtype 17 (FRAME_FRAME_BASED)
bFrameIndex 1
bmCapabilities 0x01
Still image supported
wWidth 1920
wHeight 1080
dwMinBitRate 33554432
dwMaxBitRate 268435456
dwDefaultFrameInterval 166666
bFrameIntervalType 9
dwBytesPerLine 0
dwFrameInterval( 0) 83333
dwFrameInterval( 1) 83416
dwFrameInterval( 2) 166666
dwFrameInterval( 3) 166833
dwFrameInterval( 4) 200000
dwFrameInterval( 5) 333333
dwFrameInterval( 6) 333667
dwFrameInterval( 7) 400000
dwFrameInterval( 8) 416666
VideoStreaming Interface Descriptor:
bLength 42
bDescriptorType 36
bDescriptorSubtype 17 (FRAME_FRAME_BASED)
bFrameIndex 2
bmCapabilities 0x01
Still image supported
wWidth 3840
wHeight 2160
dwMinBitRate 33554432
dwMaxBitRate 268435456
dwDefaultFrameInterval 333333
bFrameIntervalType 4
dwBytesPerLine 0
dwFrameInterval( 0) 333333
dwFrameInterval( 1) 333667
dwFrameInterval( 2) 400000
dwFrameInterval( 3) 416666
VideoStreaming Interface Descriptor:
bLength 34
bDescriptorType 36
bDescriptorSubtype 17 (FRAME_FRAME_BASED)
bFrameIndex 3
bmCapabilities 0x01
Still image supported
wWidth 2560
wHeight 1440
dwMinBitRate 33554432
dwMaxBitRate 268435456
dwDefaultFrameInterval 166666
bFrameIntervalType 2
dwBytesPerLine 0
dwFrameInterval( 0) 166666
dwFrameInterval( 1) 166833
VideoStreaming Interface Descriptor:
bLength 34
bDescriptorType 36
bDescriptorSubtype 17 (FRAME_FRAME_BASED)
bFrameIndex 4
bmCapabilities 0x01
Still image supported
wWidth 1280
wHeight 800
dwMinBitRate 33554432
dwMaxBitRate 268435456
dwDefaultFrameInterval 166666
bFrameIntervalType 2
dwBytesPerLine 0
dwFrameInterval( 0) 166666
dwFrameInterval( 1) 166833
VideoStreaming Interface Descriptor:
bLength 38
bDescriptorType 36
bDescriptorSubtype 17 (FRAME_FRAME_BASED)
bFrameIndex 5
bmCapabilities 0x01
Still image supported
wWidth 1280
wHeight 720
dwMinBitRate 33554432
dwMaxBitRate 268435456
dwDefaultFrameInterval 166666
bFrameIntervalType 3
dwBytesPerLine 0
dwFrameInterval( 0) 166666
dwFrameInterval( 1) 166833
dwFrameInterval( 2) 200000
VideoStreaming Interface Descriptor:
bLength 34
bDescriptorType 36
bDescriptorSubtype 17 (FRAME_FRAME_BASED)
bFrameIndex 6
bmCapabilities 0x01
Still image supported
wWidth 720
wHeight 576
dwMinBitRate 33554432
dwMaxBitRate 268435456
dwDefaultFrameInterval 200000
bFrameIntervalType 2
dwBytesPerLine 0
dwFrameInterval( 0) 200000
dwFrameInterval( 1) 400000
VideoStreaming Interface Descriptor:
bLength 42
bDescriptorType 36
bDescriptorSubtype 17 (FRAME_FRAME_BASED)
bFrameIndex 7
bmCapabilities 0x01
Still image supported
wWidth 720
wHeight 480
dwMinBitRate 33554432
dwMaxBitRate 268435456
dwDefaultFrameInterval 166666
bFrameIntervalType 4
dwBytesPerLine 0
dwFrameInterval( 0) 166666
dwFrameInterval( 1) 166833
dwFrameInterval( 2) 333333
dwFrameInterval( 3) 333667
VideoStreaming Interface Descriptor:
bLength 34
bDescriptorType 36
bDescriptorSubtype 17 (FRAME_FRAME_BASED)
bFrameIndex 8
bmCapabilities 0x01
Still image supported
wWidth 640
wHeight 480
dwMinBitRate 33554432
dwMaxBitRate 268435456
dwDefaultFrameInterval 166666
bFrameIntervalType 2
dwBytesPerLine 0
dwFrameInterval( 0) 166666
dwFrameInterval( 1) 166833
VideoStreaming Interface Descriptor:
bLength 6
bDescriptorType 36
bDescriptorSubtype 13 (COLORFORMAT)
bColorPrimaries 0 (Unspecified)
bTransferCharacteristics 0 (Unspecified)
bMatrixCoefficients 0 (Unspecified)
VideoStreaming Interface Descriptor:
bLength 11
bDescriptorType 36
bDescriptorSubtype 6 (FORMAT_MJPEG)
bFormatIndex 3
bNumFrameDescriptors 1
bFlags 0
Fixed-size samples: No
bDefaultFrameIndex 1
bAspectRatioX 0
bAspectRatioY 0
bmInterlaceFlags 0x00
Interlaced stream or variable: No
Fields per frame: 1 fields
Field 1 first: No
Field pattern: Field 1 only
bCopyProtect 1
VideoStreaming Interface Descriptor:
bLength 30
bDescriptorType 36
bDescriptorSubtype 7 (FRAME_MJPEG)
bFrameIndex 1
bmCapabilities 0x01
Still image supported
wWidth 1920
wHeight 1080
dwMinBitRate 314572800
dwMaxBitRate 314572800
dwMaxVideoFrameBufferSize 4147200
dwDefaultFrameInterval 166666
bFrameIntervalType 1
dwFrameInterval( 0) 166666
VideoStreaming Interface Descriptor:
bLength 6
bDescriptorType 36
bDescriptorSubtype 13 (COLORFORMAT)
bColorPrimaries 0 (Unspecified)
bTransferCharacteristics 0 (Unspecified)
bMatrixCoefficients 0 (Unspecified)
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x81 EP 1 IN
bmAttributes 2
Transfer Type Bulk
Synch Type None
Usage Type Data
wMaxPacketSize 0x0200 1x 512 bytes
bInterval 0
Interface Association:
bLength 8
bDescriptorType 11
bFirstInterface 2
bInterfaceCount 2
bFunctionClass 1 Audio
bFunctionSubClass 2 Streaming
bFunctionProtocol 0
iFunction 0
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 2
bAlternateSetting 0
bNumEndpoints 0
bInterfaceClass 1 Audio
bInterfaceSubClass 1 Control Device
bInterfaceProtocol 0
iInterface 0
AudioControl Interface Descriptor:
bLength 9
bDescriptorType 36
bDescriptorSubtype 1 (HEADER)
bcdADC 1.00
wTotalLength 0x0026
bInCollection 1
baInterfaceNr(0) 3
AudioControl Interface Descriptor:
bLength 12
bDescriptorType 36
bDescriptorSubtype 2 (INPUT_TERMINAL)
bTerminalID 1
wTerminalType 0x0602 Digital Audio Interface
bAssocTerminal 0
bNrChannels 2
wChannelConfig 0x0003
Left Front (L)
Right Front (R)
iChannelNames 0
iTerminal 0
AudioControl Interface Descriptor:
bLength 9
bDescriptorType 36
bDescriptorSubtype 3 (OUTPUT_TERMINAL)
bTerminalID 2
wTerminalType 0x0101 USB Streaming
bAssocTerminal 0
bSourceID 3
iTerminal 0
AudioControl Interface Descriptor:
bLength 8
bDescriptorType 36
bDescriptorSubtype 6 (FEATURE_UNIT)
bUnitID 3
bSourceID 1
bControlSize 1
bmaControls(0) 0x03
Mute Control
Volume Control
iFeature 0
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 3
bAlternateSetting 0
bNumEndpoints 0
bInterfaceClass 1 Audio
bInterfaceSubClass 2 Streaming
bInterfaceProtocol 0
iInterface 0
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 3
bAlternateSetting 1
bNumEndpoints 1
bInterfaceClass 1 Audio
bInterfaceSubClass 2 Streaming
bInterfaceProtocol 0
iInterface 0
AudioStreaming Interface Descriptor:
bLength 7
bDescriptorType 36
bDescriptorSubtype 1 (AS_GENERAL)
bTerminalLink 2
bDelay 1 frames
wFormatTag 0x0001 PCM
AudioStreaming Interface Descriptor:
bLength 11
bDescriptorType 36
bDescriptorSubtype 2 (FORMAT_TYPE)
bFormatType 1 (FORMAT_TYPE_I)
bNrChannels 2
bSubframeSize 2
bBitResolution 16
bSamFreqType 1 Discrete
tSamFreq[ 0] 48000
Endpoint Descriptor:
bLength 9
bDescriptorType 5
bEndpointAddress 0x83 EP 3 IN
bmAttributes 5
Transfer Type Isochronous
Synch Type Asynchronous
Usage Type Data
wMaxPacketSize 0x00c4 1x 196 bytes
bInterval 4
bRefresh 0
bSynchAddress 0
AudioStreaming Endpoint Descriptor:
bLength 7
bDescriptorType 37
bDescriptorSubtype 1 (EP_GENERAL)
bmAttributes 0x01
Sampling Frequency
bLockDelayUnits 0 Undefined
wLockDelay 0x0000

---
 drivers/media/usb/uvc/uvc_driver.c | 11 +++++++++++
 1 file changed, 11 insertions(+)
drivers/media/usb/uvc/uvc_driver.c +11 -0
index d070711b4f2d3..e9fe09ed6968a 100644
@@ -2793,6 +2793,17 @@ static const struct usb_device_id uvc_ids[] = {
 	  .bInterfaceSubClass	= 1,
 	  .bInterfaceProtocol	= 0,
 	  .driver_info		= (kernel_ulong_t)&uvc_quirk_fix_bandwidth },
+	/* Avermedia GC515 */
+	{ .match_flags		= USB_DEVICE_ID_MATCH_DEVICE
+				| USB_DEVICE_ID_MATCH_INT_INFO,
+	  .idVendor		= 0x07ca,
+	  .idProduct		= 0x1515,
+	  .bInterfaceClass	= USB_CLASS_VIDEO,
+	  .bInterfaceSubClass	= 1,
+	  .bInterfaceProtocol	= UVC_PC_PROTOCOL_15,
+	  .driver_info		= (kernel_ulong_t)&(const struct uvc_device_info){
+		.uvc_version = 0x0110,
+	  } },
 	/* AVerMedia Live Gamer HD 2 capture card */
 	{ .match_flags		= USB_DEVICE_ID_MATCH_DEVICE
 				| USB_DEVICE_ID_MATCH_INT_INFO,
Signature · 1 line
2.53.0
author maintainer
#787 lore raw

PATCH 782/1848 genirq/kexec: Do not take the bus lock of an interrupt chip on the crash path

In reply to Greg Kroah-Hartman

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

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

From: Igor Velkov <[email protected]>

commit 717862eac6eff0eea8ac30a0c0de0bed84922aab upstream.

machine_kexec_mask_interrupts() calls irq_set_irqchip_state() for every started interrupt. That function takes the bus lock of the chip and desc->lock, and syncs the chip when it drops them. On the crash path interrupts are off and the other CPUs are stopped, so a chip whose bus transfer is completed by an interrupt never returns from the sync.

On RK3399 boards with an RK808 PMIC the RTC alarm interrupt belongs to the regmap-irq chip of the RK808, which sits on I2C. rk808_irq_chip sets init_ack_masked, so regmap_irq_sync_unlock() writes the ack register on every unlock, and the I2C controller needs its own interrupt to finish the transfer. A panic with a crash kernel loaded prints

SMP: stopping secondary CPUs

and then nothing until the watchdog resets the board.

machine_kexec_mask_interrupts() takes neither lock for the other operations on the descriptor. Move the search for the chip that implements irq_set_irqchip_state() into __irq_set_irqchip_state(), which takes no locks, and call it from machine_kexec_mask_interrupts().

---
 arch/arm64/kernel/machine_kexec.c |  2 +-
 include/linux/interrupt.h         |  1 +
 kernel/irq/manage.c               | 49 ++++++++++++++++---------------
 3 files changed, 27 insertions(+), 25 deletions(-)
arch/arm64/kernel/machine_kexec.c +1 -1
index a0b144cfaea71..f36a37eee1cd4 100644
@@ -230,7 +230,7 @@ static void machine_kexec_mask_interrupts(void)
 		 * First try to remove the active state. If this
 		 * fails, try to EOI the interrupt.
 		 */
-		ret = irq_set_irqchip_state(i, IRQCHIP_STATE_ACTIVE, false);
+		ret = __irq_set_irqchip_state(desc, IRQCHIP_STATE_ACTIVE, false);
 
 		if (ret && irqd_irq_inprogress(&desc->irq_data) &&
 		    chip->irq_eoi)
include/linux/interrupt.h +1 -0
index 3b85bebd82d5e..e52c742715847 100644
@@ -520,6 +520,7 @@ extern int irq_get_irqchip_state(unsigned int irq, enum irqchip_irq_state which,
 				 bool *state);
 extern int irq_set_irqchip_state(unsigned int irq, enum irqchip_irq_state which,
 				 bool state);
+extern int __irq_set_irqchip_state(struct irq_desc *desc, enum irqchip_irq_state which, bool val);
 
 #ifdef CONFIG_IRQ_FORCED_THREADING
 # ifdef CONFIG_PREEMPT_RT
kernel/irq/manage.c +25 -24

67 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#788 lore raw

PATCH 783/1848 efi/libstub: arm64: Dont use the platform register x18

In reply to Greg Kroah-Hartman

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

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

From: Ard Biesheuvel <[email protected]>

commit 4c86b5f3fa78347fa9cbc9e8ec06615b2f80e397 upstream

The UEFI specification designates x18, the platform register, as "do not use" on AArch64, so that UEFI code is compatible both with an OS that assigns a fixed role to x18, and with one that uses it as a temporary register.

The arm64 EFI stub and the EFI zboot decompressor only avoid x18 if the kernel is built with shadow call stacks, as that is the only case where -ffixed-x18 is added to KBUILD_CFLAGS, which the stub inherits. Otherwise, the compiler is free to use x18 as a temporary register, and it does so.

So pass -ffixed-x18 unconditionally when building the stub for arm64, so that the image can be run by loaders that rely on x18 being left alone, such as a kernel that uses it for its shadow call stack.

---
 drivers/firmware/efi/libstub/Makefile | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/firmware/efi/libstub/Makefile +1 -1
index d719134e2d3aa..b17a082675430 100644
@@ -19,7 +19,7 @@ cflags-$(CONFIG_X86)		+= -m$(BITS) -D__KERNEL__ -std=gnu89 \
 # arm64 uses the full KBUILD_CFLAGS so it's necessary to explicitly
 # disable the stackleak plugin
 cflags-$(CONFIG_ARM64)		:= $(subst $(CC_FLAGS_FTRACE),,$(KBUILD_CFLAGS)) \
-				   -fpie $(DISABLE_STACKLEAK_PLUGIN) \
+				   -fpie $(DISABLE_STACKLEAK_PLUGIN) -ffixed-x18 \
 				   $(call cc-option,-mbranch-protection=none)
 cflags-$(CONFIG_ARM)		:= $(subst $(CC_FLAGS_FTRACE),,$(KBUILD_CFLAGS)) \
 				   -fno-builtin -fpic \
Signature · 1 line
2.53.0
author maintainer
#789 lore raw

PATCH 784/1848 net: atl1c: drop oversized RX frames instead of panicking

In reply to Greg Kroah-Hartman

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

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

From: Federico Musto <[email protected]>

[ Upstream commit c4ba1716853de5178a9df785844ebb5e397a80e6 ]

atl1c sizes its receive buffers from the netdev MTU plus a fixed set of L2 overheads, which comes to 1522 bytes at the default MTU. A link partner that sends a longer frame - in practice a MikroTik CCR2004-1G-2XS-PCIe, whose RouterOS side defaults to l2mtu 1600 while the host stays at MTU 1500
- makes the length reported by the RX return descriptor exceed what the hardware wrote, and skb_put() then either includes bytes that were never received or trips skb_over_panic and takes the host down.

Compare the descriptor length against buffer_info->length, the length the hardware was given, rather than against skb_tailroom(): the skb carries 64 bytes of slack for the DMA erratum, so tailroom is larger than the DMA buffer and a frame in between would pass the check and still be delivered with a tail the device never wrote. The same test rejects frames shorter than ETH_HLEN + ETH_FCS_LEN; before this change a reported length below ETH_FCS_LEN underflowed in skb_put().

The frame is dropped with kfree_skb_reason(SKB_DROP_REASON_PKT_TOO_BIG) so drop_monitor and the kfree_skb tracepoint see it, and counted through dev_core_stats_rx_dropped_inc(), which survives atl1c_get_stats() overwriting the hardware counters on every read. It also counts as work:
atl1c_clean_rfd() has already recycled the RFD, and the refill at the end of the poll only runs when work_done is non-zero, so sustained oversized traffic would otherwise drain the ring and stop RX.

Tested on a MikroTik CCR2004-1G-2XS-PCIe (4x AR8151) in a Proxmox VE host, with atl1c built from a DKMS tree carrying this change: the l2mtu-1600 traffic that panics the stock driver is dropped and counted with the patch applied, and received normally once the host MTU is raised to match.

This complements commit 36c2009d90f2 ("net: atl1c: fix soft lockup on out-of-range tpd_cons read"), which fixed the TX side of the same "host dies while the card resets" problem.

Fixes 43250ddd75a3 ("atl1c: Atheros L1C Gigabit Ethernet driver")

[ Federico Musto: 5.10.y has neither dev_core_stats_rx_dropped_inc() nor
kfree_skb_reason(): count the drop in netdev->rx_dropped, the counter dev_core_stats replaced, which dev_get_stats() adds to what atl1c_get_stats() returns, and free the skb with kfree_skb(). The RX loop is atl1c_clean_rx_irq() here: work_done is an int * and the refill at the end of the poll is gated on the local count, so the drop path bumps both. 5.10.y does not have the 64 bytes of RX slack from commit 86565682e905 ("atl1c: Work around the DMA RX overflow issue"), but the skb can still be larger than the buffer mapped for DMA, so the bound is the same and only the comment is reworded. Build-tested only, not run on hardware. ]

---
 .../net/ethernet/atheros/atl1c/atl1c_main.c   | 34 +++++++++++++++++++
 1 file changed, 34 insertions(+)
drivers/net/ethernet/atheros/atl1c/atl1c_main.c +34 -0
index 46a293b8a21c9..1a930cdf285cf 100644
@@ -1844,6 +1844,40 @@ static void atl1c_clean_rx_irq(struct atl1c_adapter *adapter,
 			break;
 		}
 		atl1c_clean_rfd(rfd_ring, rrs, rfd_num);
+
+		/* A link partner whose l2mtu is larger than ours can hand us a
+		 * frame that does not fit the buffer the hardware was given:
+		 * the descriptor reports the untruncated length while at most
+		 * buffer_info->length bytes were written.  skb_put() of such a
+		 * length would pull in whatever the tail of the buffer holds
+		 * and, past the end of the skb, trips skb_over_panic and takes
+		 * the host down.  Bound it by what the device actually wrote
+		 * rather than by skb_tailroom(): the skb can be larger than
+		 * the buffer mapped for DMA, so the two are not the same.
+		 *
+		 * Frames shorter than an Ethernet header plus its FCS are
+		 * rejected by the same test; before this, a length below
+		 * ETH_FCS_LEN underflowed in skb_put().
+		 */
+		if (unlikely(length < ETH_HLEN + ETH_FCS_LEN ||
+			     length > buffer_info->length)) {
+			atomic_long_inc(&netdev->rx_dropped);
+			if (netif_msg_rx_err(adapter))
+				dev_warn_ratelimited(&pdev->dev,
+						     "dropped rx frame: %u bytes, buffer %u\n",
+						     length, buffer_info->length);
+			kfree_skb(skb);
+			/* atl1c_clean_rfd() has already recycled the RFD, so
+			 * count the drop as work: the refill at the end of the
+			 * poll only runs when count is non-zero, and
+			 * sustained oversized traffic would otherwise drain the
+			 * ring and stop RX for good.
+			 */
+			(*work_done)++;
+			count++;
+			continue;
+		}
+
 		skb_put(skb, length - ETH_FCS_LEN);
 		skb->protocol = eth_type_trans(skb, netdev);
 		atl1c_rx_checksum(adapter, skb, rrs);
Signature · 1 line
2.53.0
author maintainer
#790 lore raw

PATCH 785/1848 f2fs: force out-place update for all writes on compressed file

In reply to Greg Kroah-Hartman

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

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

From: Jiucheng Xu <[email protected]>

commit a64a3fec11e77a3a0dc0009bdc58b925e45a1bb4 upstream.

For compressed file, compressed write may fail and fall back to raw write.

-Thread A - Thread B

  - f2fs_write_multi_pages                          - f2fs_down_write(&sbi->cp_rwsem);
   - f2fs_write_compressed_pages                    - ...
    - f2fs_trylock_op                               - ...
     - f2fs_down_read_trylock(&sbi->cp_rwsem);      - ...
   - f2fs_write_raw_pages                           - ...

Thread B acquires the lock first, which causes Thread A to fail lock acquisition and fall back to raw-data write.
IPU_FORCE is enabled on small-capacity storage devices (< 16GB), so f2fs_write_raw_pages() overwrites the original compressed data in-place.

The in-memory node has been updated with raw-data addresses, while the node metadata stored on eMMC still remains in compressed state. If a power-cut occurs before the node is flushed to disk, on-disk inconsistency arises: disk data is raw, yet metadata treats it as a compressed cluster, leading to decompression failure.

To eliminate this risk completely, force out-place update for all write operations on compressed file.

Fixes 4c8ff7095bef ("f2fs: support data compression")
(cherry picked from commit a64a3fec11e77a3a0dc0009bdc58b925e45a1bb4)
---
 fs/f2fs/data.c | 8 ++++++++
 1 file changed, 8 insertions(+)
fs/f2fs/data.c +8 -0
index 2933b32032e79..f3ff1865868c3 100644
@@ -2669,6 +2669,14 @@ bool f2fs_should_update_outplace(struct inode *inode, struct f2fs_io_info *fio)
 		return true;
 	if (f2fs_is_atomic_file(inode))
 		return true;
+	/*
+	 * rewrite low ratio compress data w/ OPU mode to avoid fragmentation.
+	 * If IO comes from compressed write path and fallback to raw write,
+	 * force out-place to prevent metadata-data inconsistency.
+	 */
+	if (f2fs_compressed_file(inode))
+		return true;
+
 	if (fio) {
 		if (is_cold_data(fio->page))
 			return true;
Signature · 1 line
2.53.0
author maintainer
#791 lore raw

PATCH 786/1848 f2fs: allow pinning empty compressed files

In reply to Greg Kroah-Hartman

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

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

From: Joanne Chang <[email protected]>

commit 2eebc31ae5f53e1066bb6238c8087c23b688ad17 upstream.

Commit a64a3fec11e7 ("f2fs: force out-place update for all writes on compressed file") updated f2fs_should_update_outplace() to always return true for compressed files. However, this function is also called during f2fs_ioc_set_pin_file() validation, so pinning an empty file with compression enabled now fails with -EINVAL before the compression flag can be stripped.

Fix this by guarding the f2fs_compressed_file(inode) check with fio in f2fs_should_update_outplace(). This preserves forced OPU for actual compressed writes (fio != NULL), while allowing f2fs_ioc_set_pin_file() (fio == NULL) to proceed to f2fs_disable_compressed_file(inode).

Fixes a64a3fec11e7 ("f2fs: force out-place update for all writes on compressed file")
Assisted-by LLM
(cherry picked from commit 2eebc31ae5f53e1066bb6238c8087c23b688ad17)
---
 fs/f2fs/data.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/f2fs/data.c +1 -1
index f3ff1865868c3..512aeb6a0f989 100644
@@ -2674,7 +2674,7 @@ bool f2fs_should_update_outplace(struct inode *inode, struct f2fs_io_info *fio)
 	 * If IO comes from compressed write path and fallback to raw write,
 	 * force out-place to prevent metadata-data inconsistency.
 	 */
-	if (f2fs_compressed_file(inode))
+	if (fio && f2fs_compressed_file(inode))
 		return true;
 
 	if (fio) {
Signature · 1 line
2.53.0
author maintainer
#792 lore raw

PATCH 787/1848 iommu/amd: Force device table to maximum size

In reply to Greg Kroah-Hartman

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

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

From: Suravee Suthikulpanit <[email protected]>

commit 6e2213dae78b41976c60133eb10cf99e81916638 upstream.

IOMMU can perform out-of-bounds read of the device table entry (DTE) that is adjacent to the last DTE and falls outside the device table. For example, if the device table can hold 0 to N-1 entries, then the IOMMU can be made to fetch the Nth entry, which falls outside the device table.

The device table is owned by the hypervisor (HV) and is assigned in 4KB pages that are contiguous in system physical address (SPA). If the out-of-bound DTE falls on a guest-owned page, then the guest can exploit this bug to setup malicious table walks to corrupt HV pages and/or bring down the system. Note that this bug does not manifest when the device table size is set to its maximum size of 2MB.

Therefore, force the device table size to the maximum 2MB on affected processors. These are CPU family 0x17 (Zen1/Zen2) through family 0x1a (Zen5/BRH).

This is a mitigation for CVE-2024-21963.

kdump copies the previous kernel's device table only when the size encoded in the IOMMU device-table register matches dev_table_size. A mixed rollout disagrees: the unpatched kernel uses the IVRS-derived size and the patched kernel uses 2MB, so copy_device_table() rejects the table and reinitializes translation. Kernels that both have this patch agree on 2MB and the copy succeeds. Update the production kernel and the crash kernel together.

This kernel has one global device table. Only that size is forced to 2MB. Alias and rlookup sizes stay derived from the IVRS.

This backport adds X86_FEATURE_ZEN6. Bit 3*32+6 is still X86_FEATURE_P3 here, so the new flag uses free bit 21*32+7. Family 0x1a models 0x50-0x5f, 0x80-0xaf, 0xc0-0xcf, and 0xd8-0xef are Zen6 and are excluded from the workaround. This kernel has no X86_FEATURE_ZEN5. Other family 0x1a models stay unmarked and still take the 2MB device table.

---
 arch/x86/include/asm/cpufeatures.h |  6 ++++++
 arch/x86/kernel/cpu/amd.c          | 18 ++++++++++++++++++
 drivers/iommu/amd/init.c           | 23 ++++++++++++++++++++++-
 3 files changed, 46 insertions(+), 1 deletion(-)
arch/x86/include/asm/cpufeatures.h +6 -0
index 19a18df50a2ea..12928845f136c 100644
@@ -416,6 +416,12 @@
 #define X86_FEATURE_IBPB_BRTYPE		(20*32+28) /* "" MSR_PRED_CMD[IBPB] flushes all branch type predictions */
 #define X86_FEATURE_SRSO_NO		(20*32+29) /* "" CPU is not affected by SRSO */
 
+/*
+ * Upstream defines X86_FEATURE_ZEN6 as (3*32+6). That bit is still
+ * X86_FEATURE_P3 in this kernel, so use a free bit in this word.
+ */
+#define X86_FEATURE_ZEN6		(21*32+7) /* "" CPU based on Zen6 microarchitecture */
+
 #define X86_FEATURE_TSA_SQ_NO          (22*32+11) /* "" AMD CPU not vulnerable to TSA-SQ */
 #define X86_FEATURE_TSA_L1_NO          (22*32+12) /* "" AMD CPU not vulnerable to TSA-L1 */
 #define X86_FEATURE_CLEAR_CPU_BUF_VM   (22*32+13) /* "" Clear CPU buffers using VERW before VMRUN */
arch/x86/kernel/cpu/amd.c +18 -0
index 0ded215bcaf63..2abed4f24dbc9 100644
@@ -769,6 +769,24 @@ static void bsp_init_amd(struct cpuinfo_x86 *c)
 		}
 		break;
 	}
+	case 0x1a: {
+		switch (c->x86_model) {
+		case 0x50 ... 0x5f:
+		case 0x80 ... 0xaf:
+		case 0xc0 ... 0xcf:
+		case 0xd8 ... 0xef:
+			setup_force_cpu_cap(X86_FEATURE_ZEN6);
+			break;
+		default:
+			/*
+			 * Zen5 models in family 0x1a have no feature bit
+			 * in this kernel. Leave them unmarked so the
+			 * device-table workaround still applies.
+			 */
+			break;
+		}
+		break;
+	}
 	default:
 		break;
 	}
drivers/iommu/amd/init.c +22 -1
index cccbe59c2604e..c643ea095c972 100644
@@ -21,6 +21,7 @@
 #include <linux/kmemleak.h>
 #include <linux/mem_encrypt.h>
 #include <linux/iopoll.h>
+#include <linux/sizes.h>
 #include <asm/pci-direct.h>
 #include <asm/iommu.h>
 #include <asm/apic.h>
@@ -2664,6 +2665,21 @@ static void __init ivinfo_init(void *ivrs)
 	amd_iommu_ivinfo = *((u32 *)(ivrs + IOMMU_IVINFO_OFFSET));
 }
 
+/*
+ * Apply workaround for Zen1 to Zen5(BRH) generation of processors.
+ * References: CVE-2024-21963
+ */
+static bool __init amd_iommu_force_max_dev_table(void)
+{
+	if (boot_cpu_data.x86 >= 0x17 && boot_cpu_data.x86 <= 0x1a) {
+		if (cpu_feature_enabled(X86_FEATURE_ZEN6))
+			return false;
+		else
+			return true;
+	}
+	return false;
+}
+
 /*
  * This is the hardware init function for AMD IOMMU in the system.
  * This function is called either from amd_iommu_init or from the interrupt
@@ -2732,7 +2748,12 @@ static int __init early_amd_iommu_init(void)
 	if (ret)
 		goto out;
 
-	dev_table_size     = tbl_size(DEV_TABLE_ENTRY_SIZE);
+	if (amd_iommu_force_max_dev_table()) {
+		pr_info("Force device table to maximum size\n");
+		dev_table_size = SZ_2M;
+	} else {
+		dev_table_size = tbl_size(DEV_TABLE_ENTRY_SIZE);
+	}
 	alias_table_size   = tbl_size(ALIAS_TABLE_ENTRY_SIZE);
 	rlookup_table_size = tbl_size(RLOOKUP_TABLE_ENTRY_SIZE);
 
Signature · 1 line
2.53.0
author maintainer
#793 lore raw

PATCH 788/1848 drm/nouveau/svm: drain fault handler before freeing svmm

In reply to Greg Kroah-Hartman

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

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

From: Zhenhao Wan <[email protected]>

[ Upstream commit b46ddaf0823405f81e681eb26ec98508f3eb9a07 ]

The SVM fault handler nouveau_svm_fault() looks up each fault's nouveau_svmm under svm->mutex, caches it in the fault array, then drops svm->mutex and dereferences the svmm across blocking faults (mmu_interval_notifier_insert(), hmm_range_fault()).

nouveau_svmm is not refcounted. On DRM file close nouveau_svmm_fini() -> mmu_notifier_put() frees it asynchronously via call_srcu() without waiting for the handler, and mmget_not_zero() pins the mm, not the svmm. flush_work() on the fault buffer otherwise runs only at device removal and suspend, never on close, so a fault handled concurrently with a close can dereference a freed svmm.

The instance is already unlinked by nouveau_svmm_part() earlier in the same close, so no new fault can resolve to it. Drain the handler in nouveau_svmm_fini() before the free, guarding the flush with a NULL check on drm->svm: on device teardown nouveau_svm_fini() runs first and frees drm->svm (NULL) after blocking the notify and flushing the buffer, so the handler is already drained; on per-client close drm->svm is alive and the flush runs.

Fixes eeaf06ac1a55 ("drm/nouveau/svm: initial support for shared virtual memory")
Assisted-by Claude:claude-opus-5
---
 drivers/gpu/drm/nouveau/nouveau_svm.c | 13 +++++++++++++
 1 file changed, 13 insertions(+)
drivers/gpu/drm/nouveau/nouveau_svm.c +13 -0
index f67700c028c75..a723c72049df0 100644
@@ -302,6 +302,19 @@ nouveau_svmm_fini(struct nouveau_svmm **psvmm)
 {
 	struct nouveau_svmm *svmm = *psvmm;
 	if (svmm) {
+		struct nouveau_svm *svm = svmm->vmm->cli->drm->svm;
+
+		/* The fault handler caches svmm pointers under svm->mutex and
+		 * dereferences them after dropping it, across blocking faults.
+		 * The instance is already unlinked (nouveau_svmm_part), so drain
+		 * the handler before the free to release any in-flight reference.
+		 *
+		 * On device teardown nouveau_svm_fini() ran first and freed
+		 * drm->svm (NULL) after draining the buffer; nothing to flush.
+		 */
+		if (svm)
+			flush_work(&svm->buffer[0].notify.work);
+
 		mutex_lock(&svmm->mutex);
 		svmm->vmm = NULL;
 		mutex_unlock(&svmm->mutex);
Signature · 1 line
2.53.0
author maintainer
#794 lore raw

PATCH 789/1848 aio: prevent eventfd/epoll recursion on poll

In reply to Greg Kroah-Hartman

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

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

From: Daehyeon Ko <[email protected]>

[ Upstream commit 398e3fa789aa5ffddc8689d8cbc7b31e1824130c ]

aio_poll_wake() can complete a keyed poll request inline while the provider waitqueue lock is held. If the polled file is an epoll instance and the AIO result eventfd is watched by that same instance, signaling the result can feed back into epoll and try to take the provider waitqueue lock again.

For example, a timerfd wake can follow this path:

timerfd -> ep_poll_callback -> aio_poll_wake -> aio_complete

          -> eventfd_signal -> ep_poll_callback -> ep_poll_safewake

The second ep_poll_safewake() recursively acquires ep->poll_wait.lock. eventfd_signal_allowed() does not prevent this because the wake chain did not begin in eventfd, so the task's eventfd recursion bit is still clear when aio_poll_wake() decides to complete inline.

An unprivileged process can construct this graph and make a CPU spin on the recursive lock. DEBUG_SPINLOCK reports "BUG: spinlock recursion", and lockdep reports the same epoll waitqueue lock as both held and requested.

Always defer eventfd-backed poll completions through the existing aio_poll_put_work() path. At this point the request has already been detached from the waitqueue and active request list, so the work item can publish the completion after the provider callback releases its lock. Poll completions without a result eventfd remain inline.

Fixes e8693bcfa0b4 ("aio: allow direct aio poll comletions for keyed wakeups")
[ sashal: Removed the existing eventfd_signal_count() check instead of upstream's !eventfd_signal_allowed() check. ]
---
 fs/aio.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
fs/aio.c +6 -1
index 22b6e20322741..16ceed755b7e5 100644
@@ -1777,7 +1777,12 @@ static int aio_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
 		list_del_init(&req->wait.entry);
 		list_del(&iocb->ki_list);
 		iocb->ki_res.res = mangle_poll(mask);
-		if (iocb->ki_eventfd && eventfd_signal_count()) {
+		/*
+		 * We hold an arbitrary provider waitqueue lock here.  Signaling a
+		 * result eventfd can feed back through epoll and try to take the same
+		 * lock again.  Defer all eventfd-backed poll completions.
+		 */
+		if (iocb->ki_eventfd) {
 			iocb = NULL;
 			INIT_WORK(&req->work, aio_poll_put_work);
 			schedule_work(&req->work);
Signature · 1 line
2.53.0
author maintainer
#795 lore raw

PATCH 790/1848 udf: Avoid invalid LVID used on mount

In reply to Greg Kroah-Hartman

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

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

From: Jan Kara <[email protected]>

[ Upstream commit c8f1140cb82dc843e72697dc6f8c7ee1acce5d28 ]

udf_load_logicalvolint() loads logical volume integrity descriptors. Since there can be multiple blocks with LVIDs, we verify the contents of only the last (prevailing) LVID found. However if we fail to load the last LVID (either due to IO error or because it's checksum fails to match), we never perform the verification of validity of the LVID we are going to use. If such LVID contains invalid data, we can hit out-of-bounds access or similar issues. Fix the problem by verifying each LVID we are potentially going to accept.

Stable-dep-of: a61fb39759d7 ("udf: Make sure there's enough space for LVID implementation use field")

---
 fs/udf/super.c | 42 +++++++++++++++++++++++++-----------------
 1 file changed, 25 insertions(+), 17 deletions(-)
fs/udf/super.c +25 -17
index 467e760863486..58bc19b82afa4 100644
@@ -1574,6 +1574,20 @@ static int udf_load_logicalvol(struct super_block *sb, sector_t block,
 	return ret;
 }
 
+static bool udf_lvid_valid(struct super_block *sb,
+			   struct logicalVolIntegrityDesc *lvid)
+{
+	u32 parts, impuselen;
+
+	parts = le32_to_cpu(lvid->numOfPartitions);
+	impuselen = le32_to_cpu(lvid->lengthOfImpUse);
+	if (parts >= sb->s_blocksize || impuselen >= sb->s_blocksize ||
+	    sizeof(struct logicalVolIntegrityDesc) + impuselen +
+	    2 * parts * sizeof(u32) > sb->s_blocksize)
+		return false;
+	return true;
+}
+
 /*
  * Find the prevailing Logical Volume Integrity Descriptor.
  */
@@ -1584,7 +1598,6 @@ static void udf_load_logicalvolint(struct super_block *sb, struct kernel_extent_
 	struct udf_sb_info *sbi = UDF_SB(sb);
 	struct logicalVolIntegrityDesc *lvid;
 	int indirections = 0;
-	u32 parts, impuselen;
 
 	while (++indirections <= UDF_MAX_LVID_NESTING) {
 		final_bh = NULL;
@@ -1606,32 +1619,27 @@ static void udf_load_logicalvolint(struct super_block *sb, struct kernel_extent_
 		if (!final_bh)
 			return;
 
-		brelse(sbi->s_lvid_bh);
-		sbi->s_lvid_bh = final_bh;
-
 		lvid = (struct logicalVolIntegrityDesc *)final_bh->b_data;
+		if (udf_lvid_valid(sb, lvid)) {
+			brelse(sbi->s_lvid_bh);
+			sbi->s_lvid_bh = final_bh;
+		} else {
+			udf_warn(sb, "Corrupted LVID (parts=%u, impuselen=%u), "
+				 "ignoring.\n",
+				 le32_to_cpu(lvid->numOfPartitions),
+				 le32_to_cpu(lvid->lengthOfImpUse));
+		}
+
 		if (lvid->nextIntegrityExt.extLength == 0)
-			goto check;
+			return;
 
 		loc = leea_to_cpu(lvid->nextIntegrityExt);
 	}
 
 	udf_warn(sb, "Too many LVID indirections (max %u), ignoring.\n",
 		UDF_MAX_LVID_NESTING);
-out_err:
 	brelse(sbi->s_lvid_bh);
 	sbi->s_lvid_bh = NULL;
-	return;
-check:
-	parts = le32_to_cpu(lvid->numOfPartitions);
-	impuselen = le32_to_cpu(lvid->lengthOfImpUse);
-	if (parts >= sb->s_blocksize || impuselen >= sb->s_blocksize ||
-	    sizeof(struct logicalVolIntegrityDesc) + impuselen +
-	    2 * parts * sizeof(u32) > sb->s_blocksize) {
-		udf_warn(sb, "Corrupted LVID (parts=%u, impuselen=%u), "
-			 "ignoring.\n", parts, impuselen);
-		goto out_err;
-	}
 }
 
 /*
Signature · 1 line
2.53.0
author maintainer
#796 lore raw

PATCH 791/1848 udf: Make sure theres enough space for LVID implementation use field

In reply to Greg Kroah-Hartman

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

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

From: Jan Kara <[email protected]>

[ Upstream commit a61fb39759d719a4f4966742b4d28387e33d81c4 ]

udf_lvid_valid() verifies that the LVID has enough space for all the tables and the reported length of ImplementationUse field. However it doesn't make sure the reported length is large enough to contain logicalVolIntegrityDescImpUse structure which OSTA specification requires. This can thus lead to accesses beyond the end of LVID buffer for suitably corrupted UDF filesystem. Add the length check.

---
 fs/udf/super.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
fs/udf/super.c +4 -1
index 58bc19b82afa4..6994cf6a09d66 100644
@@ -1581,7 +1581,10 @@ static bool udf_lvid_valid(struct super_block *sb,
 
 	parts = le32_to_cpu(lvid->numOfPartitions);
 	impuselen = le32_to_cpu(lvid->lengthOfImpUse);
-	if (parts >= sb->s_blocksize || impuselen >= sb->s_blocksize ||
+	if (sizeof(struct logicalVolIntegrityDescImpUse) > impuselen ||
+	    impuselen >= sb->s_blocksize)
+		return false;
+	if (parts >= sb->s_blocksize ||
 	    sizeof(struct logicalVolIntegrityDesc) + impuselen +
 	    2 * parts * sizeof(u32) > sb->s_blocksize)
 		return false;
Signature · 1 line
2.53.0
author maintainer
#797 lore raw

PATCH 792/1848 crypto: algif_skcipher - rewind rounded output bytes

In reply to Greg Kroah-Hartman

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

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

From: Daehyeon Ko <[email protected]>

[ Upstream commit 2f90facc7b94934653eb7ebfadcc25d503b89196 ]

af_alg_get_rsgl() advances the receive iterator by the unrounded RX scatterlist length. For a continuing skcipher request, _skcipher_recvmsg() then rounds its local length down to a whole chunksize without restoring the iterator.

A later chunk starts after bytes which the provider never wrote, while the syscall returns only the processed length. When copy_splice_read() supplies non-zeroed pages and publishes that return as a dense prefix, the gap exposes stale bytes from a previous page lifetime.

With unprivileged xts(aes), a 31-byte MSG_MORE request followed by one final byte advances a 47-byte destination while returning 32 bytes. A hardened v7.2-rc5 image retained all 15 seeded stale bytes in 4,829 of 4,829 records. With init_on_alloc enabled, all 72,345 gap bytes observed were zero.

Rewind the iterator by the tail excluded during rounding, before rejecting a zero processed length. The crypto request uses only the rounded length; af_alg_free_resources() releases the entire RX list before another receive iteration.

The fixed target-like kernel returned byte-identical dense 48-byte output in 4,771 of 4,771 rounds. The unmodified kernel returned the vulnerable 32-byte short record in 2,409 of 2,409 rounds.

Fixes e870456d8e7c ("crypto: algif_skcipher - overhaul memory management")
Assisted-by LLM
[ sashal: added the zero-length guard where no short-input check previously existed ]
---
 crypto/algif_skcipher.c | 13 +++++++++++--
 1 file changed, 11 insertions(+), 2 deletions(-)
crypto/algif_skcipher.c +11 -2
index 6a1a71284fe82..c037c3969e9d6 100644
@@ -82,8 +82,17 @@ static int _skcipher_recvmsg(struct socket *sock, struct msghdr *msg,
 	 * If more buffers are to be expected to be processed, process only
 	 * full block size buffers.
 	 */
-	if (ctx->more || len < ctx->used)
-		len -= len % bs;
+	if (ctx->more || len < ctx->used) {
+		size_t excess = len % bs;
+
+		len -= excess;
+		iov_iter_revert(&msg->msg_iter, excess);
+
+		if (!len) {
+			err = -EINVAL;
+			goto free;
+		}
+	}
 
 	/*
 	 * Create a per request TX SGL for this request which tracks the
Signature · 1 line
2.53.0
author maintainer
#798 lore raw

PATCH 793/1848 batman-adv: Limit number of aggregated packets directly

In reply to Greg Kroah-Hartman

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

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

From: Sven Eckelmann <[email protected]>

commit 434becf57bdc89f939db635ed3337b9d1da5967e upstream.

The currently selected size in BATADV_MAX_AGGREGATION_BYTES (512) is chosen such that the number of possible aggregated packets is lower than 32. This number must be limited so that the type of batadv_forw_packet->direct_link_flags has enough bits to represent each packet (with the size of at least 24 bytes).

This requirement is better implemented in code instead of having it inside a comment.

---
 net/batman-adv/bat_iv_ogm.c | 4 ++++
 net/batman-adv/main.h       | 3 ---
 2 files changed, 4 insertions(+), 3 deletions(-)
net/batman-adv/bat_iv_ogm.c +4 -0
index cc4fbfd0b7553..06908c324f110 100644
@@ -451,6 +451,7 @@ batadv_iv_ogm_can_aggregate(const struct batadv_ogm_packet *new_bat_ogm_packet,
 	struct batadv_ogm_packet *batadv_ogm_packet;
 	int aggregated_bytes = forw_packet->packet_len + packet_len;
 	struct batadv_hard_iface *primary_if = NULL;
+	u8 packet_num = forw_packet->num_packets + 1;
 	bool res = false;
 	unsigned long aggregation_end_time;
 
@@ -476,6 +477,9 @@ batadv_iv_ogm_can_aggregate(const struct batadv_ogm_packet *new_bat_ogm_packet,
 	if (aggregated_bytes > BATADV_MAX_AGGREGATION_BYTES)
 		return false;
 
+	if (packet_num >= BITS_PER_TYPE(forw_packet->direct_link_flags))
+		return false;
+
 	/* packet is not leaving on the same interface. */
 	if (forw_packet->if_outgoing != if_outgoing)
 		return false;
net/batman-adv/main.h +0 -3
index a47dc332d7968..369f7c8d0c01f 100644
@@ -103,9 +103,6 @@
  */
 #define BATADV_TQ_SIMILARITY_THRESHOLD 50
 
-/* should not be bigger than 512 bytes or change the size of
- * forw_packet->direct_link_flags
- */
 #define BATADV_MAX_AGGREGATION_BYTES 512
 #define BATADV_MAX_AGGREGATION_MS 100
 
Signature · 1 line
2.53.0
author maintainer
#799 lore raw

PATCH 794/1848 batman-adv: Close OGM aggregation before transmission

In reply to Greg Kroah-Hartman

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

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

From: Chengfeng Ye <[email protected]>

commit f91f64a91682c07e6c5f059804e709656364e8a6 upstream.

The OGM send worker leaves its forwarding packet on forw_bat_list until after batadv_iv_ogm_emit() returns. Aggregation holds forw_bat_list_lock, but emission reads and clones the packet without that lock.

CPU 0 can therefore start emitting a queued packet while CPU 1 takes the list lock, finds the same packet and appends another OGM. The sender can observe the new packet length before the corresponding direct-link flag is set, or clone the skb while its length and payload are being updated. This can transmit an OGM with incorrect flags or inconsistent data.

KCSAN reported:

  BUG: KCSAN: data-race in batadv_iv_ogm_queue_add / batadv_iv_send_outstanding_bat_ogm_packet
  write to 0xffff888100fedcf8 of 2 bytes by interrupt on cpu 1:
  read to 0xffff888100fedcf8 of 2 bytes by task 70 on cpu 2:
  value changed: 0x00c0 -> 0x00d8

Mark the aggregate as full under forw_bat_list_lock before emission. This waits for any ongoing append and prevents further aggregation. Emission uses packet_len to walk the OGMs, so all queued packets are still sent. Keep the packet on the list so interface purging can find the worker, wait for it to finish and free the packet.

Fixes 9b4aec647a92 ("batman-adv: fix rare race conditions on interface removal")
Cc [email protected] # 4.10.x: 434becf57bdc ("batman-adv: Limit number of aggregated packets directly")
Cc [email protected] # 4.10.x
[ Use BITS_PER_TYPE(...) instead of BATADV_MAX_AGGREGATION_PACKETS ]
---
 net/batman-adv/bat_iv_ogm.c | 5 +++++
 net/batman-adv/types.h      | 8 +++++++-
 2 files changed, 12 insertions(+), 1 deletion(-)
net/batman-adv/bat_iv_ogm.c +5 -0
index 06908c324f110..7dd42f91ac2d3 100644
@@ -1807,6 +1807,11 @@ static void batadv_iv_send_outstanding_bat_ogm_packet(struct work_struct *work)
 		goto out;
 	}
 
+	/* Mark aggregate as full before forcing emit. */
+	spin_lock_bh(&bat_priv->forw_bat_list_lock);
+	forw_packet->num_packets = BITS_PER_TYPE(forw_packet->direct_link_flags);
+	spin_unlock_bh(&bat_priv->forw_bat_list_lock);
+
 	batadv_iv_ogm_emit(forw_packet);
 
 	/* we have to have at least one packet in the queue to determine the
net/batman-adv/types.h +7 -1
index 49cef1a85639a..b9337958fa8f7 100644
@@ -2209,7 +2209,13 @@ struct batadv_forw_packet {
 	/** @direct_link_flags: direct link flags for aggregated OGM packets */
 	u32 direct_link_flags;
 
-	/** @num_packets: counter for aggregated OGMv1 packets */
+	/**
+	 * @num_packets: counter for aggregated OGMv1 packets. Set to
+	 *  BITS_PER_TYPE(forw_packet->direct_link_flags) (independent of the
+	 *  real number of aggregated packets) by the send worker to prevent
+	 *  further aggregation while the packet is emitted. It must therefore
+	 *  not be used to iterate over the aggregated packets
+	 */
 	u8 num_packets;
 
 	/** @delayed_work: work queue callback item for packet sending */
Signature · 1 line
2.53.0
author maintainer
#800 lore raw

PATCH 795/1848 batman-adv: tpmeter: fix u32 truncation of reported bytes

In reply to Greg Kroah-Hartman

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

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

From: Sven Eckelmann <[email protected]>

commit 1025b76d13288a311e8259a0eefde0854fa63c41 upstream.

When more than 4 GB are transferred by the throughput meter, batadv_tp_batctl_notify() will cut of the upper 32 bit of the u64 counter and thus under-report the actual transferred bytes.

The data type of the temporary storage variable must therefore still continue to use u64.

Fixes 33a3bb4a3345 ("batman-adv: throughput meter implementation")
[ Context ]
---
 net/batman-adv/tp_meter.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/batman-adv/tp_meter.c +1 -1
index 3a1561f579198..7910e7a7f79fc 100644
@@ -225,9 +225,9 @@ static void batadv_tp_batctl_notify(enum batadv_tp_meter_reason reason,
 				    unsigned long start_time, u64 total_sent,
 				    u32 cookie)
 {
+	u64 total_bytes;
 	u32 test_time;
 	u8 result;
-	u32 total_bytes;
 
 	if (!batadv_tp_is_error(reason)) {
 		result = BATADV_TP_REASON_COMPLETE;
Signature · 1 line
2.53.0
author maintainer
#801 lore raw

PATCH 796/1848 batman-adv: stop originator purge worker before freeing TT

In reply to Greg Kroah-Hartman

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

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

From: Sven Eckelmann <[email protected]>

commit f89eda5a9ccf82cba06b085b42ebc4886b8dfe9e upstream.

batadv_mesh_free() releases the translation tables via batadv_tt_free() before batadv_originator_free() stops orig_work. The purge worker can therefore still run while the TT is torn down. When an originator times out, batadv_purge_orig_ref() calls batadv_tt_global_del_orig(), which loads tt.global_hash and walks all buckets while taking their locks:

  CPU0                          CPU1
  batadv_tt_free()              batadv_purge_orig()
                                  batadv_tt_global_del_orig()
                                    hash = ...tt.global_hash;
    batadv_tt_global_table_free()
      batadv_hash_destroy(hash);
                                    spin_lock_bh(&hash->list_locks[i]);

Disable orig_work at the beginning of batadv_mesh_free(), directly after the mesh was marked as deactivating. The second disable_delayed_work_sync() in batadv_originator_free() is harmless because it is free'd anyway.

Fixes 9d31b3ce8168 ("batman-adv: fix potential TT client + orig-node memory leak")
[ Switch to cancel_delayed_work_sync() ]
---
 net/batman-adv/main.c | 5 +++++
 1 file changed, 5 insertions(+)
net/batman-adv/main.c +5 -0
index 860194a06e534..e484128f1bbc2 100644
@@ -269,6 +269,11 @@ void batadv_mesh_free(struct net_device *soft_iface)
 
 	atomic_set(&bat_priv->mesh_state, BATADV_MESH_DEACTIVATING);
 
+	/* the originator purge worker accesses (among others) the TT tables
+	 * and must therefore be stopped before any of them are freed
+	 */
+	cancel_delayed_work_sync(&bat_priv->orig_work);
+
 	batadv_purge_outstanding_packets(bat_priv, NULL);
 	batadv_tp_stop_all(bat_priv);
 
Signature · 1 line
2.53.0
author maintainer
#802 lore raw

PATCH 797/1848 batman-adv: tt: only transmit local ROAM flag together with DEL

In reply to Greg Kroah-Hartman

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

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

From: Sven Eckelmann <[email protected]>

commit 10f24f058417024a2c19cb8d88a6a0678a58a21b upstream.

BATADV_TT_CLIENT_ROAM is part of BATADV_TT_REMOTE_MASK but on the wire it only has a defined meaning together with BATADV_TT_CLIENT_DEL: the originator no longer serves the client because it roamed to another node. Such a DEL is only relevant for events (non-full table requests).

An ADD carrying ROAM is processed (by accident) by the receiver like a
ROAMING_ADV: a newly created global entry is marked as roaming and is excluded from the global CRC. But the sender includes it in its local CRC.

But such a behavior doesn't make sense for non-ROAM_ADV because a new TTVN is meant as announced commit of the local TT table of a node and should therefore not be used to create a temporary (roam) global entry in a node.

At the moment, such an ADD with the BATADV_TT_CLIENT_ROAM flag set can happen due to two mechanisms:

batadv_tt_local_valid() copies all flags of the local entry into a full table response. It is not synchronized with batadv_tt_local_mark_removed(). An entry which was marked as ROAM|PENDING by a ROAMING_ADV is still part of the current TTVN and is sent with the ROAM flag set. The receivers then create a roaming global entry for it and detect a CRC mismatch, which causes them to request the full table again.

The same can happen for an ADD change which is queued for an entry which (still) has the ROAM flag set. For example when only the dynamic WIFI or ISOLA flags were updated.

It is not triggered by batadv_send_other_tt_response() because batadv_tt_global_valid() is already taking care of filtering out BATADV_TT_CLIENT_ROAM entries.

For the two problematic announcement mechanism, only send the ROAM flag of local entries together with a DEL.

This only fixes the ROAM marking of the global entry and the resulting CRC mismatch. When the requester of the full table is the node which sent the ROAMING_ADV, the still announced entry will (independent of the ROAM flag) cause batadv_tt_global_purge_local() to remove the requester's own (new) local entry for the client. This is not addressed here.

Fixes 27b37ebfa2d2 ("batman-adv: correctly pass the client flag on tt_response")
Fixes 068ee6e204e1 ("batman-adv: roaming handling mechanism redesign")
[ Context, use direct tt_common_entry->flags access ]
---
 net/batman-adv/translation-table.c | 16 ++++++++++++++--
 1 file changed, 14 insertions(+), 2 deletions(-)
net/batman-adv/translation-table.c +14 -2
index 8ebbc9cf1195f..96a2078d9c387 100644
@@ -471,7 +471,6 @@ static void batadv_tt_local_event(struct batadv_priv *bat_priv,
 	if (!tt_change_node)
 		return;
 
-	tt_change_node->change.flags = flags;
 	memset(tt_change_node->change.reserved, 0,
 	       sizeof(tt_change_node->change.reserved));
 	ether_addr_copy(tt_change_node->change.addr, common->addr);
@@ -479,6 +478,15 @@ static void batadv_tt_local_event(struct batadv_priv *bat_priv,
 
 	del_op_requested = flags & BATADV_TT_CLIENT_DEL;
 
+	/* the ROAM flag is only meaningful for the receiver in combination
+	 * with a DEL. An ADD with ROAM would be interpreted as a roaming
+	 * advertisement
+	 */
+	if (!del_op_requested)
+		flags &= ~BATADV_TT_CLIENT_ROAM;
+
+	tt_change_node->change.flags = flags;
+
 	/* check for ADD+DEL or DEL+ADD events */
 	spin_lock_bh(&bat_priv->tt.changes_list_lock);
 	list_for_each_entry_safe(entry, safe, &bat_priv->tt.changes_list,
@@ -2984,8 +2992,12 @@ static bool batadv_tt_local_valid(const void *entry_ptr,
 	if (tt_common_entry->flags & BATADV_TT_CLIENT_NEW)
 		return false;
 
+	/* the entry is (still) announced. A ROAM flag of an entry which is
+	 * pending to be removed must not be transmitted. Otherwise, the
+	 * receiver would handle it like a roaming advertisement
+	 */
 	if (flags)
-		*flags = tt_common_entry->flags;
+		*flags = tt_common_entry->flags & ~BATADV_TT_CLIENT_ROAM;
 
 	return true;
 }
Signature · 1 line
2.53.0
author maintainer
#803 lore raw

PATCH 798/1848 batman-adv: tt: clear ROAM flag when re-adding a pending local client

In reply to Greg Kroah-Hartman

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

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

From: Sven Eckelmann <[email protected]>

commit cc2186d7854785b30d423f5d43757b086b300e55 upstream.

When a ROAMING_ADV is received for an announced local client, batadv_tt_local_mark_removed() sets BATADV_TT_CLIENT_ROAM, queues a DEL|ROAM change and marks the entry as BATADV_TT_CLIENT_PENDING. If the client sends a frame again before the next TTVN commit, batadv_tt_local_add_existing() only clears the PENDING flag and returns early. The ADD cancels the queued DEL, but the entry keeps the ROAM flag:

* batadv_is_my_client() reports the client as not served by this node
* batadv_tt_local_client_is_roaming() reroutes unicast frames for it to the node which sent the ROAMING_ADV

The ROAM flag is only removed with the next frame of the client.

Since BATADV_TT_CLIENT_ROAM is set together with BATADV_TT_CLIENT_PENDING, it has to be cleared also at the same time with BATADV_TT_CLIENT_PENDING when the client roamed back.

Fixes 068ee6e204e1 ("batman-adv: roaming handling mechanism redesign")
[ adjust code still in batadv_tt_local_add ]
---
 net/batman-adv/translation-table.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
net/batman-adv/translation-table.c +6 -3
index 96a2078d9c387..23d34e1b48eec 100644
@@ -659,6 +659,7 @@ bool batadv_tt_local_add(struct net_device *soft_iface, const u8 *addr,
 	int hash_added, table_size, packet_size_max;
 	bool ret = false;
 	bool roamed_back = false;
+	bool added = false;
 	u8 remote_flags;
 	u32 match_mark;
 
@@ -685,7 +686,7 @@ bool batadv_tt_local_add(struct net_device *soft_iface, const u8 *addr,
 			 * flag can be reset like it was never enqueued
 			 */
 			tt_local->common.flags &= ~BATADV_TT_CLIENT_PENDING;
-			goto add_event;
+			added = true;
 		}
 
 		if (tt_local->common.flags & BATADV_TT_CLIENT_ROAM) {
@@ -766,10 +767,12 @@ bool batadv_tt_local_add(struct net_device *soft_iface, const u8 *addr,
 		goto out;
 	}
 
-add_event:
-	batadv_tt_local_event(bat_priv, tt_local, BATADV_NO_FLAGS);
+	added = true;
 
 check_roaming:
+	if (added)
+		batadv_tt_local_event(bat_priv, tt_local, BATADV_NO_FLAGS);
+
 	/* Check whether it is a roaming, but don't do anything if the roaming
 	 * process has already been handled
 	 */
Signature · 1 line
2.53.0
author maintainer
#804 lore raw

PATCH 799/1848 batman-adv: tt: send ROAM_ADV on each roamed back client

In reply to Greg Kroah-Hartman

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

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

From: Sven Eckelmann <[email protected]>

commit aff4d5d10f2dcb4a9b604e27414dafa1d51b6406 upstream.

When a ROAMING_ADV is received for an announced local client, batadv_roam_tvlv_unicast_handler_v1() creates a global entry with the BATADV_TT_CLIENT_ROAM flag set.

If the client sends a frame again before the next TTVN commit, batadv_tt_local_add_roam() is expected to announce this return via a ROAM_ADV frame. But this doesn't happen because the global entry (created by the first ROAMING_ADV) carries BATADV_TT_CLIENT_ROAM until the new originator announces the client.

Let batadv_tt_local_add_roam() always handle a roamed back client - independent of the ROAM flag of the global entry:

* trigger sending of the ROAM_ADV frame(s)
* remove the (with the roaming) associated global entry

Fixes 068ee6e204e1 ("batman-adv: roaming handling mechanism redesign")
[ adjust code still in batadv_tt_local_add ]
---
 net/batman-adv/translation-table.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
net/batman-adv/translation-table.c +2 -1
index 23d34e1b48eec..1065003c99dfd 100644
@@ -776,7 +776,8 @@ bool batadv_tt_local_add(struct net_device *soft_iface, const u8 *addr,
 	/* Check whether it is a roaming, but don't do anything if the roaming
 	 * process has already been handled
 	 */
-	if (tt_global && !(tt_global->common.flags & BATADV_TT_CLIENT_ROAM)) {
+	if (tt_global &&
+	    (roamed_back || !(tt_global->common.flags & BATADV_TT_CLIENT_ROAM))) {
 		/* These node are probably going to update their tt table */
 		head = &tt_global->orig_list;
 		rcu_read_lock();
Signature · 1 line
2.53.0
author maintainer
#805 lore raw

PATCH 800/1848 batman-adv: tt: ignore ROAM flag of received ADD changes

In reply to Greg Kroah-Hartman

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

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

From: Sven Eckelmann <[email protected]>

commit c5d68abe6e7f1dbd132a602cb696fe1fff0389eb upstream.

A received TT change (OGM diff or full table response) with the ROAM flag but without DEL is handled by batadv_tt_global_add() like a ROAMING_ADV:

* a newly created global entry gets BATADV_TT_CLIENT_ROAM and is therefore excluded from the global CRC. The sender has it in its local CRC and the receiver has to request the full table again
* batadv_tt_global_purge_local() removes the local entry of the receiver. The receiver's own client is considered as roamed to the sender and frames for it are rerouted

The ROAM flag only has a meaning together with DEL. Drop it on reception to keep it from populating the global table with a temporary ROAMING entry which is not part of the CRC - and therefore causing a CRC mismatch.

Fixes 068ee6e204e1 ("batman-adv: roaming handling mechanism redesign")
[ Context ]
---
 net/batman-adv/translation-table.c | 15 ++++++++++++---
 1 file changed, 12 insertions(+), 3 deletions(-)
net/batman-adv/translation-table.c +12 -3
index 1065003c99dfd..ce36340f97459 100644
@@ -3572,20 +3572,29 @@ static void _batadv_tt_update_changes(struct batadv_priv *bat_priv,
 {
 	int i;
 	int roams;
+	u8 flags;
 
 	for (i = 0; i < tt_num_changes; i++) {
-		if ((tt_change + i)->flags & BATADV_TT_CLIENT_DEL) {
-			roams = (tt_change + i)->flags & BATADV_TT_CLIENT_ROAM;
+		flags = (tt_change + i)->flags;
+
+		if (flags & BATADV_TT_CLIENT_DEL) {
+			roams = flags & BATADV_TT_CLIENT_ROAM;
 			batadv_tt_global_del(bat_priv, orig_node,
 					     (tt_change + i)->addr,
 					     ntohs((tt_change + i)->vid),
 					     "tt removed by changes",
 					     roams);
 		} else {
+			/* an announced client cannot have roamed away from
+			 * orig_node. Only a ROAMING_ADV is allowed to add a
+			 * global entry with the ROAM flag
+			 */
+			flags &= ~BATADV_TT_CLIENT_ROAM;
+
 			if (!batadv_tt_global_add(bat_priv, orig_node,
 						  (tt_change + i)->addr,
 						  ntohs((tt_change + i)->vid),
-						  (tt_change + i)->flags, ttvn))
+						  flags, ttvn))
 				/* In case of problem while storing a
 				 * global_entry, we stop the updating
 				 * procedure without committing the
Signature · 1 line
2.53.0