Skip to contentSkip to conversation

7.3.2-rc1 review

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

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

PATCH 237/547 mm: khugepaged: fix folio is used after pte_unmap_unlock()

In reply to Greg Kroah-Hartman

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

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

From: Vernon Yang <[email protected]>

commit ba2f1f92ddfabd340c9248fd2380104f717ee8b1 upstream.

After the page table lock has dropped, the folio can be freed concurrently. The trace_mm_khugepaged_scan_pmd() is left with a dangling folio pointer.

So using the folio_pfn() before dropping the page table lock, closing use-after-free window.

And other pre-existing bug, When the for (i = 0; i < HPAGE_PMD_NR; i++) iteration to terminate and the folio operation preceding is normal, but pfn will be incorrect. so we really only trace the PFN if it really was problematic.

---
 include/trace/events/huge_memory.h |    6 +++---
 mm/khugepaged.c                    |   10 +++++++++-
 2 files changed, 12 insertions(+), 4 deletions(-)
include/trace/events/huge_memory.h +3 -3
@@ -55,10 +55,10 @@ SCAN_STATUS
 
 TRACE_EVENT(mm_khugepaged_scan_pmd,
 
-	TP_PROTO(struct mm_struct *mm, struct folio *folio,
+	TP_PROTO(struct mm_struct *mm, unsigned long pfn,
 		 int referenced, int none_or_zero, int status, int unmapped),
 
-	TP_ARGS(mm, folio, referenced, none_or_zero, status, unmapped),
+	TP_ARGS(mm, pfn, referenced, none_or_zero, status, unmapped),
 
 	TP_STRUCT__entry(
 		__field(struct mm_struct *, mm)
@@ -71,7 +71,7 @@ TRACE_EVENT(mm_khugepaged_scan_pmd,
 
 	TP_fast_assign(
 		__entry->mm = mm;
-		__entry->pfn = folio ? folio_pfn(folio) : -1;
+		__entry->pfn = pfn;
 		__entry->referenced = referenced;
 		__entry->none_or_zero = none_or_zero;
 		__entry->status = status;
mm/khugepaged.c +9 -1
@@ -1612,6 +1612,7 @@ static enum scan_result collapse_scan_pm
 	enum scan_result result = SCAN_FAIL;
 	struct page *page = NULL;
 	struct folio *folio = NULL;
+	unsigned long failed_pfn = -1;
 	unsigned long addr;
 	unsigned long enabled_orders;
 	spinlock_t *ptl;
@@ -1706,11 +1707,13 @@ static enum scan_result collapse_scan_pm
 		if (cc->is_khugepaged && !(vma->vm_flags & VM_DROPPABLE) &&
 		    folio_test_lazyfree(folio) && !pte_dirty(pteval)) {
 			result = SCAN_PAGE_LAZYFREE;
+			failed_pfn = folio_pfn(folio);
 			goto out_unmap;
 		}
 
 		if (!folio_test_anon(folio)) {
 			result = SCAN_PAGE_ANON;
+			failed_pfn = folio_pfn(folio);
 			goto out_unmap;
 		}
 
@@ -1721,6 +1724,7 @@ static enum scan_result collapse_scan_pm
 		if (folio_maybe_mapped_shared(folio)) {
 			if (++shared > max_ptes_shared) {
 				result = SCAN_EXCEED_SHARED_PTE;
+				failed_pfn = folio_pfn(folio);
 				count_collapse_event(HPAGE_PMD_ORDER, THP_SCAN_EXCEED_SHARED_PTE,
 						     MTHP_STAT_COLLAPSE_EXCEED_SHARED);
 				goto out_unmap;
@@ -1738,15 +1742,18 @@ static enum scan_result collapse_scan_pm
 		node = folio_nid(folio);
 		if (collapse_scan_abort(node, cc)) {
 			result = SCAN_SCAN_ABORT;
+			failed_pfn = folio_pfn(folio);
 			goto out_unmap;
 		}
 		cc->node_load[node]++;
 		if (!folio_test_lru(folio)) {
 			result = SCAN_PAGE_LRU;
+			failed_pfn = folio_pfn(folio);
 			goto out_unmap;
 		}
 		if (folio_test_locked(folio)) {
 			result = SCAN_PAGE_LOCK;
+			failed_pfn = folio_pfn(folio);
 			goto out_unmap;
 		}
 
@@ -1759,6 +1766,7 @@ static enum scan_result collapse_scan_pm
 		 */
 		if (folio_expected_ref_count(folio) != folio_ref_count(folio)) {
 			result = SCAN_PAGE_COUNT;
+			failed_pfn = folio_pfn(folio);
 			goto out_unmap;
 		}
 
@@ -1784,7 +1792,7 @@ out_unmap:
 		*lock_dropped = true;
 	}
 out:
-	trace_mm_khugepaged_scan_pmd(mm, folio, referenced,
+	trace_mm_khugepaged_scan_pmd(mm, failed_pfn, referenced,
 				     none_or_zero, result, unmapped);
 	return result;
 }
author maintainer
#238 lore raw

PATCH 238/547 mm: khugepaged: fix swap entry value to folio_pfn()

In reply to Greg Kroah-Hartman

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

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

From: Vernon Yang <[email protected]>

commit 942c8ec27aa4ffc587511650718349964e1696e6 upstream.

Patch series "mm: khugepaged: fix tracepoint UAF", v5.

The khugepaged tracepoints take a folio pointer and call folio_pfn(), but by then the folio may no longer be valid: freed after folio_put(), folio_unlock() or pte_unmap_unlock(), or not a folio at all but an xarray-encoded swap entry. On classic SPARSEMEM, dereferencing it oopses khugepaged as soon as the trace event is enabled; on other memory models it merely prints a bogus pfn.

Pass the pfn to the tracepoints directly, captured while the folio is still pinned, closing the use-after-free windows in mm_khugepaged_scan_file(), mm_khugepaged_scan_pmd() and mm_khugepaged_collapse_file().

This patch (of 3):

When the swap entries found exceed max_ptes_swap, the loop is left via break with folio still holding the xarray value that encodes the swap entry, not valid folio pointer.

That value is passed to trace_mm_khugepaged_scan_file(), which feeds it to folio_pfn(). On FLATMEM and SPARSEMEM_VMEMMAP, the page_to_pfn() is plain pointer arithmetic, so the trace event merely prints bogus scan_pfn. On classic SPARSEMEM, the page_to_pfn() reads page->flags, dereferencing the tiny encoded integer and oopsing khugepaged whenever the trace event is enabled.

So when folio is the swap entry value, simply set pfn to -1, just like exhausted scan naturally.

And the folio_put() has maybe dropped the last reference of folio. The trace_mm_khugepaged_scan_file() is left with a dangling folio pointer. so using the folio_pfn() before dropping the reference, closing use-after-free window.

Fixes d41fd2016ed0 ("mm/khugepaged: add tracepoint to hpage_collapse_scan_file()")
Cc Barry Song <[email protected]>
Cc Dev Jain <[email protected]>
Cc Lance Yang <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Ryan Roberts <[email protected]>
Cc Zach O'Keefe <[email protected]>
---
 include/trace/events/huge_memory.h |    6 +++---
 mm/khugepaged.c                    |    7 ++++++-
 2 files changed, 9 insertions(+), 4 deletions(-)
include/trace/events/huge_memory.h +3 -3
@@ -178,10 +178,10 @@ TRACE_EVENT(mm_collapse_huge_page_swapin
 
 TRACE_EVENT(mm_khugepaged_scan_file,
 
-	TP_PROTO(struct mm_struct *mm, struct folio *folio, struct file *file,
+	TP_PROTO(struct mm_struct *mm, unsigned long pfn, struct file *file,
 		 int present, int swap, int result),
 
-	TP_ARGS(mm, folio, file, present, swap, result),
+	TP_ARGS(mm, pfn, file, present, swap, result),
 
 	TP_STRUCT__entry(
 		__field(struct mm_struct *, mm)
@@ -194,7 +194,7 @@ TRACE_EVENT(mm_khugepaged_scan_file,
 
 	TP_fast_assign(
 		__entry->mm = mm;
-		__entry->pfn = folio ? folio_pfn(folio) : -1;
+		__entry->pfn = pfn;
 		__assign_str(filename);
 		__entry->present = present;
 		__entry->swap = swap;
mm/khugepaged.c +6 -1
@@ -2693,6 +2693,7 @@ static enum scan_result collapse_scan_fi
 	int present, swap;
 	int node = NUMA_NO_NODE;
 	enum scan_result result = SCAN_SUCCEED;
+	unsigned long failed_pfn = -1;
 
 	present = 0;
 	swap = 0;
@@ -2725,6 +2726,7 @@ static enum scan_result collapse_scan_fi
 
 		if (is_pmd_order(folio_order(folio))) {
 			result = SCAN_PTE_MAPPED_HUGEPAGE;
+			failed_pfn = folio_pfn(folio);
 			/*
 			 * PMD-sized THP implies that we can only try
 			 * retracting the PTE table.
@@ -2736,6 +2738,7 @@ static enum scan_result collapse_scan_fi
 		node = folio_nid(folio);
 		if (collapse_scan_abort(node, cc)) {
 			result = SCAN_SCAN_ABORT;
+			failed_pfn = folio_pfn(folio);
 			folio_put(folio);
 			break;
 		}
@@ -2743,12 +2746,14 @@ static enum scan_result collapse_scan_fi
 
 		if (!folio_test_lru(folio)) {
 			result = SCAN_PAGE_LRU;
+			failed_pfn = folio_pfn(folio);
 			folio_put(folio);
 			break;
 		}
 
 		if (folio_expected_ref_count(folio) + 1 != folio_ref_count(folio)) {
 			result = SCAN_PAGE_COUNT;
+			failed_pfn = folio_pfn(folio);
 			folio_put(folio);
 			break;
 		}
@@ -2783,7 +2788,7 @@ static enum scan_result collapse_scan_fi
 		}
 	}
 
-	trace_mm_khugepaged_scan_file(mm, folio, file, present, swap, result);
+	trace_mm_khugepaged_scan_file(mm, failed_pfn, file, present, swap, result);
 	return result;
 }
 
author maintainer
#239 lore raw

PATCH 239/547 mptcp: hold MP_JOIN msk ref when cloning reqsk

In reply to Greg Kroah-Hartman

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

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

From: Ruide Cao <[email protected]>

commit c9c90cf437a9e6597611b6d3aad6e255fad22867 upstream.

TCP request migration clones pending request sockets with inet_reqsk_clone(). For MPTCP MP_JOIN requests this byte-copies subflow_req->msk, but the clone does not own a reference.

The original and cloned requests can consequently drop the same msk reference, leaving one request with a dangling pointer. This manifests as a KASAN slab-use-after-free in subflow_req_destructor():

  BUG: KASAN: slab-use-after-free in subflow_req_destructor (net/mptcp/subflow.c:45)
  Write of size 4 at addr ff1100010e008d40 by task swapper/0/0
  CPU: 0 UID: 0 PID: 0 Comm: swapper/0 Not tainted 7.2.0-rc5-00353-gc27e36054537 #10 PREEMPT(full)

  Call Trace:
   subflow_req_destructor (net/mptcp/subflow.c:45)
   subflow_v4_req_destructor (net/mptcp/subflow.c:694)
   __reqsk_free (net/ipv4/inet_connection_sock.c:906)
   reqsk_timer_handler (include/net/request_sock.h:137 net/ipv4/inet_connection_sock.c:1147)

  Allocated by task 10014:
   sk_prot_alloc (net/core/sock.c:2246)
   sk_clone (net/core/sock.c:2488)
   mptcp_sk_clone_init (include/net/sock.h:1848 net/mptcp/protocol.c:3564)
   subflow_syn_recv_sock (net/mptcp/subflow.c:883)
   tcp_check_req (net/ipv4/tcp_minisocks.c:934)

  Freed by task 0:
   slab_free_after_rcu_debug (include/linux/kasan.h:235 mm/slub.c:2677 mm/slub.c:6439)
   rcu_core (kernel/rcu/tree.c:2645 kernel/rcu/tree.c:2897)

  Last potentially related work creation:
   kmem_cache_free (mm/slub.c:2638 mm/slub.c:6377 mm/slub.c:6504)
   __sk_destruct (net/core/sock.c:2289 net/core/sock.c:2391)
   sk_destruct (net/core/sock.c:2419)
   __sk_free (net/core/sock.c:2430)
   sk_free (net/core/sock.c:2441)
   mptcp_close (include/net/sock.h:2020 net/mptcp/protocol.c:3399)
   inet_release (net/ipv4/af_inet.c:442)

  The buggy address belongs to the cache MPTCP of size 2968
  The buggy address is 128 bytes inside a freed 2968-byte region

A non-NULL subflow_req->msk means that the request owns one reference. The third ACK can concurrently transfer the original request reference to the child and release it, so taking an unconditional hold on the copied pointer is unsafe.

MPTCP sockets use SLAB_TYPESAFE_BY_RCU and all current inet_reqsk_clone() callers run in an RCU read-side critical section. Document and lockdep-check that calling-context requirement. Read the pointer from the original request and acquire a reference only if it is still live. Use refcount_inc_not_zero_acquire() so the subsequent ownership validation cannot be reordered before the try-get, then re-read the original request to verify that it still owns the same msk. If either check fails, clear the clone pointer; otherwise its normal destructor balances the new reference. Mark the ownership-transfer store with WRITE_ONCE() to match the lockless reads.

The following patch completes the clone fixup for MP_CAPABLE token ownership. Both patches carry the same Fixes tag and are required for stable backports.

---
 include/net/mptcp.h             |    9 +++++++++
 net/ipv4/inet_connection_sock.c |    4 ++++
 net/mptcp/subflow.c             |   35 ++++++++++++++++++++++++++++++++++-
 3 files changed, 47 insertions(+), 1 deletion(-)
include/net/mptcp.h +9 -0
@@ -219,6 +219,9 @@ int mptcp_subflow_init_cookie_req(struct
 struct request_sock *mptcp_subflow_reqsk_alloc(const struct request_sock_ops *ops,
 					       struct sock *sk_listener,
 					       bool attach_listener);
+/* Caller must hold an RCU read-side lock. */
+void mptcp_subflow_reqsk_clone(struct request_sock *req,
+			       struct request_sock *new_req);
 
 __be32 mptcp_get_reset_option(const struct sk_buff *skb);
 
@@ -305,6 +308,12 @@ static inline struct request_sock *mptcp
 	return NULL;
 }
 
+/* Caller must hold an RCU read-side lock. */
+static inline void mptcp_subflow_reqsk_clone(struct request_sock *req,
+					     struct request_sock *new_req)
+{
+}
+
 static inline __be32 mptcp_reset_option(const struct sk_buff *skb)  { return htonl(0u); }
 
 static inline void mptcp_active_detect_blackhole(struct sock *sk, bool expired) { }
net/ipv4/inet_connection_sock.c +4 -0
@@ -21,6 +21,7 @@
 #include <net/xfrm.h>
 #include <net/tcp.h>
 #include <net/tcp_ecn.h>
+#include <net/mptcp.h>
 #include <net/sock_reuseport.h>
 #include <net/addrconf.h>
 
@@ -961,6 +962,9 @@ static struct request_sock *inet_reqsk_c
 		rcu_assign_pointer(tcp_sk(nreq->sk)->fastopen_rsk, nreq);
 	}
 
+	if (rsk_is_mptcp(req))
+		mptcp_subflow_reqsk_clone(req, nreq);
+
 	return nreq;
 }
 
net/mptcp/subflow.c +34 -1
@@ -47,6 +47,39 @@ static void subflow_req_destructor(struc
 	mptcp_token_destroy_request(req);
 }
 
+void mptcp_subflow_reqsk_clone(struct request_sock *req,
+			       struct request_sock *new_req)
+{
+	struct mptcp_subflow_request_sock *subflow_req = mptcp_subflow_rsk(req);
+	struct mptcp_subflow_request_sock *new_subflow_req;
+	struct mptcp_sock *msk;
+
+	new_subflow_req = mptcp_subflow_rsk(new_req);
+	RCU_LOCKDEP_WARN(!rcu_read_lock_any_held(),
+			 "MPTCP reqsk clone called without RCU");
+
+	/* A non-NULL ->msk means the request owns one reference.  The clone
+	 * copied only the pointer, while the original request can concurrently
+	 * transfer its reference to the child.  Acquire a reference for the
+	 * clone, then verify that the original request still owns the same msk.
+	 * MPTCP sockets use SLAB_TYPESAFE_BY_RCU and all clone callers run in
+	 * an RCU read-side critical section, keeping the memory stable here.
+	 */
+	msk = READ_ONCE(subflow_req->msk);
+	if (msk) {
+		struct sock *sk = (struct sock *)msk;
+
+		if (!refcount_inc_not_zero_acquire(&sk->sk_refcnt)) {
+			msk = NULL;
+		} else if (READ_ONCE(subflow_req->msk) != msk) {
+			sock_put(sk);
+			msk = NULL;
+		}
+	}
+
+	new_subflow_req->msk = msk;
+}
+
 static void subflow_generate_hmac(u64 key1, u64 key2, u32 nonce1, u32 nonce2,
 				  void *hmac)
 {
@@ -927,7 +960,7 @@ create_child:
 			}
 
 			/* move the msk reference ownership to the subflow */
-			subflow_req->msk = NULL;
+			WRITE_ONCE(subflow_req->msk, NULL);
 			ctx->conn = (struct sock *)owner;
 
 			if (subflow_use_different_sport(owner, sk)) {
author maintainer
#240 lore raw

PATCH 240/547 mshv_vtl: detach poll waiter on POLLFREE

In reply to Greg Kroah-Hartman

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

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

From: Daehyeon Ko <[email protected]>

commit efc5dc4c15713fdd6e87882686a26ed1deb22dab upstream.

MSHV_SET_POLL_FILE keeps a poll wait entry after the ioctl returns. A file reference does not always pin the registered waitqueue:
signalfd_poll() uses current->sighand->signalfd_wqh, whose lifetime is tied to the task.

signalfd_cleanup() sends POLLFREE before the sighand is freed. The MSHV callback currently leaves its entry linked, so __wake_up_pollfree() warns and a later replacement calls remove_wait_queue() through a stale wqh pointer. A source-equivalent KASAN run reproduced:

  BUG: KASAN: slab-use-after-free in _raw_spin_lock_irqsave
  _raw_spin_lock_irqsave
  remove_wait_queue
  harness_ioctl [mshv_pollfree_harness]

The object belonged to sighand_cache and had been released through slab_free_after_rcu_debug() after __cleanup_sighand().

On POLLFREE, unlink the entry under the provider waitqueue lock. Preserve the existing CPU cancellation before publishing a NULL wqh, since a NULL load lets a racing replacement reuse the persistent poll state. Use a matching acquire load under RCU when removing a normal registration.

The callback takes no mutex and does not sleep, so the existing mutex-to-waitqueue-lock order is unchanged.

An LLM assisted the source audit, fix development, and validation of this issue.

Fixes 7bfe3b8ea6e3 ("Drivers: hv: Introduce mshv_vtl driver")
---
 drivers/hv/mshv_vtl_main.c |   28 +++++++++++++++++++++++++---
 1 file changed, 25 insertions(+), 3 deletions(-)
drivers/hv/mshv_vtl_main.c +25 -3
@@ -17,6 +17,7 @@
 #include <linux/entry-virt.h>
 #include <linux/eventfd.h>
 #include <linux/poll.h>
+#include <linux/rcupdate.h>
 #include <linux/file.h>
 #include <linux/vmalloc.h>
 #include <asm/debugreg.h>
@@ -448,12 +449,35 @@ static void mshv_vtl_cancel(int cpu)
 static int mshv_vtl_poll_file_wake(wait_queue_entry_t *wait, unsigned int mode, int sync, void *key)
 {
 	struct mshv_vtl_poll_file *poll_file = container_of(wait, struct mshv_vtl_poll_file, wait);
+	__poll_t pollflags = key_to_poll(key);
+
+	if (pollflags & POLLFREE)
+		list_del_init(&wait->entry);
 
 	mshv_vtl_cancel(poll_file->cpu);
 
+	if (pollflags & POLLFREE) {
+		/* Publish teardown last; pair with acquire in the removal path. */
+		smp_store_release(&poll_file->wqh, NULL);
+	}
+
 	return 0;
 }
 
+static void mshv_vtl_poll_file_remove_wait_queue(struct mshv_vtl_poll_file *poll_file)
+{
+	wait_queue_head_t *wqh;
+
+	/* POLLFREE providers RCU-delay the waitqueue free. */
+	rcu_read_lock();
+	/* Pair with the release store in the POLLFREE callback. */
+	wqh = smp_load_acquire(&poll_file->wqh);
+	if (wqh)
+		remove_wait_queue(wqh, &poll_file->wait);
+	rcu_read_unlock();
+	WRITE_ONCE(poll_file->wqh, NULL);
+}
+
 static void mshv_vtl_ptable_queue_proc(struct file *file, wait_queue_head_t *wqh, poll_table *pt)
 {
 	struct mshv_vtl_poll_file *poll_file = container_of(pt, struct mshv_vtl_poll_file, pt);
@@ -490,9 +514,7 @@ static int mshv_vtl_ioctl_set_poll_file(
 
 	mutex_lock(&mshv_vtl_poll_file_lock);
 
-	if (poll_file->wqh)
-		remove_wait_queue(poll_file->wqh, &poll_file->wait);
-	poll_file->wqh = NULL;
+	mshv_vtl_poll_file_remove_wait_queue(poll_file);
 
 	old_file = poll_file->file;
 	poll_file->file = file;
author maintainer
#241 lore raw

PATCH 241/547 mtd: virt-concat: unlink concat node before freeing it

In reply to Greg Kroah-Hartman

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

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

From: Harshit Mogalapalli <[email protected]>

commit 532caaa2f445b22b74b88b4023a810426772db54 upstream.

mtd_virt_concat_create_item() links each new mtd_virt_concat_node to concat_node_list. mtd_virt_concat_destroy() later frees the node after destroying its concatenated MTD device, but fails to unlink it. A later list traversal dereferences the freed node, causing a use-after-free.

Remove the node from concat_node_list before freeing it.

Fixes 43db6366fc2d ("mtd: Add driver for concatenating devices")
Assisted-by Codex:gpt-5.6, smatch
---
 drivers/mtd/mtd_virt_concat.c | 1 +
 1 file changed, 1 insertion(+)
drivers/mtd/mtd_virt_concat.c +1 -0
index da4277ced4d6..4fad0967a96e 100644
@@ -130,6 +130,7 @@ int mtd_virt_concat_destroy(struct mtd_info *mtd)
 			mtd_concat_destroy(&concat->mtd);
 		}
 
+		list_del(&item->head);
 		for (idx = 0; idx < item->count; idx++)
 			of_node_put(item->nodes[idx]);
 
Signature · 1 line
2.56.0
author maintainer
#242 lore raw

PATCH 242/547 mtd: virt-concat: unlink discarded items before freeing

In reply to Greg Kroah-Hartman

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

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

From: Harshit Mogalapalli <[email protected]>

commit 112a666bd82e96e4a01e0cd8a0fb9c88dd0bce38 upstream.

mtd_virt_concat_destroy_items() frees each item without removing it from concat_node_list. list_for_each_entry_safe() protects the current traversal, but concat_node_list still points to the freed items afterward.

The function also unwinds errors from mtd_virt_concat_node_create().

A later initialization can traverse a freed item in mtd_is_part_concat(), causing a use-after-free.

Unlink each item before freeing it.

Fixes 43db6366fc2d ("mtd: Add driver for concatenating devices")
Assisted-by Codex:gpt-5.6, smatch
---
 drivers/mtd/mtd_virt_concat.c | 1 +
 1 file changed, 1 insertion(+)
drivers/mtd/mtd_virt_concat.c +1 -0
index 4fad0967a96e..637219e20b80 100644
@@ -202,6 +202,7 @@ void mtd_virt_concat_destroy_items(void)
 	int i;
 
 	list_for_each_entry_safe(item, temp, &concat_node_list, head) {
+		list_del(&item->head);
 		for (i = 0; i < item->count; i++)
 			of_node_put(item->nodes[i]);
 
Signature · 1 line
2.56.0
author maintainer
#243 lore raw

PATCH 243/547 net: sched: prevent scheduling deactivated qdiscs

In reply to Greg Kroah-Hartman

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

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

From: Kyle Zeng <[email protected]>

commit d6f81fd6abe209f9803d8f74ce9ec69b8126bad3 upstream.

TAPRIO can schedule a deactivated qdisc after some_qdisc_is_busy() has reported it idle.

Commit 47e8dbb6e763 ("net/sched: do not reset queues in graft operations") made graft deactivation skip queue reset, leaving TAPRIO's timer armed.

A late callback schedules NET_TX softirq work, whose dequeue path can race the unlocked child-queue reset in taprio_reset(). The same skb can be queued for deferred freeing by RTNL and dequeued for transmission. In the reproducer, the TAP reader frees it before __rtnl_unlock() reads its next pointer. KASAN reports a slab-use-after-free in __rtnl_unlock+0xa3/0xd0, with a read of size 8 from the freed skb.

Reject deactivated qdiscs in __netif_schedule(). Callers' RCU protection lets the existing grace period join earlier scheduling calls before the busy check. Restart nonempty transmit queues on reactivation so suppressed scheduling does not strand packets.

Fixes 47e8dbb6e763 ("net/sched: do not reset queues in graft operations")
Assisted-by Codex:gpt-5.6-sol Codex:gpt-5.5-cyber
---
 net/core/dev.c          |    3 +++
 net/sched/sch_generic.c |    4 ++++
 2 files changed, 7 insertions(+)
net/core/dev.c +3 -0
@@ -3440,6 +3440,9 @@ static void __netif_reschedule(struct Qd
 
 void __netif_schedule(struct Qdisc *q)
 {
+	if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state)))
+		return;
+
 	/* If q->defer_list is not empty, at least one thread is
 	 * in __dev_xmit_skb() before llist_del_all(&q->defer_list).
 	 * This thread will attempt to run the queue.
net/sched/sch_generic.c +4 -0
@@ -1288,6 +1288,10 @@ static void transition_one_qdisc(struct
 	if (need_watchdog_p) {
 		WRITE_ONCE(dev_queue->trans_start, jiffies);
 		*need_watchdog_p = 1;
+
+		/* Resume backlog left by a suppressed schedule while deactivated. */
+		if (!qdisc_is_empty(new_qdisc))
+			netif_schedule_queue(dev_queue);
 	}
 }
 
author maintainer
#244 lore raw

PATCH 244/547 scsi: dc395x: sync the waiting_timer before freeing the host

In reply to Greg Kroah-Hartman

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

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

From: Fan Wu <[email protected]>

commit 0b1a79f2791a06f139dce5450e487307cf0e241f upstream.

The waiting_timer callback re-arms itself and takes the host lock. adapter_uninit() currently stops it with timer_delete(), which does not wait for a callback already running on another CPU. The final scsi_host_put() that frees the host (and the host lock the callback dereferences) runs right after adapter_uninit(), so a concurrent or just re-armed callback can fire after the free, leaving a potential use-after-free window.

Replace timer_delete() with timer_shutdown_sync() at the top of adapter_uninit(), before the host-lock section: the timer is dequeued, a running callback is waited for and rearming is blocked before the chip is halted, so it cannot fire at all once the adapter has ceased to function. Waiting outside the lock avoids the self-deadlock that would result from syncing a callback blocked on the lock we still hold.

No shutdown is needed for selto_timer because it has no reachable armer or callback.

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

---
 drivers/scsi/dc395x.c |   10 ++++------
 1 file changed, 4 insertions(+), 6 deletions(-)
drivers/scsi/dc395x.c +4 -6
@@ -3808,13 +3808,11 @@ static void adapter_uninit_chip(struct A
 static void adapter_uninit(struct AdapterCtlBlk *acb)
 {
 	unsigned long flags;
-	DC395x_LOCK_IO(acb->scsi_host, flags);
 
-	/* remove timers */
-	if (timer_pending(&acb->waiting_timer))
-		timer_delete(&acb->waiting_timer);
-	if (timer_pending(&acb->selto_timer))
-		timer_delete(&acb->selto_timer);
+	/* Drain the self-rearming timer; must not run under host_lock. */
+	timer_shutdown_sync(&acb->waiting_timer);
+
+	DC395x_LOCK_IO(acb->scsi_host, flags);
 
 	adapter_uninit_chip(acb);
 	adapter_remove_and_free_all_devices(acb);
author maintainer
#245 lore raw

PATCH 245/547 serial: core: shut down initialized port on removal

In reply to Greg Kroah-Hartman

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

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

From: Igor Putko <[email protected]>

commit 810d467c11f0c85107874d08dfdd11acba6aa0c0 upstream.

When a serial port configured as a console is opened and subsequently closed, tty_port_shutdown() skips invoking port->ops->shutdown() because port->console is true. As a result, tty_port_initialized() remains true and the port's interrupt handler stays registered in the irq subsystem.

If the underlying device is later unbound or removed (e.g. via sysfs driver unbind or device hot-unplug), serial_core_remove_one_port() unregisters the console, frees uport->name via kfree(), and tears down the port without shutting it down or freeing its IRQ. Consequently, the irqaction descriptor remains registered in genirq with action->name pointing to freed memory.

This triggers a use-after-free read whenever genirq accesses action->name, such as when reading /proc/interrupts:

  BUG: KASAN: slab-use-after-free in string+0x476/0x570
  Call Trace:
   string+0x476/0x570
   vsnprintf+0x422/0x1300
   seq_printf+0x...
   show_interrupts+...

Fix this by acquiring port->mutex in serial_core_remove_one_port() after console unregistration, clearing port->console under the mutex to prevent data races with concurrent tty_port_shutdown(), and invoking uart_shutdown(NULL, state) if the port remains initialized. This ensures that port->ops->shutdown() is called and the IRQ is freed before kfree(uport->name).

Reported-by [email protected]
Cc stable <[email protected]>
Fixes 761ed4a94582 ("tty: serial_core: convert uart_close to use tty_port_close")
Fixes f7048b15900f ("tty: serial_core: Add name field to uart_port struct")
---
 drivers/tty/serial/serial_core.c |    7 +++++++
 1 file changed, 7 insertions(+)
drivers/tty/serial/serial_core.c +7 -0
@@ -3241,6 +3241,13 @@ static void serial_core_remove_one_port(
 	if (uart_console(uport))
 		unregister_console(uport->cons);
 
+	scoped_guard(mutex, &port->mutex) {
+		port->console = false;
+
+		if (tty_port_initialized(port))
+			uart_shutdown(NULL, state);
+	}
+
 	/*
 	 * Free the port IO and memory resources, if any.
 	 */
author maintainer
#246 lore raw

PATCH 246/547 staging: rtl8723bs: fix protected RX frame validation in decrypt path

In reply to Greg Kroah-Hartman

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

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

From: Tianchu Chen <[email protected]>

commit 495cb31c791bdf3f9efef255a9587b05b0526c9d upstream.

The RX software decrypt path mishandles crafted protected frames from a malicious AP in two ways:

1) decryptor() never checks that a protected frame is long enough to hold the 802.11 header plus the per-cipher trailer. All of rtw_wep_decrypt(), rtw_tkip_decrypt() and rtw_aes_decrypt() compute

	length = hdr.len - hdrlen - iv_len;

and act on the result, and recvframe_chkmic() similarly computes

	datalen = hdr.len - hdrlen - iv_len - icv_len - 8;

for TKIP (the 8-byte Michael MIC is not accounted for in icv_len). A frame shorter than hdrlen + iv_len + icv_len (+ 8 for TKIP) underflows these unsigned subtractions, turning into a ~4 GiB iteration count in aes_decipher()/arc4_crypt()/rtw_seccalctkipmic() or a ~4 GiB crc32_le() length, causing out-of-bounds reads/writes of up to ~4 GiB starting from the rx skb. Reject such frames in decryptor() before touching the IV; this covers all three ciphers and the TKIP MIC check, and also keeps the unconditional iv[3] access within the frame.

2) validate_80211w_mgmt() keeps using the frame - two memcpys through the stale rx_data pointer and a pkt_len update - before checking whether decryptor() returned NULL. On decrypt failure (e.g. a unicast protected deauth/disassoc/action frame with a bad MIC, which this path always software-decrypts) the skb has already been freed, so this is a use-after-free read/write, and the caller's error path frees the frame a second time, drifting free_recvframe_cnt. Bail out immediately when decryptor() fails, freeing the temporary mgmt_DATA buffer first.

Discovered by Atuin - Automated Vulnerability Discovery Engine.

Fixes 554c0a3abf21 ("staging: Add rtl8723bs sdio wifi driver")
Assisted-by LLM
---
 drivers/staging/rtl8723bs/core/rtw_recv.c |   21 ++++++++++++++++++---
 1 file changed, 18 insertions(+), 3 deletions(-)
drivers/staging/rtl8723bs/core/rtw_recv.c +18 -3
@@ -426,8 +426,21 @@ static union recv_frame *decryptor(struc
 	u32  res = _SUCCESS;
 
 	if (prxattrib->encrypt > 0) {
-		u8 *iv = precv_frame->u.hdr.rx_data + prxattrib->hdrlen;
+		u8 *iv;
+		u32 min_len = prxattrib->hdrlen + prxattrib->iv_len + prxattrib->icv_len;
 
+		/* TKIP appends an 8-byte Michael MIC that icv_len doesn't account for */
+		if (prxattrib->encrypt == _TKIP_)
+			min_len += 8;
+
+		/* a protected frame must be long enough to hold the IV and ICV/MIC */
+		if (precv_frame->u.hdr.len < min_len) {
+			rtw_free_recvframe(precv_frame,
+					   &padapter->recvpriv.free_recv_queue);
+			return NULL;
+		}
+
+		iv = precv_frame->u.hdr.rx_data + prxattrib->hdrlen;
 		prxattrib->key_index = (((iv[3]) >> 6) & 0x3);
 
 		if (prxattrib->key_index > WEP_KEYS) {
@@ -1395,6 +1408,10 @@ static signed int validate_80211w_mgmt(s
 			if (!mgmt_DATA)
 				goto validate_80211w_fail;
 			precv_frame = decryptor(adapter, precv_frame);
+			if (!precv_frame) {
+				kfree(mgmt_DATA);
+				goto validate_80211w_fail;
+			}
 			/* save actual management data frame body */
 			memcpy(mgmt_DATA, ptr + pattrib->hdrlen + pattrib->iv_len, data_len);
 			/* overwrite the iv field */
@@ -1402,8 +1419,6 @@ static signed int validate_80211w_mgmt(s
 			/* remove the iv and icv length */
 			pattrib->pkt_len = pattrib->pkt_len - pattrib->iv_len - pattrib->icv_len;
 			kfree(mgmt_DATA);
-			if (!precv_frame)
-				goto validate_80211w_fail;
 		} else if (is_multicast_ether_addr(GetAddr1Ptr(ptr)) &&
 			(subtype == WIFI_DEAUTH || subtype == WIFI_DISASSOC)) {
 			signed int BIP_ret = _SUCCESS;
author maintainer
#247 lore raw

PATCH 247/547 xen-blkfront: unbind irq before tearing down ring and shadow requests

In reply to Greg Kroah-Hartman

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

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

From: Yuchao Zhang <[email protected]>

commit f3e27b7955727a4d7c0e9264a2a209fbba788bdc upstream.

In blkif_free_ring(), the driver tears down the ring's persistent grants, shadow request arrays, and shared ring structure (xenbus_teardown_ring), and only calls unbind_from_irqhandler() at the very end.

While blkif_free_ring() is freeing persistent grants and clearing the shadow array, the event channel interrupt (blkif_interrupt) is still registered and active. If an interrupt arrives from the backend during this teardown window, blkif_interrupt() reads rinfo->ring.sring and, via blkif_completion(), accesses rinfo->shadow[id].grants_used and rinfo->shadow[id].sg. blkif_free_ring() tears these structures down without holding rinfo->ring_lock, and the handler only checks info->connected at entry, so this is a real race resulting in a use-after-free or NULL pointer dereference.

Fix this by moving unbind_from_irqhandler() to the beginning of blkif_free_ring(). Calling unbind_from_irqhandler() first frees the IRQ and synchronizes with any in-flight interrupt handlers on other CPUs before ring memory and shadow request structures are deallocated, matching the teardown order in drivers/net/xen-netfront.c.

Fixes 11659569f720 ("xen/blkfront: split per device io_lock")

Message-ID: <[email protected]>

---
 drivers/block/xen-blkfront.c |   12 ++++++++----
 1 file changed, 8 insertions(+), 4 deletions(-)
drivers/block/xen-blkfront.c +8 -4
@@ -1211,6 +1211,14 @@ static void blkif_free_ring(struct blkfr
 	int i, j, segs;
 
 	/*
+	 * Interrupt teardown must be done ahead of freeing queue-related
+	 * data, otherwise the interrupt handler can race with the cleanup.
+	 */
+	if (rinfo->irq)
+		unbind_from_irqhandler(rinfo->irq, rinfo);
+	rinfo->evtchn = rinfo->irq = 0;
+
+	/*
 	 * Remove indirect pages, this only happens when using indirect
 	 * descriptors but not persistent grants
 	 */
@@ -1292,10 +1300,6 @@ free_shadow:
 	/* Free resources associated with old device channel. */
 	xenbus_teardown_ring((void **)&rinfo->ring.sring, info->nr_ring_pages,
 			     rinfo->ring_ref);
-
-	if (rinfo->irq)
-		unbind_from_irqhandler(rinfo->irq, rinfo);
-	rinfo->evtchn = rinfo->irq = 0;
 }
 
 static void blkif_free(struct blkfront_info *info, int suspend)
author maintainer
#248 lore raw

PATCH 248/547 wifi: ath9k: delete channel-context timers on deinit

In reply to Greg Kroah-Hartman

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

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

From: Rosen Penev <[email protected]>

commit 81394dfb9a7905472957628b560ae894eae3a30f upstream.

ath9k_deinit_channel_context() cancels chanctx_work but does not delete the offchannel and sched timers set up by ath9k_init_channel_context(). If either timer fires after deinit (e.g. during driver unload or suspend), it accesses sc->sc_ah which may already be freed by ath9k_hw_deinit(), causing a use-after-free.

Delete both timers with timer_shutdown_sync() before cancelling the work item.

Assisted-by LLM
Fixes 705d0bf83dbe ("ath9k: Add a routine for initializing channel contexts")
---
 drivers/net/wireless/ath/ath9k/channel.c |    2 ++
 1 file changed, 2 insertions(+)
drivers/net/wireless/ath/ath9k/channel.c +2 -0
@@ -1363,6 +1363,8 @@ void ath9k_init_channel_context(struct a
 
 void ath9k_deinit_channel_context(struct ath_softc *sc)
 {
+	timer_shutdown_sync(&sc->sched.timer);
+	timer_shutdown_sync(&sc->offchannel.timer);
 	cancel_work_sync(&sc->chanctx_work);
 }
 
author maintainer
#249 lore raw

PATCH 249/547 wifi: mt76: mt7996: unlink TWT flow if the MCU rejects the agreement

In reply to Greg Kroah-Hartman

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

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

From: Zhao Li <[email protected]>

commit 022f5f8b7a0580da50fcbc34da853d03d4321fe2 upstream.

mt7996_mac_add_twt_setup() links a new flow into dev->twt_list before asking the MCU to add the agreement, but exits without unlinking the flow if the request fails. The flow-ID and table masks are only committed after MCU success, so the still-linked flow is invisible to the mask-gated teardown paths.

If the station retries the setup, the same slot is cleared and its embedded list node reinitialized while it is still linked, corrupting dev->twt_list. If the station disassociates instead, teardown skips the flow and station storage can be freed while the node remains linked. A later scheduling or debugfs twt_stats walk can then dereference the freed flow, resulting in a use-after-free.

Unlink the flow when the MCU rejects the agreement. This restores the list to its pre-request state while leaving the unchanged mask and agreement accounting untouched.

Fixes 98686cd21624 ("wifi: mt76: mt7996: add driver for MediaTek Wi-Fi 7 (802.11be) devices")
Assisted-by Codex:gpt-5.6-sol
Assisted-by Kimi:K3
---
 drivers/net/wireless/mediatek/mt76/mt7996/mac.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/net/wireless/mediatek/mt76/mt7996/mac.c +3 -1
@@ -3285,8 +3285,10 @@ void mt7996_mac_add_twt_setup(struct iee
 	flow->tsf = le64_to_cpu(twt_agrt->twt);
 
 	if (mt7996_mcu_twt_agrt_update(dev, &msta->vif->deflink, flow,
-				       MCU_TWT_AGRT_ADD))
+				       MCU_TWT_AGRT_ADD)) {
+		list_del(&flow->list);
 		goto unlock;
+	}
 
 	setup_cmd = TWT_SETUP_CMD_ACCEPT;
 	dev->twt.table_mask |= BIT(table_id);
author maintainer
#250 lore raw

PATCH 250/547 virtio_net: atomically disable rx mode work

In reply to Greg Kroah-Hartman

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

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

From: Weiming Shi <[email protected]>

commit 1234707482053f1d1ac7c5756207d2c29057974c upstream.

virtio-net uses a boolean to gate rx_mode_work during device teardown. The flag is changed under RTNL, but ndo_set_rx_mode checks it under the address-list lock. A callback can therefore pass the check and enqueue work after teardown has flushed it. The work is also enabled before late probe operations that can fail, allowing probe unwind to free the netdev with work still queued.

KASAN reports the worker using a virtqueue that probe unwind already freed:

  BUG: KASAN: slab-use-after-free in virtqueue_add_split
  Workqueue: events virtnet_rx_mode_work
  Call Trace:
   virtqueue_add_split (drivers/virtio/virtio_ring.c:706)
   virtqueue_add_sgs (drivers/virtio/virtio_ring.c:2839)
   virtnet_send_command_reply (drivers/net/virtio_net.c:3565)
   virtnet_rx_mode_work (drivers/net/virtio_net.c:3833)
   process_one_work (kernel/workqueue.c:3322)
   worker_thread (kernel/workqueue.c:3405)
  Freed by task 119:
   kfree (mm/slub.c:6625)
   vp_del_vq.isra.0 (drivers/virtio/virtio_pci_common.c:259)
   vp_del_vqs (drivers/virtio/virtio_pci_common.c:285)
   virtnet_probe (drivers/net/virtio_net.c:7129)

Use the workqueue disable mechanism to atomically reject new queue attempts and drain running work. Keep work disabled until probe succeeds or restore has reattached the netdev, then enable it and replay receive-mode state for a running interface. Disable it before resource teardown in freeze and remove.

Fixes b9f7425239a0 ("virtio-net: convert rx mode setting to use workqueue")
Assisted-by LLM
---
 drivers/net/virtio_net.c |   26 +++++++++-----------------
 1 file changed, 9 insertions(+), 17 deletions(-)
drivers/net/virtio_net.c +9 -17
@@ -441,9 +441,6 @@ struct virtnet_info {
 	/* Work struct for setting rx mode */
 	struct work_struct rx_mode_work;
 
-	/* OK to queue work setting RX mode? */
-	bool rx_mode_work_enabled;
-
 	/* Does the affinity hint is set for virtqueues? */
 	bool affinity_hint_set;
 
@@ -710,16 +707,13 @@ static void virtnet_rq_free_buf(struct v
 
 static void enable_rx_mode_work(struct virtnet_info *vi)
 {
-	rtnl_lock();
-	vi->rx_mode_work_enabled = true;
-	rtnl_unlock();
+	if (enable_work(&vi->rx_mode_work) && netif_running(vi->dev))
+		schedule_work(&vi->rx_mode_work);
 }
 
 static void disable_rx_mode_work(struct virtnet_info *vi)
 {
-	rtnl_lock();
-	vi->rx_mode_work_enabled = false;
-	rtnl_unlock();
+	disable_work_sync(&vi->rx_mode_work);
 }
 
 static void virtqueue_napi_schedule(struct napi_struct *napi,
@@ -3925,8 +3919,7 @@ static void virtnet_set_rx_mode(struct n
 {
 	struct virtnet_info *vi = netdev_priv(dev);
 
-	if (vi->rx_mode_work_enabled)
-		schedule_work(&vi->rx_mode_work);
+	schedule_work(&vi->rx_mode_work);
 }
 
 static int virtnet_vlan_rx_add_vid(struct net_device *dev,
@@ -5742,7 +5735,6 @@ static void virtnet_freeze_down(struct v
 	/* Make sure no work handler is accessing the device */
 	flush_work(&vi->config_work);
 	disable_rx_mode_work(vi);
-	flush_work(&vi->rx_mode_work);
 
 	if (netif_running(vi->dev)) {
 		rtnl_lock();
@@ -5772,8 +5764,6 @@ static int virtnet_restore_up(struct vir
 
 	virtio_device_ready(vdev);
 
-	enable_rx_mode_work(vi);
-
 	if (netif_running(vi->dev)) {
 		rtnl_lock();
 		err = virtnet_open(vi->dev);
@@ -5785,6 +5775,8 @@ static int virtnet_restore_up(struct vir
 	netif_tx_lock_bh(vi->dev);
 	netif_device_attach(vi->dev);
 	netif_tx_unlock_bh(vi->dev);
+
+	enable_rx_mode_work(vi);
 	return 0;
 
 err_destroy_pools:
@@ -6880,6 +6872,7 @@ static int virtnet_probe(struct virtio_d
 
 	INIT_WORK(&vi->config_work, virtnet_config_changed_work);
 	INIT_WORK(&vi->rx_mode_work, virtnet_rx_mode_work);
+	disable_work(&vi->rx_mode_work);
 
 	if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF)) {
 		vi->mergeable_rx_bufs = true;
@@ -7038,8 +7031,6 @@ static int virtnet_probe(struct virtio_d
 	if (vi->has_rss || vi->has_rss_hash_report)
 		virtnet_init_default_rss(vi);
 
-	enable_rx_mode_work(vi);
-
 	for (i = 0; i < ARRAY_SIZE(guest_offloads); i++) {
 		unsigned int fbit;
 
@@ -7143,6 +7134,8 @@ static int virtnet_probe(struct virtio_d
 		goto free_unregister_netdev;
 	}
 
+	enable_rx_mode_work(vi);
+
 	pr_debug("virtnet: registered device %s with %d RX and TX vq's\n",
 		 dev->name, max_queue_pairs);
 
@@ -7195,7 +7188,6 @@ static void virtnet_remove(struct virtio
 	/* Make sure no work handler is accessing the device. */
 	flush_work(&vi->config_work);
 	disable_rx_mode_work(vi);
-	flush_work(&vi->rx_mode_work);
 
 	virtnet_free_irq_moder(vi);
 
author maintainer
#251 lore raw

PATCH 251/547 vfio/nvgrace-gpu: Use a core-only open_device in fallback mode

In reply to Greg Kroah-Hartman

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

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

From: Andrea Parri <[email protected]>

commit 9c48b994b66d7b585698f9aaee8ff559a7755c0a upstream.

When the ACPI memory properties are missing or the C2C link is down, the device is exposed through nvgrace_gpu_pci_core_ops. That table opens through nvgrace_gpu_open_device() but closes through vfio_pci_core_close_device(), so open and close are not symmetric.

nvgrace_gpu_open_device() registers nvdev->usemem for poison handling unconditionally. In fallback mode usemem.memlength is zero, and register_pfn_address_space() inserts a node covering [0, ULONG_MAX]. Nothing removes it: a second open fails with -EBUSY, and once the device is unbound the node outlives the nvdev that contains it. The next open after a rebind reports:

  BUG: KASAN: slab-use-after-free in interval_tree_iter_first+0x209/0x310
  Read of size 8 at addr ffff88800894aa30 by task nvgrace_repro/203
  Call Trace:
   <TASK>
   dump_stack_lvl+0x5d/0x80
   print_report+0x153/0x4c6
   kasan_report+0xe4/0x1a0
   interval_tree_iter_first+0x209/0x310
   register_pfn_address_space+0x97/0x100
   nvgrace_gpu_open_device+0x21c/0x730
   vfio_df_open+0x213/0x520
   vfio_df_ioctl_bind_iommufd+0x3e8/0x6e0
   vfio_device_fops_unl_ioctl+0x782/0x1570
   __x64_sys_ioctl+0x13c/0x1c0
   do_syscall_64+0x106/0x630
   entry_SYSCALL_64_after_hwframe+0x77/0x7f
   </TASK>

  Allocated by task 188:
   ...
   _vfio_alloc_device+0x3a/0x500
   nvgrace_gpu_probe+0xcb/0x660
   local_pci_probe+0xcf/0x170
   ...

  Freed by task 188:
   ...
   kfree+0x20d/0x600
   device_release+0xcf/0x250
   kobject_put+0x152/0x2f0
   pci_device_remove+0xb0/0x1c0
   device_release_driver_internal+0x38d/0x540
   unbind_store+0xde/0x100
   ...

Give the fallback table its own open_device that only calls vfio_pci_core_enable() and vfio_pci_core_finish_enable(), the counterpart of vfio_pci_core_close_device(). Fallback mode then never touches the nvgrace memory regions, as Alex suggested.

This should be safe because the fallback table uses the vfio-pci core read, write and mmap handlers, so nothing there uses the state nvgrace_gpu_open_device() sets up. The one visible difference is that a fallback open no longer fails when BAR0 cannot be mapped, which matches vfio-pci.

Fixes e5f19b619fa0 ("vfio/nvgrace-gpu: register device memory for poison handling")
Assisted-by LLM
---
 drivers/vfio/pci/nvgrace-gpu/main.c |   17 ++++++++++++++++-
 1 file changed, 16 insertions(+), 1 deletion(-)
drivers/vfio/pci/nvgrace-gpu/main.c +16 -1
@@ -1083,6 +1083,21 @@ static const struct vfio_device_ops nvgr
 	.detach_ioas	= vfio_iommufd_physical_detach_ioas,
 };
 
+static int nvgrace_gpu_core_open_device(struct vfio_device *core_vdev)
+{
+	struct vfio_pci_core_device *vdev =
+		container_of(core_vdev, struct vfio_pci_core_device, vdev);
+	int ret;
+
+	ret = vfio_pci_core_enable(vdev);
+	if (ret)
+		return ret;
+
+	vfio_pci_core_finish_enable(vdev);
+
+	return 0;
+}
+
 static const struct vfio_pci_device_ops nvgrace_gpu_pci_dev_core_ops = {
 	.get_dmabuf_phys = vfio_pci_core_get_dmabuf_phys,
 };
@@ -1091,7 +1106,7 @@ static const struct vfio_device_ops nvgr
 	.name		= "nvgrace-gpu-vfio-pci-core",
 	.init		= vfio_pci_core_init_dev,
 	.release	= vfio_pci_core_release_dev,
-	.open_device	= nvgrace_gpu_open_device,
+	.open_device	= nvgrace_gpu_core_open_device,
 	.close_device	= vfio_pci_core_close_device,
 	.ioctl		= vfio_pci_core_ioctl,
 	.get_region_info_caps = vfio_pci_ioctl_get_region_info,
author maintainer
#252 lore raw

PATCH 252/547 usb: gadget: fix refcount underflow in gadgetfs_bind() error path

In reply to Greg Kroah-Hartman

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

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

From: Nguyen Quang Le Kien <[email protected]>

commit cb3b441f2698455a48e9a023d5f7f4e3fcb94c73 upstream.

gadgetfs_bind() calls get_dev() only on the success path, but gadgetfs_unbind() called from the enomem error label unconditionally calls put_dev(). When bind fails (e.g. ENOMEM), put_dev() fires without a matching get_dev(), leaving the refcount unbalanced.

A subsequent close of the ep0 file descriptor calls dev_release() -> put_dev() which hits zero and frees the object; then gadgetfs_kill_sb() calls put_dev(the_device) again on the already-freed pointer, triggering a refcount underflow and use-after-free.

Fix by calling get_dev() at the start of gadgetfs_bind(), before any error path that invokes gadgetfs_unbind(), so the reference is always balanced regardless of whether bind succeeds or fails.

---
 drivers/usb/gadget/legacy/inode.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/usb/gadget/legacy/inode.c +2 -1
@@ -1692,6 +1692,8 @@ static int gadgetfs_bind(struct usb_gadg
 	dev->gadget = gadget;
 	gadget->ep0->driver_data = dev;
 
+	get_dev (dev);
+
 	/* preallocate control response and buffer */
 	dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
 	if (!dev->req)
@@ -1706,7 +1708,6 @@ static int gadgetfs_bind(struct usb_gadg
 	spin_lock_irq(&dev->lock);
 	dev->state = STATE_DEV_UNCONNECTED;
 	spin_unlock_irq(&dev->lock);
-	get_dev (dev);
 	return 0;
 
 enomem:
author maintainer
#253 lore raw

PATCH 253/547 ufs: use u64 for directory size in ufs_last_byte

In reply to Greg Kroah-Hartman

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

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

From: YANXIN LI <[email protected]>

commit 1eff23433e73d7da4f9e3529d2701e34962b161f upstream.

ufs1_read_inode() and ufs2_read_inode() copy the untrusted 64-bit on-disk size into inode->i_size. ufs_last_byte() then truncates that value to an unsigned int before calculating the valid extent of a directory folio.

A directory size of exactly 4 GiB is truncated to zero. In ufs_find_entry(), subtracting the requested record length from that zero forms an endpoint almost 4 GiB beyond the mapped folio. A crafted UFS2 image produces:

  BUG: KASAN: use-after-free in ufs_find_entry+0x583/0x6e0 [ufs]
  Read of size 1
  ...
  ufs_find_entry
  ufs_inode_by_name
  ufs_lookup
  __lookup_slow
  path_lookupat

The KASAN classification reflects that the adjacent physical page was free; the source-level operation is an out-of-folio read. A controlled UFS1 test with CONFIG_UFS_FS_WRITE enabled also made ufs_find_entry() return a directory entry from an adjacent anonymous page. unlink() then passed that pointer to ufs_delete_entry(), which cleared the adjacent page's 3
2-bit d_ino. This write result reproduced three out of three times.

UFS normally requires a privileged mount path. A relevant boundary is a privileged automounter or image-processing service handling an attacker-supplied filesystem. The write primitive additionally requires UFS1 to be mounted read-write with CONFIG_UFS_FS_WRITE enabled; the read is reachable with read-only UFS2.

Keep the intermediate size arithmetic at 64 bits so non-final pages are bounded at PAGE_SIZE. With this change, the same controlled tests reach the real on-disk directory entry and produce no adjacent-page write or KASAN report. A reproducer and full validation logs are available on request.

The vulnerable helper is present in v7.2-rc3, v7.1, v6.18.38, v6.12.95, v6.6.111, and upstream master at 1229e2e57a5c. Runtime reproduction and fix validation were performed in an x86-64 QEMU guest running v7.2-rc3 with generic KASAN.

Fixes b71034e5e67d ("[PATCH] ufs: directory and page cache: from blocks to pages")
---
 fs/ufs/dir.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/ufs/dir.c +1 -1
@@ -213,7 +213,7 @@ fail:
 static unsigned
 ufs_last_byte(struct inode *inode, unsigned long page_nr)
 {
-	unsigned last_byte = inode->i_size;
+	u64 last_byte = inode->i_size;
 
 	last_byte -= page_nr << PAGE_SHIFT;
 	if (last_byte > PAGE_SIZE)
author maintainer
#254 lore raw

PATCH 254/547 spi: spi-pci1xxxx: quiesce DMA engines on transfer timeout

In reply to Greg Kroah-Hartman

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

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

From: Weibin Liu <[email protected]>

commit 0b591332a2bdc13d3f9163793131fe3651d1556a upstream.

If a DMA-mapped transfer times out waiting for DMA_TERM and neither DMA abort interrupt arrived, pci1xxxx_spi_transfer_with_dma() returns through the error label while both DMA engines are still enabled, the done/abort interrupt status is still armed and the transfer state (p->xfer, p->tx_sgl, p->rx_sgl) is still registered.

The ISRs keep firing afterwards: they reprogram the DMA engines from p->tx_sgl / p->rx_sgl and signal completion through p->xfer and p->spi_xfer_done, all of which the SPI core is free to unmap or reuse once transfer_one() has returned, which is a use-after-free. A late done interrupt can also start the next transfer queued behind the failed one.

Stop both DMA engines, drain the pending done/abort interrupt status and synchronize the DMA IRQs before dropping the in-progress state and the transfer pointers, and re-enable the engines afterwards so that subsequent transfers keep working. The engines are only turned back on once both were confirmed to have stopped: re-enabling an engine that failed to stop would cancel the pending stop request and let it keep running into buffers the SPI core is about to unmap or free, which is exactly the window this patch closes. An engine that failed to stop is left disabled, as the abort paths already do.

The DMA interrupt status and mask registers are shared between the two SPI instances, so the cleanup drains only this instance's done/abort status bits instead of masking the interrupt lines, which would also suppress the peer instance's completion interrupts.

Also make the DMA ISRs ignore interrupts while no transfer is in progress so that a stray MSI after the cleanup can no longer act on the cleared state.

No PCI1XXXX hardware was available for testing and QEMU has no model of this PCIe part, so the timeout path was exercised with a userspace replica of the timeout branch and the DMA ISRs, with the register and interrupt accesses mocked: on the unfixed code both a wedged engine that clears after the timeout and a late done interrupt touch the freed transfer state, while with this fix applied neither does and an engine that failed to stop is left disabled. The module was also loaded and unloaded in a QEMU x86_64 guest running a kernel with this fix applied.

Fixes 9538edeb72c9 ("spi: mchp-pci1xxxx: DMA support for copying data to and from SPI Buf")
---
 drivers/spi/spi-pci1xxxx.c |   71 +++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 71 insertions(+)
drivers/spi/spi-pci1xxxx.c +71 -0
@@ -542,6 +542,8 @@ static int pci1xxxx_spi_transfer_with_dm
 	struct pci1xxxx_spi_internal *p = spi_controller_get_devdata(spi_ctlr);
 	struct pci1xxxx_spi *par = p->parent;
 	dma_addr_t tx_dma_addr = 0;
+	unsigned long flags;
+	bool engines_stopped;
 	int ret = 0;
 	u32 regval;
 
@@ -618,12 +620,72 @@ static int pci1xxxx_spi_transfer_with_dm
 			p->dma_aborted_wr = false;
 			ret = -ECANCELED;
 		}
+
+		/*
+		 * A timed out transfer leaves the DMA engines running and
+		 * the done/abort interrupt status armed with p->xfer,
+		 * p->tx_sgl and p->rx_sgl still registered.  Stop the
+		 * engines, drain the pending status and synchronize the
+		 * IRQs before dropping the transfer state, otherwise a
+		 * late interrupt makes the ISRs reprogram the engines
+		 * from or signal completion through memory which the SPI
+		 * core is about to unmap or free.
+		 */
+		writel(SPI_DMA_ENGINE_DIS,
+		       par->dma_offset_bar + SPI_DMA_GLOBAL_WR_ENGINE_EN);
+		writel(SPI_DMA_ENGINE_DIS,
+		       par->dma_offset_bar + SPI_DMA_GLOBAL_RD_ENGINE_EN);
+		engines_stopped =
+			!(readl_poll_timeout(par->dma_offset_bar +
+					     SPI_DMA_GLOBAL_WR_ENGINE_EN,
+					     regval, regval == 0x0, 0,
+					     USEC_PER_MSEC) ||
+			  readl_poll_timeout(par->dma_offset_bar +
+					     SPI_DMA_GLOBAL_RD_ENGINE_EN,
+					     regval, regval == 0x0, 0,
+					     USEC_PER_MSEC));
+		if (!engines_stopped)
+			dev_warn(&par->dev->dev,
+				 "SPI DMA engines failed to stop\n");
+
+		spin_lock_irqsave(&par->dma_wr_reg_lock, flags);
+		writel((SPI_DMA_DONE_INT_MASK(p->hw_inst) |
+			SPI_DMA_ABORT_INT_MASK(p->hw_inst)),
+		       par->dma_offset_bar + SPI_DMA_INTR_WR_CLR);
+		spin_unlock_irqrestore(&par->dma_wr_reg_lock, flags);
+		spin_lock_irqsave(&par->dma_rd_reg_lock, flags);
+		writel((SPI_DMA_DONE_INT_MASK(p->hw_inst) |
+			SPI_DMA_ABORT_INT_MASK(p->hw_inst)),
+		       par->dma_offset_bar + SPI_DMA_INTR_RD_CLR);
+		spin_unlock_irqrestore(&par->dma_rd_reg_lock, flags);
+
+		p->spi_xfer_in_progress = false;
+		synchronize_irq(p->irq[1]);
+		synchronize_irq(p->irq[2]);
+
+		/*
+		 * Turn the engines back on only once both are confirmed
+		 * to have stopped: re-enabling an engine that failed to
+		 * stop would cancel the pending stop request and let it
+		 * run into buffers the SPI core is about to unmap or
+		 * free.  An engine that failed to stop is left disabled,
+		 * as the abort paths already do.
+		 */
+		if (engines_stopped) {
+			writel(SPI_DMA_ENGINE_EN,
+			       par->dma_offset_bar + SPI_DMA_GLOBAL_WR_ENGINE_EN);
+			writel(SPI_DMA_ENGINE_EN,
+			       par->dma_offset_bar + SPI_DMA_GLOBAL_RD_ENGINE_EN);
+		}
 		goto error;
 	}
 	ret = 0;
 
 error:
 	p->spi_xfer_in_progress = false;
+	p->xfer = NULL;
+	p->tx_sgl = NULL;
+	p->rx_sgl = NULL;
 
 	return ret;
 }
@@ -695,6 +757,9 @@ static irqreturn_t pci1xxxx_spi_isr_dma_
 	unsigned long flags;
 	u32 regval;
 
+	if (!p->spi_xfer_in_progress)
+		return IRQ_NONE;
+
 	/* Clear the DMA RD INT and start spi xfer*/
 	regval = readl(p->parent->dma_offset_bar + SPI_DMA_INTR_RD_STS);
 	if (regval) {
@@ -723,6 +788,9 @@ static irqreturn_t pci1xxxx_spi_isr_dma_
 	unsigned long flags;
 	u32 regval;
 
+	if (!p->spi_xfer_in_progress)
+		return IRQ_NONE;
+
 	/* Clear the DMA WR INT */
 	regval = readl(p->parent->dma_offset_bar + SPI_DMA_INTR_WR_STS);
 	if (regval) {
@@ -755,6 +823,9 @@ static irqreturn_t pci1xxxx_spi_isr_dma(
 	irqreturn_t spi_int_fired = IRQ_NONE;
 	u32 regval;
 
+	if (!p->spi_xfer_in_progress)
+		return IRQ_NONE;
+
 	/* Clear the SPI GO_BIT Interrupt */
 	regval = readl(p->parent->reg_base + SPI_MST_EVENT_REG_OFFSET(p->hw_inst));
 	if (regval & SPI_INTR) {
author maintainer
#255 lore raw

PATCH 255/547 resource: report a devm_request_resource() conflict under the lock

In reply to Greg Kroah-Hartman

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

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

From: Nickolai Zeldovich <[email protected]>

commit d2f7bdfdeac8137e942b32e0badc40e181127d7b upstream.

devm_request_resource() calls request_resource_conflict(), which takes resource_lock, tries to insert the new resource and returns a pointer to the conflicting resource after dropping the lock. The error message is then formatted from that pointer: conflict->name and the %pR argument read the name, start, end, flags and desc of a resource that nothing pins any more. The owner of the conflicting resource may call release_resource() and free it the moment the lock is dropped.

The conflicting resource normally belongs to another device. With two devices whose drivers claim overlapping regions (two PCI host bridges whose "ranges" windows overlap, two instances of a controller on the same aperture, or a stale claim an administrator is replacing), the following interleaving reads freed memory:

CPU 0: driver B probe CPU 1: driver A unbind
devm_request_resource(devB, root, resB)

    request_resource_conflict()
      write_lock(&resource_lock)
      __request_resource() -> resA
      write_unlock(&resource_lock)
                                         devres_release_all(devA)
                                           devm_resource_release()
                                             release_resource(resA)
                                         put_device() -> kfree(resA)
    dev_err(..., resA->name, resA)        use after free

Both halves are reachable from userspace on any kernel: a write to the "unbind" file of the driver that holds the region and a write to the "bind" file of the driver that wants it. One in-tree path is drivers/pci/bus.c devm_request_pci_bus_resources(), called from host bridge probe for every bridge window; the windows are the embedded struct resource of kzalloc'ed resource_entry objects that pci_free_resource_list() frees when the other bridge is released. In the common case the "resource collision" message is garbled; with the slab object poisoned (CONFIG_SLUB_DEBUG) or reused, formatting conflict->name oopses, and KASAN reports a slab-use-after-free read in devm_request_resource(). All of this happens in a probe that is already failing with -EBUSY. The window is a few hundred instructions wide and exists only when two devices actually collide, so the race has not been observed outside of analysis.

Do the same here: take resource_lock, insert with __request_resource() and print the diagnostic while the lock still keeps the conflicting resource in the tree, then drop the lock. The return values and the devres handling are unchanged.

The change was built for x86_64 and RISC-V; the resource KUnit tests pass on both.

Found by formal verification of kernel/resource.c against the kernel binary.

Fixes 8d38821cbcf5 ("resources: Add device-managed request/release_resource()")
Assisted-by LLM
Cc Bjorn Helgaas <[email protected]>
Cc Ilpo Järvinen <[email protected]>
Cc Thierry Reding <[email protected]>
---
 kernel/resource.c |    9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
kernel/resource.c +7 -2
@@ -1695,10 +1695,15 @@ int devm_request_resource(struct device
 
 	*ptr = new;
 
-	conflict = request_resource_conflict(root, new);
-	if (conflict) {
+	/* Report a conflict while the lock still keeps it in the tree. */
+	write_lock(&resource_lock);
+	conflict = __request_resource(root, new);
+	if (conflict)
 		dev_err(dev, "resource collision: %pR conflicts with %s %pR\n",
 			new, conflict->name, conflict);
+	write_unlock(&resource_lock);
+
+	if (conflict) {
 		devres_free(ptr);
 		return -EBUSY;
 	}
author maintainer
#256 lore raw

PATCH 256/547 phy: core: Fix race-condition between _of_phy_get() and try_module_get()

In reply to Greg Kroah-Hartman

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

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

From: Bryan O'Donoghue <[email protected]>

commit 090055ee629523092688da42428558ba56d4272f upstream.

Sashiko asked during a patch review if the existing usage pattern had a race condition; specifically in of_phy_get() if it was possible between returning from _of_phy_get() and running try_module_get() that a module might be unbound leading to use-after-free.

Looking at the code this appears to be so, there is no linkage between the phy and module under a synchronisation primitive.

Using the phy_provider_mutex in phy_get() will ensure there is a link between the returned phy pointer and the module_get() bumping the module reference count.

Amend phy_get(), of_phy_get() and devm_of_phy_get_by_index() to fix the same usage pattern.

phy_provider_unregister() must take the phy_provider_mutex so amending phy_get()/of_phy_get() to take that same mutex guarantees there is no use-after-free.

---
 drivers/phy/phy-core.c |   45 ++++++++++++++++++++++++++++++---------------
 1 file changed, 30 insertions(+), 15 deletions(-)
drivers/phy/phy-core.c +30 -15
@@ -124,13 +124,13 @@ static struct phy *phy_find(struct devic
 	const char *dev_id = dev_name(dev);
 	struct phy_lookup *p, *pl = NULL;
 
-	mutex_lock(&phy_provider_mutex);
+	lockdep_assert_held(&phy_provider_mutex);
+
 	list_for_each_entry(p, &phys, node)
 		if (!strcmp(p->dev_id, dev_id) && !strcmp(p->con_id, con_id)) {
 			pl = p;
 			break;
 		}
-	mutex_unlock(&phy_provider_mutex);
 
 	return pl ? pl->phy : ERR_PTR(-ENODEV);
 }
@@ -624,6 +624,8 @@ static struct phy *_of_phy_get(struct de
 	struct phy *phy = NULL;
 	struct of_phandle_args args;
 
+	lockdep_assert_held(&phy_provider_mutex);
+
 	ret = of_parse_phandle_with_args(np, "phys", "#phy-cells",
 		index, &args);
 	if (ret)
@@ -635,11 +637,10 @@ static struct phy *_of_phy_get(struct de
 		goto out_put_node;
 	}
 
-	mutex_lock(&phy_provider_mutex);
 	phy_provider = of_phy_provider_lookup(args.np);
 	if (IS_ERR(phy_provider) || !try_module_get(phy_provider->owner)) {
 		phy = ERR_PTR(-EPROBE_DEFER);
-		goto out_unlock;
+		goto out_put_node;
 	}
 
 	if (!of_device_is_available(args.np)) {
@@ -653,8 +654,6 @@ static struct phy *_of_phy_get(struct de
 out_put_module:
 	module_put(phy_provider->owner);
 
-out_unlock:
-	mutex_unlock(&phy_provider_mutex);
 out_put_node:
 	of_node_put(args.np);
 
@@ -678,15 +677,21 @@ struct phy *of_phy_get(struct device_nod
 	if (con_id)
 		index = of_property_match_string(np, "phy-names", con_id);
 
+	mutex_lock(&phy_provider_mutex);
+
 	phy = _of_phy_get(np, index);
 	if (IS_ERR(phy))
-		return phy;
+		goto out_unlock;
 
-	if (!try_module_get(phy->ops->owner))
-		return ERR_PTR(-EPROBE_DEFER);
+	if (!try_module_get(phy->ops->owner)) {
+		phy = ERR_PTR(-EPROBE_DEFER);
+		goto out_unlock;
+	}
 
 	get_device(&phy->dev);
 
+out_unlock:
+	mutex_unlock(&phy_provider_mutex);
 	return phy;
 }
 EXPORT_SYMBOL_GPL(of_phy_get);
@@ -786,6 +791,7 @@ struct phy *phy_get(struct device *dev,
 	struct phy *phy;
 	struct device_link *link;
 
+	mutex_lock(&phy_provider_mutex);
 	if (dev->of_node) {
 		if (string)
 			index = of_property_match_string(dev->of_node, "phy-names",
@@ -796,15 +802,18 @@ struct phy *phy_get(struct device *dev,
 	} else {
 		if (string == NULL) {
 			dev_WARN(dev, "missing string\n");
-			return ERR_PTR(-EINVAL);
+			phy = ERR_PTR(-EINVAL);
+			goto out_unlock;
 		}
 		phy = phy_find(dev, string);
 	}
 	if (IS_ERR(phy))
-		return phy;
+		goto out_unlock;
 
-	if (!try_module_get(phy->ops->owner))
-		return ERR_PTR(-EPROBE_DEFER);
+	if (!try_module_get(phy->ops->owner)) {
+		phy = ERR_PTR(-EPROBE_DEFER);
+		goto out_unlock;
+	}
 
 	get_device(&phy->dev);
 
@@ -813,6 +822,8 @@ struct phy *phy_get(struct device *dev,
 		dev_dbg(dev, "failed to create device link to %s\n",
 			dev_name(phy->dev.parent));
 
+out_unlock:
+	mutex_unlock(&phy_provider_mutex);
 	return phy;
 }
 EXPORT_SYMBOL_GPL(phy_get);
@@ -961,15 +972,17 @@ struct phy *devm_of_phy_get_by_index(str
 	if (!ptr)
 		return ERR_PTR(-ENOMEM);
 
+	mutex_lock(&phy_provider_mutex);
 	phy = _of_phy_get(np, index);
 	if (IS_ERR(phy)) {
 		devres_free(ptr);
-		return phy;
+		goto out_unlock;
 	}
 
 	if (!try_module_get(phy->ops->owner)) {
 		devres_free(ptr);
-		return ERR_PTR(-EPROBE_DEFER);
+		phy = ERR_PTR(-EPROBE_DEFER);
+		goto out_unlock;
 	}
 
 	get_device(&phy->dev);
@@ -982,6 +995,8 @@ struct phy *devm_of_phy_get_by_index(str
 		dev_dbg(dev, "failed to create device link to %s\n",
 			dev_name(phy->dev.parent));
 
+out_unlock:
+	mutex_unlock(&phy_provider_mutex);
 	return phy;
 }
 EXPORT_SYMBOL_GPL(devm_of_phy_get_by_index);
author maintainer
#257 lore raw

PATCH 257/547 power: supply: pf1550: drain IRQ work before unregistering supplies

In reply to Greg Kroah-Hartman

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

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

From: Myeonghun Pak <[email protected]>

commit 4856b49317ccd4ce96a0e8970df7d13ce8975a02 upstream.

The VBUS work calls power_supply_changed(), but its managed cancellation is registered before the supplies. Cleanup can therefore unregister a supply while IRQ-triggered work is still pending.

Commit 838767f50747 ("power: supply: pf1550: Fix use-after-free in power_supply_changed()") moved IRQ requests after supply registration, but left work cancellation before the supplies. That change protects the direct IRQ callbacks, while this fix drains the work they queue.

Register the three work items after both supplies and before the IRQs. Cleanup then frees the IRQ producers, drains the work, and unregisters the supplies.

The teardown ordering issue was found by static analysis.

Fixes 4b6b6433a97d ("power: supply: pf1550: add battery charger support")
Assisted-by LLM
---
 drivers/power/supply/pf1550-charger.c |   32 ++++++++++++++++----------------
 1 file changed, 16 insertions(+), 16 deletions(-)
drivers/power/supply/pf1550-charger.c +16 -16
@@ -566,6 +566,22 @@ static int pf1550_charger_probe(struct p
 
 	platform_set_drvdata(pdev, chg);
 
+	psy_cfg.drv_data = chg;
+
+	chg->charger = devm_power_supply_register(&pdev->dev,
+						  &pf1550_charger_desc,
+						  &psy_cfg);
+	if (IS_ERR(chg->charger))
+		return dev_err_probe(&pdev->dev, PTR_ERR(chg->charger),
+				     "failed: power supply register\n");
+
+	chg->battery = devm_power_supply_register(&pdev->dev,
+						  &pf1550_battery_desc,
+						  &psy_cfg);
+	if (IS_ERR(chg->battery))
+		return dev_err_probe(&pdev->dev, PTR_ERR(chg->battery),
+				     "failed: power supply register\n");
+
 	ret = devm_delayed_work_autocancel(chg->dev, &chg->vbus_sense_work,
 					   pf1550_chg_vbus_work);
 	if (ret)
@@ -584,22 +600,6 @@ static int pf1550_charger_probe(struct p
 		return dev_err_probe(chg->dev, ret,
 				     "failed to add battery sense work\n");
 
-	psy_cfg.drv_data = chg;
-
-	chg->charger = devm_power_supply_register(&pdev->dev,
-						  &pf1550_charger_desc,
-						  &psy_cfg);
-	if (IS_ERR(chg->charger))
-		return dev_err_probe(&pdev->dev, PTR_ERR(chg->charger),
-				     "failed: power supply register\n");
-
-	chg->battery = devm_power_supply_register(&pdev->dev,
-						  &pf1550_battery_desc,
-						  &psy_cfg);
-	if (IS_ERR(chg->battery))
-		return dev_err_probe(&pdev->dev, PTR_ERR(chg->battery),
-				     "failed: power supply register\n");
-
 	for (i = 0; i < PF1550_CHARGER_IRQ_NR; i++) {
 		irq = platform_get_irq(pdev, i);
 		if (irq < 0)
author maintainer
#258 lore raw

PATCH 258/547 power: supply: sbs-battery: disable polling before supply teardown

In reply to Greg Kroah-Hartman

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

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

From: Myeonghun Pak <[email protected]>

commit 5c1c602463d597c5189ddc5a73dece588ba2c57a upstream.

The managed poll-work cancellation is registered before the power supply, so cleanup unregisters the supply before draining polling. A pending or running poller can then call power_supply_changed() on the released supply.

Commit 8d59cf3887fb ("power: supply: sbs-battery: Fix use-after-free in power_supply_changed()") moved the IRQ request after supply registration, but did not change the poll-work cancellation order.

Add a later managed action that disables and drains polling before supply teardown. Its retained disabled state prevents external-power callbacks from rearming the poll work after it has been drained. Keep the original autocancel to initialize work before supply callbacks can run and to cover failed supply registration.

The teardown ordering issue was found by static analysis.

Fixes 6d0c5de2fd84 ("power: supply: Clean-up few drivers by using managed work init")
Assisted-by LLM
---
 drivers/power/supply/sbs-battery.c |   11 +++++++++++
 1 file changed, 11 insertions(+)
drivers/power/supply/sbs-battery.c +11 -0
@@ -1068,6 +1068,13 @@ static void sbs_alert(struct i2c_client
 	sbs_supply_changed(i2c_get_clientdata(client));
 }
 
+static void sbs_disable_work(void *data)
+{
+	struct sbs_info *chip = data;
+
+	disable_delayed_work_sync(&chip->work);
+}
+
 static void sbs_external_power_changed(struct power_supply *psy)
 {
 	struct sbs_info *chip = power_supply_get_drvdata(psy);
@@ -1208,6 +1215,10 @@ static int sbs_probe(struct i2c_client *
 		return dev_err_probe(&client->dev, PTR_ERR(chip->power_supply),
 				     "Failed to register power supply\n");
 
+	rc = devm_add_action_or_reset(&client->dev, sbs_disable_work, chip);
+	if (rc)
+		return rc;
+
 	if (!chip->gpio_detect)
 		goto out;
 
author maintainer
#259 lore raw

PATCH 259/547 pps: generators: dont use the drivers info after unregister

In reply to Greg Kroah-Hartman

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

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

From: Danish Khateeb <[email protected]>

commit 4e8063cae337cb7328e6856235cf4de5d165516e upstream.

A file that was opened before pps_gen_unregister_source() keeps pps_gen, and with it the pointer to the driver's pps_gen_source_info. PPS_GEN_SETENABLE and PPS_GEN_USESYSTEMCLOCK keep using that pointer after the driver has gone:

- pps_gen_tio allocates its info with devm_kzalloc(), so after an unbind both ioctls read freed memory, and SETENABLE calls the driver's enable() with its freed private data.

- pps_gen-dummy does not set info->owner, so it can be unloaded while the file is open, and the ioctls then read the unloaded module's data and call its code.

TIO can't probe in a VM, as it needs ART. A test driver that registers its info in devm memory like TIO does, unbound while /dev/pps-gen0 is open, gives:

  BUG: KASAN: slab-use-after-free in pps_gen_cdev_ioctl+0x4c1/0x580
  Read of size 1 at addr ffff88800e647f38 by task ppsgen64/145
  ...
  Freed by task 146:
   kfree+0x25a/0x6d0
   release_nodes+0xd1/0x140
   devres_release_all+0x10e/0x1a0
   device_unbind_cleanup+0x71/0x250
   device_release_driver_internal+0x41b/0x570
   unbind_store+0xd9/0x100

and unloading pps_gen-dummy while its file is open oopses:

  BUG: unable to handle page fault for address: ffffffffa0203040
  Oops: Oops: 0000 [#1] SMP KASAN NOPTI
  RIP: 0010:pps_gen_cdev_ioctl+0x372/0x580

Protect info in the ioctl handler with a mutex, and clear it under the mutex on unregister, so that unregister waits for the ioctls using it and later ones fail with -ENODEV. PPS_KC_BIND does the same for a removed PPS device since commit 3649f9a6b897 ("pps: don't allow PPS_KC_BIND on removed devices"). The sysfs attributes need nothing
new: they are removed, and their callbacks drained, before info is cleared.

---
 drivers/pps/generators/pps_gen.c |   31 ++++++++++++++++++++++++++-----
 include/linux/pps_gen_kernel.h   |    2 ++
 2 files changed, 28 insertions(+), 5 deletions(-)
drivers/pps/generators/pps_gen.c +26 -5
@@ -69,17 +69,28 @@ static long pps_gen_cdev_ioctl(struct fi
 		if (ret)
 			return -EFAULT;
 
-		ret = pps_gen->info->enable(pps_gen, status);
-		if (ret)
-			return ret;
-		pps_gen->enabled = status;
+		scoped_guard(mutex, &pps_gen->info_lock) {
+			if (!pps_gen->info)
+				return -ENODEV;
+
+			ret = pps_gen->info->enable(pps_gen, status);
+			if (ret)
+				return ret;
+			pps_gen->enabled = status;
+		}
 
 		break;
 
 	case PPS_GEN_USESYSTEMCLOCK:
 		dev_dbg(&pps_gen->dev, "PPS_GEN_USESYSTEMCLOCK\n");
 
-		ret = put_user(pps_gen->info->use_system_clock, uiuarg);
+		scoped_guard(mutex, &pps_gen->info_lock) {
+			if (!pps_gen->info)
+				return -ENODEV;
+			status = pps_gen->info->use_system_clock;
+		}
+
+		ret = put_user(status, uiuarg);
 		if (ret)
 			return -EFAULT;
 
@@ -212,6 +223,15 @@ static void pps_gen_unregister_cdev(stru
 {
 	pr_debug("unregistering pps-gen%d\n", pps_gen->id);
 	cdev_device_del(&pps_gen->cdev, &pps_gen->dev);
+
+	/*
+	 * An open file keeps pps_gen around, but the driver may free info as
+	 * soon as we return. The sysfs files are gone now, so wait for the
+	 * ioctls using info and make later ones fail.
+	 */
+	scoped_guard(mutex, &pps_gen->info_lock)
+		pps_gen->info = NULL;
+
 	put_device(&pps_gen->dev);
 }
 
@@ -243,6 +263,7 @@ struct pps_gen_device *pps_gen_register_
 	pps_gen->info = info;
 	pps_gen->enabled = false;
 
+	mutex_init(&pps_gen->info_lock);
 	init_waitqueue_head(&pps_gen->queue);
 	spin_lock_init(&pps_gen->lock);
 
include/linux/pps_gen_kernel.h +2 -0
@@ -11,6 +11,7 @@
 #include <linux/pps_gen.h>
 #include <linux/cdev.h>
 #include <linux/device.h>
+#include <linux/mutex.h>
 
 /*
  * Global defines
@@ -44,6 +45,7 @@ struct pps_gen_source_info {
 /* The main struct */
 struct pps_gen_device {
 	const struct pps_gen_source_info *info;	/* PSS generator info */
+	struct mutex info_lock;			/* protects info */
 	bool enabled;				/* PSS generator status */
 
 	unsigned int event;
author maintainer
#260 lore raw

PATCH 260/547 nvmem: core: Fix OOB read for bit offsets of more than one byte

In reply to Greg Kroah-Hartman

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

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

From: Janne Grunau <[email protected]>

commit 24530401e8001aaa637dd5007fcdc6fbc00300be upstream.

When the bit offset is BITS_PER_BYTE or larger the read position is advanced by bytes_offset. This is not taken into account in the per-byte read loop which still reads cell->bytes resulting in an out of bounds read of bytes_offset bytes. The information read OOB does not leak directly as the erroneously read bits are cleared.

Detected by KASAN while looking for a use-after-free in simplefb.c.

---
 drivers/nvmem/core.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/nvmem/core.c +3 -1
@@ -1598,12 +1598,14 @@ static void nvmem_shift_read_buffer_in_p
 		*p = *b++ >> bit_offset;
 
 		/* setup rest of the bytes if any */
-		for (i = 1; i < cell->bytes; i++) {
+		for (i = 1; i < (cell->bytes - bytes_offset); i++) {
 			/* Get bits from next byte and shift them towards msb */
 			*p++ |= *b << (BITS_PER_BYTE - bit_offset);
 
 			*p = *b++ >> bit_offset;
 		}
+		/* point to end of the buffer unused bits will be cleared */
+		p = buf + cell->bytes - 1;
 	} else if (p != b) {
 		memmove(p, b, cell->bytes - bytes_offset);
 		p += cell->bytes - 1;
author maintainer
#261 lore raw

PATCH 261/547 nvmet-auth: serialize access to DH-HMAC-CHAP state to fix UAF

In reply to Greg Kroah-Hartman

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

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

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

commit 53f6efe00cea0c0cf7bd99debe3cdac8567170b5 upstream.

A REPLY AUTH_SEND command can derive a dhchap_skey key while a concurrent AUTH_RECEIVE command observing this REPLY state executes the failure path and frees that key. The REPLY command then continues and writes into freed memory, causing a use-after-free. KASAN reports it as:

  BUG: KASAN: slab-use-after-free in __sha256_final
  Write of size 4 at addr ffff88800359c540
  ...
  nvmet_auth_sq_free (drivers/nvme/target/auth.c:237)
  nvmet_execute_auth_receive (drivers/nvme/target/fabrics-cmd-auth.c:621)

Add a mutex to each submission queue to serialize authentication commands and timeout handling. Unlock the mutex before completing requests and ignore outdated timeout callbacks. Limit timeout delays to prevent immediate expiry on 32-bit kernels.

Fixes 7a277c37d352 ("nvmet-auth: Diffie-Hellman key exchange support")
Assisted-by LLM
---
 drivers/nvme/target/auth.c             |    1 +
 drivers/nvme/target/fabrics-cmd-auth.c |   32 ++++++++++++++++++++++++++++----
 drivers/nvme/target/nvmet.h            |    2 ++
 3 files changed, 31 insertions(+), 4 deletions(-)
drivers/nvme/target/auth.c +1 -0
@@ -229,6 +229,7 @@ out_unlock:
 
 void nvmet_auth_sq_free(struct nvmet_sq *sq)
 {
+	sq->auth_expiry_active = false;
 	cancel_delayed_work(&sq->auth_expired_work);
 	kfree(sq->dhchap_c1);
 	sq->dhchap_c1 = NULL;
drivers/nvme/target/fabrics-cmd-auth.c +28 -4
@@ -6,6 +6,7 @@
  */
 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
 #include <linux/blkdev.h>
+#include <linux/jiffies.h>
 #include <linux/random.h>
 #include <linux/nvme-auth.h>
 #include <crypto/kpp.h>
@@ -17,16 +18,27 @@ static void nvmet_auth_expired_work(stru
 	struct nvmet_sq *sq = container_of(to_delayed_work(work),
 			struct nvmet_sq, auth_expired_work);
 
+	mutex_lock(&sq->auth_lock);
+	/* A command may have cancelled or rearmed this timeout. */
+	if (!sq->auth_expiry_active ||
+	    delayed_work_pending(&sq->auth_expired_work))
+		goto out_unlock;
+	sq->auth_expiry_active = false;
+
 	pr_debug("%s: ctrl %d qid %d transaction %u expired, resetting\n",
 		 __func__, sq->ctrl->cntlid, sq->qid, sq->dhchap_tid);
 	sq->dhchap_step = NVME_AUTH_DHCHAP_MESSAGE_NEGOTIATE;
 	sq->dhchap_tid = -1;
+out_unlock:
+	mutex_unlock(&sq->auth_lock);
 }
 
 void nvmet_auth_sq_init(struct nvmet_sq *sq)
 {
 	/* Initialize in-band authentication */
+	mutex_init(&sq->auth_lock);
 	INIT_DELAYED_WORK(&sq->auth_expired_work, nvmet_auth_expired_work);
+	sq->auth_expiry_active = false;
 	sq->authenticated = false;
 	sq->dhchap_step = NVME_AUTH_DHCHAP_MESSAGE_NEGOTIATE;
 }
@@ -256,6 +268,8 @@ void nvmet_execute_auth_send(struct nvme
 	u16 status = 0;
 	u8 dhchap_status;
 
+	mutex_lock(&req->sq->auth_lock);
+
 	if (req->cmd->auth_send.secp != NVME_AUTH_DHCHAP_PROTOCOL_IDENTIFIER) {
 		status = NVME_SC_INVALID_FIELD | NVME_STATUS_DNR;
 		req->error_loc =
@@ -281,8 +295,10 @@ void nvmet_execute_auth_send(struct nvme
 			offsetof(struct nvmf_auth_send_command, tl);
 		goto done;
 	}
-	if (!nvmet_check_transfer_len(req, tl)) {
+	if (unlikely(tl != req->transfer_len)) {
 		pr_debug("%s: transfer length mismatch (%u)\n", __func__, tl);
+		mutex_unlock(&req->sq->auth_lock);
+		nvmet_check_transfer_len(req, tl);
 		return;
 	}
 
@@ -406,10 +422,12 @@ done:
 			 status, req->error_loc);
 	if (req->sq->dhchap_step != NVME_AUTH_DHCHAP_MESSAGE_SUCCESS2 &&
 	    req->sq->dhchap_step != NVME_AUTH_DHCHAP_MESSAGE_FAILURE2) {
-		unsigned long auth_expire_secs = ctrl->kato ? ctrl->kato : 120;
+		unsigned long auth_expire = min_t(u64, MAX_JIFFY_OFFSET,
+			(u64)(ctrl->kato ? ctrl->kato : 120) * HZ);
 
+		req->sq->auth_expiry_active = true;
 		mod_delayed_work(system_percpu_wq, &req->sq->auth_expired_work,
-				 auth_expire_secs * HZ);
+				 auth_expire);
 		goto complete;
 	}
 	/* Final states, clear up variables */
@@ -418,6 +436,7 @@ done:
 		nvmet_ctrl_fatal_error(ctrl);
 
 complete:
+	mutex_unlock(&req->sq->auth_lock);
 	nvmet_req_complete(req, status);
 }
 
@@ -536,6 +555,8 @@ void nvmet_execute_auth_receive(struct n
 	u32 al;
 	u16 status = 0;
 
+	mutex_lock(&req->sq->auth_lock);
+
 	if (req->cmd->auth_receive.secp != NVME_AUTH_DHCHAP_PROTOCOL_IDENTIFIER) {
 		status = NVME_SC_INVALID_FIELD | NVME_STATUS_DNR;
 		req->error_loc =
@@ -561,8 +582,10 @@ void nvmet_execute_auth_receive(struct n
 			offsetof(struct nvmf_auth_receive_command, al);
 		goto done;
 	}
-	if (!nvmet_check_transfer_len(req, al)) {
+	if (unlikely(al != req->transfer_len)) {
 		pr_debug("%s: transfer length mismatch (%u)\n", __func__, al);
+		mutex_unlock(&req->sq->auth_lock);
+		nvmet_check_transfer_len(req, al);
 		return;
 	}
 
@@ -621,5 +644,6 @@ done:
 		nvmet_auth_sq_free(req->sq);
 		nvmet_ctrl_fatal_error(ctrl);
 	}
+	mutex_unlock(&req->sq->auth_lock);
 	nvmet_req_complete(req, status);
 }
drivers/nvme/target/nvmet.h +2 -0
@@ -161,8 +161,10 @@ struct nvmet_sq {
 	u32			sqhd;
 	bool			sqhd_disabled;
 #ifdef CONFIG_NVME_TARGET_AUTH
+	struct mutex		auth_lock;
 	bool			authenticated;
 	struct delayed_work	auth_expired_work;
+	bool			auth_expiry_active;
 	u16			dhchap_tid;
 	u8			sc_c;
 	u8			dhchap_status;
author maintainer
#262 lore raw

PATCH 262/547 media: rc: Ensure that rc_unregister_device() does not free input device

In reply to Greg Kroah-Hartman

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

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

From: Sean Young <[email protected]>

commit 61c7ca95d2483c77dfdde1b007cbe846f145dec4 upstream.

During or after rc_unregister_device(), IR may still be reported which results in a input event being reported. This could result in a null pointer deref in rc_keydown() or a use-after-free of the input device if the pointer was read before it is set to NULL.

Fixes dccc0c3ddf8f ("media: rc: fix race between unregister and urb/irq callbacks")
---
 drivers/media/rc/rc-main.c |    8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
drivers/media/rc/rc-main.c +4 -4
@@ -1742,7 +1742,7 @@ void rc_free_device(struct rc_dev *dev)
 	if (!dev)
 		return;
 
-	input_free_device(dev->input_dev);
+	input_put_device(dev->input_dev);
 
 	put_device(&dev->dev);
 
@@ -1854,6 +1854,8 @@ static int rc_setup_rx_device(struct rc_
 	if (rc)
 		return rc;
 
+	input_get_device(dev->input_dev);
+
 	/*
 	 * Default delay of 250ms is too short for some protocols, especially
 	 * since the timeout is currently set to 250ms. Increase it to 500ms,
@@ -1880,10 +1882,8 @@ static void rc_free_rx_device(struct rc_
 	if (!dev)
 		return;
 
-	if (dev->input_dev) {
+	if (dev->input_dev)
 		input_unregister_device(dev->input_dev);
-		dev->input_dev = NULL;
-	}
 
 	ir_free_table(&dev->rc_map);
 }
author maintainer
#263 lore raw

PATCH 263/547 media: rc: Ensure registered is cleared in error path

In reply to Greg Kroah-Hartman

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

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

From: Sean Young <[email protected]>

commit 37efd09ba2c62e46e3a3a793025c186f8cd1a417 upstream.

If rc_register_device() fails, ensure that registered is not set to true. If lirc_register() succeeded, then userspace could have an open file descriptor open. This leads to a use-after-free.

lirc_unregister() must be called with registered = false, else there is a possibility that an fd is open and polling, which would never return POLLERR unless registered is false.

Note that registered must be changed under dev->lock, many functions read registered under lock (e.g. lirc_ioctl).

Fixes dccc0c3ddf8f ("media: rc: fix race between unregister and urb/irq callbacks")
---
 drivers/media/rc/rc-main.c |   16 ++++++++++++----
 1 file changed, 12 insertions(+), 4 deletions(-)
drivers/media/rc/rc-main.c +12 -4
@@ -1929,7 +1929,8 @@ int rc_register_device(struct rc_dev *de
 			goto out_raw;
 	}
 
-	dev->registered = true;
+	scoped_guard(mutex, &dev->lock)
+		dev->registered = true;
 
 	rc = device_add(&dev->dev);
 	if (rc)
@@ -1949,7 +1950,7 @@ int rc_register_device(struct rc_dev *de
 	if (dev->allowed_protocols != RC_PROTO_BIT_CEC) {
 		rc = lirc_register(dev);
 		if (rc < 0)
-			goto out_dev;
+			goto out_lirc;
 	}
 
 	if (dev->driver_type != RC_DRIVER_IR_RAW_TX) {
@@ -1972,11 +1973,18 @@ int rc_register_device(struct rc_dev *de
 out_rx:
 	rc_free_rx_device(dev);
 out_lirc:
-	if (dev->allowed_protocols != RC_PROTO_BIT_CEC)
+	scoped_guard(mutex, &dev->lock)
+		dev->registered = false;
+
+	if (device_is_registered(&dev->lirc_dev))
 		lirc_unregister(dev);
-out_dev:
 	device_del(&dev->dev);
+	/* registered already cleared above */
+	goto out_free_table;
 out_rx_free:
+	scoped_guard(mutex, &dev->lock)
+		dev->registered = false;
+out_free_table:
 	ir_free_table(&dev->rc_map);
 out_raw:
 	ir_raw_event_free(dev);
author maintainer
#264 lore raw

PATCH 264/547 media: rc: fintek-cir: process a full RX buffer instead of overflowing it

In reply to Greg Kroah-Hartman

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

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

From: Weigang He <[email protected]>

commit d1febef1bcfa7bbc401729f994c375b91a833911 upstream.

fintek_get_rx_ir_data() drains the CIR RX FIFO into fintek->buf[], which holds RX_BUF_LEN (32) bytes, for as long as CIR_STATUS reports pending RX data:

	do {
		sample = fintek_cir_reg_read(fintek, CIR_RX_DATA);
		...
		fintek->buf[fintek->pkts] = sample;
		fintek->pkts++;
		...
	} while (status & rx_irqs);

Nothing bounds fintek->pkts. If the hardware reports data for more than RX_BUF_LEN reads in one interrupt, the loop writes past the end of buf[], starting with the pkts counter that follows it in struct fintek_dev.

Hand a full buffer to fintek_process_rx_ir_data(), which parses the samples and resets fintek->pkts, before storing the next sample. This keeps the parser state consistent and drops no samples. The loop still relies on the status register to terminate.

The driver does not document the hardware FIFO depth, so it is not known whether a working device can trigger this.

Found by static analysis tool CodeQL.

Fixes 9bdc79ea07d9 ("[media] fintek-cir: new driver for Fintek LPC SuperIO CIR function")
Assisted-by LLM codeql
---
 drivers/media/rc/fintek-cir.c |    4 ++++
 1 file changed, 4 insertions(+)
drivers/media/rc/fintek-cir.c +4 -0
@@ -340,6 +340,10 @@ static void fintek_get_rx_ir_data(struct
 		sample = fintek_cir_reg_read(fintek, CIR_RX_DATA);
 		fit_dbg("%s: sample: 0x%02x", __func__, sample);
 
+		/* Process a full buffer before storing the next sample. */
+		if (fintek->pkts >= RX_BUF_LEN)
+			fintek_process_rx_ir_data(fintek);
+
 		fintek->buf[fintek->pkts] = sample;
 		fintek->pkts++;
 
author maintainer
#265 lore raw

PATCH 265/547 media: rc: Fix race between bpf(BPG_PROG_ATTACH) and device unregister

In reply to Greg Kroah-Hartman

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

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

From: Sean Young <[email protected]>

commit b3f5daf3222999d3f92f606a4eb5e35ab90fd0e4 upstream.

Mark the device as unregistered before tearing down raw IR/bpf state, so that racing bpf(BPF_PROG_{ATTACH,DETACH,QUERY}) calls cannot slip in between ir_raw_event_unregister() completing and dev->registered being cleared.

Fixes dccc0c3ddf8f ("media: rc: fix race between unregister and urb/irq callbacks")
---
 drivers/media/rc/rc-main.c |   12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
drivers/media/rc/rc-main.c +6 -6
@@ -2026,18 +2026,18 @@ void rc_unregister_device(struct rc_dev
 	if (!dev)
 		return;
 
+	mutex_lock(&dev->lock);
+	dev->registered = false;
+	if (dev->users && dev->close)
+		dev->close(dev);
+	mutex_unlock(&dev->lock);
+
 	if (dev->driver_type == RC_DRIVER_IR_RAW)
 		ir_raw_event_unregister(dev);
 
 	timer_delete_sync(&dev->timer_keyup);
 	timer_delete_sync(&dev->timer_repeat);
 
-	mutex_lock(&dev->lock);
-	if (dev->users && dev->close)
-		dev->close(dev);
-	dev->registered = false;
-	mutex_unlock(&dev->lock);
-
 	rc_free_rx_device(dev);
 
 	/*
author maintainer
#266 lore raw

PATCH 266/547 media: rc: Fix race condition during rc_register_device()

In reply to Greg Kroah-Hartman

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

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

From: Sean Young <[email protected]>

commit ec7cb49871e5c4f85d57290320c50ee0bae4db84 upstream.

Device drivers can call ir_raw_event_store() or ir_raw_event_handle() right after rc_allocate_device(). This means that while rc_register_device() is being called, those functions can be called from e.g. interrupt handlers.

Currently dev->raw is being allocated and populated by ir_raw_event_prepare() which is called from rc_register_device(). This is not done in a safe way, e.g. dev->raw is being set before the raw members are populated.

Call ir_raw_event_prepare() from rc_allocate_device() instead.

Fixes a3572c34da8d ("V4L/DVB: ir-core: Add logic to decode IR protocols at the IR core")
---
 drivers/media/rc/rc-ir-raw.c |   20 +-------------------
 drivers/media/rc/rc-main.c   |   19 +++++++++++--------
 2 files changed, 12 insertions(+), 27 deletions(-)
drivers/media/rc/rc-ir-raw.c +1 -19
@@ -71,9 +71,6 @@ static int ir_raw_event_thread(void *dat
  */
 int ir_raw_event_store(struct rc_dev *dev, struct ir_raw_event *ev)
 {
-	if (!dev->raw)
-		return -EINVAL;
-
 	dev_dbg(&dev->dev, "sample: (%05dus %s)\n",
 		ev->duration, TO_STR(ev->pulse));
 
@@ -102,9 +99,6 @@ int ir_raw_event_store_edge(struct rc_de
 	ktime_t			now;
 	struct ir_raw_event	ev = {};
 
-	if (!dev->raw)
-		return -EINVAL;
-
 	now = ktime_get();
 	ev.duration = ktime_to_us(ktime_sub(now, dev->raw->last_event));
 	ev.pulse = !pulse;
@@ -129,9 +123,6 @@ int ir_raw_event_store_with_timeout(stru
 	ktime_t		now;
 	int		rc = 0;
 
-	if (!dev->raw)
-		return -EINVAL;
-
 	now = ktime_get();
 
 	spin_lock(&dev->raw->edge_spinlock);
@@ -166,9 +157,6 @@ EXPORT_SYMBOL_GPL(ir_raw_event_store_wit
  */
 int ir_raw_event_store_with_filter(struct rc_dev *dev, struct ir_raw_event *ev)
 {
-	if (!dev->raw)
-		return -EINVAL;
-
 	/* Ignore spaces in idle mode */
 	if (dev->idle && !ev->pulse)
 		return 0;
@@ -200,9 +188,6 @@ EXPORT_SYMBOL_GPL(ir_raw_event_store_wit
  */
 void ir_raw_event_set_idle(struct rc_dev *dev, bool idle)
 {
-	if (!dev->raw)
-		return;
-
 	dev_dbg(&dev->dev, "%s idle mode\n", idle ? "enter" : "leave");
 
 	if (idle) {
@@ -226,7 +211,7 @@ EXPORT_SYMBOL_GPL(ir_raw_event_set_idle)
  */
 void ir_raw_event_handle(struct rc_dev *dev)
 {
-	if (!dev->raw || !dev->raw->thread)
+	if (!dev->raw->thread)
 		return;
 
 	wake_up_process(dev->raw->thread);
@@ -612,9 +597,6 @@ EXPORT_SYMBOL(ir_raw_encode_carrier);
  */
 int ir_raw_event_prepare(struct rc_dev *dev)
 {
-	if (!dev)
-		return -EINVAL;
-
 	dev->raw = kzalloc_obj(*dev->raw);
 	if (!dev->raw)
 		return -ENOMEM;
drivers/media/rc/rc-main.c +11 -8
@@ -1701,14 +1701,24 @@ static const struct device_type rc_dev_t
 struct rc_dev *rc_allocate_device(enum rc_driver_type type)
 {
 	struct rc_dev *dev;
+	int ret;
 
 	dev = kzalloc_obj(*dev);
 	if (!dev)
 		return NULL;
 
+	if (type == RC_DRIVER_IR_RAW) {
+		ret = ir_raw_event_prepare(dev);
+		if (ret < 0) {
+			kfree(dev);
+			return NULL;
+		}
+	}
+
 	if (type != RC_DRIVER_IR_RAW_TX) {
 		dev->input_dev = input_allocate_device();
 		if (!dev->input_dev) {
+			ir_raw_event_free(dev);
 			kfree(dev);
 			return NULL;
 		}
@@ -1724,6 +1734,7 @@ struct rc_dev *rc_allocate_device(enum r
 		spin_lock_init(&dev->rc_map.lock);
 		spin_lock_init(&dev->keylock);
 	}
+
 	mutex_init(&dev->lock);
 
 	dev->dev.type = &rc_dev_type;
@@ -1917,12 +1928,6 @@ int rc_register_device(struct rc_dev *de
 		dev->sysfs_groups[attr++] = &rc_dev_wakeup_filter_attr_grp;
 	dev->sysfs_groups[attr++] = NULL;
 
-	if (dev->driver_type == RC_DRIVER_IR_RAW) {
-		rc = ir_raw_event_prepare(dev);
-		if (rc < 0)
-			goto out_minor;
-	}
-
 	if (dev->driver_type != RC_DRIVER_IR_RAW_TX) {
 		rc = rc_prepare_rx_device(dev);
 		if (rc)
@@ -1987,8 +1992,6 @@ out_rx_free:
 out_free_table:
 	ir_free_table(&dev->rc_map);
 out_raw:
-	ir_raw_event_free(dev);
-out_minor:
 	ida_free(&rc_ida, minor);
 	return rc;
 }
author maintainer
#267 lore raw

PATCH 267/547 media: rc: mce_kbd: Fix inconsistent locking of keylock

In reply to Greg Kroah-Hartman

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

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

From: Sean Young <[email protected]>

commit 29ee25fa9beb3232808e6d0b3e8ebfb0427cb820 upstream.

data->keylock is taken with spin_lock() in ir_mce_kbd_decode(), which runs in the raw IR decode kthread with local interrupts enabled, but with spin_lock_irqsave() in mce_kbd_rx_timeout(), the rx_timeout timer callback, which runs in softirq context.

If the decode kthread is holding keylock via spin_lock() when a timer interrupt fires on the same CPU and the softirq runs mce_kbd_rx_timeout(), the softirq spins forever waiting for a lock that only the now-preempted kthread can release, while the kthread cannot run again until the softirq gives up the CPU. This deadlocks the CPU.

Fixes 53a62800efb2 ("media: rc: mce_kbd decoder: fix race condition")
---
 drivers/media/rc/ir-mce_kbd-decoder.c |    5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/media/rc/ir-mce_kbd-decoder.c +3 -2
@@ -219,6 +219,7 @@ static int ir_mce_kbd_decode(struct rc_d
 	struct mce_kbd_dec *data = &dev->raw->mce_kbd;
 	u32 scancode;
 	unsigned long delay;
+	unsigned long flags;
 	struct lirc_scancode lsc = {};
 
 	if (!is_timing_event(ev)) {
@@ -319,7 +320,7 @@ again:
 			scancode = data->body & 0xffffff;
 			dev_dbg(&dev->dev, "keyboard data 0x%08x\n",
 				data->body);
-			spin_lock(&data->keylock);
+			spin_lock_irqsave(&data->keylock, flags);
 			if (scancode) {
 				delay = usecs_to_jiffies(dev->timeout) +
 					msecs_to_jiffies(100);
@@ -329,7 +330,7 @@ again:
 			}
 			/* Pass data to keyboard buffer parser */
 			ir_mce_kbd_process_keyboard_data(dev, scancode);
-			spin_unlock(&data->keylock);
+			spin_unlock_irqrestore(&data->keylock, flags);
 			lsc.rc_proto = RC_PROTO_MCIR2_KBD;
 			break;
 		case MCIR2_MOUSE_NBITS:
author maintainer
#268 lore raw

PATCH 268/547 media: rc: Use after free in ir_raw_event_handle()

In reply to Greg Kroah-Hartman

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

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

From: Sean Young <[email protected]>

commit 3ae19773168104fa57d2a2ec57731e89df54175f upstream.

If rc_unregister_device() is called while IR is being processed, then ir_raw_event_handle() could call wake_up_process(dev->raw->thread) after kthread_stop(dev->raw->thread). Avoid use after free by using get_task_struct().

Fixes dccc0c3ddf8f ("media: rc: fix race between unregister and urb/irq callbacks")
---
 drivers/media/rc/rc-ir-raw.c |   16 ++++++++++++++--
 1 file changed, 14 insertions(+), 2 deletions(-)
drivers/media/rc/rc-ir-raw.c +14 -2
@@ -630,8 +630,13 @@ int ir_raw_event_register(struct rc_dev
 
 void ir_raw_event_free(struct rc_dev *dev)
 {
-	kfree(dev->raw);
-	dev->raw = NULL;
+	if (dev->raw) {
+		timer_delete_sync(&dev->raw->edge_handle);
+		if (dev->raw->thread)
+			put_task_struct(dev->raw->thread);
+		kfree(dev->raw);
+		dev->raw = NULL;
+	}
 }
 
 void ir_raw_event_unregister(struct rc_dev *dev)
@@ -641,6 +646,13 @@ void ir_raw_event_unregister(struct rc_d
 	if (!dev || !dev->raw)
 		return;
 
+	/*
+	 * After ir_raw_event_unregister() is called, an sync
+	 * call to ir_raw_event_handle() can still arrive. This function
+	 * may call wake_up_process(dev->raw->thread). Ensure this memory
+	 * is not freed by kthread_stop().
+	 */
+	get_task_struct(dev->raw->thread);
 	kthread_stop(dev->raw->thread);
 	timer_delete_sync(&dev->raw->edge_handle);
 
author maintainer
#269 lore raw

PATCH 269/547 media: rc: After rc_unregister_device() timers can be re-armed

In reply to Greg Kroah-Hartman

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

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

From: Sean Young <[email protected]>

commit ef41a67979aed4d7d4f393c56c1e25b6754e2b78 upstream.

If rc_keydown() is called after rc_register_device(), then the timers can be re-armed. Delete them again for a final time.

Fixes dccc0c3ddf8f ("media: rc: fix race between unregister and urb/irq callbacks")
---
 drivers/media/rc/rc-main.c |    5 +++++
 1 file changed, 5 insertions(+)
drivers/media/rc/rc-main.c +5 -0
@@ -1753,6 +1753,11 @@ void rc_free_device(struct rc_dev *dev)
 	if (!dev)
 		return;
 
+	if (dev->input_dev) {
+		timer_delete_sync(&dev->timer_keyup);
+		timer_delete_sync(&dev->timer_repeat);
+	}
+
 	input_put_device(dev->input_dev);
 
 	put_device(&dev->dev);
author maintainer
#270 lore raw

PATCH 270/547 media: rc: Fix use after free in bpf progs

In reply to Greg Kroah-Hartman

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

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

From: Sean Young <[email protected]>

commit f95a9f8472f97c30106513fc7494b7abad243949 upstream.

Since commit dccc0c3ddf8f ("media: rc: fix race between unregister and urb/irq callbacks"), rcdev->raw is no longer set to NULL after device unregister. raw->progs could point to stale data.

Fixes dccc0c3ddf8f ("media: rc: fix race between unregister and urb/irq callbacks")
---
 drivers/media/rc/bpf-lirc.c  |   18 +++++++++++++-----
 drivers/media/rc/rc-ir-raw.c |   11 +++--------
 2 files changed, 16 insertions(+), 13 deletions(-)
drivers/media/rc/bpf-lirc.c +13 -5
@@ -148,12 +148,13 @@ static int lirc_bpf_attach(struct rc_dev
 	if (ret)
 		return ret;
 
-	raw = rcdev->raw;
-	if (!raw) {
+	if (!rcdev->registered) {
 		ret = -ENODEV;
 		goto unlock;
 	}
 
+	raw = rcdev->raw;
+
 	old_array = lirc_rcu_dereference(raw->progs);
 	if (old_array && bpf_prog_array_length(old_array) >= BPF_MAX_PROGS) {
 		ret = -E2BIG;
@@ -186,12 +187,13 @@ static int lirc_bpf_detach(struct rc_dev
 	if (ret)
 		return ret;
 
-	raw = rcdev->raw;
-	if (!raw) {
+	if (!rcdev->registered) {
 		ret = -ENODEV;
 		goto unlock;
 	}
 
+	raw = rcdev->raw;
+
 	old_array = lirc_rcu_dereference(raw->progs);
 	ret = bpf_prog_array_copy(old_array, prog, NULL, 0, &new_array);
 	/*
@@ -235,7 +237,8 @@ void lirc_bpf_free(struct rc_dev *rcdev)
 	struct bpf_prog_array_item *item;
 	struct bpf_prog_array *array;
 
-	array = lirc_rcu_dereference(rcdev->raw->progs);
+	array = rcu_replace_pointer(rcdev->raw->progs, NULL,
+				    lockdep_is_held(&ir_raw_handler_lock));
 	if (!array)
 		return;
 
@@ -316,6 +319,11 @@ int lirc_prog_query(const union bpf_attr
 	if (ret)
 		goto put;
 
+	if (!rcdev->registered) {
+		ret = -ENODEV;
+		goto unlock;
+	}
+
 	progs = lirc_rcu_dereference(rcdev->raw->progs);
 	cnt = progs ? bpf_prog_array_length(progs) : 0;
 
drivers/media/rc/rc-ir-raw.c +3 -8
@@ -632,8 +632,11 @@ void ir_raw_event_free(struct rc_dev *de
 {
 	if (dev->raw) {
 		timer_delete_sync(&dev->raw->edge_handle);
+		mutex_lock(&ir_raw_handler_lock);
 		if (dev->raw->thread)
 			put_task_struct(dev->raw->thread);
+		lirc_bpf_free(dev);
+		mutex_unlock(&ir_raw_handler_lock);
 		kfree(dev->raw);
 		dev->raw = NULL;
 	}
@@ -643,9 +646,6 @@ void ir_raw_event_unregister(struct rc_d
 {
 	struct ir_raw_handler *handler;
 
-	if (!dev || !dev->raw)
-		return;
-
 	/*
 	 * After ir_raw_event_unregister() is called, an sync
 	 * call to ir_raw_event_handle() can still arrive. This function
@@ -665,11 +665,6 @@ void ir_raw_event_unregister(struct rc_d
 
 	lirc_bpf_free(dev);
 
-	/*
-	 * A user can be calling bpf(BPF_PROG_{QUERY|ATTACH|DETACH}), so
-	 * ensure that the raw member is null on unlock; this is how
-	 * "device gone" is checked.
-	 */
 	mutex_unlock(&ir_raw_handler_lock);
 }
 
author maintainer
#271 lore raw

PATCH 271/547 media: rc: Fix ABBA deadlock by making locks more fine grained

In reply to Greg Kroah-Hartman

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

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

From: Sean Young <[email protected]>

commit c6d68866ad8aa1e957a3e5a6ede971148f1e3d59 upstream.

The ir_raw_event_unregister() function takes the ir_raw_handler_lock first and then the rc_dev->lock. Other functions like change_protocol do this in the reverse order.

This means that an ir decoder module unload and writing to the protocol sysfs file can cause a deadlock.

ir_raw_handler_lock protects the client list, amongst other things. Split this out into a separate lock so we can ensure the locking order is always the same.

Fixes 93cffffc18f6 ("[media] media: rc: fix decoder module unloading")
---
 drivers/media/rc/rc-ir-raw.c |   39 ++++++++++++++++++++++++---------------
 1 file changed, 24 insertions(+), 15 deletions(-)
drivers/media/rc/rc-ir-raw.c +24 -15
@@ -10,7 +10,8 @@
 #include <linux/sched.h>
 #include "rc-core-priv.h"
 
-/* Used to keep track of IR raw clients, protected by ir_raw_handler_lock */
+/* Used to keep track of IR raw clients, protected by ir_raw_client_lock */
+static DEFINE_MUTEX(ir_raw_client_lock);
 static LIST_HEAD(ir_raw_client_list);
 
 /* Used to handle IR raw handler extensions */
@@ -273,13 +274,6 @@ static int change_protocol(struct rc_dev
 	return 0;
 }
 
-static void ir_raw_disable_protocols(struct rc_dev *dev, u64 protocols)
-{
-	mutex_lock(&dev->lock);
-	dev->enabled_protocols &= ~protocols;
-	mutex_unlock(&dev->lock);
-}
-
 /**
  * ir_raw_gen_manchester() - Encode data with Manchester (bi-phase) modulation.
  * @ev:		Pointer to pointer to next free event. *@ev is incremented for
@@ -615,15 +609,18 @@ int ir_raw_event_register(struct rc_dev
 {
 	struct task_struct *thread;
 
+	/* Holding dev->lock could result in a dead-lock */
+	lockdep_assert_not_held(&dev->lock);
+
 	thread = kthread_run(ir_raw_event_thread, dev->raw, "rc%u", dev->minor);
 	if (IS_ERR(thread))
 		return PTR_ERR(thread);
 
 	dev->raw->thread = thread;
 
-	mutex_lock(&ir_raw_handler_lock);
+	mutex_lock(&ir_raw_client_lock);
 	list_add_tail(&dev->raw->list, &ir_raw_client_list);
-	mutex_unlock(&ir_raw_handler_lock);
+	mutex_unlock(&ir_raw_client_lock);
 
 	return 0;
 }
@@ -656,16 +653,19 @@ void ir_raw_event_unregister(struct rc_d
 	kthread_stop(dev->raw->thread);
 	timer_delete_sync(&dev->raw->edge_handle);
 
-	mutex_lock(&ir_raw_handler_lock);
+	mutex_lock(&ir_raw_client_lock);
 	list_del(&dev->raw->list);
+
+	mutex_lock(&ir_raw_handler_lock);
 	list_for_each_entry(handler, &ir_raw_handler_list, list)
 		if (handler->raw_unregister &&
 		    (handler->protocols & dev->enabled_protocols))
 			handler->raw_unregister(dev);
 
 	lirc_bpf_free(dev);
-
 	mutex_unlock(&ir_raw_handler_lock);
+
+	mutex_unlock(&ir_raw_client_lock);
 }
 
 /*
@@ -688,15 +688,24 @@ void ir_raw_handler_unregister(struct ir
 	struct ir_raw_event_ctrl *raw;
 	u64 protocols = ir_raw_handler->protocols;
 
+	mutex_lock(&ir_raw_client_lock);
+
 	mutex_lock(&ir_raw_handler_lock);
 	list_del(&ir_raw_handler->list);
+	atomic64_andnot(protocols, &available_protocols);
+	mutex_unlock(&ir_raw_handler_lock);
+
 	list_for_each_entry(raw, &ir_raw_client_list, list) {
+		mutex_lock(&raw->dev->lock);
+		mutex_lock(&ir_raw_handler_lock);
 		if (ir_raw_handler->raw_unregister &&
 		    (raw->dev->enabled_protocols & protocols))
 			ir_raw_handler->raw_unregister(raw->dev);
-		ir_raw_disable_protocols(raw->dev, protocols);
+		raw->dev->enabled_protocols &= ~protocols;
+		mutex_unlock(&ir_raw_handler_lock);
+		mutex_unlock(&raw->dev->lock);
 	}
-	atomic64_andnot(protocols, &available_protocols);
-	mutex_unlock(&ir_raw_handler_lock);
+
+	mutex_unlock(&ir_raw_client_lock);
 }
 EXPORT_SYMBOL(ir_raw_handler_unregister);
author maintainer
#272 lore raw

PATCH 272/547 ocfs2/heartbeat: unlink live slots when their node is missing

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

commit 3ccd24c3f7a577b84a532cb027f1378385b82ef6 upstream.

o2hb_shutdown_slot() returns immediately when its node is no longer in the configfs registry. A slot can still be linked in o2hb_live_slots when that lookup fails. Region teardown or startup-error cleanup then frees the slot array without removing its embedded list member.

With the same peer live in another region, the next list update can follow a predecessor into the freed array. Reusing the node number can also make a later insertion encounter that stale member.

Always remove the slot under o2hb_live_lock, even when node lookup fails. Preserve aggregate membership accounting and the last-region DOWN
callback: the existing callback interface explicitly permits a NULL node for DOWN events. Only drop the node reference when lookup returned one. This closes both normal release and startup-abort paths without changing the publication or callback locking protocol.

Also require a configured node before admitting a new live slot in o2hb_check_slot(). The early live-bitmap check is not held through
admission: the last live slot in another region can be removed in between. Without a node, admission can then queue an UP event with a NULL argument and hit the event helper's BUG_ON. Existing live slots can still leave and generate NULL-node DOWN events.

A controlled probe-instrumented test reproduced this while stopping one of two regions after removing the peer from configfs. Its KASAN report includes:

  BUG: KASAN: slab-use-after-free in __list_del_entry_valid_or_report+0x1e0/0x210
  Read of size 8 at addr ffff888106a4ac60 by task o2hb-pmbd0058_b/497
  Call Trace:
   <TASK>
   dump_stack_lvl+0x93/0xd0
   print_report+0xce/0x630
   kasan_report+0xe0/0x110
   __list_del_entry_valid_or_report+0x1e0/0x210
   o2hb_do_disk_heartbeat+0x1591/0x2c50
   o2hb_thread+0x1ed/0xe70
   kthread+0x351/0x460
   ret_from_fork+0x659/0x940
   ret_from_fork_asm+0x1a/0x30
   </TASK>
  Allocated by task 491:
   kasan_save_stack+0x33/0x60
   kasan_save_track+0x14/0x30
   __kasan_kmalloc+0xaa/0xb0
   __kmalloc_noprof+0x2de/0x780
   o2hb_region_dev_store+0x7c2/0x1b60
   configfs_write_iter+0x2f9/0x4f0
   vfs_write+0x639/0x1010
   ksys_write+0x111/0x200
   do_syscall_64+0x114/0x620
   entry_SYSCALL_64_after_hwframe+0x77/0x7f
  Freed by task 491:
   kasan_save_stack+0x33/0x60
   kasan_save_track+0x14/0x30
   kasan_save_free_info+0x3b/0x60
   __kasan_slab_free+0x5f/0x80
   kfree+0x308/0x580
   o2hb_unmap_slot_data+0x1db/0x330
   o2hb_region_release+0x14b/0x4f0
   config_item_cleanup+0x14b/0x230
   config_item_put+0x79/0x90
   configfs_rmdir+0x58a/0x910
   vfs_rmdir+0x2e8/0x820
   filename_rmdir+0x3b1/0x520
   __x64_sys_rmdir+0x4b/0x70
   do_syscall_64+0x114/0x620
   entry_SYSCALL_64_after_hwframe+0x77/0x7f
Fixes a7f6a5fb4bde ("[PATCH] OCFS2: The Second Oracle Cluster Filesystem")
Assisted-by LLM
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
Cc Yufan Chen <[email protected]>
Cc Kees Cook <[email protected]>
Cc Jia-Ju Bai <[email protected]>
---
 fs/ocfs2/cluster/heartbeat.c |   12 ++++++++----
 1 file changed, 8 insertions(+), 4 deletions(-)
fs/ocfs2/cluster/heartbeat.c +8 -4
@@ -880,8 +880,11 @@ static void o2hb_shutdown_slot(struct o2
 	int queued = 0;
 
 	node = o2nm_get_node_by_num(slot->ds_node_num);
-	if (!node)
-		return;
+	/*
+	 * The node may have been removed from the node table while this
+	 * region's slot is still linked.  The list member must still be
+	 * removed before the region releases its slot array.
+	 */
 
 	spin_lock(&o2hb_live_lock);
 	if (!list_empty(&slot->ds_live_item)) {
@@ -903,7 +906,8 @@ static void o2hb_shutdown_slot(struct o2
 	if (queued)
 		o2hb_run_event_list(&event);
 
-	o2nm_node_put(node);
+	if (node)
+		o2nm_node_put(node);
 }
 
 static void o2hb_set_quorum_device(struct o2hb_region *reg)
@@ -1038,7 +1042,7 @@ static int o2hb_check_slot(struct o2hb_r
 fire_callbacks:
 	/* dead nodes only come to life after some number of
 	 * changes at any time during their dead time */
-	if (list_empty(&slot->ds_live_item) &&
+	if (node && list_empty(&slot->ds_live_item) &&
 	    slot->ds_changed_samples >= O2HB_LIVE_THRESHOLD) {
 		mlog(ML_HEARTBEAT, "Node %d (id 0x%llx) joined my region\n",
 		     slot->ds_node_num, (long long)slot->ds_last_generation);
author maintainer
#273 lore raw

PATCH 273/547 ocfs2/dlm: hold a lock reference across grant AST enqueue

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

commit 71743471204e21113295c786e5cfa570294234a4 upstream.

A newly granted remote lock must remain alive until its grant AST is queued. dlmlock_master() publishes the lock on res->granted with its base and queue references, then drops res->spinlock before calling dlm_queue_ast(). The resource's reserved AST count does not retain the lock itself.

This can fail when a peer dies with an immediately grantable CREATE buffered on its socket. O2NET's node-down callback flushes receive work before DLM cleanup, but the flush only waits for work queued on entry. A data-ready callback that already selected the socket container can queue new receive work after the flush advances its work color. Socket shutdown does not discard bytes already queued for TCP receive.

The late receive work and DLM node-down cleanup can interleave as follows (the lock reference operations shown are before this fix):

  Socket data-ready        Node-down thread         Receive worker
  -----------------        ----------------         --------------

o2net_data_ready()
select sc under
callback read lock
o2net_disconnect_node()
queue shutdown
begin flush; new color
queue sc_rx_work
in the new color
release callback lock
shutdown socket
flush returns
read buffered CREATE dlmlock_master()
lock res->spinlock add lock to granted unlock res->spinlock
DLM node-down cleanup
lock res->spinlock dlm_free_dead_locks()
unlink lock
put queue/base refs
free lock
unlock res->spinlock
dlm_queue_ast()
__dlm_queue_ast() read lock->lockres (use-after-free)

DLM cleanup holds res->spinlock while dlm_free_dead_locks() drops the queue and base references. The CREATE handler no longer holds that spinlock when __dlm_queue_ast() reads the lock, before taking its AST list reference.

Take a temporary lock reference under res->spinlock when a grant AST will be queued, and drop it after dlm_queue_ast(). This keeps the lock alive across cleanup until the AST path has taken its own reference, without reversing the existing AST/resource lock order.

KASAN report as below:

    BUG: KASAN: slab-use-after-free in __dlm_queue_ast+0x8a4/0xc00
    Read of size 8 at addr ffff88810ead5940 by task kworker/u16:3/52

    CPU: 3 UID: 0 PID: 52 Comm: kworker/u16:3 Not tainted 7.3.0-rc4-next-20260921-pmb-bt-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: o2net o2net_rx_until_empty
    Call Trace:
     <TASK>
     dump_stack_lvl+0x93/0xd0
     print_report+0xce/0x630
     ? __dlm_queue_ast+0x8a4/0xc00
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __virt_addr_valid+0x20e/0x420
     ? __dlm_queue_ast+0x8a4/0xc00
     kasan_report+0xe0/0x110
     ? __dlm_queue_ast+0x8a4/0xc00
     __dlm_queue_ast+0x8a4/0xc00
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? do_raw_spin_lock+0x130/0x270
     ? __pfx___dlm_queue_ast+0x10/0x10
     ? __pfx_do_raw_spin_lock+0x10/0x10
     ? _raw_spin_unlock_irqrestore+0x45/0x60
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lockdep_hardirqs_on_prepare+0xeb/0x1a0
     dlm_queue_ast+0x46/0x70
     dlmlock_master+0x51f/0xf50
     ? __pfx_dlmlock_master+0x10/0x10
     ? dlm_create_lock_handler+0x2b2/0x870
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_release+0xc8/0x290
     dlm_create_lock_handler+0x35b/0x870
     ? __pfx_dlm_create_lock_handler+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? trace_hardirqs_on+0x18/0x160
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? kvm_clock_get_cycles+0x31/0x60
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx_dlm_create_lock_handler+0x10/0x10
     o2net_rx_until_empty+0x1dae/0x32c0
     ? reacquire_held_locks+0xdd/0x200
     ? __pfx_o2net_rx_until_empty+0x10/0x10
     ? lock_acquire+0x190/0x300
     ? process_one_work+0x935/0x1b40
     ? 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 52:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     __kasan_slab_alloc+0x89/0x90
     kmem_cache_alloc_noprof+0x20b/0x5c0
     dlm_new_lock+0x39/0x5f0
     dlm_create_lock_handler+0x16e/0x870
     o2net_rx_until_empty+0x1dae/0x32c0
     process_one_work+0x9a8/0x1b40
     worker_thread+0x65c/0xe40
     kthread+0x351/0x460
     ret_from_fork+0x659/0x940
     ret_from_fork_asm+0x1a/0x30

    Freed by task 603:
     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
     dlm_lock_release+0x1df/0x2f0
     dlm_lock_put+0x51/0x80
     __dlm_hb_node_down+0x15be/0x2710
     dlm_hb_node_down_cb+0x6c/0xa0
     o2hb_run_event_list+0x34a/0x500
     o2hb_do_disk_heartbeat+0x1a07/0x2950
     o2hb_thread+0x1ed/0xdc0
     kthread+0x351/0x460
     ret_from_fork+0x659/0x940
     ret_from_fork_asm+0x1a/0x30

    The buggy address belongs to the object at ffff88810ead5900
     which belongs to the cache o2dlm_lock of size 184
    The buggy address is located 64 bytes inside of
     freed 184-byte region [ffff88810ead5900, ffff88810ead59b8)

[Page and shadow memory dumps omitted.]

---
 fs/ocfs2/dlm/dlmlock.c |    8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
fs/ocfs2/dlm/dlmlock.c +6 -2
@@ -138,6 +138,8 @@ static enum dlm_status dlmlock_master(st
 					  res->lockname.len)) {
 			kick_thread = 1;
 			call_ast = 1;
+			/* Keep the lock alive through AST enqueue. */
+			dlm_lock_get(lock);
 		} else {
 			mlog(0, "%s: returning DLM_NORMAL to "
 			     "node %u for reco lock\n", dlm->name,
@@ -166,10 +168,12 @@ static enum dlm_status dlmlock_master(st
 	wake_up(&res->wq);
 
 	/* either queue the ast or release it */
-	if (call_ast)
+	if (call_ast) {
 		dlm_queue_ast(dlm, lock);
-	else
+		dlm_lock_put(lock);
+	} else {
 		dlm_lockres_release_ast(dlm, res);
+	}
 
 	dlm_lockres_calc_usage(dlm, res);
 	if (kick_thread)
author maintainer
#274 lore raw

PATCH 274/547 ocfs2/dlm: hold the lookup reference across convert AST enqueue

In reply to Greg Kroah-Hartman

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

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

From: Joseph Qi <[email protected]>

commit 125fe08ff6cfa064e1212f586f01993ee45c0330 upstream.

dlm_convert_lock_handler() drops the reference it took when it found the lock on res->granted at its leave label, one statement before it calls dlm_queue_ast(). dlm_free_dead_locks() takes res->spinlock and drops the list and base references, so a peer death landing in that gap leaves the handler's own put as the one that frees the lock, and __dlm_queue_ast() then reads lock->lockres from freed memory.

The handler is registered next to dlm_create_lock_handler(), so a convert message buffered on a dying peer's socket arrives on the same o2net receive work that o2net_disconnect_node() does not wait for. The two can interleave as follows, with the reference counts as they are before this fix:

  Socket data-ready       Node-down thread      Receive worker
  -----------------       ----------------      --------------

o2net_data_ready()
select sc under
callback read lock
o2net_disconnect_node()
queue shutdown
begin flush; new color
queue sc_rx_work
in the new color
release callback lock
shutdown socket
flush returns
read buffered convert_lock dlm_convert_lock_handler()
find lock on res->granted dlm_lock_get() refs = 3 lock res->spinlock __dlmconvert_master()
call_ast = 1
unlock res->spinlock
DLM node-down cleanup
lock res->spinlock dlm_free_dead_locks()
unlink lock
put list ref refs = 2
put base ref refs = 1
unlock res->spinlock
dlm_lock_put() refs = 0
free lock
dlm_queue_ast()
__dlm_queue_ast() read lock->lockres (use-after-free)

__dlmconvert_master() only moves the lock between lists, so the count entering the gap is base, list and lookup. Drop the lookup reference after the AST is queued instead of before it and the race ends with the one __dlm_queue_ast() took, which dlm_flush_asts() releases later with ast_pending cleared and ast_list unlinked. No extra get is needed, and the normal case ends with the same count as before.

dlmconvert_master() has the same shape but is only reached from dlmlock() for a lock this node owns, which dlm_free_dead_locks() never matches.

Fixes 2c5c54aca9d0 ("ocfs2/dlm: Add missing dlm_lock_put()s")
Cc Mark Fasheh <[email protected]>
Cc Joel Becker <[email protected]>
---
 fs/ocfs2/dlm/dlmconvert.c |   10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)
fs/ocfs2/dlm/dlmconvert.c +7 -3
@@ -534,15 +534,19 @@ int dlm_convert_lock_handler(struct o2ne
 	}
 
 leave:
-	if (lock)
-		dlm_lock_put(lock);
-
 	/* either queue the ast or release it, if reserved */
 	if (call_ast)
 		dlm_queue_ast(dlm, lock);
 	else if (ast_reserved)
 		dlm_lockres_release_ast(dlm, res);
 
+	/*
+	 * Keep the lock alive through AST enqueue: a concurrent
+	 * dlm_free_dead_locks() drops the list and base references.
+	 */
+	if (lock)
+		dlm_lock_put(lock);
+
 	if (kick_thread)
 		dlm_kick_thread(dlm, res);
 
author maintainer
#275 lore raw

PATCH 275/547 ocfs2: cancel quota sync work before freeing quota info

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

commit 1dd1f005026d52642b994d63baa16b0b31f3b14f upstream.

OCFS2 quota info owns dqi_sync_work and must outlive both its timer and qsync_work_fn(). ocfs2_local_free_info() frees that owner without cancelling the work, relying on the quota suspend/disable wrappers.

Loading quotas on a read-only to read-write remount can successfully queue the work in ocfs2_global_read_info() and then fail while attaching a dquot to an existing inode in add_dquot_ref(). The quota core unwinds that failure directly through dquot_disable(), bypassing the OCFS2 wrapper:

Remount task (s_umount write) Timer/workqueue
ocfs2_global_read_info()
schedules dqi_sync_work
add_dquot_ref() returns an error
dquot_disable()
ocfs2_local_free_info()
frees oinfo
delayed-work timer expires qsync_work_fn() reads oinfo

The timer core can then write to the freed embedded timer, or qsync_work_fn() can read oinfo->dqi_gqinode before its s_umount trylock. The outer ocfs2_disable_quotas() cleanup skips the failed type because dquot_disable() has already cleared its loaded state.

Cancel dqi_sync_work synchronously at the start of ocfs2_local_free_info(), before dropping the global inode or freeing any owner state. The work is initialized whenever read_file_info() succeeds. dquot_disable() holds s_umount for write, so the callback skips its quota scan via down_read_trylock() and can finish without waiting for teardown. The synchronous cancel also handles its self-rearm.

KASAN report as below:

    BUG: KASAN: slab-use-after-free in __run_timers+0x9e9/0xa10
    Write of size 8 at addr ffff888111b0aad0 by task swapper/3/0

    Call Trace:
     <IRQ>
     dump_stack_lvl+0x93/0xd0
     print_report+0xce/0x630
     ? __run_timers+0x9e9/0xa10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __virt_addr_valid+0x20e/0x420
     ? __run_timers+0x9e9/0xa10
     kasan_report+0xe0/0x110
     ? __run_timers+0x9e9/0xa10
     __run_timers+0x9e9/0xa10
     ? __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
     ? ct_kernel_exit.constprop.0+0xc5/0xf0
     ? do_idle+0x3ae/0x650
     default_idle+0x9/0x10
     default_idle_call+0x6c/0xb0
     do_idle+0x3ae/0x650
     ? cpuhp_online_idle+0x9c/0xb0
     ? __pfx_do_idle+0x10/0x10
     ? __entry_text_end+0x1020f6/0x1020f9
     ? lockdep_hardirqs_on_prepare+0xeb/0x1a0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? trace_hardirqs_on+0x18/0x160
     ? srso_alias_return_thunk+0x5/0xfbef5
     cpu_startup_entry+0x54/0x60
     start_secondary+0x223/0x2d0
     ? __pfx_start_secondary+0x10/0x10
     common_startup_64+0x13e/0x158
     </TASK>

    Allocated by task 523:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     __kasan_kmalloc+0xaa/0xb0
     __kmalloc_cache_noprof+0x28d/0x610
     ocfs2_local_read_info+0x181/0x1580
     dquot_load_quota_sb+0x69e/0x11c0
     dquot_load_quota_inode+0x227/0x3e0
     ocfs2_enable_quotas+0x27c/0x520
     ocfs2_reconfigure+0x964/0xd00
     reconfigure_super+0x3ca/0xa70
     path_mount+0x141e/0x1e80
     __x64_sys_mount+0x24b/0x2d0
     do_syscall_64+0x114/0x620
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    Freed by task 523:
     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_local_free_info+0x47b/0x800
     dquot_disable+0x5d9/0x17a0
     dquot_load_quota_sb+0xd3c/0x11c0
     dquot_load_quota_inode+0x227/0x3e0
     ocfs2_enable_quotas+0x27c/0x520
     ocfs2_reconfigure+0x964/0xd00
     reconfigure_super+0x3ca/0xa70
     path_mount+0x141e/0x1e80
     __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 ffff888111b0a800
     which belongs to the cache kmalloc-1k of size 1024
    The buggy address is located 720 bytes inside of
     freed 1024-byte region [ffff888111b0a800, ffff888111b0ac00)

Host details, register and page dumps omitted.

---
 fs/ocfs2/quota_local.c |    3 +++
 1 file changed, 3 insertions(+)
fs/ocfs2/quota_local.c +3 -0
@@ -816,6 +816,9 @@ static int ocfs2_local_free_info(struct
 	int mark_clean = 1, len;
 	int status = 0;
 
+	/* Quota-core error paths can bypass ocfs2_disable_quotas(). */
+	cancel_delayed_work_sync(&oinfo->dqi_sync_work);
+
 	iput(oinfo->dqi_gqinode);
 	ocfs2_simple_drop_lockres(OCFS2_SB(sb), &oinfo->dqi_gqlock);
 	ocfs2_lock_res_free(&oinfo->dqi_gqlock);
author maintainer
#276 lore raw

PATCH 276/547 ocfs2: fix chunk number of the first chunk in a local quota file

In reply to Greg Kroah-Hartman

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

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

From: Jiaming Zhang <[email protected]>

commit 4effccfd50baee4f325694964aeee997dca7bd96 upstream.

Mounting a crafted OCFS2 image can corrupt kernel memory. When the local quota file header of such an image claims zero chunks, the first quota entry allocated during the mount gets a chunk number taken from a kernel pointer, and releasing that entry clears a bit far outside the chunk bitmap.

The write will corrupt the data stored at that address, and the corruption may lead to a system crash or damage unrelated data. Mounting requires CAP_SYS_ADMIN, so it takes an untrusted image, such as removable media or a loop mount of a file from elsewhere.

Since the chunk number comes from a kernel pointer, the address of the bit that gets cleared differs from boot to boot, and the issue has been reported under several titles:

- BUG: unable to handle kernel paging request in ocfs2_local_release_dquot
- KASAN: use-after-free Write in ocfs2_local_release_dquot
- KASAN: slab-out-of-bounds Write in ocfs2_local_release_dquot
- KASAN: slab-use-after-free Write in ocfs2_local_release_dquot
- KFENCE: use-after-free write in ocfs2_local_release_dquot

Note that none of these is a use-after-free in the quota code: the chunk and its buffer head are alive. The bit that gets cleared lies far outside the bitmap. KASAN and KFENCE name each report based on the object occupying that address, which explains why the same issue is reported under so many different titles. In the report I sent, the address fell in a free page, which KASAN labels use-after-free.

There are known reproducers. Both a syzkaller and a C reproducer are available from the Google Drive link [1] in my report thread. The issue was found by our modified syzkaller, not a theoretical thing found by an LLM. I have not seen it outside fuzzing, so it is not affecting me in the real world.

The local quota file in OCFS2 is divided into chunks, and each chunk begins with a header block holding a bitmap of the quota entries that chunk has handed out. Chunks are numbered from zero, and that number is used to convert the file offset of an entry back into a bit position in the bitmap. ocfs2_local_quota_add_chunk() appends a new chunk to the in-memory list and numbers it one past the chunk that was last:

	list_add_tail(&chunk->qc_chunk, &oinfo->dqi_chunk);
	chunk->qc_num = list_entry(chunk->qc_chunk.prev,
				   struct ocfs2_quota_chunk,
				   qc_chunk)->qc_num + 1;

The predecessor is looked up after the new chunk is added to the list, so if the list was empty, the prev pointer is the list head itself. The head is the dqi_chunk member of struct ocfs2_mem_dqinfo and is not a chunk, so reading qc_num through it lands 16 bytes past the start of the head, on the dqi_gqinode pointer that follows it. The first chunk of the file is then numbered with the lower half of a kernel pointer instead of 0.

The list is empty when the local quota file header claims the file has no chunks. ocfs2_local_read_info() takes dqi_chunks from that header without validating it, so an image with dqi_chunks == 0 takes this path when the first quota entry is allocated.

ocfs2_create_local_dquot() turns the bad number into a file offset with ol_dqblk_off(), which shifts a 32-bit block number left by the block size bits, so the top bits of such a large block number are lost. ocfs2_local_release_dquot() turns the offset back into a bit index with ol_dqblk_chunk_off(), using the full chunk number, so the lost bits push that index far outside the bitmap, and clearing it corrupts unrelated memory.

Compute the chunk number before putting the chunk on the list, and use 0 when the list is empty.

---
 fs/ocfs2/quota_local.c |    9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
fs/ocfs2/quota_local.c +6 -3
@@ -1074,10 +1074,13 @@ static struct ocfs2_quota_chunk *ocfs2_l
 		goto out;
 	}
 
+	if (list_empty(&oinfo->dqi_chunk))
+		chunk->qc_num = 0;
+	else
+		chunk->qc_num = list_entry(oinfo->dqi_chunk.prev,
+					   struct ocfs2_quota_chunk,
+					   qc_chunk)->qc_num + 1;
 	list_add_tail(&chunk->qc_chunk, &oinfo->dqi_chunk);
-	chunk->qc_num = list_entry(chunk->qc_chunk.prev,
-				   struct ocfs2_quota_chunk,
-				   qc_chunk)->qc_num + 1;
 	chunk->qc_headerbh = bh;
 	*offset = 0;
 	return chunk;
author maintainer
#277 lore raw

PATCH 277/547 ocfs2: pin refcount trees before dropping the lookup lock

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

commit 8c714a074074af7ae59233c1fa6ef9d7aa710462 upstream.

A refcount tree returned to ocfs2_lock_refcount_tree() must stay alive until that caller releases its operation reference. However, ocfs2_get_refcount_tree() returns the cached pointer after dropping osb_lock, and the caller only takes its kref afterwards. The registry reference does not protect this gap from concurrent removal.

This can happen when another node frees a refcount root and reuses its block with a different generation while this mount retains the old cached tree. Two local operations on different inodes sharing the new root, such as data CoW and an external xattr update, can then look up the same stale tree. Their inode locks are independent, and both the REFCOUNT DLM lock and rf_sem are acquired after the first operation reference.

The following ordering is possible, with no other operation references:

Data CoW Xattr update
-------- ------------
Look up the old tree under
osb_lock, then drop osb_lock
Look up the same tree and take a kref Acquire the tree locks and read the
new on-disk generation
Erase the old tree under osb_lock Unlock and drop the operation kref Drop the registry kref, freeing tree
Take a kref through the
freed tree pointer

The final kref_get() accesses freed rf_getcnt storage, and subsequent accesses in ocfs2_lock_refcount_tree() also use the freed allocation.

Take the operation reference in ocfs2_get_refcount_tree() before releasing osb_lock, including when an insertion loses to another lookup. Removal must acquire the same lock, so it cannot drop the registry reference before the lookup has pinned the tree. Keep the existing unlock and error path puts. The two callers that already hold the refcount tree lock keep their borrowed lookup behavior and do not acquire an extra reference.

KASAN report as below:

    BUG: KASAN: slab-use-after-free in ocfs2_lock_refcount_tree+0x94a/0x9b0
    Read of size 4 at addr ffff888117212820 by task python3/497

[Kernel and hardware identification omitted.]

    Call Trace:
     <TASK>
     dump_stack_lvl+0x93/0xd0
     print_report+0xce/0x630
     ? ocfs2_lock_refcount_tree+0x94a/0x9b0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __virt_addr_valid+0x20e/0x420
     ? ocfs2_lock_refcount_tree+0x94a/0x9b0
     kasan_report+0xe0/0x110
     ? ocfs2_lock_refcount_tree+0x94a/0x9b0
     ocfs2_lock_refcount_tree+0x94a/0x9b0
     ? __pfx_ocfs2_lock_refcount_tree+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? ocfs2_refcount_cow+0x3b6/0xd90
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __kmalloc_cache_noprof+0x28d/0x610
     ? ocfs2_refcount_cow+0x3b6/0xd90
     ocfs2_refcount_cow+0x410/0xd90
     ? __pfx_ocfs2_refcount_cow+0x10/0x10
     ? __pfx___might_resched+0x10/0x10
     ? down_write+0x11a/0x1f0
     ? __pfx_down_write+0x10/0x10
     ? ocfs2_inode_unlock+0x1a9/0x260
     ? __pfx_ocfs2_inode_unlock+0x10/0x10
     ? ocfs2_file_write_iter+0x1413/0x1d30
     ocfs2_file_write_iter+0x157b/0x1d30
     ? __pfx_ocfs2_file_write_iter+0x10/0x10
     ? lock_acquire+0x190/0x300
     ? __x64_sys_pwrite64+0x1b7/0x220
     ? __pfx___might_resched+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? security_file_permission+0x26/0x80
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_is_held_type+0x8f/0x100
     vfs_write+0x639/0x1010
     ? __pfx_ocfs2_file_write_iter+0x10/0x10
     ? lock_vma_under_rcu+0x154/0x4a0
     ? __pfx_vfs_write+0x10/0x10
     ? lock_release+0x121/0x290
     ? srso_alias_return_thunk+0x5/0xfbef5
     __x64_sys_pwrite64+0x1b7/0x220
     ? __pfx___x64_sys_pwrite64+0x10/0x10
     ? irqentry_exit+0xbe/0x820
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? trace_hardirqs_on_prepare+0x11d/0x150
     ? srso_alias_return_thunk+0x5/0xfbef5
     do_syscall_64+0x114/0x620
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

[Register dump omitted.]

     </TASK>

    Allocated by task 491:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     __kasan_kmalloc+0xaa/0xb0
     __kmalloc_cache_noprof+0x28d/0x610
     ocfs2_allocate_refcount_tree+0x49/0x1a0
     ocfs2_create_refcount_tree+0x5d7/0x1630
     ocfs2_attach_refcount_tree+0x57d/0x1100
     __ocfs2_reflink.isra.0+0x1c4/0x1940
     ocfs2_reflink+0x501/0x9b0
     ocfs2_reflink_ioctl+0x6b2/0x920
     ocfs2_ioctl+0x538/0x640
     __x64_sys_ioctl+0x163/0x1d0
     do_syscall_64+0x114/0x620
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    Freed by task 498:
     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_lock_refcount_tree+0x672/0x9b0
     ocfs2_xattr_set+0x72c/0x2530
     ocfs2_xattr_user_set+0xaf/0xf0
     __vfs_setxattr+0x143/0x1b0
     __vfs_setxattr_noperm+0x112/0x5b0
     __vfs_setxattr_locked+0xfe/0x2b0
     vfs_setxattr+0x13c/0x370
     do_setxattr+0x128/0x170
     filename_setxattr+0x147/0x190
     path_setxattrat+0x1ac/0x260
     __x64_sys_setxattr+0xcb/0x140
     do_syscall_64+0x114/0x620
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    The buggy address belongs to the object at ffff888117212800
     which belongs to the cache kmalloc-1k of size 1024
    The buggy address is located 32 bytes inside of
     freed 1024-byte region [ffff888117212800, ffff888117212c00)

[Page and memory dumps omitted.]

---
 fs/ocfs2/refcounttree.c |   15 +++++++++------
 1 file changed, 9 insertions(+), 6 deletions(-)
fs/ocfs2/refcounttree.c +9 -6
@@ -348,8 +348,10 @@ ocfs2_allocate_refcount_tree(struct ocfs
 	return new;
 }
 
+/* Callers without the refcount tree lock must request a reference. */
 static int ocfs2_get_refcount_tree(struct ocfs2_super *osb, u64 rf_blkno,
-				   struct ocfs2_refcount_tree **ret_tree)
+				   struct ocfs2_refcount_tree **ret_tree,
+				   bool get_ref)
 {
 	int ret = 0;
 	struct ocfs2_refcount_tree *tree, *new = NULL;
@@ -406,6 +408,8 @@ static int ocfs2_get_refcount_tree(struc
 	new = NULL;
 
 out:
+	if (get_ref)
+		ocfs2_refcount_tree_get(tree);
 	*ret_tree = tree;
 
 	osb->osb_ref_tree_lru = tree;
@@ -479,14 +483,12 @@ int ocfs2_lock_refcount_tree(struct ocfs
 	struct ocfs2_refcount_block *rb;
 
 again:
-	ret = ocfs2_get_refcount_tree(osb, ref_blkno, &tree);
+	ret = ocfs2_get_refcount_tree(osb, ref_blkno, &tree, true);
 	if (ret) {
 		mlog_errno(ret);
 		return ret;
 	}
 
-	ocfs2_refcount_tree_get(tree);
-
 	ret = __ocfs2_lock_refcount_tree(osb, tree, rw);
 	if (ret) {
 		mlog_errno(ret);
@@ -2328,7 +2330,8 @@ int ocfs2_decrease_refcount(struct inode
 		goto out;
 	}
 
-	ret = ocfs2_get_refcount_tree(OCFS2_SB(inode->i_sb), ref_blkno, &tree);
+	ret = ocfs2_get_refcount_tree(OCFS2_SB(inode->i_sb), ref_blkno,
+				      &tree, false);
 	if (ret) {
 		mlog_errno(ret);
 		goto out;
@@ -2563,7 +2566,7 @@ int ocfs2_prepare_refcount_change_for_de
 	BUG_ON(!ocfs2_is_refcount_inode(inode));
 
 	ret = ocfs2_get_refcount_tree(OCFS2_SB(inode->i_sb),
-				      refcount_loc, &tree);
+				      refcount_loc, &tree, false);
 	if (ret) {
 		mlog_errno(ret);
 		goto out;
author maintainer
#278 lore raw

PATCH 278/547 ocfs2: snapshot dentry names in file and setattr traces

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

commit 8cd3ff30659775a6831c66687a69d2b83d163591 upstream.

Patch series "ocfs2: stabilize dentry names in file and setattr traces", v4.

Snapshot names at all six users of ocfs2__file_ops and at the separate setattr event. Patch 1 handles the five ordinary file-operation callers and setattr. Patch 2 handles release separately to preserve its locked open-count sample and take the snapshot outside that critical section.

The release explanation distinguishes its existing RCU lifetime coverage from name/length consistency. It does not claim that the ordinary callers' external-name UAF interleaving crosses the held inode spinlock. The release source change is unchanged from v3.

Patch 1 also removes the read callback's redundant NULL-inode check. The two patches apply independently and leave trace formats unchanged.

This patch (of 2):

The open, fsync, read, write and splice-read trace calls pass the live dentry name and length to the shared ocfs2__file_ops event class. ocfs2_setattr() passes the same unprotected arguments to its own event. Both events size and copy a __string field separately. A reference to the dentry does not pin the external storage backing an individual name.

With an event enabled, a caller can be preempted after loading the name pointer. A long-to-short rename can then replace the name and reclaim its old external allocation before the trace callback sizes or copies it, provided no other snapshot retains that allocation.

The setattr inode lock does not exclude every rename: a same-directory rename of a source directory need not take that directory's inode lock. It can therefore change the dentry name while setattr records its event. Inline names and separately loaded lengths can also change during trace record sizing and copying.

Take a dentry name snapshot around each of these six trace calls and pass both the string and length from the snapshot. Check event enablement before taking a snapshot. Keep the event classes and formats unchanged.

Also remove the redundant NULL-inode check in the read callback. file_inode() returns the open file's inode, which is already used by the trace call above the check.

The historical report below is from the read path.

KASAN report as below:

    BUG: KASAN: slab-use-after-free in strlen+0x85/0xa0
    Read of size 1 at addr ffff88810a5b2b18 by task python3/496
    [CPU and host details omitted.]
    Call Trace:
     <TASK>
     dump_stack_lvl+0x93/0xd0
     print_report+0xce/0x630
     ? strlen+0x85/0xa0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __virt_addr_valid+0x20e/0x420
     ? strlen+0x85/0xa0
     kasan_report+0xe0/0x110
     ? strlen+0x85/0xa0
     strlen+0x85/0xa0
     trace_event_raw_event_ocfs2__file_ops+0xf0/0x480
     ? __pfx_trace_event_raw_event_ocfs2__file_ops+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? pmbd_probe_hit_cookie+0xe7/0x1c0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx_pmbd_probe_hit_cookie+0x10/0x10
     ocfs2_file_read_iter+0x6cd/0xb30
     ? __pfx_ocfs2_file_read_iter+0x10/0x10
     ? selinux_file_permission+0x11d/0x540
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? security_file_permission+0x26/0x80
     vfs_read+0x7d2/0xc20
     ? __pfx_vfs_read+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx_do_sys_openat2+0x10/0x10
     ksys_read+0x111/0x200
     ? __pfx_ksys_read+0x10/0x10
     ? irqentry_exit+0xbe/0x820
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? trace_hardirqs_on_prepare+0x11d/0x150
     ? srso_alias_return_thunk+0x5/0xfbef5
     do_syscall_64+0x114/0x620
     entry_SYSCALL_64_after_hwframe+0x77/0x7f
    [User register dump omitted.]
     </TASK>

    Allocated by task 489:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     __kasan_kmalloc+0xaa/0xb0
     __kmalloc_noprof+0x2de/0x780
     __d_alloc+0x5fc/0x8c0
     d_alloc_parallel+0x106/0x11d0
     lookup_open+0x3ff/0x13e0
     path_openat+0x95e/0x2020
     do_file_open+0x21e/0x470
     do_sys_openat2+0xf4/0x1b0
     __x64_sys_openat+0x136/0x1e0
     do_syscall_64+0x114/0x620
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    Freed by task 0:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     kasan_save_free_info+0x3b/0x60
     __kasan_slab_free+0x5f/0x80
     __rcu_free_sheaf_prepare+0x65/0x2a0
     rcu_free_sheaf_nobarn+0x1d/0x50
     rcu_core+0x6be/0x1ed0
     handle_softirqs+0x1fa/0x8d0
     __irq_exit_rcu+0x113/0x1e0
     irq_exit_rcu+0xe/0x20
     sysvec_apic_timer_interrupt+0x6c/0x80
     asm_sysvec_apic_timer_interrupt+0x1a/0x20

    The buggy address belongs to the object at ffff88810a5b2b00
     which belongs to the cache kmalloc-rcl-192 of size 192
    The buggy address is located 24 bytes inside of
     freed 192-byte region [ffff88810a5b2b00, ffff88810a5b2bc0)

    [Page and shadow-memory dumps omitted.]
---
 fs/ocfs2/file.c |  102 +++++++++++++++++++++++++++++++++++---------------------
 1 file changed, 65 insertions(+), 37 deletions(-)
fs/ocfs2/file.c +65 -37
@@ -85,10 +85,17 @@ static int ocfs2_file_open(struct inode
 	int mode = file->f_flags;
 	struct ocfs2_inode_info *oi = OCFS2_I(inode);
 
-	trace_ocfs2_file_open(inode, file, file->f_path.dentry,
-			      (unsigned long long)oi->ip_blkno,
-			      file->f_path.dentry->d_name.len,
-			      file->f_path.dentry->d_name.name, mode);
+	if (trace_ocfs2_file_open_enabled()) {
+		struct dentry *dentry = file->f_path.dentry;
+		struct name_snapshot name;
+
+		take_dentry_name_snapshot(&name, dentry);
+		trace_ocfs2_file_open(inode, file, dentry,
+				      oi->ip_blkno,
+				      name.name.len, name.name.name,
+				      mode);
+		release_dentry_name_snapshot(&name);
+	}
 
 	if (file->f_mode & FMODE_WRITE) {
 		status = dquot_initialize(inode);
@@ -174,11 +181,17 @@ static int ocfs2_sync_file(struct file *
 	tid_t commit_tid;
 	bool needs_barrier = false;
 
-	trace_ocfs2_sync_file(inode, file, file->f_path.dentry,
-			      oi->ip_blkno,
-			      file->f_path.dentry->d_name.len,
-			      file->f_path.dentry->d_name.name,
-			      (unsigned long long)datasync);
+	if (trace_ocfs2_sync_file_enabled()) {
+		struct dentry *dentry = file->f_path.dentry;
+		struct name_snapshot name;
+
+		take_dentry_name_snapshot(&name, dentry);
+		trace_ocfs2_sync_file(inode, file, dentry,
+				      oi->ip_blkno,
+				      name.name.len, name.name.name,
+				      (unsigned long long)datasync);
+		release_dentry_name_snapshot(&name);
+	}
 
 	if (unlikely(ocfs2_emergency_state(osb)))
 		return -EROFS;
@@ -1132,15 +1145,19 @@ int ocfs2_setattr(struct mnt_idmap *idma
 	int had_lock;
 	struct ocfs2_lock_holder oh;
 
-	trace_ocfs2_setattr(inode, dentry,
-			    (unsigned long long)OCFS2_I(inode)->ip_blkno,
-			    dentry->d_name.len, dentry->d_name.name,
-			    attr->ia_valid,
-				attr->ia_valid & ATTR_MODE ? attr->ia_mode : 0,
-				attr->ia_valid & ATTR_UID ?
+	if (trace_ocfs2_setattr_enabled()) {
+		struct name_snapshot name;
+
+		take_dentry_name_snapshot(&name, dentry);
+		trace_ocfs2_setattr(inode, dentry, OCFS2_I(inode)->ip_blkno,
+				    name.name.len, name.name.name, attr->ia_valid,
+				    attr->ia_valid & ATTR_MODE ? attr->ia_mode : 0,
+				    attr->ia_valid & ATTR_UID ?
 					from_kuid(&init_user_ns, attr->ia_uid) : 0,
-				attr->ia_valid & ATTR_GID ?
+				    attr->ia_valid & ATTR_GID ?
 					from_kgid(&init_user_ns, attr->ia_gid) : 0);
+		release_dentry_name_snapshot(&name);
+	}
 
 	status = ocfs2_emergency_state(osb);
 	if (unlikely(status)) {
@@ -2392,11 +2409,17 @@ static ssize_t ocfs2_file_write_iter(str
 	int direct_io = iocb->ki_flags & IOCB_DIRECT ? 1 : 0;
 	int nowait = iocb->ki_flags & IOCB_NOWAIT ? 1 : 0;
 
-	trace_ocfs2_file_write_iter(inode, file, file->f_path.dentry,
-		(unsigned long long)OCFS2_I(inode)->ip_blkno,
-		file->f_path.dentry->d_name.len,
-		file->f_path.dentry->d_name.name,
-		(unsigned int)from->nr_segs);	/* GRRRRR */
+	if (trace_ocfs2_file_write_iter_enabled()) {
+		struct dentry *dentry = file->f_path.dentry;
+		struct name_snapshot name;
+
+		take_dentry_name_snapshot(&name, dentry);
+		trace_ocfs2_file_write_iter(inode, file, dentry,
+					    OCFS2_I(inode)->ip_blkno,
+					    name.name.len, name.name.name,
+					    (unsigned int)from->nr_segs);
+		release_dentry_name_snapshot(&name);
+	}
 
 	if (!direct_io && nowait)
 		return -EOPNOTSUPP;
@@ -2542,17 +2565,16 @@ static ssize_t ocfs2_file_read_iter(stru
 	int direct_io = iocb->ki_flags & IOCB_DIRECT ? 1 : 0;
 	int nowait = iocb->ki_flags & IOCB_NOWAIT ? 1 : 0;
 
-	trace_ocfs2_file_read_iter(inode, filp, filp->f_path.dentry,
-			(unsigned long long)OCFS2_I(inode)->ip_blkno,
-			filp->f_path.dentry->d_name.len,
-			filp->f_path.dentry->d_name.name,
-			to->nr_segs);	/* GRRRRR */
-
-
-	if (!inode) {
-		ret = -EINVAL;
-		mlog_errno(ret);
-		goto bail;
+	if (trace_ocfs2_file_read_iter_enabled()) {
+		struct dentry *dentry = filp->f_path.dentry;
+		struct name_snapshot name;
+
+		take_dentry_name_snapshot(&name, dentry);
+		trace_ocfs2_file_read_iter(inode, filp, dentry,
+					   OCFS2_I(inode)->ip_blkno,
+					   name.name.len, name.name.name,
+					   to->nr_segs);
+		release_dentry_name_snapshot(&name);
 	}
 
 	if (!direct_io && nowait)
@@ -2624,11 +2646,17 @@ static ssize_t ocfs2_file_splice_read(st
 	ssize_t ret = 0;
 	int lock_level = 0;
 
-	trace_ocfs2_file_splice_read(inode, in, in->f_path.dentry,
-				     (unsigned long long)OCFS2_I(inode)->ip_blkno,
-				     in->f_path.dentry->d_name.len,
-				     in->f_path.dentry->d_name.name,
-				     flags);
+	if (trace_ocfs2_file_splice_read_enabled()) {
+		struct dentry *dentry = in->f_path.dentry;
+		struct name_snapshot name;
+
+		take_dentry_name_snapshot(&name, dentry);
+		trace_ocfs2_file_splice_read(inode, in, dentry,
+					     OCFS2_I(inode)->ip_blkno,
+					     name.name.len, name.name.name,
+					     flags);
+		release_dentry_name_snapshot(&name);
+	}
 
 	/*
 	 * We're fine letting folks race truncates and extending writes with
author maintainer
#279 lore raw

PATCH 279/547 smb: client: fix OOB last_entry pointer from unbounded LastNameOffset

In reply to Greg Kroah-Hartman

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

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

From: Diego Oliva <[email protected]>

commit 570c783a96f054dd3ac409a92772e9afb705d21c upstream.

CIFSFindFirst() and CIFSFindNext() locate the last entry of a TRANS2_FIND_FIRST2 or TRANS2_FIND_NEXT2 response by adding the LastNameOffset of the response parameters to the start of the data area, and store the result in psrch_inf->last_entry. MS-CIFS 2.2.6.2.2 defines that offset as the offset of the entry's file name; the client follows the reading of NT and Samba servers, which point it at the entry. LastNameOffset is only checked against CIFSMaxBufSize, which says nothing about the response actually received: validate_t2() lets the data area start up to 1024 bytes into the buffer, and SendReceive() copies at most CIFSMaxBufSize + MAX_CIFS_HDR_SIZE bytes of a response, 16468 by default, into a cifs_request allocation of CIFSMaxBufSize + MAX_SMB2_HDR_SIZE bytes, 16588 by default. The pointer itself can therefore be placed anywhere from the end of the received data to 820 bytes past the end of the allocation.

The read through that pointer is far larger than its displacement. find_cifs_entry() hands last_entry to cifs_save_resume_key() after every FindNext and after the FindFirst of a search rewind, and cifs_fill_dirent() takes the length of the name from the entry itself: a __le32 FileNameLength for most levels, a __u8 for SMB_FIND_FILE_INFO_STANDARD, and for SMB_FIND_FILE_UNIX the result of a scan for the terminating NUL over up to PATH_MAX + 1 UTF-16 units. The name is recorded as the resume name of the search, and the next CIFSFindNext() rejects only a recorded length of PATH_MAX or more before copying the name into the ResumeFileName of its request and sending it with the resume key taken from the same entry: up to 4 KiB of memory from past the end of the allocation leaks to the server, and for SMB_FIND_FILE_UNIX the NUL scan runs about twice as far before the length is even known. The entry does not have to lie outside the response for that either: a maximal response ends about 120 bytes before the end of the allocation, so an entry in its last bytes with a name just under PATH_MAX has nearly all of that name copied from past the allocation.

It needs nothing unusual from the client: a FindNext response that reports no entries and does not end the search makes find_cifs_entry() send the next FindNext at once, carrying whatever was parsed at LastNameOffset, and a search rewind can do the same after its FindFirst. SMB1 is not negotiated by default: this takes a malicious or compromised server, a mount of it with an explicit vers=1.0, which CONFIG_CIFS_ALLOW_INSECURE_LEGACY (default y) permits, and a directory listing on that mount.

With KASAN enabled, a response that places the last entry past the buffer, with a large DataOffset and a LastNameOffset near the end of its range, gives:

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

 BUG: KASAN: slab-out-of-bounds in cifs_save_resume_key.isra.0+0x7aa/0x7f0
 Read of size 4 at addr ffff88807b55c33b by task ls/83

 CPU: 1 UID: 0 PID: 83 Comm: ls Not tainted 7.3.0-rc4-00457-gf14572c203d5 #69 PREEMPT(lazy)
 Call Trace:
  <TASK>
  kasan_report+0xdf/0x1a0
  cifs_save_resume_key.isra.0+0x7aa/0x7f0
  cifs_readdir+0x1ed6/0x29c0
  iterate_dir+0x1c0/0x570
  __x64_sys_getdents64+0x133/0x270
  do_syscall_64+0x109/0x5d0
  entry_SYSCALL_64_after_hwframe+0x77/0x7f
  </TASK>

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

 The buggy address belongs to the object at ffff88807b558000
  which belongs to the cache cifs_request of size 16588
 The buggy address is located 623 bytes to the right of
  allocated 16588-byte region [ffff88807b558000, ffff88807b55c0cc)
 ==================================================================

The four bytes read there are the FileNameLength of the entry, which cifs_fill_dirent() takes before anything checks where the entry lies.

Ignore the last entry when it does not start inside the received response or the response holds no entries; for a response without entries, last_entry pointed into or past its empty data area and cifs_save_resume_key() parsed whatever the buffer held there. The entry is bounded by the response that was received, which is what the buffer holds, rather than by the data area the response declares, which a later patch checks against the received length. Record the search handle before the last entry is examined, since a response without a usable last entry still carries the handle that the search is continued and closed with; leaving the assignment in the else branch would drop the handle of every response without entries.

This bounds where the last entry starts, not how far it is parsed: an entry that starts within the final bytes of the response still has its fixed part read past the end of the received data and its name, up to 4095 bytes, copied from past the end of the allocation, until the following patch bounds the parse itself. A response without a usable last entry continues the search with an empty resume name, since the preceding patch, "smb: client: fix use-after-free infoleak via the readdir resume name", drops the recorded name whenever a new response is installed. This patch applies on top of that one and relies on it: without it, every response rejected here would leave the previous name in place, pointing into a buffer that has been released.

A conforming server is not affected: the last entry lies inside the data area of the response.

Fixes 0752f1522a91 ("[CIFS] make sure we have the right resume info before calling CIFSFindNext")
Fixes b77d753c413e ("[CIFS] Check that last search entry resume key is valid")
Assisted-by Bynario AI
---
 fs/smb/client/cifssmb.c |   14 ++++++++++----
 1 file changed, 10 insertions(+), 4 deletions(-)
fs/smb/client/cifssmb.c +10 -4
@@ -4546,14 +4546,17 @@ findFirstRetry:
 	psrch_inf->presume_name = NULL;
 	psrch_inf->resume_name_len = 0;
 	psrch_inf->resume_key = 0;
+	if (pnetfid)
+		*pnetfid = parms->SearchHandle;
 	lnoff = le16_to_cpu(parms->LastNameOffset);
-	if (CIFSMaxBufSize < lnoff) {
+	if (!psrch_inf->entries_in_buffer) {
+		psrch_inf->last_entry = NULL;
+	} else if (psrch_inf->srch_entries_start + lnoff >=
+		   psrch_inf->ntwrk_buf_start + bytes_returned) {
 		cifs_dbg(VFS, "ignoring corrupt resume name\n");
 		psrch_inf->last_entry = NULL;
 	} else {
 		psrch_inf->last_entry = psrch_inf->srch_entries_start + lnoff;
-		if (pnetfid)
-			*pnetfid = parms->SearchHandle;
 	}
 	return 0;
 }
@@ -4672,7 +4675,10 @@ int CIFSFindNext(const unsigned int xid,
 	psrch_inf->resume_name_len = 0;
 	psrch_inf->resume_key = 0;
 	lnoff = le16_to_cpu(parms->LastNameOffset);
-	if (CIFSMaxBufSize < lnoff) {
+	if (!psrch_inf->entries_in_buffer) {
+		psrch_inf->last_entry = NULL;
+	} else if (psrch_inf->srch_entries_start + lnoff >=
+		   psrch_inf->ntwrk_buf_start + bytes_returned) {
 		cifs_dbg(VFS, "ignoring corrupt resume name\n");
 		psrch_inf->last_entry = NULL;
 	} else {
author maintainer
#280 lore raw

PATCH 280/547 smb: client: hold server info until cifsd exits

In reply to Greg Kroah-Hartman

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

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

From: Eduard Zateev <[email protected]>

commit 482c117c6dbeee382790168af10959810450ab09 upstream.

The last session reference can be dropped while the cifsd demultiplex thread is still running clean_demultiplex_info(). That thread frees TCP_Server_Info there, racing with cifs_put_tcp_session() as it releases the server crypto state. syzbot reported a KASAN use-after-free in cifs_crypto_secmech_release().

Keep an object reference for the cifsd thread. Defer final crypto, session-key, network namespace, string, and structure cleanup until both the last session reference and the thread reference are dropped. Drop the thread reference after clean_demultiplex_info() has finished using the server.

Build-tested with ARCH=arm64 and W=1 for fs/smb/client/connect.o. The KASAN reproducer was not run on the patched kernel.

---
 fs/smb/client/cifsglob.h |    2 ++
 fs/smb/client/connect.c  |   33 +++++++++++++++++++++------------
 2 files changed, 23 insertions(+), 12 deletions(-)
fs/smb/client/cifsglob.h +2 -0
@@ -16,6 +16,7 @@
 #include <linux/scatterlist.h>
 #include <linux/mm.h>
 #include <linux/mempool.h>
+#include <linux/refcount.h>
 #include <linux/workqueue.h>
 #include <linux/utsname.h>
 #include <linux/sched/mm.h>
@@ -679,6 +680,7 @@ struct TCP_Server_Info {
 	spinlock_t srv_lock;  /* protect anything here that is not protected */
 	__u64 conn_id; /* connection identifier (useful for debugging) */
 	int srv_count; /* reference counter */
+	refcount_t obj_refs; /* struct lifetime: srv_count users + cifsd */
 	int rfc1001_sessinit; /* whether to estasblish netbios session */
 	bool with_rfc1001; /* if netbios session is used */
 	/* 15 character server name + 0x20 16th byte indicating type = srv */
fs/smb/client/connect.c +21 -12
@@ -1062,6 +1062,19 @@ cifs_enable_signing(struct TCP_Server_In
 	return 0;
 }
 
+static void cifs_tcp_server_put(struct TCP_Server_Info *server)
+{
+	if (!refcount_dec_and_test(&server->obj_refs))
+		return;
+
+	cifs_crypto_secmech_release(server);
+	kfree_sensitive(server->session_key.response);
+	put_net(cifs_net_ns(server));
+	kfree(server->leaf_fullpath);
+	kfree(server->hostname);
+	kfree_sensitive(server);
+}
+
 static noinline_for_stack void
 clean_demultiplex_info(struct TCP_Server_Info *server)
 {
@@ -1147,14 +1160,11 @@ clean_demultiplex_info(struct TCP_Server
 		 */
 	}
 
-	put_net(cifs_net_ns(server));
-	kfree(server->leaf_fullpath);
-	kfree(server->hostname);
-	kfree_sensitive(server);
-
 	length = atomic_dec_return(&tcpSesAllocCount);
 	if (length > 0)
 		mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
+
+	cifs_tcp_server_put(server);
 }
 
 static int
@@ -1731,7 +1741,7 @@ cifs_put_tcp_session(struct TCP_Server_I
 	else
 		cancel_delayed_work_sync(&server->reconnect);
 
-	/* For secondary channels, we pick up ref-count on the primary server */
+	/* For secondary channels, drop the reference on the primary server */
 	if (SERVER_IS_CHAN(server))
 		cifs_put_tcp_session(server->primary_server, from_reconnect);
 
@@ -1739,15 +1749,11 @@ cifs_put_tcp_session(struct TCP_Server_I
 	server->tcpStatus = CifsExiting;
 	spin_unlock(&server->srv_lock);
 
-	cifs_crypto_secmech_release(server);
-
-	kfree_sensitive(server->session_key.response);
-	server->session_key.response = NULL;
-	server->session_key.len = 0;
-
 	task = xchg(&server->tsk, NULL);
 	if (task)
 		send_sig(SIGKILL, task, 1);
+
+	cifs_tcp_server_put(server);
 }
 
 struct TCP_Server_Info *
@@ -1769,6 +1775,7 @@ cifs_get_tcp_session(struct smb3_fs_cont
 		rc = -ENOMEM;
 		goto out_err;
 	}
+	refcount_set(&tcp_ses->obj_refs, 1);
 
 	tcp_ses->hostname = kstrdup(ctx->server_hostname, GFP_KERNEL);
 	if (!tcp_ses->hostname) {
@@ -1907,6 +1914,8 @@ smbd_connected:
 		module_put(THIS_MODULE);
 		goto out_err_crypto_release;
 	}
+	/* Keep the server alive until the demultiplex thread has exited */
+	refcount_inc(&tcp_ses->obj_refs);
 	/* thread created, put it on the list */
 	spin_lock(&cifs_tcp_ses_lock);
 	list_add(&tcp_ses->tcp_ses_list, &cifs_tcp_ses_list);
author maintainer
#281 lore raw

PATCH 281/547 smb: client: stop processing a read response after a receive error

In reply to Greg Kroah-Hartman

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

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

From: Weiming Shi <[email protected]>

commit 51efca72345acdbedc4af76782d464bd15ba50ff upstream.

cifs_read_iter_from_socket() may call cifs_reconnect() before returning an error. The reconnect path aborts pending mids and invokes their callbacks. The callback can then release the cifs_io_subrequest containing rdata.

cifs_readv_receive() nevertheless continues after a negative return and may dereference rdata in cifs_readv_discard(). KASAN reports the resulting UAF:

  BUG: KASAN: slab-use-after-free in cifs_readv_receive
  Read of size 4 by task cifsd
  cifs_readv_receive (fs/smb/client/transport.c:1284)
  cifs_demultiplex_thread (fs/smb/client/connect.c:1355)
  kthread (kernel/kthread.c:436)
  ret_from_fork (arch/x86/kernel/process.c:158)

  Freed by task 148:
  netfs_put_subrequest (fs/netfs/objects.c:267)
  netfs_read_collection (fs/netfs/read_collect.c:460)
  netfs_wait_for_in_progress (fs/netfs/misc.c:462)

Return the socket error immediately, as this path did before the iterator conversion. This also avoids adding a negative length to total_read.

Fixes d08089f649a0 ("cifs: Change the I/O paths to use an iterator rather than a page list")
Reported-by [email protected]
Assisted-by LLM
---
 fs/smb/client/transport.c |    2 ++
 1 file changed, 2 insertions(+)
fs/smb/client/transport.c +2 -0
@@ -1317,6 +1317,8 @@ cifs_readv_receive(struct TCP_Server_Inf
 #endif
 		length = cifs_read_iter_from_socket(server, &rdata->subreq.io_iter,
 						    data_len);
+	if (length < 0)
+		return length;
 	if (length > 0)
 		rdata->got_bytes += length;
 	server->total_read += length;
author maintainer
#282 lore raw

PATCH 282/547 ovl: hold a reference on the parent in readdir

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

commit 16d319e12328acafeafd3eecdf09c46d7fb43452 upstream.

Listing a directory on an overlay uses a freed dentry and crashes the kernel when a lookup moves the directory at the same time.

Code that can sleep may only use d_parent without a reference while something stops a move of the dentry. ovl_iterate_real(), ovl_need_adjust_d_ino() and ovl_cache_update() use the d_parent of the listed directory and hold only the lock of that directory. When a lookup finds the directory under another parent after a change to a layer, d_splice_alias() moves it without that lock and drops its reference on the old parent.

With a delay in ovl_iterate_real(), getdents64 on an overlay directory raced a rename in the lower layer and a lookup that moved its dentry, and after an rmdir of the old parent KASAN reported a use-after-free in security_inode_getattr().

Fix this by using dget_parent() in the three functions.

Fixes b5efccbe0a12 ("ovl: constant d_ino across copy up")
[amir: fix comments in ovl_need_adjust_d_ino()]
---
 fs/overlayfs/readdir.c |   33 +++++++++++++++++++++++++--------
 1 file changed, 25 insertions(+), 8 deletions(-)
fs/overlayfs/readdir.c +25 -8
@@ -568,8 +568,8 @@ static int ovl_cache_update(const struct
 			goto get;
 		}
 		if (p->len == 2) {
-			/* we shall not be moved */
-			this = dget(dir->d_parent);
+			/* d_splice_alias() can move even a locked dir */
+			this = dget_parent(dir);
 			goto get;
 		}
 	}
@@ -797,6 +797,7 @@ static int ovl_iterate_real(struct file
 	struct dentry *dir = file->f_path.dentry;
 	struct ovl_fs *ofs = OVL_FS(dir->d_sb);
 	const struct ovl_layer *lower_layer = ovl_layer_lower(dir);
+	struct dentry *parent;
 	struct ovl_readdir_translate rdt = {
 		.ctx.actor = ovl_fill_real,
 		.ctx.count = ctx->count,
@@ -808,18 +809,26 @@ static int ovl_iterate_real(struct file
 	if (rdt.xinobits && lower_layer)
 		rdt.fsid = lower_layer->fsid;
 
-	if (OVL_TYPE_MERGE(ovl_path_type(dir->d_parent))) {
+	/*
+	 * The lock on dir does not stop d_splice_alias() from moving it to
+	 * another parent, which drops the reference dir holds on this one.
+	 */
+	parent = dget_parent(dir);
+	if (OVL_TYPE_MERGE(ovl_path_type(parent))) {
 		struct kstat stat;
 		struct path statpath = file->f_path;
 
-		statpath.dentry = dir->d_parent;
+		statpath.dentry = parent;
 		err = vfs_getattr(&statpath, &stat, STATX_INO, 0);
-		if (err)
+		if (err) {
+			dput(parent);
 			return err;
+		}
 
 		WARN_ON_ONCE(dir->d_sb->s_dev != stat.dev);
 		rdt.parent_ino = stat.ino;
 	}
+	dput(parent);
 
 	if (ovl_is_impure_dir(file)) {
 		rdt.cache = ovl_cache_get_impure(&file->f_path);
@@ -875,8 +884,10 @@ static bool ovl_need_adjust_d_ino(struct
 {
 	struct dentry *dentry = file->f_path.dentry;
 	struct ovl_fs *ofs = OVL_FS(dentry->d_sb);
+	struct dentry *parent;
+	enum ovl_path_type type;
 
-	/* If parent is merge, then need to adjust d_ino for '..' */
+	/* With xino, need to map real d_ino to the unified overlay ino space */
 	if (ovl_xino_bits(ofs))
 		return true;
 
@@ -885,8 +896,14 @@ static bool ovl_need_adjust_d_ino(struct
 		return false;
 
 	/* If dir is impure then need to adjust d_ino for copied up entries */
-	if (ovl_is_impure_dir(file) ||
-	    OVL_TYPE_MERGE(ovl_path_type(dentry->d_parent)))
+	if (ovl_is_impure_dir(file))
+		return true;
+
+	/* If parent is merge, then need to adjust d_ino for '..' */
+	parent = dget_parent(dentry);
+	type = ovl_path_type(parent);
+	dput(parent);
+	if (OVL_TYPE_MERGE(type))
 		return true;
 
 	/* Pure: no need to adjust d_ino */
author maintainer
#283 lore raw

PATCH 283/547 ovl: set OVL_WHITEOUTS before publishing the upper dir

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

commit cbec8610ec5aaf35df50094ff639febc23f20773 upstream.

Listing a directory while it is copied up causes a use-after-free of the readdir cache.

A merge directory must never be iterated as a real upper directory:
that mode frees the cache in OVL_I(inode)->cache without looking at its refcount, while files opened in merged mode still use it. ovl_copy_up_workdir() publishes the upper dentry before it sets OVL_WHITEOUTS, and ovl_dir_open() samples both without a lock, so an open between the two stores finds the upper directory and takes it for a real one.

With a delay between the two stores, an unprivileged process that listed a directory during its copy-up saw only "." and "..", and its next getdents freed the readdir cache of another descriptor.

Fix this by setting OVL_WHITEOUTS before ovl_inode_update(), so that ovl_dir_reset() agrees with ovl_dir_open(), and by testing OVL_TYPE_MERGE() of the path type in ovl_dir_open(), so that an open that observes the upper dentry never iterates a merge dir as a real dir, regardless of the order in which it observes the flag.

Fixes b79e05aaa166 ("ovl: no direct iteration for dir with origin xattr")
[amir: test OVL_TYPE_MERGE() instead of smp_rmb() in ovl_dir_open()]
---
 fs/overlayfs/copy_up.c |    2 +-
 fs/overlayfs/readdir.c |    3 ++-
 2 files changed, 3 insertions(+), 2 deletions(-)
fs/overlayfs/copy_up.c +1 -1
@@ -834,9 +834,9 @@ static int ovl_copy_up_workdir(struct ov
 
 	if (!c->metacopy)
 		ovl_set_upperdata(inode);
-	ovl_inode_update(inode, temp);
 	if (S_ISDIR(inode->i_mode))
 		ovl_set_flag(OVL_WHITEOUTS, inode);
+	ovl_inode_update(inode, temp);
 out:
 	ovl_end_write(c->dentry);
 
fs/overlayfs/readdir.c +2 -1
@@ -1072,7 +1072,8 @@ static int ovl_dir_open(struct inode *in
 		return PTR_ERR(realfile);
 	}
 	od->realfile = realfile;
-	od->is_real = ovl_dir_is_real(inode);
+	od->is_real = !OVL_TYPE_MERGE(type) &&
+		      !ovl_test_flag(OVL_WHITEOUTS, inode);
 	od->is_upper = OVL_TYPE_UPPER(type);
 	file->private_data = od;
 
author maintainer
#284 lore raw

PATCH 284/547 ovl: take a snapshot of the name for copy up

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

commit 65bf000962a33ec9d2488e4e1797b6cf630abcbb upstream.

The copy up of a directory reads a freed dentry name when a lookup moves the directory at the same time.

A pointer to the name of a dentry is only valid while something stops a move of the dentry. ovl_do_copy_up() keeps a plain copy of c->dentry->d_name in c->destname, and ovl_copy_up_start() only keeps ovl_rename() away. When a lookup finds the same directory under another name after a change to the lower layer, d_splice_alias() moves the dentry and frees its external name.

With a delay in ovl_do_copy_up(), a chmod of a lower-only directory with a 60 byte name raced with a rename of that directory in the lower layer and a stat of the new name, and KASAN reported a use-after-free in lookup_noperm_common().

Fix this by using take_dentry_name_snapshot() for c->destname.

Fixes 829c28be9bb9 ("ovl: use d_splice_alias() in place of d_add() in lookup")
---
 fs/overlayfs/copy_up.c |   18 ++++++++++++------
 1 file changed, 12 insertions(+), 6 deletions(-)
fs/overlayfs/copy_up.c +12 -6
@@ -935,6 +935,7 @@ static int ovl_do_copy_up(struct ovl_cop
 	struct ovl_fs *ofs = OVL_FS(c->dentry->d_sb);
 	struct dentry *origin = c->lowerpath.dentry;
 	struct ovl_fh *fh = NULL;
+	struct name_snapshot name;
 	bool to_index = false;
 
 	/*
@@ -972,12 +973,15 @@ static int ovl_do_copy_up(struct ovl_cop
 		goto out_free_fh;
 	} else {
 		/*
-		 * c->dentry->d_name is stabilzed by ovl_copy_up_start(),
-		 * because if we got here, it means that c->dentry has no upper
-		 * alias and changing ->d_name means going through ovl_rename()
-		 * that will call ovl_copy_up() on source and target dentry.
+		 * ovl_copy_up_start() keeps ovl_rename() away from c->dentry,
+		 * because ovl_rename() calls ovl_copy_up() on source and target
+		 * dentry.  It does not stop d_splice_alias() from moving a
+		 * directory that a lookup found under another name after a
+		 * change to the lower layer.  That move frees an external name,
+		 * so take a snapshot.
 		 */
-		c->destname = c->dentry->d_name;
+		take_dentry_name_snapshot(&name, c->dentry);
+		c->destname = name.name;
 		/*
 		 * Mark parent "impure" because it may now contain non-pure
 		 * upper
@@ -986,7 +990,7 @@ static int ovl_do_copy_up(struct ovl_cop
 		err = ovl_set_impure(c->parent, c->destdir);
 		ovl_end_write(c->dentry);
 		if (err)
-			goto out_free_fh;
+			goto out;
 	}
 
 	/* Should we copyup with O_TMPFILE or with workdir? */
@@ -1020,6 +1024,8 @@ static int ovl_do_copy_up(struct ovl_cop
 out:
 	if (to_index)
 		kfree(c->destname.name);
+	else
+		release_dentry_name_snapshot(&name);
 out_free_fh:
 	kfree(fh);
 	return err;
author maintainer
#285 lore raw

PATCH 285/547 ovl: use the pinned upper dir in ovl_fix_origin()

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

commit 4f61ff2ebfb3d2967b83b6a4d456242244d5a61f upstream.

Renames made directly on the upper filesystem during a lookup crash the kernel.

A dentry that is passed to vfs_setxattr() must be pinned. ovl_fix_origin() passes upper->d_parent to ovl_set_impure() without a reference, and the lookup holds no lock of the upper directory. A rename on the upper filesystem changes d_parent, and only the child pins the new parent, so a second rename and an rmdir free it.

With delays in ovl_fix_origin() and ovl_set_impure(), renaming the upper directory twice and removing the intermediate parent during the lookup of a merge directory without an origin xattr gave a KASAN use-after-free in vfs_setxattr().

Fix this by passing the upper dentry that the overlay parent holds.

Fixes 9678e6303057 ("ovl: fix inconsistent d_ino for legacy merge dir")
[amir: add helper ovl_set_impure_dir()]
---
 fs/overlayfs/namei.c     |    6 ++++--
 fs/overlayfs/overlayfs.h |    6 ++++++
 2 files changed, 10 insertions(+), 2 deletions(-)
fs/overlayfs/namei.c +4 -2
@@ -942,8 +942,10 @@ static int ovl_fix_origin(struct ovl_fs
 		goto out;
 
 	err = ovl_set_origin_fh(ofs, fh, upper);
-	if (!err)
-		err = ovl_set_impure(dentry->d_parent, upper->d_parent);
+	if (!err) {
+		/* upper->d_parent is not stable, use the overlay parent */
+		err = ovl_set_impure_dir(dentry->d_parent);
+	}
 
 	ovl_drop_write(dentry);
 out:
fs/overlayfs/overlayfs.h +6 -0
@@ -572,6 +572,12 @@ int ovl_check_setxattr(struct ovl_fs *of
 		       enum ovl_xattr ox, const void *value, size_t size,
 		       int xerr);
 int ovl_set_impure(struct dentry *dentry, struct dentry *upperdentry);
+
+static inline int ovl_set_impure_dir(struct dentry *dentry)
+{
+	return ovl_set_impure(dentry, ovl_dentry_upper(dentry));
+}
+
 bool ovl_inuse_trylock(struct dentry *dentry);
 void ovl_inuse_unlock(struct dentry *dentry);
 bool ovl_is_inuse(struct dentry *dentry);
author maintainer
#286 lore raw

PATCH 286/547 ovl: always encode the origin fh when index is enabled

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

commit 949f9d8a5580c77a45fa759123367682aba4d173 upstream.

On an overlay with index=on,nfs_export=on, copy up of a directory crashes the kernel once an LSM has started to deny CAP_DAC_READ_SEARCH to the mounter, the task that mounted the overlay. The mount and the LSM policy change require root. After that, any user who can write to a directory that exists only in a lower layer triggers the oops by doing so.

Before a file or directory that exists only in a lower layer is changed for the first time, overlayfs copies it to the writable upper layer. This is called copy up.

On copy up, ovl_get_origin_fh() encodes the file handle of the lower inode, called the origin. It returns NULL if ovl_can_decode_fh() says that the lower filesystem cannot decode handles. Whether the callers can handle NULL depends on the index option:

- Without an index, NULL is fine: the callers store an empty origin xattr.
- With index enabled, overlayfs keeps entries for copied up inodes in an internal index directory. The name of an index entry is derived from the handle, so ovl_get_origin_fh() must return a handle or an error.

The mount only enables the index if ovl_can_decode_fh() succeeds for all layers, but the result can change later. The function checks the export operations of the filesystem and capable(CAP_DAC_READ_SEARCH). Copy up runs with the mounter's credentials, and an LSM can start to deny the capability to those credentials after the mount. ovl_get_origin_fh() then returns NULL with index enabled.

This goes wrong in two callers:

- With nfs_export=on, copy up of a directory creates an index entry for the directory. ovl_create_index() passes the NULL handle to ovl_get_index_name_fh(), which dereferences it.
- If the result changes while mount(2) is still running, ovl_get_indexdir() passes a NULL from ovl_get_origin_fh() to ovl_verify_set_fh() in the same way.

Before the commit in the Fixes tag, these two callers encoded the handle themselves, without consulting ovl_can_decode_fh().

Reproduced with a BPF LSM program that started to deny the capability after the mount. An unprivileged touch in a directory that had not been copied up yet oopsed in ovl_get_index_name_fh(). With this patch the touch succeeds and the directory gets its index entry.

Fix this by calling ovl_can_decode_fh() in ovl_get_origin_fh() only when index is disabled.

Fixes 5b02bfc1e7e3 ("ovl: do not encode lower fh with upper sb_writers held")
---
 fs/overlayfs/copy_up.c |    6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
fs/overlayfs/copy_up.c +5 -1
@@ -476,8 +476,12 @@ struct ovl_fh *ovl_get_origin_fh(struct
 	 * When lower layer doesn't support export operations store a 'null' fh,
 	 * so we can use the overlay.origin xattr to distignuish between a copy
 	 * up and a pure upper inode.
+	 *
+	 * With index enabled, mount already found that all layers can decode
+	 * file handles.  Do not ask again, because an LSM may change its answer
+	 * about CAP_DAC_READ_SEARCH and index users cannot cope with a 'null' fh.
 	 */
-	if (!ovl_can_decode_fh(origin->d_sb))
+	if (!ofs->config.index && !ovl_can_decode_fh(origin->d_sb))
 		return NULL;
 
 	return ovl_encode_real_fh(ofs, d_inode(origin), false);
author maintainer
#287 lore raw

PATCH 287/547 ovl: check that the parents of volatile/dirty are dirs

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

commit e34d2ef818e4c7676d8d8e1bf43e6a1ed39efb2a upstream.

An unprivileged user crashes the kernel by mounting overlayfs with the volatile option.

A dentry that serves as the parent of a lookup must be a directory. ovl_create_volatile_dirty() walks work/incompat/volatile/dirty by name, and ovl_lookup_or_create() returns an existing entry whatever its type. A file or a symlink that another task creates during the mount becomes the parent of the next lookup, which calls a NULL ->lookup.

An unprivileged user mounted overlayfs with "volatile" in a user namespace while a second process created a symlink named work/incompat, and the mount task oopsed on a NULL ->lookup call.

Fix this by returning -ENOTDIR from ovl_lookup_or_create() when the caller asked for a directory and the existing entry is a non-dir.

Fixes c86243b090bc ("ovl: provide a mount option "volatile"")
---
 fs/overlayfs/super.c |   13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)
fs/overlayfs/super.c +9 -4
@@ -621,16 +621,21 @@ cleanup_temp:
 
 static struct dentry *ovl_lookup_or_create(struct ovl_fs *ofs,
 					   struct dentry *parent,
-					   const char *name, umode_t mode)
+					   const char *name, bool is_dir)
 {
 	struct dentry *child;
 
 	child = ovl_start_creating_upper(ofs, parent, &QSTR(name));
 	if (!IS_ERR(child)) {
-		if (!child->d_inode)
+		if (!child->d_inode) {
 			child = ovl_create_real(ofs, parent, child,
 						&QSTR(name),
-						OVL_CATTR(mode));
+						OVL_CATTR(is_dir ? S_IFDIR :
+								   S_IFREG));
+		} else if (is_dir && !d_can_lookup(child)) {
+			end_creating(child);
+			child = ERR_PTR(-ENOTDIR);
+		}
 		end_creating_keep(child);
 	}
 	dput(parent);
@@ -652,7 +657,7 @@ static int ovl_create_volatile_dirty(str
 	const char *const *name = volatile_path;
 
 	for (ctr = ARRAY_SIZE(volatile_path); ctr; ctr--, name++) {
-		d = ovl_lookup_or_create(ofs, d, *name, ctr > 1 ? S_IFDIR : S_IFREG);
+		d = ovl_lookup_or_create(ofs, d, *name, ctr > 1);
 		if (IS_ERR(d))
 			return PTR_ERR(d);
 	}
author maintainer
#288 lore raw

PATCH 288/547 ovl: check the casefold flag of directories only

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

commit 1d27da7de3f74405b1de85ad26c5ea90f826114b upstream.

On an overlay over casefolded (case-insensitive) directories, every lookup of a file that is not a directory fails with EREMOTE, and the first file create triggers a kernel warning. No privilege is needed: an unprivileged user can cause both in a user namespace, with the layers on a tmpfs that they have mounted with the casefold option.

Some filesystems support casefolding, which is case-insensitive name lookup. It is enabled per directory, and the inode of a casefolded directory has the S_CASEFOLD flag.

overlayfs accepts layers on a filesystem that supports casefolding as long as casefolding is enabled on every directory of the layers, or on none. The mount records which of the two applies in ofs->casefold. ovl_lookup_single() compares the S_CASEFOLD flag of each file that it finds against ofs->casefold and returns -EREMOTE on a mismatch.

Filesystems only set S_CASEFOLD on directories, so with casefolded layers a regular file, a symlink or a special file never matches and its lookup fails.

ovl_get_inode() does the same comparison in a WARN_ON_ONCE() for each new overlay inode. A failed lookup never gets that far, so it is the first file create that trips the warning.

Reproduced on an overlay over casefolded tmpfs or ext4 directories, with stat() of a regular file, a symlink and a FIFO, and with a file create:
each stat() failed with EREMOTE. For an unprivileged user in a user namespace, on tmpfs, stat() of a regular file failed in the same way, and the file create triggered the warning.

Fix this by limiting both checks to directories.

Fixes 16754d61dc69 ("ovl: Support mounting case-insensitive enabled layers")
---
 fs/overlayfs/inode.c |    2 +-
 fs/overlayfs/namei.c |    3 ++-
 2 files changed, 3 insertions(+), 2 deletions(-)
fs/overlayfs/inode.c +1 -1
@@ -1279,7 +1279,7 @@ struct inode *ovl_get_inode(struct super
 	}
 	ovl_fill_inode(inode, realinode->i_mode, realinode->i_rdev);
 	ovl_inode_init(inode, oip, ino, fsid);
-	WARN_ON_ONCE(!!IS_CASEFOLDED(inode) != ofs->casefold);
+	WARN_ON_ONCE(is_dir && !!IS_CASEFOLDED(inode) != ofs->casefold);
 
 	if (upperdentry && ovl_is_impuredir(sb, upperdentry))
 		ovl_set_flag(OVL_IMPURE, inode);
fs/overlayfs/namei.c +2 -1
@@ -266,7 +266,8 @@ static int ovl_lookup_single(struct dent
 		goto out_err;
 	}
 
-	if (ofs->casefold != ovl_dentry_casefolded(this)) {
+	/* Filesystems set the casefold flag only on directories */
+	if (d_is_dir(this) && ofs->casefold != ovl_dentry_casefolded(this)) {
 		warn = "child wrong casefold";
 		err = -EREMOTE;
 		goto out_warn;
author maintainer
#289 lore raw

PATCH 289/547 ovl: do not copy up a dentry that was removed

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

commit f635192ad223d2009ee640b63adf5ce3198aa338 upstream.

A change to a removed file through an open descriptor replaces whatever has its old name in the upper layer.

Copy up must only create a name in the upper directory, never replace one. After an unlink, an rmdir or a rename over a lower dentry, a dentry that an open file keeps alive still has its old parent and name, but in the upper directory that name is now a whiteout or a new object. ovl_copy_up_workdir() renames the copy over it, which brings back the removed object and destroys whatever took its name.

An unprivileged user opened a lower FIFO and unlinked it, root created a file at that name, and fchmod on the old descriptor replaced the file of root with the FIFO.

Fix this by looking up the target name of the rename in ovl_copy_up_workdir() with LOOKUP_EXCL, so that copy up fails with -EEXIST if the name is taken, as copy up with O_TMPFILE already does when it links the copy to the name.

Fixes e9be9d5e76e3 ("overlay filesystem")
[amir: use LOOKUP_EXCL instead of relying on d_unhashed()]
---
 fs/overlayfs/copy_up.c |    5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
fs/overlayfs/copy_up.c +3 -2
@@ -812,9 +812,10 @@ static int ovl_copy_up_workdir(struct ov
 	rd.old_parent = c->workdir;
 	rd.new_parent = c->destdir;
 	rd.flags = 0;
-	err = start_renaming_dentry(&rd, 0, temp,
+	/* The name may have been taken since lookup, never replace it */
+	err = start_renaming_dentry(&rd, LOOKUP_EXCL, temp,
 				    &QSTR_LEN(c->destname.name, c->destname.len));
-	if (err) {
+	if (err && err != -EEXIST) {
 		/* temp or workdir moved underneath us? map to -EIO */
 		err = -EIO;
 	}
author maintainer
#290 lore raw

PATCH 290/547 ovl: do not copy up an xattr value that was never read

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

commit 755b5c5c9277be251a51623d6065abab948c61bc upstream.

Copy-up stores uninitialized kernel memory in an xattr of the upper file, where the user can read it.

ovl_copy_xattr() may only pass bytes to ovl_do_setxattr() that ovl_do_getxattr() has read. When the read fails with -ERANGE the function asks for the size again, and if the new size fits the buffer it stores the buffer although nothing was read into it. The buffer comes from kvmalloc(), or it still holds the value of the previous xattr.

A FUSE lower layer that answers every sized GETXATTR with -ERANGE made copy-up store 4096 bytes that the server never sent, with a kernel pointer in them, as an xattr of the upper file.

Fix this by failing the copy-up with -EIO when the size that follows -ERANGE fits the buffer.

---
 fs/overlayfs/copy_up.c |    6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
fs/overlayfs/copy_up.c +5 -1
@@ -131,8 +131,12 @@ int ovl_copy_xattr(struct super_block *s
 
 retry:
 		size = ovl_do_getxattr(oldpath, name, value, value_size);
-		if (size == -ERANGE)
+		if (size == -ERANGE) {
 			size = ovl_do_getxattr(oldpath, name, NULL, 0);
+			/* Nothing was read into value, so it must not be used */
+			if (size >= 0 && size <= value_size)
+				size = -EIO;
+		}
 
 		if (size < 0) {
 			error = size;
author maintainer
#291 lore raw

PATCH 291/547 ovl: fix a torn path in ovl_get_redirect()

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

commit 2001cd7ca5560198131e46c6ca3c3472b06145c2 upstream.

A hard link of a metacopy file that races with a rename of an ancestor stores a redirect to the wrong lower file.

Each component of an absolute redirect must be the name that a dentry has in the parent that the walk continues with. ovl_get_redirect() copies the name under d_lock and calls dget_parent() after the unlock, and the callers for a hard link hold no lock that stops a rename across directories. A rename between the two steps combines the old name with the new parent.

With delays in ovl_get_redirect(), an unprivileged user hard-linked a metacopy file while renaming its ancestor to another directory, the stored redirect named another lower path, and after a remount the file showed the data of a root-only file.

Fix this by taking the parent first and checking it again under d_lock.

Fixes e04527fefba6 ("ovl: fix dentry leak in ovl_get_redirect")
---
 fs/overlayfs/dir.c |   14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)
fs/overlayfs/dir.c +13 -1
@@ -1027,7 +1027,19 @@ static char *ovl_get_redirect(struct den
 		const char *name;
 		int thislen;
 
+		/*
+		 * A rename can move d to another directory at any time.  Hold
+		 * d_lock to copy the name that d has in this very parent, or
+		 * else the path mixes the old name with the new parent.
+		 */
+		tmp = dget_parent(d);
 		spin_lock(&d->d_lock);
+		if (unlikely(tmp != d->d_parent)) {
+			spin_unlock(&d->d_lock);
+			dput(tmp);
+			continue;
+		}
+
 		name = ovl_dentry_get_redirect(d);
 		if (name) {
 			thislen = strlen(name);
@@ -1040,13 +1052,13 @@ static char *ovl_get_redirect(struct den
 		if (thislen + (name[0] != '/') > buflen) {
 			ret = ERR_PTR(-EXDEV);
 			spin_unlock(&d->d_lock);
+			dput(tmp);
 			goto out_put;
 		}
 
 		buflen -= thislen;
 		memcpy(&buf[buflen], name, thislen);
 		spin_unlock(&d->d_lock);
-		tmp = dget_parent(d);
 
 		dput(d);
 		d = tmp;
author maintainer
#292 lore raw

PATCH 292/547 ovl: fix mount setup failing when override_creds drops CAP_SYS_ADMIN

In reply to Greg Kroah-Hartman

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

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

From: Amir Goldstein <[email protected]>

commit 333ad304d4794d6384087ea7fc16e58ab642809b upstream.

When a process drops CAP_SYS_ADMIN and calls fsconfig(FSCONFIG_SET_FLAG, "override_creds"), overlayfs saves those restricted credentials in ofs->creator_cred. ovl_fill_super() then wraps the entire mount setup in with_ovl_creds(), switching to those restricted credentials for the duration.

Mount setup calls clone_private_mount(), which checks CAP_SYS_ADMIN against current credentials. With restricted credentials active, this check fails with -EPERM even though the task issuing FSCONFIG_CMD_CREATE is fully privileged.

Use the mounter's real credentials only for cloning the private layer mounts. Keep all other backing filesystem operations during mount setup under the stashed credentials.

Fixes c28f922c9dcee ("clone_private_mnt(): make sure that caller has CAP_SYS_ADMIN in the right userns")
---
 fs/overlayfs/super.c |   18 ++++++++++++++++--
 1 file changed, 16 insertions(+), 2 deletions(-)
fs/overlayfs/super.c +16 -2
@@ -497,6 +497,20 @@ static int ovl_report_in_use(struct ovl_
 	}
 }
 
+/*
+ * clone_private_mount() checks CAP_SYS_ADMIN in current->cred.
+ * ovl_fill_super_creds() runs under the stashed creator cred, which
+ * override_creds may have dropped.
+ * The task that issued FSCONFIG_CMD_CREATE is still current->real_cred, so
+ * use that only for the clone. creator_cred stays in effect for every other
+ * backing-fs operation.
+ */
+static struct vfsmount *ovl_clone_private_mount(const struct path *path)
+{
+	scoped_with_creds(current_real_cred())
+		return clone_private_mount(path);
+}
+
 static int ovl_get_upper(struct super_block *sb, struct ovl_fs *ofs,
 			 struct ovl_layer *upper_layer,
 			 const struct path *upperpath)
@@ -520,7 +534,7 @@ static int ovl_get_upper(struct super_bl
 	if (err)
 		goto out;
 
-	upper_mnt = clone_private_mount(upperpath);
+	upper_mnt = ovl_clone_private_mount(upperpath);
 	err = PTR_ERR(upper_mnt);
 	if (IS_ERR(upper_mnt)) {
 		pr_err("failed to clone upperpath\n");
@@ -1098,7 +1112,7 @@ static int ovl_get_layers(struct super_b
 			}
 		}
 
-		mnt = clone_private_mount(&l->path);
+		mnt = ovl_clone_private_mount(&l->path);
 		err = PTR_ERR(mnt);
 		if (IS_ERR(mnt)) {
 			pr_err("failed to clone lowerpath\n");
author maintainer
#293 lore raw

PATCH 293/547 ovl: fortify ovl_copy_xattr() against underlying layer modifications

In reply to Greg Kroah-Hartman

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

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

From: Amir Goldstein <[email protected]>

commit e6b9117076fb4c0ff4a670efa9c876d9a50d79ab upstream.

Adapt ovl_getxattr_value() to be used from ovl_copy_xattr(), by allowing to pass it a pre-allocated buffer, which can be resized and by handling the ENODATA/EOPNOTSUPP return codes in the caller.

This replaces the retry loop in ovl_copy_xattr() with a single retry after resizing the buffer. If the value changed again by then, the underlying layer was modified, so return -EIO instead of retrying.

As a side effect, ovl_copy_up_meta_inode_data() now returns -EIO instead of -ERANGE in this case of underlying xattr size changes.

---
 fs/overlayfs/copy_up.c |   68 +++++++++++++++++++++++--------------------------
 1 file changed, 32 insertions(+), 36 deletions(-)
fs/overlayfs/copy_up.c +32 -36
@@ -72,6 +72,9 @@ static int ovl_copy_acl(struct ovl_fs *o
 	return err;
 }
 
+static ssize_t ovl_getxattr_value(const struct path *path, char *name,
+				  char **value, ssize_t *value_size);
+
 int ovl_copy_xattr(struct super_block *sb, const struct path *oldpath, struct dentry *new)
 {
 	struct dentry *old = oldpath->dentry;
@@ -129,34 +132,12 @@ int ovl_copy_xattr(struct super_block *s
 			break;
 		}
 
-retry:
-		size = ovl_do_getxattr(oldpath, name, value, value_size);
-		if (size == -ERANGE) {
-			size = ovl_do_getxattr(oldpath, name, NULL, 0);
-			/* Nothing was read into value, so it must not be used */
-			if (size >= 0 && size <= value_size)
-				size = -EIO;
-		}
-
+		size = ovl_getxattr_value(oldpath, name, &value, &value_size);
 		if (size < 0) {
 			error = size;
 			break;
 		}
 
-		if (size > value_size) {
-			void *new;
-
-			new = kvmalloc(size, GFP_KERNEL);
-			if (!new) {
-				error = -ENOMEM;
-				break;
-			}
-			kvfree(value);
-			value = new;
-			value_size = size;
-			goto retry;
-		}
-
 		error = ovl_do_setxattr(OVL_FS(sb), new, name, value, size, 0);
 		if (error) {
 			if (error != -EOPNOTSUPP || ovl_must_copy_xattr(name))
@@ -1070,26 +1051,39 @@ static bool ovl_need_meta_copy_up(struct
 	return true;
 }
 
-static ssize_t ovl_getxattr_value(const struct path *path, char *name, char **value)
+static ssize_t ovl_getxattr_value(const struct path *path, char *name,
+				  char **value, ssize_t *value_size)
 {
 	ssize_t res;
 	char *buf;
 
-	res = ovl_do_getxattr(path, name, NULL, 0);
-	if (res == -ENODATA || res == -EOPNOTSUPP)
-		res = 0;
+	res = ovl_do_getxattr(path, name, *value, *value_size);
+	if (res == -ERANGE) {
+		res = ovl_do_getxattr(path, name, NULL, 0);
+		/* Xattr changed underneath us? */
+		if (res >= 0 && res <= *value_size)
+			return -EIO;
+	}
 
-	if (res > 0) {
-		buf = kzalloc(res, GFP_KERNEL);
+	if (res > *value_size) {
+		buf = kvmalloc(res, GFP_KERNEL);
 		if (!buf)
 			return -ENOMEM;
 
 		res = ovl_do_getxattr(path, name, buf, res);
-		if (res < 0)
-			kfree(buf);
-		else
-			*value = buf;
+		if (res < 0) {
+			kvfree(buf);
+			/* Xattr changed underneath us? */
+			if (res == -ERANGE)
+				return -EIO;
+			return res;
+		}
+
+		kvfree(*value);
+		*value = buf;
+		*value_size = res;
 	}
+
 	return res;
 }
 
@@ -1100,7 +1094,7 @@ static int ovl_copy_up_meta_inode_data(s
 	struct path upperpath;
 	int err;
 	char *capability = NULL;
-	ssize_t cap_size;
+	ssize_t cap_size = 0;
 
 	ovl_path_upper(c->dentry, &upperpath);
 	if (WARN_ON(upperpath.dentry == NULL))
@@ -1108,7 +1102,9 @@ static int ovl_copy_up_meta_inode_data(s
 
 	if (c->stat.size) {
 		err = cap_size = ovl_getxattr_value(&upperpath, XATTR_NAME_CAPS,
-						    &capability);
+						    &capability, &cap_size);
+		if (cap_size == -ENODATA || cap_size == -EOPNOTSUPP)
+			cap_size = 0;
 		if (cap_size < 0)
 			goto out;
 	}
@@ -1138,7 +1134,7 @@ static int ovl_copy_up_meta_inode_data(s
 	ovl_clear_flag(OVL_VERIFIED_DIGEST, d_inode(c->dentry));
 	ovl_set_upperdata(d_inode(c->dentry));
 out_free:
-	kfree(capability);
+	kvfree(capability);
 out:
 	return err;
 }
author maintainer
#294 lore raw

PATCH 294/547 ovl: read the nlink xattr of every indexed non-dir

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

commit eb644ed5c6d9afdb1554c41cef1f39d150fbc554 upstream.

With nfs_export=on, data written through a file handle to a lower file, i.e. a file that exists only in a lower layer of the overlay, can be lost on the next mount. A lookup of the file by name then returns -EIO. Also, a file with one name reports st_nlink 2 once it has been copied to the upper layer. After such a file is removed, its file handle can still open it until the next mount.

Before a lower file is changed for the first time, overlayfs copies it to the writable upper layer. This is called copy up.

The index directory is $workdir/index, where $workdir is the directory given by the workdir= option. Each entry is named after the file handle of a lower inode, so that overlayfs can get from the handle to the copied up inode.

With nfs_export=on, copy up indexes every non-directory: it copies the file to an entry in the index directory and then hard links that entry into the upper directory. The index entry is an extra link to the upper inode, so overlayfs stores the link count that users should see in the overlay.nlink xattr.

A file can also be opened by handle, either by an NFS client or by a process with CAP_DAC_READ_SEARCH calling open_by_handle_at(). If the file is not in the dcache, its overlay dentry is disconnected, i.e. it has no parent yet. Copy up then creates the index entry but no hard link in the upper directory. The index entry has i_nlink 1 and holds the only copy of the data written to the file.

ovl_get_nlink() reads the stored count. Its caller passes a default, which the function returns if there is no stored count. If the lower inode has i_nlink 1, the function returns the default without reading the xattr. That was correct as long as only lower files with multiple links were indexed.

On the next mount, ovl_verify_index() looks for orphans, i.e. index entries of files whose last name was removed. For an index entry with i_nlink 1, it passes a default of 0 to ovl_get_nlink() and treats a result of 0 as an orphan. Here the lower inode also has i_nlink 1, so the result is the default. ovl_indexdir_cleanup() then replaces the entry with a whiteout, which in the index marks a file as deleted. The written data is lost.

A lookup by name then returns -EIO, because a whiteout as the index entry of a lower file that still exists is a bad index.

ovl_get_inode() gets the wrong count the same way. Its default is the i_nlink of the upper inode, which includes the index entry, so a copied up file with one name reports st_nlink 2.

When that name is removed, the count drops to 1 rather than 0. ovl_nlink_end() replaces the index entry with a whiteout only at a count of 0, so the entry stays, and the handle of the removed file still opens it.

Reproduced by writing through open_by_handle_at() to an uncached lower file with one link. After a remount the data was lost, and the name returned EIO.

Fix this by adding an argument to ovl_get_nlink() that says whether the caller found an index entry, and by skipping the xattr only if the caller found none.

Known gaps:
- An index entry that a kernel without this patch left behind for a removed file now stays, and the handle of that file keeps working. The entry has i_nlink 1 and a stored count of 1, just like the entry of a file that was only written by handle. Without this patch, the next mount treated it as an orphan.

Fixes fbd2d2074bde ("ovl: index all non-dir on copy up for NFS export")
---
 fs/overlayfs/inode.c     |   14 +++++++++++---
 fs/overlayfs/namei.c     |    2 +-
 fs/overlayfs/overlayfs.h |    2 +-
 3 files changed, 13 insertions(+), 5 deletions(-)
fs/overlayfs/inode.c +11 -3
@@ -999,7 +999,7 @@ int ovl_set_nlink_lower(struct dentry *d
 }
 
 unsigned int ovl_get_nlink(struct ovl_fs *ofs, struct dentry *lowerdentry,
-			   struct dentry *upperdentry,
+			   struct dentry *upperdentry, bool indexed,
 			   unsigned int fallback)
 {
 	int nlink_diff;
@@ -1007,7 +1007,15 @@ unsigned int ovl_get_nlink(struct ovl_fs
 	char buf[13];
 	int err;
 
-	if (!lowerdentry || !upperdentry || d_inode(lowerdentry)->i_nlink == 1)
+	if (!lowerdentry || !upperdentry)
+		return fallback;
+
+	/*
+	 * A lower inode with one link is not indexed on copy up, unless all
+	 * files are indexed for NFS export.  If the caller found an index entry,
+	 * then the xattr holds the union nlink, whatever the lower nlink is.
+	 */
+	if (!indexed && d_inode(lowerdentry)->i_nlink == 1)
 		return fallback;
 
 	err = ovl_getxattr_upper(ofs, upperdentry, OVL_XATTR_NLINK,
@@ -1264,7 +1272,7 @@ struct inode *ovl_get_inode(struct super
 		/* Recalculate nlink for non-dir due to indexing */
 		if (!is_dir)
 			nlink = ovl_get_nlink(ofs, lowerdentry, upperdentry,
-					      nlink);
+					      oip->index, nlink);
 		set_nlink(inode, nlink);
 		ino = key->i_ino;
 	} else {
fs/overlayfs/namei.c +1 -1
@@ -713,7 +713,7 @@ int ovl_verify_index(struct ovl_fs *ofs,
 		if (err)
 			goto fail;
 
-		if (ovl_get_nlink(ofs, origin.dentry, index, 0) == 0)
+		if (ovl_get_nlink(ofs, origin.dentry, index, true, 0) == 0)
 			goto orphan;
 	}
 
fs/overlayfs/overlayfs.h +1 -1
@@ -808,7 +808,7 @@ static inline bool ovl_dir_is_real(struc
 int ovl_set_nlink_upper(struct dentry *dentry);
 int ovl_set_nlink_lower(struct dentry *dentry);
 unsigned int ovl_get_nlink(struct ovl_fs *ofs, struct dentry *lowerdentry,
-			   struct dentry *upperdentry,
+			   struct dentry *upperdentry, bool indexed,
 			   unsigned int fallback);
 int ovl_permission(struct mnt_idmap *idmap, struct inode *inode,
 		   int mask);
author maintainer
#295 lore raw

PATCH 295/547 ovl: reserve space for the casefolded name terminator

In reply to Greg Kroah-Hartman

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

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

From: Hungyu Lin <[email protected]>

commit a65eb1808177a4381718abe563dddebf840598f9 upstream.

ovl_casefold() allocates NAME_MAX bytes and passes that capacity to utf8_casefold(), which also needs room for a terminating NUL. A valid name whose folded form is exactly NAME_MAX bytes therefore fails to fold, and ovl_fill_merge() falls back to comparing the original bytes.

For example, when two casefolded layers contain directories named with 255 uppercase and lowercase ASCII letters respectively, readdir lists both names even though lookup treats them as the same directory. The same names merge correctly at 254 bytes.

Reserve one additional byte in both the allocation and the folding capacity so that NAME_MAX-byte folded names use the canonical merge key.

Fixes ee95c5fc86dd ("ovl: Create ovl_casefold() to support casefolded strncmp()")
---
 fs/overlayfs/readdir.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/overlayfs/readdir.c +2 -2
@@ -81,13 +81,13 @@ static int ovl_casefold(struct ovl_readd
 	    name_is_dot_dotdot(str, len))
 		return 0;
 
-	cf_name = kmalloc(NAME_MAX, GFP_KERNEL);
+	cf_name = kmalloc(NAME_MAX + 1, GFP_KERNEL);
 	if (!cf_name) {
 		rdd->err = -ENOMEM;
 		return -ENOMEM;
 	}
 
-	cf_len = utf8_casefold(rdd->map, &qstr, cf_name, NAME_MAX);
+	cf_len = utf8_casefold(rdd->map, &qstr, cf_name, NAME_MAX + 1);
 	if (cf_len > 0)
 		*dst = cf_name;
 	else
author maintainer
#296 lore raw

PATCH 296/547 ovl: set the revalidate flags after d_instantiate()

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

commit 75e89c0055c1d7f7eeb462995f11253ca5864f79 upstream.

stat() of a file on an overlayfs mount triggers a kernel warning and fails with ECHILD if another task is creating that file at the same time. This happens on an overlay with a FUSE upper layer, which is the layer where overlayfs creates new files. Write access to a directory on such an overlay is all a user needs to run the two tasks.

The revalidate flags are DCACHE_OP_REVALIDATE and DCACHE_OP_WEAK_REVALIDATE. They tell path walk to call ->d_revalidate() or ->d_weak_revalidate() on a dentry, so that the filesystem can check that the cached dentry is still valid. An overlay dentry only has one of these flags if a dentry in one of its layers has it. FUSE dentries have the first one.

When a flag is set on an overlay dentry, path walk calls ovl_dentry_revalidate_common(). That function only expects a dentry without an inode in RCU walk, while the dentry is being destroyed. For such a dentry outside of RCU walk, it hits a WARN_ON() and returns -ECHILD. So a negative overlay dentry must never have the flags set.

ovl_instantiate() breaks this rule. When a task creates a file, the overlay dentry for the new name is hashed but still negative. ovl_instantiate() then works in this order:

- It copies the flags from the new upper dentry to the overlay dentry.
- It calls ovl_get_inode(), which can sleep in a getxattr request to the FUSE server.
- Only then does it call d_instantiate().

A second task that looks up the name between the first step and the last finds a negative dentry with the flags set and revalidates it.

Reproduced with a FUSE server that delays its getxattr reply: stat() of a name that was being created hit the WARN_ON() and failed with ECHILD.

Fix this by setting the flags after d_instantiate().

Fixes bccece1ead36 ("ovl: allow remote upper")
---
 fs/overlayfs/dir.c |    8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
fs/overlayfs/dir.c +7 -1
@@ -304,7 +304,6 @@ static int ovl_instantiate(struct dentry
 	};
 
 	ovl_dentry_set_upper_alias(dentry);
-	ovl_dentry_init_reval(dentry, newdentry, NULL);
 
 	if (!hardlink) {
 		/*
@@ -335,6 +334,13 @@ static int ovl_instantiate(struct dentry
 		d_mark_tmpfile(tmpfile, inode);
 
 	d_instantiate(dentry, inode);
+	/*
+	 * Unless it is a tmpfile, the dentry is hashed and a path walk can find
+	 * it at any time.  Set the revalidate flags only now, because
+	 * ovl_dentry_revalidate_common() does not expect them on a negative
+	 * dentry.
+	 */
+	ovl_dentry_init_reval(dentry, ovl_dentry_upper(dentry), NULL);
 	if (inode != oip.newinode) {
 		pr_warn_ratelimited("newly created inode found in cache (%pd2)\n",
 				    dentry);
author maintainer
#297 lore raw

PATCH 297/547 ovl: skip copy up of empty security.capability

In reply to Greg Kroah-Hartman

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

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

From: Amir Goldstein <[email protected]>

commit 50912a1715b8a7c614b654011a0db750e372b43e upstream.

ovl_copy_xattr() gives up if it can't read an attribute that listxattr() has named. An empty security.capability, which anybody has been able to store on any file for a long time, is such a case: it is listed, and getxattr() has nothing to return for it. A file in a lower layer that carries one can't be copied up: it can't be written to, renamed or have its mode changed.

There is nothing to copy if there are no data. Go on with the next one.

Fixes 8db6c34f1dbc ("Introduce v3 namespaced file capabilities")

[amir: treat -EINVAL as no capability too, and do the same in
ovl_copy_up_meta_inode_data()]

---
 fs/overlayfs/copy_up.c |   17 +++++++++++++++--
 1 file changed, 15 insertions(+), 2 deletions(-)
fs/overlayfs/copy_up.c +15 -2
@@ -75,6 +75,15 @@ static int ovl_copy_acl(struct ovl_fs *o
 static ssize_t ovl_getxattr_value(const struct path *path, char *name,
 				  char **value, ssize_t *value_size);
 
+/*
+ * Any user can store an empty security.capability, which fails to read with
+ * -EINVAL.  It grants no capability, so treat it as none, like no xattr.
+ */
+static bool ovl_no_fscap(ssize_t err)
+{
+	return err == -ENODATA || err == -EOPNOTSUPP || err == -EINVAL;
+}
+
 int ovl_copy_xattr(struct super_block *sb, const struct path *oldpath, struct dentry *new)
 {
 	struct dentry *old = oldpath->dentry;
@@ -134,6 +143,10 @@ int ovl_copy_xattr(struct super_block *s
 
 		size = ovl_getxattr_value(oldpath, name, &value, &value_size);
 		if (size < 0) {
+			if (!strcmp(name, XATTR_NAME_CAPS) && ovl_no_fscap(size)) {
+				error = 0;
+				continue;
+			}
 			error = size;
 			break;
 		}
@@ -1103,9 +1116,9 @@ static int ovl_copy_up_meta_inode_data(s
 	if (c->stat.size) {
 		err = cap_size = ovl_getxattr_value(&upperpath, XATTR_NAME_CAPS,
 						    &capability, &cap_size);
-		if (cap_size == -ENODATA || cap_size == -EOPNOTSUPP)
+		if (ovl_no_fscap(cap_size))
 			cap_size = 0;
-		if (cap_size < 0)
+		else if (cap_size < 0)
 			goto out;
 	}
 
author maintainer
#298 lore raw

PATCH 298/547 xfs: clear the symlink zapped flag if inline symlink is ok

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit f8d0d90f2e24b1f4a14796ae63cebfd820cadfcd upstream.

LOLLM noticed that we fail to clear the SYMLINK_ZAPPED flag if an inline symlink checks out ok, even after a repair. Fix that.

Fixes d9041681dd2f53 ("xfs: set inode sick state flags when we zap either ondisk fork")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/symlink.c |   17 ++++++++---------
 1 file changed, 8 insertions(+), 9 deletions(-)
fs/xfs/scrub/symlink.c +8 -9
@@ -70,21 +70,20 @@ xchk_symlink(
 		return 0;
 	}
 
-	/* Inline symlink? */
 	if (ifp->if_format == XFS_DINODE_FMT_LOCAL) {
+		/* Inline symlink? */
 		if (len > xfs_inode_data_fork_size(ip) ||
 		    len > strnlen(ifp->if_data, xfs_inode_data_fork_size(ip)))
 			xchk_fblock_set_corrupt(sc, XFS_DATA_FORK, 0);
-		return 0;
+	} else {
+		/* Remote symlink; must read the contents. */
+		error = xfs_symlink_remote_read(sc->ip, sc->buf);
+		if (!xchk_fblock_process_error(sc, XFS_DATA_FORK, 0, &error))
+			return error;
+		if (strnlen(sc->buf, XFS_SYMLINK_MAXLEN) < len)
+			xchk_fblock_set_corrupt(sc, XFS_DATA_FORK, 0);
 	}
 
-	/* Remote symlink; must read the contents. */
-	error = xfs_symlink_remote_read(sc->ip, sc->buf);
-	if (!xchk_fblock_process_error(sc, XFS_DATA_FORK, 0, &error))
-		return error;
-	if (strnlen(sc->buf, XFS_SYMLINK_MAXLEN) < len)
-		xchk_fblock_set_corrupt(sc, XFS_DATA_FORK, 0);
-
 	/* If a remote symlink is clean, it is clearly not zapped. */
 	xchk_mark_healthy_if_clean(sc, XFS_SICK_INO_SYMLINK_ZAPPED);
 	return 0;
author maintainer
#299 lore raw

PATCH 299/547 xfs: mark cow extents bad if theres no rmap mapping for them

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 2ffc0619c9c2881443c5fffb10db8f2bc0aa2ce8 upstream.

LOLLM noticed that we fail to mark cow staging extents as bad if there's a cow staging extent but no rmap record for the cow staging event. Close this gap.

Fixes dbbdbd0086320a ("xfs: repair problems in CoW forks")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/cow_repair.c |   84 ++++++++++++++++++++++++++++++----------------
 1 file changed, 55 insertions(+), 29 deletions(-)
fs/xfs/scrub/cow_repair.c +55 -29
@@ -200,29 +200,35 @@ xrep_cow_mark_missing_staging_rmap(
 	void				*priv)
 {
 	struct xrep_cow			*xc = priv;
-	xfs_agblock_t			rec_bno;
-	xfs_extlen_t			rec_len;
-	unsigned int			adj;
-
-	if (rec->rm_owner == XFS_RMAP_OWN_COW)
-		return 0;
+	const xfs_agblock_t		rec_end =
+			rec->rm_startblock + rec->rm_blockcount;
+	int				error = 0;
 
-	rec_bno = rec->rm_startblock;
-	rec_len = rec->rm_blockcount;
-	if (rec_bno < xc->irec_startbno) {
-		adj = xc->irec_startbno - rec_bno;
-		rec_len -= adj;
-		rec_bno += adj;
+	/* Was there a gap since the last rmap? */
+	if (xc->next_bno < rec->rm_startblock) {
+		error = xrep_cow_mark_file_range(xc,
+				xfs_gbno_to_fsb(cur->bc_group, xc->next_bno),
+				rec->rm_startblock - xc->next_bno);
+		if (error)
+			return error;
 	}
 
-	if (rec_bno + rec_len > xc->irec_startbno + xc->irec.br_blockcount) {
-		adj = (rec_bno + rec_len) -
-		      (xc->irec_startbno + xc->irec.br_blockcount);
-		rec_len -= adj;
+	if (rec->rm_owner != XFS_RMAP_OWN_COW) {
+		const xfs_agblock_t	bad_bno =
+				max(xc->irec_startbno, rec->rm_startblock);
+		const xfs_agblock_t	irec_end =
+				xc->irec_startbno + xc->irec.br_blockcount;
+		const xfs_extlen_t	bad_end = min(irec_end, rec_end);
+
+		error = xrep_cow_mark_file_range(xc,
+				xfs_gbno_to_fsb(cur->bc_group, bad_bno),
+				bad_end - bad_bno);
+		if (error)
+			return error;
 	}
 
-	return xrep_cow_mark_file_range(xc,
-			xfs_gbno_to_fsb(cur->bc_group, rec_bno), rec_len);
+	xc->next_bno = max(xc->next_bno, rec_end);
+	return error;
 }
 
 /*
@@ -263,10 +269,12 @@ xrep_cow_find_bad(
 	struct xfs_perag		*pag;
 	struct xfs_scrub		*sc = xc->sc;
 	xfs_agnumber_t			agno;
+	xfs_agblock_t			irec_end;
 	int				error;
 
 	agno = XFS_FSB_TO_AGNO(sc->mp, xc->irec.br_startblock);
 	xc->irec_startbno = XFS_FSB_TO_AGBNO(sc->mp, xc->irec.br_startblock);
+	irec_end = xc->irec_startbno + xc->irec.br_blockcount;
 
 	pag = xfs_perag_get(sc->mp, agno);
 	if (!pag)
@@ -278,7 +286,7 @@ xrep_cow_find_bad(
 
 	/* Mark any CoW fork extents that are shared. */
 	rc_low.rc_startblock = xc->irec_startbno;
-	rc_high.rc_startblock = xc->irec_startbno + xc->irec.br_blockcount - 1;
+	rc_high.rc_startblock = irec_end - 1;
 	rc_low.rc_domain = rc_high.rc_domain = XFS_REFC_DOMAIN_SHARED;
 	error = xfs_refcount_query_range(sc->sa.refc_cur, &rc_low, &rc_high,
 			xrep_cow_mark_shared_staging, xc);
@@ -287,7 +295,7 @@ xrep_cow_find_bad(
 
 	/* Make sure there are CoW staging extents for the whole mapping. */
 	rc_low.rc_startblock = xc->irec_startbno;
-	rc_high.rc_startblock = xc->irec_startbno + xc->irec.br_blockcount - 1;
+	rc_high.rc_startblock = irec_end - 1;
 	rc_low.rc_domain = rc_high.rc_domain = XFS_REFC_DOMAIN_COW;
 	xc->next_bno = xc->irec_startbno;
 	error = xfs_refcount_query_range(sc->sa.refc_cur, &rc_low, &rc_high,
@@ -295,11 +303,10 @@ xrep_cow_find_bad(
 	if (error)
 		goto out_sa;
 
-	if (xc->next_bno < xc->irec_startbno + xc->irec.br_blockcount) {
+	if (xc->next_bno < irec_end) {
 		error = xrep_cow_mark_file_range(xc,
 				xfs_agbno_to_fsb(pag, xc->next_bno),
-				xc->irec_startbno + xc->irec.br_blockcount -
-				xc->next_bno);
+				irec_end - xc->next_bno);
 		if (error)
 			goto out_sa;
 	}
@@ -308,11 +315,20 @@ xrep_cow_find_bad(
 	rm_low.rm_startblock = xc->irec_startbno;
 	memset(&rm_high, 0xFF, sizeof(rm_high));
 	rm_high.rm_startblock = xc->irec_startbno + xc->irec.br_blockcount - 1;
+	xc->next_bno = xc->irec_startbno;
 	error = xfs_rmap_query_range(sc->sa.rmap_cur, &rm_low, &rm_high,
 			xrep_cow_mark_missing_staging_rmap, xc);
 	if (error)
 		goto out_sa;
 
+	if (xc->next_bno < irec_end) {
+		error = xrep_cow_mark_file_range(xc,
+				xfs_agbno_to_fsb(pag, xc->next_bno),
+				irec_end - xc->next_bno);
+		if (error)
+			goto out_sa;
+	}
+
 	/*
 	 * If userspace is forcing us to rebuild the CoW fork or someone turned
 	 * on the debugging knob, replace everything in the CoW fork.
@@ -344,9 +360,11 @@ xrep_cow_find_bad_rt(
 	struct xfs_rmap_irec		rm_high = { 0 };
 	struct xfs_scrub		*sc = xc->sc;
 	struct xfs_rtgroup		*rtg;
+	xfs_agblock_t			irec_end;
 	int				error = 0;
 
 	xc->irec_startbno = xfs_rtb_to_rgbno(sc->mp, xc->irec.br_startblock);
+	irec_end = xc->irec_startbno + xc->irec.br_blockcount;
 
 	rtg = xfs_rtgroup_get(sc->mp,
 			xfs_rtb_to_rgno(sc->mp, xc->irec.br_startblock));
@@ -360,7 +378,7 @@ xrep_cow_find_bad_rt(
 
 	/* Mark any CoW fork extents that are shared. */
 	rc_low.rc_startblock = xc->irec_startbno;
-	rc_high.rc_startblock = xc->irec_startbno + xc->irec.br_blockcount - 1;
+	rc_high.rc_startblock = irec_end - 1;
 	rc_low.rc_domain = rc_high.rc_domain = XFS_REFC_DOMAIN_SHARED;
 	error = xfs_refcount_query_range(sc->sr.refc_cur, &rc_low, &rc_high,
 			xrep_cow_mark_shared_staging, xc);
@@ -369,7 +387,7 @@ xrep_cow_find_bad_rt(
 
 	/* Make sure there are CoW staging extents for the whole mapping. */
 	rc_low.rc_startblock = xc->irec_startbno;
-	rc_high.rc_startblock = xc->irec_startbno + xc->irec.br_blockcount - 1;
+	rc_high.rc_startblock = irec_end - 1;
 	rc_low.rc_domain = rc_high.rc_domain = XFS_REFC_DOMAIN_COW;
 	xc->next_bno = xc->irec_startbno;
 	error = xfs_refcount_query_range(sc->sr.refc_cur, &rc_low, &rc_high,
@@ -377,11 +395,10 @@ xrep_cow_find_bad_rt(
 	if (error)
 		goto out_sr;
 
-	if (xc->next_bno < xc->irec_startbno + xc->irec.br_blockcount) {
+	if (xc->next_bno < irec_end) {
 		error = xrep_cow_mark_file_range(xc,
 				xfs_rgbno_to_rtb(rtg, xc->next_bno),
-				xc->irec_startbno + xc->irec.br_blockcount -
-				xc->next_bno);
+				irec_end - xc->next_bno);
 		if (error)
 			goto out_sr;
 	}
@@ -389,12 +406,21 @@ xrep_cow_find_bad_rt(
 	/* Mark any area has an rmap that isn't a COW staging extent. */
 	rm_low.rm_startblock = xc->irec_startbno;
 	memset(&rm_high, 0xFF, sizeof(rm_high));
-	rm_high.rm_startblock = xc->irec_startbno + xc->irec.br_blockcount - 1;
+	rm_high.rm_startblock = irec_end - 1;
+	xc->next_bno = xc->irec_startbno;
 	error = xfs_rmap_query_range(sc->sr.rmap_cur, &rm_low, &rm_high,
 			xrep_cow_mark_missing_staging_rmap, xc);
 	if (error)
 		goto out_sr;
 
+	if (xc->next_bno < irec_end) {
+		error = xrep_cow_mark_file_range(xc,
+				xfs_rgbno_to_rtb(rtg, xc->next_bno),
+				irec_end - xc->next_bno);
+		if (error)
+			goto out_sr;
+	}
+
 	/*
 	 * If userspace is forcing us to rebuild the CoW fork or someone
 	 * turned on the debugging knob, replace everything in the
author maintainer
#300 lore raw

PATCH 300/547 xfs: compute the correct fdblocks/frextents for repair when theyre negative

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit f98d007017acf0eaec2e116ff9c0ece735f61bb3 upstream.

LOLLM observed that if either fdblocks or frextents are negative, we'll set the CORRUPT flag and exit immediately. This doesn't work for a repair because we still have to walk the filesystem metadata to compute the correct summary counters so that we can install the new values. Currently we just write zeroes into the summary counters, which isn't right.

Fixes 4ed080cd7cb077 ("xfs: repair summary counters")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/fscounters.c |    5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
fs/xfs/scrub/fscounters.c +4 -1
@@ -541,7 +541,10 @@ xchk_fscounters(
 			return -EDEADLOCK;
 
 		xchk_set_corrupt(sc);
-		return 0;
+
+		/* Need to compute all the fields in fsc for a repair */
+		if (!xchk_could_repair(sc))
+			return 0;
 	}
 
 	/* See if icount is obviously wrong. */
author maintainer
#301 lore raw

PATCH 301/547 xfs: fix ondisk symlink target validation in xrep_dinode_check_dfork

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit aafe21c23ad8263251085291019d8860ddc51da9 upstream.

LOLLM noticed that online repair of a broken symlink file could fail unnecessarily if a local-format symlink target isn't null terminated. The ondisk target isn't required to be null terminated, but repair enforces that anyway because it uses the validator for the incore symlink target. (The incore buffer is always null-terminated). Fix this by reverting the changes to xfs_symlink_shortform_verify and adding an ondisk-specific helper in inode_repair.c.

Fixes e744cef2060559 ("xfs: zap broken inode forks")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/libxfs/xfs_inode_fork.c     |    4 +---
 fs/xfs/libxfs/xfs_symlink_remote.c |    8 ++++++--
 fs/xfs/libxfs/xfs_symlink_remote.h |    2 +-
 fs/xfs/scrub/inode_repair.c        |   26 +++++++++++++++++++++++++-
 4 files changed, 33 insertions(+), 7 deletions(-)
fs/xfs/libxfs/xfs_inode_fork.c +1 -3
@@ -683,9 +683,7 @@ xfs_ifork_verify_local_data(
 		break;
 	}
 	case S_IFLNK: {
-		struct xfs_ifork	*ifp = xfs_ifork_ptr(ip, XFS_DATA_FORK);
-
-		fa = xfs_symlink_shortform_verify(ifp->if_data, ifp->if_bytes);
+		fa = xfs_symlink_shortform_verify(ip);
 		break;
 	}
 	default:
fs/xfs/libxfs/xfs_symlink_remote.c +6 -2
@@ -208,11 +208,15 @@ xfs_symlink_local_to_remote(
  */
 xfs_failaddr_t
 xfs_symlink_shortform_verify(
-	void			*sfp,
-	int64_t			size)
+	struct xfs_inode	*ip)
 {
+	struct xfs_ifork	*ifp = xfs_ifork_ptr(ip, XFS_DATA_FORK);
+	char			*sfp = (char *)ifp->if_data;
+	int			size = ifp->if_bytes;
 	char			*endp = sfp + size;
 
+	ASSERT(ifp->if_format == XFS_DINODE_FMT_LOCAL);
+
 	/*
 	 * Zero length symlinks should never occur in memory as they are
 	 * never allowed to exist on disk.
fs/xfs/libxfs/xfs_symlink_remote.h +1 -1
@@ -18,7 +18,7 @@ bool xfs_symlink_hdr_ok(xfs_ino_t ino, u
 void xfs_symlink_local_to_remote(struct xfs_trans *tp, struct xfs_buf *bp,
 				 struct xfs_inode *ip, struct xfs_ifork *ifp,
 				 void *priv);
-xfs_failaddr_t xfs_symlink_shortform_verify(void *sfp, int64_t size);
+xfs_failaddr_t xfs_symlink_shortform_verify(struct xfs_inode *ip);
 int xfs_symlink_remote_read(struct xfs_inode *ip, char *link);
 int xfs_symlink_write_target(struct xfs_trans *tp, struct xfs_inode *ip,
 		xfs_ino_t owner, const char *target_path, int pathlen,
fs/xfs/scrub/inode_repair.c +25 -1
@@ -1024,6 +1024,30 @@ xrep_dinode_bad_metabt_fork(
 	return false;
 }
 
+static xfs_failaddr_t
+xrep_symlink_shortform_verify(
+	void			*sfp,
+	int64_t			size)
+{
+	/*
+	 * Zero length symlinks should never occur in memory as they are
+	 * never allowed to exist on disk.
+	 */
+	if (!size)
+		return __this_address;
+
+	/* No negative sizes or overly long symlink targets. */
+	if (size < 0 || size > XFS_SYMLINK_MAXLEN)
+		return __this_address;
+
+	/* No NULLs in the target either. */
+	if (memchr(sfp, 0, size))
+		return __this_address;
+
+	/* ondisk symlink target isn't null terminated, unlike incore */
+	return NULL;
+}
+
 /*
  * Check the data fork for things that will fail the ifork verifiers or the
  * ifork formatters.
@@ -1099,7 +1123,7 @@ xrep_dinode_check_dfork(
 			return true;
 		/* symlink structure must pass verification. */
 		if (S_ISLNK(mode) &&
-		    xfs_symlink_shortform_verify(dfork_ptr, data_size) != NULL)
+		    xrep_symlink_shortform_verify(dfork_ptr, data_size) != NULL)
 			return true;
 		break;
 	case XFS_DINODE_FMT_EXTENTS:
author maintainer
#302 lore raw

PATCH 302/547 xfs: fix xfs_rename_space_res for non-pptr filesystems

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit a800b926346c3aa2482421f5c0272280ee7d32e8 upstream.

We don't need to reserve space for a parent pointer update for an existing target if parent pointers are disabled. Fix this regression (which LOLLM noticed) so that rename reservations go back to what they were before parent pointers.

Fixes 5a8338c88284df ("xfs: Add parent pointers to rename")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/libxfs/xfs_trans_space.c |    6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
fs/xfs/libxfs/xfs_trans_space.c +3 -3
@@ -127,10 +127,10 @@ xfs_rename_space_res(
 		if (has_whiteout)
 			ret += xfs_parent_calc_space_res(mp, src_namelen);
 		ret += 2 * xfs_parent_calc_space_res(mp, target_namelen);
-	}
 
-	if (target_exists)
-		ret += xfs_parent_calc_space_res(mp, target_namelen);
+		if (target_exists)
+			ret += xfs_parent_calc_space_res(mp, target_namelen);
+	}
 
 	return ret;
 }
author maintainer
#303 lore raw

PATCH 303/547 xfs: fix missing xfs_qm_adjust_dqlimits call in quotacheck repair

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit da483b8a9c2c3e7b23655699680feb57a194000c upstream.

LOLLM noticed that everywhere else in the kernel, a call to xfs_qm_adjust_dqlimits precedes every call to xfs_qm_adjust_dqtimers. In particular, mount-time quotacheck does this, but online quotacheck does not.

Looking at xfs_qm_adjust_dqlimits, that function is in charge of conveying default limits to a dquot if that dquot's limits have been zeroed. That's quite possible in a repair, so we actually need to do that.

However, there's a pre-existing pattern in the kernel -- for non-root dquots, first we call xfs_qm_adjust_dqlimits to set the dquot's limits to the defaults if they are zero, and then xfs_qm_adjust_dqtimers to start grace periods if the dquot's usage is above the softlimit. The grace period decision cannot be made correctly if we forget to import the default limits.

Therefore, let's combine both into a single xfs_qm_adjust_dqenforcement helper that takes care of both pieces, which fixes quotacheck and makes it hard to repeat this mistake.

Fixes 96ed2ae4a9b06b ("xfs: repair dquots based on live quotacheck results")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/quota_repair.c      |    5 +----
 fs/xfs/scrub/quotacheck_repair.c |    3 +--
 fs/xfs/xfs_dquot.c               |   20 +++++++++++++++-----
 fs/xfs/xfs_dquot.h               |    2 +-
 fs/xfs/xfs_qm.c                  |    6 +-----
 fs/xfs/xfs_trans_dquot.c         |    6 +-----
 6 files changed, 20 insertions(+), 22 deletions(-)
fs/xfs/scrub/quota_repair.c +1 -4
@@ -248,10 +248,7 @@ xrep_quota_item(
 
 	dq->q_flags |= XFS_DQFLAG_DIRTY;
 	xfs_trans_dqjoin(sc->tp, dq);
-	if (dq->q_id) {
-		xfs_qm_adjust_dqlimits(dq);
-		xfs_qm_adjust_dqtimers(dq);
-	}
+	xfs_qm_adjust_dqenforcement(dq);
 	xfs_trans_log_dquot(sc->tp, dq);
 	return xfs_trans_roll(&sc->tp);
 
fs/xfs/scrub/quotacheck_repair.c +1 -2
@@ -110,8 +110,7 @@ xqcheck_commit_dquot(
 
 	/* Commit the dirty dquot to disk. */
 	dq->q_flags |= XFS_DQFLAG_DIRTY;
-	if (dq->q_id)
-		xfs_qm_adjust_dqtimers(dq);
+	xfs_qm_adjust_dqenforcement(dq);
 	xfs_trans_log_dquot(xqc->sc->tp, dq);
 	return xrep_trans_commit(xqc->sc);
 
fs/xfs/xfs_dquot.c +15 -5
@@ -115,18 +115,15 @@ xfs_qm_dqdestroy(
  * We overwrite the dquot limits only if they are zero and this
  * is not the root dquot.
  */
-void
+static void
 xfs_qm_adjust_dqlimits(
 	struct xfs_dquot	*dq)
 {
 	struct xfs_mount	*mp = dq->q_mount;
 	struct xfs_quotainfo	*q = mp->m_quotainfo;
-	struct xfs_def_quota	*defq;
+	struct xfs_def_quota	*defq = xfs_get_defquota(q, xfs_dquot_type(dq));
 	int			prealloc = 0;
 
-	ASSERT(dq->q_id);
-	defq = xfs_get_defquota(q, xfs_dquot_type(dq));
-
 	if (!dq->q_blk.softlimit) {
 		dq->q_blk.softlimit = defq->blk.soft;
 		prealloc = 1;
@@ -223,6 +220,19 @@ xfs_qm_adjust_dqtimers(
 	xfs_qm_adjust_res_timer(dq->q_mount, &dq->q_rtb, &defq->rtb);
 }
 
+/* Adjust enforcement limits and timers after a change in usage. */
+void
+xfs_qm_adjust_dqenforcement(
+	struct xfs_dquot	*dq)
+{
+	if (dq->q_id == 0)
+		return;
+
+	xfs_qm_adjust_dqlimits(dq);
+	xfs_qm_adjust_dqtimers(dq);
+	dq->q_flags |= XFS_DQFLAG_DIRTY;
+}
+
 /*
  * initialize a buffer full of dquots and log the whole thing
  */
fs/xfs/xfs_dquot.h +1 -1
@@ -205,7 +205,7 @@ void		xfs_qm_dqdestroy(struct xfs_dquot
 int		xfs_qm_dqflush(struct xfs_dquot *dqp, struct xfs_buf *bp);
 void		xfs_qm_dqunpin_wait(struct xfs_dquot *dqp);
 void		xfs_qm_adjust_dqtimers(struct xfs_dquot *d);
-void		xfs_qm_adjust_dqlimits(struct xfs_dquot *d);
+void		xfs_qm_adjust_dqenforcement(struct xfs_dquot *d);
 xfs_dqid_t	xfs_qm_id_for_quotatype(struct xfs_inode *ip,
 				xfs_dqtype_t type);
 int		xfs_qm_dqget(struct xfs_mount *mp, xfs_dqid_t id,
fs/xfs/xfs_qm.c +1 -5
@@ -1294,11 +1294,7 @@ xfs_qm_quotacheck_dqadjust(
 	 *
 	 * There are no timers for the default values set in the root dquot.
 	 */
-	if (dqp->q_id) {
-		xfs_qm_adjust_dqlimits(dqp);
-		xfs_qm_adjust_dqtimers(dqp);
-	}
-
+	xfs_qm_adjust_dqenforcement(dqp);
 	dqp->q_flags |= XFS_DQFLAG_DIRTY;
 out_unlock:
 	mutex_unlock(&dqp->q_qlock);
fs/xfs/xfs_trans_dquot.c +1 -5
@@ -566,11 +566,7 @@ xfs_trans_apply_dquot_deltas(
 			 * Get any default limits in use.
 			 * Start/reset the timer(s) if needed.
 			 */
-			if (dqp->q_id) {
-				xfs_qm_adjust_dqlimits(dqp);
-				xfs_qm_adjust_dqtimers(dqp);
-			}
-
+			xfs_qm_adjust_dqenforcement(dqp);
 			dqp->q_flags |= XFS_DQFLAG_DIRTY;
 			/*
 			 * add this to the list of items to get logged
author maintainer
#304 lore raw

PATCH 304/547 xfs: fix buffer overruns in xfs_ioc_attr_list

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 0b9081a774ee7b9dff1e9ac3765b73c1d6bba5b2 upstream.

When we converted the al_offset array in struct xfs_attrlist into a VLA, the size of the object shrank by 4 bytes. Unfortunately, the buffer size validation in the attrlist ioctl wasn't updated to notice this, so the al_offset[0] assignment blindly writes off the end of the buffer. LOLLM noticed the omitted check and complained.

Fixes 371baf5c9750a2 ("xfs: convert flex-array declarations in struct xfs_attrlist*")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/xfs_handle.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/xfs/xfs_handle.c +1 -1
@@ -409,7 +409,7 @@ xfs_ioc_attr_list(
 	void				*buffer;
 	int				error;
 
-	if (bufsize < sizeof(struct xfs_attrlist) ||
+	if (bufsize < struct_size(alist, al_offset, 1) ||
 	    bufsize > XFS_XATTR_LIST_MAX)
 		return -EINVAL;
 
author maintainer
#305 lore raw

PATCH 305/547 xfs: online quotacheck must dirty dquot if enforcement adjustments needed

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 244425cf63d7e3a0ff5736b41f0e0afe807f7031 upstream.

LOLLM noticed that we have no way to force xchk_commit_dquot to call xfs_qm_adjust_dqenforcement if nothing else is wrong with the dquot. Therefore, add a new predicate to force the dirty flag if the dquot has zero limits and there are default limits; or if the grace period timer needs adjusting.

Fixes 96ed2ae4a9b06b ("xfs: repair dquots based on live quotacheck results")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/quotacheck_repair.c |   51 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 51 insertions(+)
fs/xfs/scrub/quotacheck_repair.c +51 -0
@@ -39,6 +39,54 @@
  * dquot is locked.
  */
 
+static bool
+xqcheck_dqres_force_dirty(
+	const struct xfs_dquot_res	*res,
+	const struct xfs_quota_limits	*qlim)
+{
+	/* zero limits mean that we should set the default limits */
+	if (res->softlimit == 0 && qlim->soft != 0)
+		return true;
+	if (res->hardlimit == 0 && qlim->hard != 0)
+		return true;
+
+	/* do we need to adjust the timer setting? */
+	if ((res->softlimit && res->count > res->softlimit) ||
+	    (res->hardlimit && res->count > res->hardlimit)) {
+		if (!res->timer)
+			return true;
+	} else {
+		if (res->timer)
+			return true;
+	}
+
+	return false;
+}
+
+/* Decide if we need to adjust the dquot limits or timers */
+static bool
+xqcheck_dquot_force_dirty(
+	const struct xfs_dquot	*dq)
+{
+	struct xfs_quotainfo	*qi = dq->q_mount->m_quotainfo;
+	struct xfs_def_quota	*defq;
+
+	/* root dquot does not enforce limits */
+	if (dq->q_id == 0)
+		return false;
+
+	defq = xfs_get_defquota(qi, xfs_dquot_type(dq));
+
+	if (xqcheck_dqres_force_dirty(&dq->q_blk, &defq->blk))
+		return true;
+	if (xqcheck_dqres_force_dirty(&dq->q_ino, &defq->ino))
+		return true;
+	if (xqcheck_dqres_force_dirty(&dq->q_rtb, &defq->rtb))
+		return true;
+
+	return false;
+}
+
 /* Commit new counters to a dquot. */
 static int
 xqcheck_commit_dquot(
@@ -91,6 +139,9 @@ xqcheck_commit_dquot(
 		dirty = true;
 	}
 
+	if (!dirty && xqcheck_dquot_force_dirty(dq))
+		dirty = true;
+
 	xcdq.flags |= (XQCHECK_DQUOT_REPAIR_SCANNED | XQCHECK_DQUOT_WRITTEN);
 	error = xfarray_store(counts, dq->q_id, &xcdq);
 	if (error == -EFBIG) {
author maintainer
#306 lore raw

PATCH 306/547 xfs: avoid cross-rtgroup reaping after a repair

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit d7c204d4ea7ef0cf0dac908388984c2936f1f94e upstream.

LOLLM notices that the extents stored in a xrtb_bitmap (aka xfs_rtblock bitmap) can span multiple rtgroups due to two circumstances. The first is that the size of an rtgroup is an exact power of two, which means that rtgroups are adjacent in the segmented xfs_rtblock_t address space. This is fairly common to reduce the amount of multiplication and division needed to handle space on the rt volume.

The second is that (unlike in the original rtgroups design), rtgroups do not have fixed-location metadata like AGs do, which means that there's nothing to force a break between rtgroups.

Therefore, we must loop through the rtgroups in xreap_rtmeta_extent to avoid running off the end of an rtgroup while reaping.

Fixes fd97fe1112088c ("xfs: fix CoW forks for realtime files")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/reap.c |   59 ++++++++++++++++++++++++++++++++++++++++++----------
 1 file changed, 48 insertions(+), 11 deletions(-)
fs/xfs/scrub/reap.c +48 -11
@@ -1080,26 +1080,23 @@ xreap_configure_rgcow_limits(
 				 XFS_RTGLOCK_RMAP | \
 				 XFS_RTGLOCK_REFCOUNT)
 
-/*
- * Break a rt file metadata extent into sub-extents by fate (crosslinked, not
- * crosslinked), and dispose of each sub-extent separately.  The extent must
- * be aligned to a realtime extent.
- */
-STATIC int
-xreap_rtmeta_extent(
-	uint64_t		rtbno,
+static int
+xreap_rtgroup_extent(
+	struct xreap_state	*rs,
+	xfs_rtblock_t		rtbno,
 	uint64_t		len,
-	void			*priv)
+	xfs_rgblock_t		*done)
 {
-	struct xreap_state	*rs = priv;
 	struct xfs_scrub	*sc = rs->sc;
 	xfs_rgblock_t		rgbno = xfs_rtb_to_rgbno(sc->mp, rtbno);
-	xfs_rgblock_t		rgbno_next = rgbno + len;
+	xfs_rgblock_t		rgbno_next;
 	int			error = 0;
 
 	ASSERT(sc->ip != NULL);
 	ASSERT(!sc->sr.rtg);
 
+	*done = 0;
+
 	/*
 	 * We're reaping blocks after repairing file metadata, which means that
 	 * we have to init the xchk_ag structure ourselves.
@@ -1110,6 +1107,7 @@ xreap_rtmeta_extent(
 
 	xfs_rtgroup_lock(sc->sr.rtg, XREAP_RTGLOCK_ALL);
 
+	rgbno_next = rgbno + min(len, (uint64_t)rtg_blocks(sc->sr.rtg) - rgbno);
 	while (rgbno < rgbno_next) {
 		xfs_extlen_t	rglen;
 		bool		crosslinked;
@@ -1136,6 +1134,7 @@ xreap_rtmeta_extent(
 		}
 
 		rgbno += rglen;
+		*done += rglen;
 	}
 
 out_unlock:
@@ -1146,6 +1145,44 @@ out_unlock:
 }
 
 /*
+ * Break a rt file metadata extent into sub-extents by fate (crosslinked, not
+ * crosslinked), and dispose of each sub-extent separately.  The extent must
+ * be aligned to a realtime extent.
+ */
+STATIC int
+xreap_rtmeta_extent(
+	uint64_t		rtbno,
+	uint64_t		len,
+	void			*priv)
+{
+	struct xreap_state	*rs = priv;
+	int			error;
+
+	/*
+	 * Space from adjacent rtgroups can be stored as a single bitmap extent
+	 * because rtgroups do not have fixed-location metadata such as a
+	 * per-group superblock that cannot be reaped.  Handle these overlaps
+	 * by only reaping within a single rtgroup at a time.
+	 *
+	 * In the somewhat unlikely event that an rtgroup size is not a power
+	 * of two, the segmented nature of xfs_rtblock_t prevents space in
+	 * adjacent rtgroups from merging in the bitmap.
+	 */
+	while (len > 0) {
+		xfs_rgblock_t	done = 0;
+
+		error = xreap_rtgroup_extent(rs, rtbno, len, &done);
+		if (error)
+			return error;
+
+		rtbno += done;
+		len -= done;
+	}
+
+	return 0;
+}
+
+/*
  * Dispose of every block of every rt metadata extent in the bitmap.
  * Do not use this to dispose of the mappings in an ondisk inode fork.
  */
author maintainer
#307 lore raw

PATCH 307/547 xfs: actually lock the metafile reservation when adjusting after repair

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit e53c620b3670fc0c162b5f768a10a3a17d0c04f6 upstream.

LOLLM reported that xrep_reset_metafile_resv performs unlocked loads and stores to the metadata file space reservation counters and thus can race with other threads. Fix this by taking the lock.

Fixes 1df8d75030b787 ("xfs: make metabtree reservations global")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/repair.c |   18 ++++++++++++------
 1 file changed, 12 insertions(+), 6 deletions(-)
fs/xfs/scrub/repair.c +12 -6
@@ -1377,12 +1377,14 @@ xrep_reset_metafile_resv(
 {
 	struct xfs_mount	*mp = sc->mp;
 	int64_t			delta;
-	int			error;
+	int			error = 0;
+
+	mutex_lock(&mp->m_metafile_resv_lock);
 
 	delta = mp->m_metafile_resv_used + mp->m_metafile_resv_avail -
 		mp->m_metafile_resv_target;
 	if (delta == 0)
-		return 0;
+		goto out_resv_lock;
 
 	/*
 	 * Too many blocks have been reserved, transfer some from the incore
@@ -1398,7 +1400,7 @@ xrep_reset_metafile_resv(
 			mp->m_metafile_resv_avail -= give_back;
 		}
 
-		return 0;
+		goto out_resv_lock;
 	}
 
 	/*
@@ -1412,14 +1414,18 @@ xrep_reset_metafile_resv(
 		if (delta == 0) {
 			xfs_warn(sc->mp,
 "Insufficient free space to reset metabtree reservation after repair.");
-			return 0;
+			error = 0;
+			goto out_resv_lock;
 		}
 		error = xfs_dec_fdblocks(mp, delta, true);
 	}
 	if (error)
-		return error;
+		goto out_resv_lock;
 
 	xfs_mod_sb_delalloc(mp, delta);
 	mp->m_metafile_resv_avail += delta;
-	return 0;
+
+out_resv_lock:
+	mutex_unlock(&mp->m_metafile_resv_lock);
+	return error;
 }
author maintainer
#308 lore raw

PATCH 308/547 xfs: fix unnecessary dapos truncation in xchk_dir_walk

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit f60a2ef8d8a7ac6dedf4d0c3325cc3fc2fe0d948 upstream.

LOLLM points out that the all the implementations of xchk_dirent_fn can handle a signed @dapos parameter, so the truncation here breaks the information captured in scrub tracepoints if the directory is very large. I don't think it ever made sense to do the truncation for the VFS readdir code for programs that can handle 64-bit offsets, but commit 15440319767942 has been around for 17 years without complaints so I'll leave that alone.

Stumbled-over: 15440319767942 ("[XFS] truncate readdir offsets to signed 32 bit values")

Fixes 4c233b5c4f29df ("xfs: streamline the directory iteration code for scrub")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/readdir.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/xfs/scrub/readdir.c +1 -1
@@ -238,7 +238,7 @@ xchk_dir_walk_leaf(
 		dep = bp->b_addr + offset;
 		length = xfs_dir2_data_entsize(mp, dep->namelen);
 
-		dapos = xfs_dir2_byte_to_dataptr(curoff) & 0x7fffffff;
+		dapos = xfs_dir2_byte_to_dataptr(curoff);
 		ino = be64_to_cpu(dep->inumber);
 		name.name = dep->name;
 		name.len = dep->namelen;
author maintainer
#309 lore raw

PATCH 309/547 xfs: fix buffer overflow in corrupt inline attr structure

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 017dd7a84ff4cd2275eb62f4ee6d63c705bac107 upstream.

LOLLM noticed a buffer overrun if the xattr scrubber encounters a file with a shortform attr fork with sf->count > 0 but if_bytes == sizeof(struct xfs_attr_sf_hdr). Basically, we have enough data to have a header with a nonzero count, but no space for any of those shortform entries. In this case, the xfs_attr_sf_nextentry() call will run off the end of if_data and blow up.

Fixes ae0506eba78fd1 ("xfs: check used space of shortform xattr structures")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/attr.c        |   11 +++++++++--
 fs/xfs/scrub/attr_repair.c |    3 +++
 2 files changed, 12 insertions(+), 2 deletions(-)
fs/xfs/scrub/attr.c +9 -2
@@ -590,12 +590,17 @@ xchk_xattr_check_sf(
 	}
 
 	for (i = 0; i < sf->count; i++) {
-		unsigned char		*name = sfe->nameval;
-		unsigned char		*value = &sfe->nameval[sfe->namelen];
+		unsigned char		*name;
+		unsigned char		*value;
 
 		if (xchk_should_terminate(sc, &error))
 			return error;
 
+		if ((unsigned char *)(sfe + 1) >= end) {
+			xchk_fblock_set_corrupt(sc, XFS_ATTR_FORK, 0);
+			break;
+		}
+
 		next = xfs_attr_sf_nextentry(sfe);
 		if ((unsigned char *)next > end) {
 			xchk_fblock_set_corrupt(sc, XFS_ATTR_FORK, 0);
@@ -618,6 +623,7 @@ xchk_xattr_check_sf(
 			break;
 		}
 
+		name = sfe->nameval;
 		if (!xchk_xattr_set_map(sc, ab->usedmap,
 				(char *)name - (char *)sf,
 				sfe->namelen)) {
@@ -625,6 +631,7 @@ xchk_xattr_check_sf(
 			break;
 		}
 
+		value = &sfe->nameval[sfe->namelen];
 		if (!xchk_xattr_set_map(sc, ab->usedmap,
 				(char *)value - (char *)sf,
 				sfe->valuelen)) {
fs/xfs/scrub/attr_repair.c +3 -0
@@ -477,6 +477,9 @@ xrep_xattr_recover_sf(
 		if (xchk_should_terminate(sc, &error))
 			return error;
 
+		if ((unsigned char *)(sfe + 1) >= end)
+			break;
+
 		next = xfs_attr_sf_nextentry(sfe);
 		if ((unsigned char *)next > end)
 			break;
author maintainer
#310 lore raw

PATCH 310/547 xfs: actually report corrupt xattrs as XFAIL during cross-referencing

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit b339cc253019518c61b8b150fb7ea727fdae59f4 upstream.

Some LLM reports that xchk_dir_parent_pointer really ought to report xattr corruption errors as XFAIL (cross-referencing failed) when a directory scrub tries to find the parent pointer for a dirent name. Let's do that.

Fixes 61b3f0df5c2358 ("xfs: check dirents have parent pointers")
---
 fs/xfs/scrub/dir.c |    2 ++
 1 file changed, 2 insertions(+)
fs/xfs/scrub/dir.c +2 -0
@@ -155,6 +155,8 @@ xchk_dir_parent_pointer(
 			&sd->pptr_args);
 	if (error == -ENOATTR)
 		xchk_fblock_xref_set_corrupt(sc, XFS_DATA_FORK, 0);
+	else
+		xchk_fblock_xref_process_error(sc, XFS_DATA_FORK, 0, &error);
 
 	return 0;
 }
author maintainer
#311 lore raw

PATCH 311/547 xfs: fix inode btree repair when a cluster is larger than a chunk

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 65b89ac3e8c2f041384f715a71b9d113edfa32e5 upstream.

LOLLM noticed that on filesystems where an inode cluster buffer is larger than an inode chunk, we can run through the loop body in xrep_ibt_process_cluster more than once, and the number of inodes that we pass to xrep_ibt_cluster_record is incorrectly large. In this case we can run right off the end of the buffer. Fix this by moving the nr_inodes computation inside the loop.

Note that this is only likely to happen on filesystems with (say) 512b inodes and 64k fsblocks.

Fixes dbfbf3bdf639a2 ("xfs: repair inode btrees")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/ialloc_repair.c |    8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
fs/xfs/scrub/ialloc_repair.c +4 -4
@@ -293,12 +293,8 @@ xrep_ibt_process_cluster(
 	struct xfs_ino_geometry	*igeo = M_IGEO(mp);
 	xfs_agino_t		cluster_ag_base;
 	xfs_agino_t		irec_index;
-	unsigned int		nr_inodes;
 	int			error;
 
-	nr_inodes = min_t(unsigned int, igeo->inodes_per_cluster,
-			XFS_INODES_PER_CHUNK);
-
 	/*
 	 * Grab the inode cluster buffer.  This is safe to do with a broken
 	 * inobt because imap_to_bp directly maps the buffer without touching
@@ -317,6 +313,10 @@ xrep_ibt_process_cluster(
 	for (irec_index = 0;
 	     irec_index < igeo->inodes_per_cluster;
 	     irec_index += XFS_INODES_PER_CHUNK) {
+		unsigned int	nr_inodes =
+			min_t(unsigned int, XFS_INODES_PER_CHUNK,
+					igeo->inodes_per_cluster - irec_index);
+
 		error = xrep_ibt_cluster_record(ri,
 				cluster_ag_base + irec_index, cluster_bp,
 				nr_inodes);
author maintainer
#312 lore raw

PATCH 312/547 xfs: always reset incore attr fork buffer when resetting fork

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 71cb13685e72a3c5d118732559c727a0c9090b7f upstream.

LOLLM noticed that the local format attr fork verifier depends on if_bytes being set correctly. However, the fork reset function doesn't reset that correctly, which can cause post-repair verifier failures. Fix that.

Fixes e5d7ce0364d8ee ("xfs: replay unlocked parent pointer updates that accrue during xattr repair")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/attr_repair.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/xfs/scrub/attr_repair.c +2 -2
@@ -840,11 +840,11 @@ xrep_xattr_full_reset(
 
 		ASSERT(ifp->if_bytes == 0);
 		ifp->if_format = XFS_DINODE_FMT_LOCAL;
-		xfs_idata_realloc(sc->tempip, sizeof(*hdr), XFS_ATTR_FORK);
 	}
 
 	/* Reinitialize the attr fork to an empty shortform structure. */
-	hdr = ifp->if_data;
+	hdr = xfs_idata_realloc(sc->tempip,
+			(int64_t)sizeof(*hdr) - ifp->if_bytes, XFS_ATTR_FORK);
 	memset(hdr, 0, sizeof(*hdr));
 	hdr->totsize = cpu_to_be16(sizeof(*hdr));
 	xfs_trans_log_inode(sc->tp, sc->tempip, XFS_ILOG_CORE | XFS_ILOG_ADATA);
author maintainer
#313 lore raw

PATCH 313/547 xfs: dont pass iget failures up when marking ondisk inodes

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 7f5e8bf335e5e257fb82cf5b3521980ded60e863 upstream.

LOLLM observes a couple of problems with this callsite -- an ENOMEM return is completely ignored and a subsequent run through the loop body obliterates the return value completely. Also, an error value indicating that the list is corrupt can get passed up (thus terminating the repair) even though we can handle corrupt lists. Fix the callsite not to have these problems.

Fixes ab97f4b1c03075 ("xfs: repair AGI unlinked inode bucket lists")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/agheader_repair.c |    6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
fs/xfs/scrub/agheader_repair.c +5 -1
@@ -1325,8 +1325,12 @@ xrep_iunlink_mark_ondisk_rec(
 		 */
 		error = xchk_iget(ragi->sc, xfs_agino_to_ino(sc->sa.pag, agino),
 				&ip);
-		if (error)
+		if (error == -ENOMEM)
+			return error;
+		if (error) {
+			error = 0;
 			continue;
+		}
 
 		trace_xrep_iunlink_reload_ondisk(ip);
 
author maintainer
#314 lore raw

PATCH 314/547 xfs: zero out di_metatype when removing the metadir file iflag

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit f5b4d8c8ce16675f77c25a4ff06caaa9a2739f31 upstream.

LOLLM pointed out that we should zero di_metatype (fka di_onlink) when we're clearing the METADIR inode flag because the file is no longer a metadata file.

Fixes 7297fd0bebbd70 ("xfs: enforce metadata inode flag")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/inode_repair.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
fs/xfs/scrub/inode_repair.c +3 -1
@@ -579,8 +579,10 @@ xrep_dinode_flags(
 
 		fa = xfs_dinode_verify_metadir(sc->mp, dip, mode, flags,
 				flags2);
-		if (fa)
+		if (fa) {
 			flags2 &= ~XFS_DIFLAG2_METADATA;
+			dip->di_metatype = cpu_to_be16(XFS_METAFILE_UNKNOWN);
+		}
 	}
 
 	dip->di_flags = cpu_to_be16(flags);
author maintainer
#315 lore raw

PATCH 315/547 xfs: flag excessive delalloc rt extents as corruption

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 2b47be015a5e54f4a3d62afa636ba593de9b67f6 upstream.

LOLLM observed that we should not allow repairs to proceed if the count of delayed-allocation realtime extents exceeds the number of free rt extents because we can't install negative numbers into the superblock. It's unclear how we could end up in that state in real life, but let's at least complain loudly about it if we ever encounter it.

Fixes e74331d6fa2c21 ("xfs: online checking of the free rt extent count")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/fscounters.c |    7 +++++++
 1 file changed, 7 insertions(+)
fs/xfs/scrub/fscounters.c +7 -0
@@ -607,6 +607,13 @@ xchk_fscounters(
 			try_again = true;
 	}
 
+	if (!xfs_has_zoned(mp) && fsc->frextents < fsc->frextents_delayed) {
+		if (fsc->frozen)
+			xchk_set_incomplete(sc);
+		else
+			try_again = true;
+	}
+
 	if (!xfs_has_zoned(mp) &&
 	    !xchk_fscount_within_range(sc, frextents,
 			&mp->m_free[XC_FREE_RTEXTENTS].count,
author maintainer
#316 lore raw

PATCH 316/547 xfs: dont fix the directory tree if live update fails

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit c8226f3d1a7eafe472addc232689e9c9a0c36a1c upstream.

LOLLM complains that we don't double-check dl->aborted one last time to before committing repairs to the filesystem. This is important because the live update handler could have set ->aborted if it encountered a runtime error.

Fixes 3f31406aef493b ("xfs: fix corruptions in the directory tree")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/dirtree_repair.c |    5 +++++
 1 file changed, 5 insertions(+)
fs/xfs/scrub/dirtree_repair.c +5 -0
@@ -427,6 +427,11 @@ again:
 		error = -ESTALE;
 		goto out_trans_cancel;
 	}
+	if (dl->aborted) {
+		mutex_unlock(&dl->lock);
+		error = -EIO;
+		goto out_trans_cancel;
+	}
 	xrep_dirpath_set_outcome(dl, path, XREP_DIRPATH_DELETING);
 	mutex_unlock(&dl->lock);
 
author maintainer
#317 lore raw

PATCH 317/547 xfs: validate rc_domain in xchk_rtrefcount_mergeable

In reply to Greg Kroah-Hartman

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

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

From: Eric Sandeen <[email protected]>

commit f04361fb8694bff98ec61e2e2030a1993426fdca upstream.

xchk_refcount_mergeable validates that the domains match, but this was omitted from the realtime version of the check; fix it.

Fixes c27929670de144 ("xfs: scrub the realtime refcount btree")
---
 fs/xfs/scrub/rtrefcount.c |    2 ++
 1 file changed, 2 insertions(+)
fs/xfs/scrub/rtrefcount.c +2 -0
@@ -379,6 +379,8 @@ xchk_rtrefcount_mergeable(
 	if (r1->rc_blockcount == 0)
 		return false;
 
+	if (r1->rc_domain != r2->rc_domain)
+		return false;
 	if (r1->rc_startblock + r1->rc_blockcount != r2->rc_startblock)
 		return false;
 	if (r1->rc_refcount != r2->rc_refcount)
author maintainer
#318 lore raw

PATCH 318/547 xfs: dont proceed with xattr repair if the live update fails

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 833f98b3be45bc7c6ce4c87bdc4892f546ab72ee upstream.

LOLLM observes that we ought to make one last check for failed live updates before replacing the xattr structure. Let's be cautious here.

Fixes e5d7ce0364d8ee ("xfs: replay unlocked parent pointer updates that accrue during xattr repair")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/attr_repair.c |    3 +++
 1 file changed, 3 insertions(+)
fs/xfs/scrub/attr_repair.c +3 -0
@@ -1477,6 +1477,9 @@ xrep_xattr_rebuild_tree(
 	if (error)
 		return error;
 
+	if (rx->live_update_aborted)
+		return -EIO;
+
 	/*
 	 * Exchange the blocks mapped by the tempfile's attr fork with the file
 	 * being repaired.  The old attr blocks will then be attached to the
author maintainer
#319 lore raw

PATCH 319/547 xfs: fix skipped inode mask handling in iscan

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 63341d4af16fe850716b454fcd18990590d07d97 upstream.

xfs_highbit64() returns -1 if none of the bits in its argument are set. In this particular callsite, a totally zeroed mask means that no inodes were skipped, so executing the if-body is incorrect. Fix that.

Fixes 82334a79c6eb1c ("xfs: iscan batching should handle unallocated inodes too")
---
 fs/xfs/scrub/iscan.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/xfs/scrub/iscan.c +1 -1
@@ -545,7 +545,7 @@ xchk_iscan_finish_batch(
 
 	mutex_lock(&iscan->lock);
 
-	if (iscan->__batch_ino != NULLFSINO) {
+	if (iscan->__batch_ino != NULLFSINO && iscan->__skipped_inomask) {
 		highest_skipped = iscan->__batch_ino +
 					xfs_highbit64(iscan->__skipped_inomask);
 		iscan->__visited_ino = max(iscan->__visited_ino,
author maintainer
#320 lore raw

PATCH 320/547 xfs: dont repair fs summary counters with garbage

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 22a8a7501c0146dba4ce99b8256975ffe945125d upstream.

LOLLM noticed that if we scan the filesystem and come up with totally garbage numbers for the summary counters, we don't actually mark the scan incomplete. Because we don't do this, repair can install the garbage values into the filesystem, making things worse. Don't do that.

Fixes 4ed080cd7cb077 ("xfs: repair summary counters")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/fscounters.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
fs/xfs/scrub/fscounters.c +3 -1
@@ -368,8 +368,10 @@ retry:
 	/* Bail out if the values we compute are totally nonsense. */
 	if (fsc->icount < fsc->icount_min || fsc->icount > fsc->icount_max ||
 	    fsc->fdblocks > mp->m_sb.sb_dblocks ||
-	    fsc->ifree > fsc->icount_max)
+	    fsc->ifree > fsc->icount_max) {
+		xchk_set_incomplete(sc);
 		return -EFSCORRUPTED;
+	}
 
 	/*
 	 * If ifree > icount then we probably had some perturbation in the
author maintainer
#321 lore raw

PATCH 321/547 xfs: fix lost errno returned from xfarray_foliosort

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 8c4f172c246717b1420f138a159ed15c315a58bd upstream.

LOLLM noticed that we stop the sort early but don't actually pass along the error code, which could enable repair code to continue running with an unsorted array. Fix that.

Fixes ee13fc67205b98 ("xfs: convert xfarray_pagesort to deal with large folios")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/xfarray.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
fs/xfs/scrub/xfarray.c +3 -1
@@ -943,8 +943,10 @@ xfarray_sort(
 		 * problems, we're done.
 		 */
 		ret = xfarray_foliosort(si, lo, hi);
-		if (ret < 0)
+		if (ret < 0) {
+			error = ret;
 			goto out_free;
+		}
 		if (ret == 1) {
 			si->stack_depth--;
 			continue;
author maintainer
#322 lore raw

PATCH 322/547 xfs: allow softlimit with no hardlimit in quota scrub

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 342c2e00b3a99099a7088f7b8c8f075670c603a9 upstream.

LOLLM observes that the sysadmin can set a user's soft limit to a nonzero value and the hard limit to zero, so those aren't corruptions.

Fixes c2fc338c87a31f ("xfs: scrub quota information")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/quota.c        |    8 ++++----
 fs/xfs/scrub/quota_repair.c |    6 +++---
 2 files changed, 7 insertions(+), 7 deletions(-)
fs/xfs/scrub/quota.c +4 -4
@@ -182,21 +182,21 @@ xchk_quota_item(
 	 * suspect, which is why we flag it for review.
 	 *
 	 * Complain about corruption if the soft limit is greater than
-	 * the hard limit.
+	 * the hard limit and there's a hard limit set.
 	 */
 	if (dq->q_blk.hardlimit > mp->m_sb.sb_dblocks)
 		xchk_fblock_set_warning(sc, XFS_DATA_FORK, offset);
-	if (dq->q_blk.softlimit > dq->q_blk.hardlimit)
+	if (dq->q_blk.hardlimit && dq->q_blk.softlimit > dq->q_blk.hardlimit)
 		xchk_fblock_set_corrupt(sc, XFS_DATA_FORK, offset);
 
 	if (dq->q_ino.hardlimit > M_IGEO(mp)->maxicount)
 		xchk_fblock_set_warning(sc, XFS_DATA_FORK, offset);
-	if (dq->q_ino.softlimit > dq->q_ino.hardlimit)
+	if (dq->q_ino.hardlimit && dq->q_ino.softlimit > dq->q_ino.hardlimit)
 		xchk_fblock_set_corrupt(sc, XFS_DATA_FORK, offset);
 
 	if (dq->q_rtb.hardlimit > mp->m_sb.sb_rblocks)
 		xchk_fblock_set_warning(sc, XFS_DATA_FORK, offset);
-	if (dq->q_rtb.softlimit > dq->q_rtb.hardlimit)
+	if (dq->q_rtb.hardlimit && dq->q_rtb.softlimit > dq->q_rtb.hardlimit)
 		xchk_fblock_set_corrupt(sc, XFS_DATA_FORK, offset);
 
 	/* Check the resource counts. */
fs/xfs/scrub/quota_repair.c +3 -3
@@ -193,17 +193,17 @@ xrep_quota_item(
 		goto out_unlock_dquot;
 
 	/* Check the limits. */
-	if (dq->q_blk.softlimit > dq->q_blk.hardlimit) {
+	if (dq->q_blk.hardlimit && dq->q_blk.softlimit > dq->q_blk.hardlimit) {
 		dq->q_blk.softlimit = dq->q_blk.hardlimit;
 		dirty = true;
 	}
 
-	if (dq->q_ino.softlimit > dq->q_ino.hardlimit) {
+	if (dq->q_ino.hardlimit && dq->q_ino.softlimit > dq->q_ino.hardlimit) {
 		dq->q_ino.softlimit = dq->q_ino.hardlimit;
 		dirty = true;
 	}
 
-	if (dq->q_rtb.softlimit > dq->q_rtb.hardlimit) {
+	if (dq->q_rtb.hardlimit && dq->q_rtb.softlimit > dq->q_rtb.hardlimit) {
 		dq->q_rtb.softlimit = dq->q_rtb.hardlimit;
 		dirty = true;
 	}
author maintainer
#323 lore raw

PATCH 323/547 xfs: assign an owner to scrub_stats_fops

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit fe67a493c7a76cf75556152af24285a114f69d34 upstream.

LOLLM complains that file_operations structs for debugfs files are supposed to have an owner set so that the module can't get unloaded if someone's sitting on a debugfs file long after unmount/rmmod. Fix that.

Fixes d7a74cad8f4513 ("xfs: track usage statistics of online fsck")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/stats.c |    2 ++
 1 file changed, 2 insertions(+)
fs/xfs/scrub/stats.c +2 -0
@@ -300,6 +300,7 @@ out:
 }
 
 static const struct file_operations scrub_stats_fops = {
+	.owner			= THIS_MODULE,
 	.open			= simple_open,
 	.read			= xchk_scrub_stats_read,
 };
@@ -327,6 +328,7 @@ xchk_clear_scrub_stats_write(
 }
 
 static const struct file_operations clear_scrub_stats_fops = {
+	.owner			= THIS_MODULE,
 	.open			= simple_open,
 	.write			= xchk_clear_scrub_stats_write,
 };
author maintainer
#324 lore raw

PATCH 324/547 xfs: bail out of directory tree repairs on error

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit d83ca4e7cc65dce6a02fd3427cefd174517657a3 upstream.

LOLLM complains that we ignore errors returned by xrep_dirpath_retain_parent and can set the dotdot entry to random stack garbage. Fix that by passing errors all the way out.

Fixes 3f31406aef493b ("xfs: fix corruptions in the directory tree")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/dirtree_repair.c |   57 ++++++++++++++++++++++++++----------------
 1 file changed, 36 insertions(+), 21 deletions(-)
fs/xfs/scrub/dirtree_repair.c +36 -21
@@ -94,7 +94,7 @@ xrep_dirtree_delete_all_paths(
 }
 
 /* Since this is the surviving path, set the dotdot entry to this value. */
-STATIC void
+STATIC int
 xrep_dirpath_retain_parent(
 	struct xchk_dirtree		*dl,
 	struct xchk_dirpath		*path)
@@ -104,18 +104,20 @@ xrep_dirpath_retain_parent(
 
 	error = xfarray_load(dl->path_steps, path->first_step, &step);
 	if (error)
-		return;
+		return error;
 
 	dl->parent_ino = be64_to_cpu(step.pptr_rec.p_ino);
+	return 0;
 }
 
 /* Find the one surviving path so we know how to set dotdot. */
-STATIC void
+STATIC int
 xrep_dirtree_find_surviving_path(
 	struct xchk_dirtree		*dl,
 	struct xchk_dirtree_outcomes	*oc)
 {
 	struct xchk_dirpath		*path;
+	int				error;
 	bool				foundit = false;
 
 	xchk_dirtree_for_each_path(dl, path) {
@@ -124,7 +126,10 @@ xrep_dirtree_find_surviving_path(
 		case XCHK_DIRPATH_LOOP:
 		case XCHK_DIRPATH_OK:
 			if (!foundit) {
-				xrep_dirpath_retain_parent(dl, path);
+				error = xrep_dirpath_retain_parent(dl, path);
+				if (error)
+					return error;
+
 				foundit = true;
 				continue;
 			}
@@ -136,16 +141,19 @@ xrep_dirtree_find_surviving_path(
 	}
 
 	ASSERT(oc->suspect + oc->good == 1);
+
+	return 0;
 }
 
 /* Delete all paths except for the one good one. */
-STATIC void
+STATIC int
 xrep_dirtree_keep_one_good_path(
 	struct xchk_dirtree		*dl,
 	struct xchk_dirtree_outcomes	*oc)
 {
 	struct xchk_dirpath		*path;
 	bool				foundit = false;
+	int				error;
 
 	xchk_dirtree_for_each_path(dl, path) {
 		switch (path->outcome) {
@@ -157,7 +165,10 @@ xrep_dirtree_keep_one_good_path(
 			break;
 		case XCHK_DIRPATH_OK:
 			if (!foundit) {
-				xrep_dirpath_retain_parent(dl, path);
+				error = xrep_dirpath_retain_parent(dl, path);
+				if (error)
+					return error;
+
 				foundit = true;
 				continue;
 			}
@@ -172,23 +183,28 @@ xrep_dirtree_keep_one_good_path(
 
 	ASSERT(oc->suspect == 0);
 	ASSERT(oc->good < 2);
+	return 0;
 }
 
 /* Delete all paths except for one suspect one. */
-STATIC void
+STATIC int
 xrep_dirtree_keep_one_suspect_path(
 	struct xchk_dirtree		*dl,
 	struct xchk_dirtree_outcomes	*oc)
 {
 	struct xchk_dirpath		*path;
 	bool				foundit = false;
+	int				error = 0;
 
 	xchk_dirtree_for_each_path(dl, path) {
 		switch (path->outcome) {
 		case XCHK_DIRPATH_CORRUPT:
 		case XCHK_DIRPATH_LOOP:
 			if (!foundit) {
-				xrep_dirpath_retain_parent(dl, path);
+				error = xrep_dirpath_retain_parent(dl, path);
+				if (error)
+					return error;
+
 				foundit = true;
 				continue;
 			}
@@ -206,13 +222,14 @@ xrep_dirtree_keep_one_suspect_path(
 
 	ASSERT(oc->suspect == 1);
 	ASSERT(oc->good == 0);
+	return error;
 }
 
 /*
  * Figure out what to do with the paths we tried to find.  Returns -EDEADLOCK
  * if the scan results have become stale.
  */
-STATIC void
+STATIC int
 xrep_dirtree_decide_fate(
 	struct xchk_dirtree		*dl,
 	struct xchk_dirtree_outcomes	*oc)
@@ -222,36 +239,32 @@ xrep_dirtree_decide_fate(
 	/* Parentless directories should not have any paths at all. */
 	if (xchk_dirtree_parentless(dl)) {
 		xrep_dirtree_delete_all_paths(dl, oc);
-		return;
+		return 0;
 	}
 
 	/* One path is exactly the number of paths we want. */
-	if (oc->good + oc->suspect == 1) {
-		xrep_dirtree_find_surviving_path(dl, oc);
-		return;
-	}
+	if (oc->good + oc->suspect == 1)
+		return xrep_dirtree_find_surviving_path(dl, oc);
 
 	/* Zero paths means we should reattach the subdir to the orphanage. */
 	if (oc->good + oc->suspect == 0) {
 		if (dl->sc->orphanage)
 			oc->needs_adoption = true;
-		return;
+		return 0;
 	}
 
 	/*
 	 * Otherwise, this subdirectory has too many parents.  If there's at
 	 * least one good path, keep it and delete the others.
 	 */
-	if (oc->good > 0) {
-		xrep_dirtree_keep_one_good_path(dl, oc);
-		return;
-	}
+	if (oc->good > 0)
+		return xrep_dirtree_keep_one_good_path(dl, oc);
 
 	/*
 	 * There are no good paths and there are too many suspect paths.
 	 * Keep the first suspect path and delete the rest.
 	 */
-	xrep_dirtree_keep_one_suspect_path(dl, oc);
+	return xrep_dirtree_keep_one_suspect_path(dl, oc);
 }
 
 /*
@@ -824,7 +837,9 @@ xrep_dirtree(
 		 * to walk again.
 		 */
 		if (!dl->stale) {
-			xrep_dirtree_decide_fate(dl, &oc);
+			error = xrep_dirtree_decide_fate(dl, &oc);
+			if (error)
+				break;
 
 			trace_xrep_dirtree_decided_fate(dl, &oc);
 
author maintainer
#325 lore raw

PATCH 325/547 xfs: fix revalidation of xchk_dquot_iter cached mappings

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 6c64d650460b455980a6023d43bc6c8859c1cfd2 upstream.

LOLLM noticed that the purpose of xchk_dquot_iter_revalidate_bmap is to revalidate the quota file mapping after we've (presumably) done something to the quota file contents. However, the "yes this is valid" code isn't quite strong enough -- the mapping must cover at least the block at fileoff, not just end after fileoff. Fix that.

Fixes 21d7500929c8a0 ("xfs: improve dquot iteration for scrub")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/dqiterate.c |    1 +
 1 file changed, 1 insertion(+)
fs/xfs/scrub/dqiterate.c +1 -0
@@ -58,6 +58,7 @@ xchk_dquot_iter_revalidate_bmap(
 	 * no need to reread the bmbt.
 	 */
 	if (cursor->bmap.br_startoff != NULLFILEOFF &&
+	    cursor->bmap.br_startoff <= fileoff &&
 	    cursor->if_seq == ifp->if_seq &&
 	    cursor->bmap.br_startoff + cursor->bmap.br_blockcount > fileoff)
 		return 0;
author maintainer
#326 lore raw

PATCH 326/547 xfs: abort dirtree repair if the live update hook dies

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 07732dea4f5d0410e1566b81a58a1154bf9dcb29 upstream.

LOLLM notices that if the live update hook for the directory tree repair code hits an error, it will set dl->aborted and stops working. If the repair code ever sees that condition, it ought to bail out immediately instead of continuing with obsolete data.

Fixes 3f31406aef493b ("xfs: fix corruptions in the directory tree")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/dirtree_repair.c |    5 +++++
 1 file changed, 5 insertions(+)
fs/xfs/scrub/dirtree_repair.c +5 -0
@@ -831,6 +831,11 @@ xrep_dirtree(
 	 */
 	mutex_lock(&dl->lock);
 	do {
+		if (dl->aborted) {
+			error = -EIO;
+			break;
+		}
+
 		/*
 		 * Decide what we're going to do, then do it.  An -ESTALE
 		 * return here means the scan results are invalid and we have
author maintainer
#327 lore raw

PATCH 327/547 xfs: check fork type against dabtree block magic number

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 43030b72a11a532e7e3c21ac84a8625425b4201b upstream.

LOLLM complains that we fail to flag dabtree blocks that should never be associated with the file fork -- data forks can't point to xattr leaves, and attr forks can't point to dirent blocks. Add the missing checks.

Fixes 7c4a07a424c18d ("xfs: scrub directory/attribute btrees")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/dabtree.c |   12 ++++++++++++
 1 file changed, 12 insertions(+)
fs/xfs/scrub/dabtree.c +12 -0
@@ -410,6 +410,10 @@ xchk_da_btree_block(
 				XFS_BLFT_ATTR_LEAF_BUF);
 		blk->magic = XFS_ATTR_LEAF_MAGIC;
 		blk->hashval = xfs_attr_leaf_lasthash(blk->bp, pmaxrecs);
+		if (dargs->whichfork != XFS_ATTR_FORK) {
+			xchk_da_set_corrupt(ds, level);
+			goto out_freebp;
+		}
 		if (ds->tree_level != 0)
 			xchk_da_set_corrupt(ds, level);
 		break;
@@ -419,6 +423,10 @@ xchk_da_btree_block(
 				XFS_BLFT_DIR_LEAFN_BUF);
 		blk->magic = XFS_DIR2_LEAFN_MAGIC;
 		blk->hashval = xfs_dir2_leaf_lasthash(ip, blk->bp, pmaxrecs);
+		if (dargs->whichfork != XFS_DATA_FORK) {
+			xchk_da_set_corrupt(ds, level);
+			goto out_freebp;
+		}
 		if (ds->tree_level != 0)
 			xchk_da_set_corrupt(ds, level);
 		break;
@@ -428,6 +436,10 @@ xchk_da_btree_block(
 				XFS_BLFT_DIR_LEAF1_BUF);
 		blk->magic = XFS_DIR2_LEAF1_MAGIC;
 		blk->hashval = xfs_dir2_leaf_lasthash(ip, blk->bp, pmaxrecs);
+		if (dargs->whichfork != XFS_DATA_FORK) {
+			xchk_da_set_corrupt(ds, level);
+			goto out_freebp;
+		}
 		if (ds->tree_level != 0)
 			xchk_da_set_corrupt(ds, level);
 		break;
author maintainer
#328 lore raw

PATCH 328/547 xfs: mark overfull dabtree node blocks as corrupt

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit f61c91a2e5994fa81141d6c06dadae1fed206018 upstream.

LOLLM observes that we need to range-check the dabtree node record count before using it to index an array. Fix that.

Fixes 7c4a07a424c18d ("xfs: scrub directory/attribute btrees")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/dabtree.c |    4 ++++
 1 file changed, 4 insertions(+)
fs/xfs/scrub/dabtree.c +4 -0
@@ -451,6 +451,10 @@ xchk_da_btree_block(
 		node = blk->bp->b_addr;
 		xfs_da3_node_hdr_from_disk(ip->i_mount, &nodehdr, node);
 		btree = nodehdr.btree;
+		if (nodehdr.count > dargs->geo->node_ents) {
+			xchk_da_set_corrupt(ds, level);
+			goto out_freebp;
+		}
 		*pmaxrecs = nodehdr.count;
 		blk->hashval = be32_to_cpu(btree[*pmaxrecs - 1].hashval);
 		if (level == 0) {
author maintainer
#329 lore raw

PATCH 329/547 xfs: jump out of xchk_bmap_check_rmap if fatal signals

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 49d300a51442bd64b627645b7b0b1cd66e492905 upstream.

LOLLM observes that we never check for fatal signals inside the loop that checks file fork mappings against the rmapbt. This can lead to lengthy delays in responding to a ^C, so add some bailout checks.

Fixes 5e777b62b0bcb6 ("xfs: bmap scrubber should do rmap xref with bmap for sparse files")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/bmap.c |    7 +++++++
 1 file changed, 7 insertions(+)
fs/xfs/scrub/bmap.c +7 -0
@@ -626,6 +626,10 @@ xchk_bmap_check_rmap(
 	struct xfs_ifork		*ifp;
 	struct xfs_scrub		*sc = sbcri->sc;
 	bool				have_map;
+	int				error = 0;
+
+	if (xchk_should_terminate(sc, &error))
+		return error;
 
 	/* Is this even the right fork? */
 	if (rec->rm_owner != I_INO(sc->ip))
@@ -657,6 +661,9 @@ xchk_bmap_check_rmap(
 	 */
 	check_rec = *rec;
 	while (have_map) {
+		if (xchk_should_terminate(sc, &error))
+			return error;
+
 		if (irec.br_startoff != check_rec.rm_offset)
 			xchk_fblock_set_corrupt(sc, sbcri->whichfork,
 					check_rec.rm_offset);
author maintainer
#330 lore raw

PATCH 330/547 xfs: cross-reference the primary superblock

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 0c61016006ab08f8346f9e7b1e38559bd4ea499e upstream.

Make sure we cross-reference the primary superblock against the rest of the AG 0 space metadata. Drop the unused @bp parameter of xchk_superblock_xref to avoid complaints about uninitialized variables.

Fixes 52dc4b44af7419 ("xfs: cross-reference with the bnobt")
---
 fs/xfs/scrub/agheader.c |   15 +++++++--------
 1 file changed, 7 insertions(+), 8 deletions(-)
fs/xfs/scrub/agheader.c +7 -8
@@ -35,8 +35,7 @@ xchk_setup_agheader(
 /* Cross-reference with the other btrees. */
 STATIC void
 xchk_superblock_xref(
-	struct xfs_scrub	*sc,
-	struct xfs_buf		*bp)
+	struct xfs_scrub	*sc)
 {
 	struct xfs_mount	*mp = sc->mp;
 	xfs_agnumber_t		agno = sc->sm->sm_agno;
@@ -106,16 +105,12 @@ xchk_superblock(
 	struct xfs_dsb		*sb;
 	struct xfs_perag	*pag;
 	size_t			sblen;
-	xfs_agnumber_t		agno;
+	xfs_agnumber_t		agno = sc->sm->sm_agno;
 	uint32_t		v2_ok;
 	__be32			features_mask;
 	int			error;
 	__be16			vernum_mask;
 
-	agno = sc->sm->sm_agno;
-	if (agno == 0)
-		return 0;
-
 	/*
 	 * Grab an active reference to the perag structure.  If we can't get
 	 * it, we're racing with something that's tearing down the AG, so
@@ -125,6 +120,9 @@ xchk_superblock(
 	if (!pag)
 		return -ENOENT;
 
+	if (agno == 0)
+		goto out_xref;
+
 	error = xfs_sb_read_secondary(mp, sc->tp, agno, &bp);
 	/*
 	 * The superblock verifier can return several different error codes
@@ -430,7 +428,8 @@ xchk_superblock(
 	if (memchr_inv((char *)sb + sblen, 0, BBTOB(bp->b_length) - sblen))
 		xchk_block_set_corrupt(sc, bp);
 
-	xchk_superblock_xref(sc, bp);
+out_xref:
+	xchk_superblock_xref(sc);
 out_pag:
 	xfs_perag_put(pag);
 	return error;
#331 lore raw

Re: [PATCH 7.3 330/547] xfs: cross-reference the primary superblock

Quoted 65 lines · Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 0c61016006ab08f8346f9e7b1e38559bd4ea499e upstream.

Make sure we cross-reference the primary superblock against the rest of the AG 0 space metadata. Drop the unused @bp parameter of xchk_superblock_xref to avoid complaints about uninitialized variables.

Fixes 52dc4b44af7419 ("xfs: cross-reference with the bnobt")
---
  fs/xfs/scrub/agheader.c |   15 +++++++--------
  1 file changed, 7 insertions(+), 8 deletions(-)
fs/xfs/scrub/agheader.c +5 -7
@@ -35,8 +35,7 @@ xchk_setup_agheader(
  /* Cross-reference with the other btrees. */
  STATIC void
  xchk_superblock_xref(
-	struct xfs_scrub	*sc,
-	struct xfs_buf		*bp)
+	struct xfs_scrub	*sc)
  {
  	struct xfs_mount	*mp = sc->mp;
  	xfs_agnumber_t		agno = sc->sm->sm_agno;
@@ -106,16 +105,12 @@ xchk_superblock(
  	struct xfs_dsb		*sb;
  	struct xfs_perag	*pag;
  	size_t			sblen;
-	xfs_agnumber_t		agno;
+	xfs_agnumber_t		agno = sc->sm->sm_agno;
  	uint32_t		v2_ok;
  	__be32			features_mask;
  	int			error;
  	__be16			vernum_mask;
 
-	agno = sc->sm->sm_agno;
-	if (agno == 0)
-		return 0;
-
  	/*
  	 * Grab an active reference to the perag structure.  If we can't get
  	 * it, we're racing with something that's tearing down the AG, so
@@ -125,6 +120,9 @@ xchk_superblock(
  	if (!pag)
  		return -ENOENT;
 
+	if (agno == 0)
+		goto out_xref;
+
  	error = xfs_sb_read_secondary(mp, sc->tp, agno, &bp);
  	/*
  	 * The superblock verifier can return several different error codes

fs/xfs/scrub/agheader.c xchk_superblock( · line 435

Quoted 9 lines
fs/xfs/scrub/agheader.c +2 -1
@@ -430,7 +428,8 @@ xchk_superblock(
  	if (memchr_inv((char *)sb + sblen, 0, BBTOB(bp->b_length) - sblen))
  		xchk_block_set_corrupt(sc, bp);
 
-	xchk_superblock_xref(sc, bp);
+out_xref:
+	xchk_superblock_xref(sc);
  out_pag:
  	xfs_perag_put(pag);
  	return error;

This patch is breaking the build for me with CONFIG_WERROR enabled, for both 6.18.61-rc1 and 7.3.2-rc1, on both arm64 and amd64, when I compile with clang (I tried 19.1.7, 22.1.8 and 23.1.5). It only happens if I build with CONFIG_XFS_ONLINE_SCRUB enabled. However, it doesn't happen with 7.4-rc1, and it does not happen with gcc.

fs/xfs/scrub/agheader.c:123:6: error: variable 'error' is used uninitialized
whenever 'if' condition is true [-Werror,-Wsometimes-uninitialized]
123 | if (agno == 0)

      |             ^~~~~~~~~
fs/xfs/scrub/agheader.c:435:9: note: uninitialized use occurs here
  435 |         return error;
      |                ^~~~~
fs/xfs/scrub/agheader.c:123:2: note: remove the 'if' if its condition is always
      false
  123 |         if (agno == 0)
      |         ^~~~~~~~~~~~~~
  124 |                 goto out_xref;
      |                 ~~~~~~~~~~~~~
fs/xfs/scrub/agheader.c:111:13: note: initialize the variable 'error' to silence
      this warning
  111 |         int                     error;
      |                                      ^
      |                                       = 0

1 error generated.
make[4]: *** [scripts/Makefile.build:287: fs/xfs/scrub/agheader.o] Error 1 make[3]: *** [scripts/Makefile.build:544: fs/xfs] Error 2 make[2]: *** [scripts/Makefile.build:544: fs] Error 2
make[2]: *** Waiting for unfinished jobs....

I bisected 7.3.2-rc1 and this patch is the culprit. Reverting it fixes the build on both 6.18.61-rc1 and 7.3.2-rc1. Another possible fix, which built successfully for me on top of both 6.18.61-rc1 and 7.3.2-rc1, is to cherry-pick commit 612d2e7506c3553b1deedc694846d1c0364ae446 from mainline ("xfs: read primary superblock from disk during scrub").

Signature · 1 line
-Barry K. Nathan  <[email protected]>
#332 lore raw

Re: [PATCH 7.3 330/547] xfs: cross-reference the primary superblock

Quoted 30 lines · Barry K. Nathan

This patch is breaking the build for me with CONFIG_WERROR enabled, for both 6.18.61-rc1 and 7.3.2-rc1, on both arm64 and amd64, when I compile with clang (I tried 19.1.7, 22.1.8 and 23.1.5). It only happens if I build with CONFIG_XFS_ONLINE_SCRUB enabled. However, it doesn't happen with 7.4-rc1, and it does not happen with gcc.

fs/xfs/scrub/agheader.c:123:6: error: variable 'error' is used uninitialized
      whenever 'if' condition is true [-Werror,-Wsometimes-uninitialized] 123 |         if (agno == 0)
      |             ^~~~~~~~~
fs/xfs/scrub/agheader.c:435:9: note: uninitialized use occurs here
  435 |         return error;
      |                ^~~~~
fs/xfs/scrub/agheader.c:123:2: note: remove the 'if' if its condition is always
      false
  123 |         if (agno == 0)
      |         ^~~~~~~~~~~~~~
  124 |                 goto out_xref;
      |                 ~~~~~~~~~~~~~
fs/xfs/scrub/agheader.c:111:13: note: initialize the variable 'error' to silence
      this warning
  111 |         int                     error;
      |                                      ^
      |                                       = 0
1 error generated.
make[4]: *** [scripts/Makefile.build:287: fs/xfs/scrub/agheader.o] Error 1 make[3]: *** [scripts/Makefile.build:544: fs/xfs] Error 2
make[2]: *** [scripts/Makefile.build:544: fs] Error 2
make[2]: *** Waiting for unfinished jobs....

Quoted 5 lines

I bisected 7.3.2-rc1 and this patch is the culprit. Reverting it fixes the build on both 6.18.61-rc1 and 7.3.2-rc1. Another possible fix, which built successfully for me on top of both 6.18.61-rc1 and 7.3.2-rc1, is to cherry-pick commit 612d2e7506c3553b1deedc694846d1c0364ae446 from mainline ("xfs: read primary superblock from disk during scrub").

This was reverted for 7.3.2, but I see that it's back in the queue again as of stable-queue commit 77ecab77b25567c54df997dcb8030dea6bca03ed ("Fixes for all trees"). I just tried applying the queue on top of 7.3.3 and the build error still happens.

Since the mainline fix is not a stable candidate, maybe something like this (just initializing error to 0 when it's first defined) would work? (This fixes the build error for me, but I haven't tried running it yet.)

fs/xfs/scrub/agheader.c +1 -1
diff -rup a/fs/xfs/scrub/agheader.c b/fs/xfs/scrub/agheader.c
@@ -108,7 +108,7 @@ xchk_superblock(
 	xfs_agnumber_t		agno = sc->sm->sm_agno;
 	uint32_t		v2_ok;
 	__be32			features_mask;
-	int			error;
+	int			error = 0;
 	__be16			vernum_mask;
 
 	/*
Signature · 1 line
-Barry K. Nathan  <[email protected]>
#333 lore raw

Re: [PATCH 7.3 330/547] xfs: cross-reference the primary superblock

Quoted 37 lines · Barry K. Nathan
Quoted 30 lines · Barry K. Nathan

This patch is breaking the build for me with CONFIG_WERROR enabled, for both 6.18.61-rc1 and 7.3.2-rc1, on both arm64 and amd64, when I compile with clang (I tried 19.1.7, 22.1.8 and 23.1.5). It only happens if I build with CONFIG_XFS_ONLINE_SCRUB enabled. However, it doesn't happen with 7.4-rc1, and it does not happen with gcc.

fs/xfs/scrub/agheader.c:123:6: error: variable 'error' is used uninitialized whenever 'if' condition is true [-Werror,-Wsometimes-uninitialized] 123 |         if (agno == 0)
       |             ^~~~~~~~~
fs/xfs/scrub/agheader.c:435:9: note: uninitialized use occurs here 435 |         return error;
       |                ^~~~~
fs/xfs/scrub/agheader.c:123:2: note: remove the 'if' if its condition is always false
   123 |         if (agno == 0)
       |         ^~~~~~~~~~~~~~
   124 |                 goto out_xref;
       |                 ~~~~~~~~~~~~~ fs/xfs/scrub/agheader.c:111:13: note: initialize the variable 'error' to silence this warning
   111 |         int                     error;
       |                                      ^
       |                                       = 0
1 error generated.
make[4]: *** [scripts/Makefile.build:287: fs/xfs/scrub/agheader.o] Error 1 make[3]: *** [scripts/Makefile.build:544: fs/xfs] Error 2
make[2]: *** [scripts/Makefile.build:544: fs] Error 2
make[2]: *** Waiting for unfinished jobs....

Quoted 5 lines

I bisected 7.3.2-rc1 and this patch is the culprit. Reverting it fixes the build on both 6.18.61-rc1 and 7.3.2-rc1. Another possible fix, which built successfully for me on top of both 6.18.61-rc1 and 7.3.2-rc1, is to cherry-pick commit 612d2e7506c3553b1deedc694846d1c0364ae446 from mainline ("xfs: read primary superblock from disk during scrub").

Quoted 4 lines

This was reverted for 7.3.2, but I see that it's back in the queue again as of stable-queue commit 77ecab77b25567c54df997dcb8030dea6bca03ed ("Fixes for all trees"). I just tried applying the queue on top of 7.3.3 and the build error still happens.

Just to be clear, I meant "dropped for 7.3.2" not "reverted for 7.3.2". (Sorry I didn't catch the mistake before hitting send.)

Quoted 18 lines

Since the mainline fix is not a stable candidate, maybe something like this (just initializing error to 0 when it's first defined) would work? (This fixes the build error for me, but I haven't tried running it yet.)

diff -rup a/fs/xfs/scrub/agheader.c b/fs/xfs/scrub/agheader.c

fs/xfs/scrub/agheader.c    2026-11-06 22:45:59.898908897 -0800 renamed from fs/xfs/scrub/agheader.c    2026-11-06 22:42:57.147299404 -0800 +1 -1
@@ -108,7 +108,7 @@ xchk_superblock(
      xfs_agnumber_t        agno = sc->sm->sm_agno;
      uint32_t        v2_ok;
      __be32            features_mask;
-    int            error;
+    int            error = 0;
      __be16            vernum_mask;
 
      /*
Signature · 1 line
-Barry K. Nathan  <[email protected]>
author maintainer
#334 lore raw

PATCH 331/547 xfs: adjust checks for cross-AG reaping issues

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 4c6668ecebc61bb0a53d4c6e95509bc960cf6bbc upstream.

While analyzing the reaping code for the previous patch, I studied the xfs_fsblock_t code to reconstruct how this code works. AGs have a superblock at the start of each AG which means that regions in the xfsb_bitmap (aka xfs_fsblock_t bitmap) cannot cross an AG boundary, so we don't need a loop here like we do for xfs_rtblock_t bitmaps.

However, the checks here are not quite right -- there can be quite a lot of reserved space in COW forks, which means that the bitmap extent actually can exceed XFS_MAX_BMBT_EXTLEN. We also don't have an explicit debugging check that we never cross AGs, so add that here.

Fixes 66da11280f7ecd ("xfs: reintroduce reaping of file metadata blocks to xrep_reap_extents")
---
 fs/xfs/scrub/reap.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/xfs/scrub/reap.c +1 -1
@@ -796,9 +796,9 @@ xreap_fsmeta_extent(
 	xfs_agblock_t		agbno_next = agbno + len;
 	int			error = 0;
 
-	ASSERT(len <= XFS_MAX_BMBT_EXTLEN);
 	ASSERT(sc->ip != NULL);
 	ASSERT(!sc->sa.pag);
+	ASSERT(agno == XFS_FSB_TO_AGNO(sc->mp, fsbno + len - 1));
 
 	/*
 	 * We're reaping blocks after repairing file metadata, which means that
author maintainer
#335 lore raw

PATCH 332/547 xfs: actually check XFS_DIFLAG2_METADATA for metadata btree data forks

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 436ae68743a6974021fefa21fd3093d9bf8e66e4 upstream.

LOLLM noticed that xrep_dinode_check_dfork doesn't require that the inode has the METADATA flag set in flags2. Add that check.

Fixes 702c90f4516223 ("xfs: support file data forks containing metadata btrees")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/inode_repair.c |    5 +++++
 1 file changed, 5 insertions(+)
fs/xfs/scrub/inode_repair.c +5 -0
@@ -1014,6 +1014,11 @@ xrep_dinode_bad_metabt_fork(
 	if (whichfork != XFS_DATA_FORK)
 		return true;
 
+	if (!xfs_has_metadir(sc->mp))
+		return true;
+	if (!(dip->di_flags2 & cpu_to_be64(XFS_DIFLAG2_METADATA)))
+		return true;
+
 	switch (be16_to_cpu(dip->di_metatype)) {
 	case XFS_METAFILE_RTRMAP:
 		return xrep_dinode_bad_rtrmapbt_fork(sc, dip, dfork_size);
author maintainer
#336 lore raw

PATCH 333/547 xfs: fix xchk_stats_estimate_bufsize to allow for the trailing null

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 6b8d60784b61a17bd591cb4c6e8aa9ed29c24f5c upstream.

LOLLM complains that xchk_stats_estimate_bufsize underestimates the buffer size by 1 byte because scnprintf wants to store a null byte after the newline in each line. Each call to scnprintf overwrites the null left by the previous call, but we still need the null byte for the last line in the file.

Fixes d7a74cad8f4513 ("xfs: track usage statistics of online fsck")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/stats.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
fs/xfs/scrub/stats.c +2 -1
@@ -168,7 +168,8 @@ xchk_stats_estimate_bufsize(
 		ret += field_width + 1;
 	}
 
-	return ret;
+	/* null byte for scnprintf */
+	return ret + 1;
 }
 
 /* Clear all counters. */
author maintainer
#337 lore raw

PATCH 334/547 netfilter: nft_payload: restrict checksum offsets to known values

In reply to Greg Kroah-Hartman

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

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

From: Florian Westphal <[email protected]>

[ Upstream commit c2226f0c7fe90b67732e5ae36dc5c3cc01ddf888 ]

We need to prevent userspace from corrupting e.g. tcp->doff, because many locations in conntrack and conntrack helpers rely on nf_conntrack_in() having validated the packet headers. nft_payload allows to alter headers later which invalidates this assumption.

The 'Fixes' commit restricts writes to safe fields, but there is another side channel: the checksum location.

Restrict this too. Reported via sashiko/gemini.

Fixes 112e447d17f7 ("netfilter: validate L4 headers after userspace packet writes")
Assisted-by Claude:claude-opus-4-6
---
 net/netfilter/nft_payload.c | 40 ++++++++++++++++++++++++++++++-------
 1 file changed, 33 insertions(+), 7 deletions(-)
net/netfilter/nft_payload.c +33 -7
index e315d35f73d4a..5b76af68b7049 100644
@@ -20,6 +20,7 @@
 #include <linux/tcp.h>
 #include <linux/udp.h>
 #include <net/gre.h>
+#include <linux/icmp.h>
 #include <linux/icmpv6.h>
 #include <linux/ip.h>
 #include <linux/ipv6.h>
@@ -1008,11 +1009,14 @@ static bool nft_payload_validate_inet_csum_offset(const struct nft_ctx *ctx,
 		if (priv->csum_flags) /* makes no sense, asks for "re-update" of L4 checksum */
 			return false;
 
-		/* no further check here; offset can't be negative so bogus
-		 * offsets can corrupt L4 or payload but not l3 headers.
-		 * We already allow arbitrary l4/inner payload writes.
-		 */
-		return true;
+		/* Validate csum_offset is one of the supported transport header checksums */
+		if (priv->csum_offset == offsetof(struct tcphdr, check) ||
+		    priv->csum_offset == offsetof(struct udphdr, check) ||
+		    priv->csum_offset == offsetof(struct icmphdr, checksum) ||
+		    priv->csum_offset == offsetof(struct icmp6hdr, icmp6_cksum))
+			return true;
+
+		return false;
 	case NFT_PAYLOAD_INNER_HEADER:
 		return true;
 	case NFT_PAYLOAD_TUN_HEADER:
@@ -1046,6 +1050,27 @@ static bool nft_payload_csum_nh_write_ok(const struct nft_payload_set *priv,
 	return false;
 }
 
+static bool nft_payload_csum_th_write_ok(const struct nft_payload_set *priv,
+					 const struct nft_pktinfo *pkt)
+{
+	if (!(pkt->flags & NFT_PKTINFO_L4PROTO))
+		return false;
+
+	switch (pkt->tprot) {
+	case IPPROTO_TCP:
+		return priv->csum_offset == offsetof(struct tcphdr, check);
+	case IPPROTO_UDP:
+	case IPPROTO_UDPLITE:
+		return priv->csum_offset == offsetof(struct udphdr, check);
+	case IPPROTO_ICMPV6:
+		return priv->csum_offset == offsetof(struct icmp6hdr, icmp6_cksum);
+	case IPPROTO_ICMP:
+		return priv->csum_offset == offsetof(struct icmphdr, checksum);
+	}
+
+	return false;
+}
+
 static bool nft_payload_csum_write_ok(const struct nft_pktinfo *pkt,
 				      const struct nft_payload_set *priv)
 {
@@ -1055,9 +1080,10 @@ static bool nft_payload_csum_write_ok(const struct nft_pktinfo *pkt,
 	case NFT_PAYLOAD_NETWORK_HEADER:
 		return nft_payload_csum_nh_write_ok(priv, pkt);
 	case NFT_PAYLOAD_TRANSPORT_HEADER:
+		return nft_payload_csum_th_write_ok(priv, pkt);
 	case NFT_PAYLOAD_INNER_HEADER:
-		/* neither offsets are validated, offsets cannot be
-		 * negative so real l3 headers cannot be mangled.
+		/* offset is not validated, offset cannot be
+		 * negative so real l3/l4 headers cannot be mangled.
 		 */
 		return true;
 	case NFT_PAYLOAD_TUN_HEADER:
Signature · 1 line
2.53.0
author maintainer
#338 lore raw

PATCH 335/547 rtnetlink: wait for RCU readers in rtnl_link_unregister()

In reply to Greg Kroah-Hartman

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

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

From: Andrea Parri <[email protected]>

[ Upstream commit 3b70edea393de445255da6c706eebb823117a955 ]

rtnl_link_ops_get() finds ops on link_ops under rcu_read_lock() and only then takes ops->srcu. rtnl_link_unregister() unlinks ops, then calls synchronize_srcu() and cleanup_srcu_struct() without first waiting for RCU readers. A reader that found ops before list_del_rcu() and has not yet taken ops->srcu is not waited for.

Such a reader then locks a cleaned-up srcu_struct and keeps using ops after the module that owns it is gone. rtnl_newlink() and rtnl_dump_ifinfo() both look up ops without RTNL, the latter for any user that dumps links filtered by kind.

With delays added between the lookup and srcu_read_lock() in rtnl_link_ops_get(), and before rtnl_link_ops_put() in rtnl_dump_ifinfo(), running "ip link show type dummy" alongside "rmmod dummy" on a KASAN kernel gives:

  BUG: KASAN: vmalloc-out-of-bounds in __srcu_read_unlock+0x57/0x70
  Read of size 8 at addr ffffffffc02ff318 by task ip/147
  Call Trace:
   __srcu_read_unlock+0x57/0x70
   rtnl_dump_ifinfo.cold+0x30/0x3b
   rtnl_dumpit+0x7a/0x1b0
   netlink_dump+0x486/0x11b0
   __netlink_dump_start+0x661/0x910
   rtnetlink_rcv_msg+0x611/0x9e0
   netlink_rcv_skb+0x126/0x380
   netlink_unicast+0x605/0x830
   netlink_sendmsg+0x6d0/0xbb0
   __sys_sendto+0x335/0x3a0

Call synchronize_rcu() before synchronize_srcu(), as rtnl_af_unregister() already does. This should be enough because rtnl_link_ops_get() is the only RCU walker of link_ops, and it takes ops->srcu before rcu_read_unlock(), so every reader that found ops is covered by synchronize_srcu() once the RCU grace period ends. The extra grace period only costs time at module unload.

Readers and the writer were serialized by RTNL until link_ops got its own mutex, which is why the missing RCU wait did not matter before.

Cc [email protected] # needs real net-admin (non-ns)
Fixes 6b57ff21a310 ("rtnetlink: Protect link_ops by mutex.")
---
 net/core/rtnetlink.c | 4 ++++
 1 file changed, 4 insertions(+)
net/core/rtnetlink.c +4 -0
index be9d1625bac31..580101b5ab585 100644
@@ -707,6 +707,10 @@ void rtnl_link_unregister(struct rtnl_link_ops *ops)
 	list_del_rcu(&ops->list);
 	mutex_unlock(&link_ops_mutex);
 
+	/* Wait for rtnl_link_ops_get() readers that found ops but have
+	 * not yet taken ops->srcu.
+	 */
+	synchronize_rcu();
 	synchronize_srcu(&ops->srcu);
 	cleanup_srcu_struct(&ops->srcu);
 
Signature · 1 line
2.53.0
author maintainer
#339 lore raw

PATCH 336/547 xfs: reduce new btree slack factor if free space is negative

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 80f13dc7225eec318da7499c7a562d7a34d25e6a upstream.

LOLLM points out that if the incore fdblocks counter is negative, the assignment to uint64_t will mask this possibly low space situation and we don't pack the btree blocks as tightly as we probably ought to. If it's the case that there's some free space and fdblocks is too low due to an error in the superblock field, then we can end up failing btree rebuilds due to ENOSPC unnecessarily. This is a corner case, but let's fix it anyway.

Fixes be408417630427 ("xfs: implement block reservation accounting for btrees we're staging")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/newbt.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/xfs/scrub/newbt.c +1 -1
@@ -71,7 +71,7 @@ xrep_newbt_estimate_slack(
 		free = sc->sa.pag->pagf_freeblks;
 		sz = xfs_ag_block_count(sc->mp, pag_agno(sc->sa.pag));
 	} else {
-		free = xfs_sum_freecounter_raw(sc->mp, XC_FREE_BLOCKS);
+		free = xfs_sum_freecounter(sc->mp, XC_FREE_BLOCKS);
 		sz = sc->mp->m_sb.sb_dblocks;
 	}
 
author maintainer
#340 lore raw

PATCH 337/547 xfs: reject absurdly large xattr value lengths in xchk_xattr_actor

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit fd012955641881169a9f01a00f656f6ca73842ec upstream.

LOLLM suggests that we shouldn't try to allocate absurdly large buffers for xattr value checks because that will push reclaim very hard, never succeed, and is pointless because nobody can create xattrs that large. Since the xattr repair code ignores values larger than XATTR_SIZE_MAX, we can flag the corruption and return early.

Fixes 6d6ccedd76823c ("xfs: only allocate memory for scrubbing attributes when we need it")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/attr.c          |    6 ++++++
 fs/xfs/scrub/parent_repair.c |    4 ++++
 2 files changed, 10 insertions(+)
fs/xfs/scrub/attr.c +6 -0
@@ -216,6 +216,12 @@ xchk_xattr_actor(
 		return -ECANCELED;
 	}
 
+	/* Don't even try to handle a bizarrely large xattr. */
+	if (valuelen > XATTR_SIZE_MAX) {
+		xchk_fblock_set_corrupt(sc, XFS_ATTR_FORK, args.blkno);
+		return -ECANCELED;
+	}
+
 	/*
 	 * Try to allocate enough memory to extract the attr value.  If that
 	 * doesn't work, return -EDEADLOCK as a signal to try again with a
fs/xfs/scrub/parent_repair.c +4 -0
@@ -910,6 +910,10 @@ xrep_parent_fetch_xattr_remote(
 	};
 	int			error;
 
+	/* Don't even try to handle a bizarrely large xattr. */
+	if (valuelen > XATTR_SIZE_MAX)
+		return -EFSCORRUPTED;
+
 	/*
 	 * If we need a larger value buffer, try to allocate one.  If that
 	 * fails, return with -EDEADLOCK to try harder.
author maintainer
#341 lore raw

PATCH 338/547 xfs: reject out-of-range attribute value lengths in xfs_attr_copy_value

In reply to Greg Kroah-Hartman

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

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

From: Aldo Ariel Panzardo <[email protected]>

commit 0643549ffecaeb716c0b75590a9b76dfa5eb35b3 upstream.

xfs_attr_copy_value() takes the value length as a signed int and, for a remote xattr, is handed args->rmtvaluelen. That field is filled from the on-disk __be32 xfs_attr_leaf_name_remote.valuelen in xfs_attr3_leaf_getvalue(), so a crafted length such as 0x80000000 is stored into the signed rmtvaluelen as a negative number.

The "buffer too small" guard in xfs_attr_copy_value() is a signed comparison:

	if (args->valuelen < valuelen)
		return -ERANGE;

A negative valuelen therefore compares as smaller than the caller's buffer size, skips the -ERANGE path, and is then used as a copy length, leading to an out-of-bounds copy of a full remote block into a small getxattr(2) buffer on a mounted crafted image.

Reject a value length that is negative or larger than the maximum xattr size before it is used, so a bogus on-disk length can no longer slip through the value copier.

Fixes 9df243a1a9e6 ("xfs: consolidate attribute value copying")
---
 fs/xfs/libxfs/xfs_attr_leaf.c |   11 +++++++++++
 1 file changed, 11 insertions(+)
fs/xfs/libxfs/xfs_attr_leaf.c +11 -0
@@ -643,6 +643,17 @@ xfs_attr_copy_value(
 	int			valuelen)
 {
 	/*
+	 * A value length that is negative or larger than the maximum xattr
+	 * size is on-disk corruption.  The remote value length is an on-disk
+	 * __be32 stored into the signed args->rmtvaluelen, so a crafted value
+	 * such as 0x80000000 becomes negative and would slip past the
+	 * "args->valuelen < valuelen" check below and be used as a copy
+	 * length.  Reject it before that can happen.
+	 */
+	if (valuelen < 0 || valuelen > XFS_XATTR_SIZE_MAX)
+		return -EFSCORRUPTED;
+
+	/*
 	 * Parent pointer lookups require the caller to specify the name and
 	 * value, so don't copy anything.
 	 */
author maintainer
#342 lore raw

PATCH 339/547 xfs: reject remote xattr entries with an out-of-range value length

In reply to Greg Kroah-Hartman

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

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

From: Aldo Ariel Panzardo <[email protected]>

commit 15ccd92a782a0253f4a17895f3d3f71e5c1d1973 upstream.

xfs_attr3_leaf_verify_entry() validates a remote attribute entry's name but never bounds its on-disk value length (xfs_attr_leaf_name_remote. valuelen, a __be32). A crafted leaf with valuelen = 0x80000000 passes the verifier and the CRC.

That length is later assigned into the signed int args->rmtvaluelen (xfs_attr3_leaf_getvalue), becoming negative, which slips past the signed -ERANGE check in xfs_attr_copy_value(); a getxattr() with a small buffer then memcpy()s a full remote block into the small kvalue buffer (xfs_attr_rmtval_copyout) -- a heap out-of-bounds write with attacker-controlled content, from an unprivileged getxattr(2) on a mounted crafted image.

Reject remote entries whose value length exceeds XFS_XATTR_SIZE_MAX in the leaf verifier, so the malicious block is rejected at read time.

Fixes c84760659dcf ("xfs: check attribute leaf block structure")
---
 fs/xfs/libxfs/xfs_attr_leaf.c |    2 ++
 1 file changed, 2 insertions(+)
fs/xfs/libxfs/xfs_attr_leaf.c +2 -0
@@ -353,6 +353,8 @@ xfs_attr3_leaf_verify_entry(
 		if (!(ent->flags & XFS_ATTR_INCOMPLETE) &&
 		    rentry->valueblk == 0)
 			return __this_address;
+		if (be32_to_cpu(rentry->valuelen) > XFS_XATTR_SIZE_MAX)
+			return __this_address;
 	}
 
 	if (name_end > buf_end)
author maintainer
#343 lore raw

PATCH 340/547 xfs: release ip after unlinked list store failure

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 9a263723d7c9ab0615bab3f5cc145d3d24454a5c upstream.

If, while processing an unlinked list we see an inode that has nonzero link count, we fail to store the incore prev/next pointers, we should release the incore inode instead of leaking it. This was in the llm fixes branch but fell out for -rc7. Weird.

Cc [email protected] # v7.2-rc7
Fixes 0052633527158b ("xfs: don't ignore runtime errors in xrep_iunlink_reload_next")
---
 fs/xfs/scrub/agheader_repair.c |    7 ++-----
 1 file changed, 2 insertions(+), 5 deletions(-)
fs/xfs/scrub/agheader_repair.c +2 -5
@@ -1081,12 +1081,9 @@ xrep_iunlink_reload_next(
 	if (VFS_I(ip)->i_nlink != 0) {
 		error = xrep_iunlink_store_next(ragi, agino, NULLAGINO);
 		if (error)
-			return error;
+			goto rele;
 
 		error = xrep_iunlink_store_prev(ragi, agino, LINKED_AGINO);
-		if (error)
-			return error;
-
 		goto rele;
 	}
 
@@ -1100,7 +1097,7 @@ xrep_iunlink_reload_next(
 	 */
 rele:
 	xchk_irele(sc, ip);
-	return 0;
+	return error;
 }
 
 /*
author maintainer
#344 lore raw

PATCH 341/547 xfs: rescan the AGs if incore delalloc counter is negative

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 47b1e941bb55f735d82ba2649412260da78b98f8 upstream.

LOLLM complains that percpu_counter_sum can return a negative number but we instead misinterpret that into a huge unsigned value and do bad things to fdblocks. It shouldn't do that, so let's add a retry loop and an attempt to freeze the filesystem to (hopefully) zero out the incore delalloc counter. It probably won't work, but at least failing the repair beats doing the wrong thing.

Fixes 75efa57d0bf5fc ("xfs: add online scrub for superblock counters")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/fscounters.c |   17 +++++++++++++++--
 1 file changed, 15 insertions(+), 2 deletions(-)
fs/xfs/scrub/fscounters.c +15 -2
@@ -297,7 +297,7 @@ xchk_fscount_aggregate_agcounts(
 {
 	struct xfs_mount	*mp = sc->mp;
 	struct xfs_perag	*pag = NULL;
-	uint64_t		delayed;
+	int64_t			delayed;
 	int			tries = 8;
 	int			error = 0;
 
@@ -359,6 +359,11 @@ retry:
 	 * of the computation.
 	 */
 	delayed = percpu_counter_sum(&mp->m_delalloc_blks);
+	if (delayed < 0) {
+		ASSERT(delayed >= 0);
+		xchk_set_incomplete(sc);
+		return -EFSCORRUPTED;
+	}
 	fsc->fdblocks -= delayed;
 
 	trace_xchk_fscounters_calc(mp, fsc->icount, fsc->ifree, fsc->fdblocks,
@@ -412,6 +417,7 @@ xchk_fscount_count_frextents(
 {
 	struct xfs_mount	*mp = sc->mp;
 	struct xfs_rtgroup	*rtg = NULL;
+	int64_t			delayed;
 	int			error;
 
 	fsc->frextents = 0;
@@ -437,7 +443,14 @@ xchk_fscount_count_frextents(
 		}
 	}
 
-	fsc->frextents_delayed = percpu_counter_sum(&mp->m_delalloc_rtextents);
+	delayed = percpu_counter_sum(&mp->m_delalloc_rtextents);
+	if (delayed < 0) {
+		ASSERT(delayed >= 0);
+		xchk_set_incomplete(sc);
+		return -EFSCORRUPTED;
+	}
+	fsc->frextents_delayed = delayed;
+
 	return 0;
 }
 #else
author maintainer
#345 lore raw

PATCH 342/547 xfs: update quota flags on secondary supers when metadir enabled

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 9d9ea6e6cbc4cb1a36fb79f873d97e1ac2fe1a64 upstream.

xfs/085 exposes an interesting bug when metadir is enabled, quotas are enabled via mount option, and the primary superblock crc fails validation:

Phase 1 - find and verify superblock... bad primary superblock - bad CRC in superblock !!!

attempting to find secondary superblock...
.found candidate secondary superblock...
verified secondary superblock...
quota accounting and enforcement flags lost

<snip>

Phase 3 - for each AG...
- scan and clear agi unlinked lists...
- process known inodes and perform inode discovery...
- agno = 0
- agno = 1
- agno = 2
unexpected regular file inode 16908418 with metadata flag will zap cleared inode 16908418
unexpected regular file inode 16908419 with metadata flag will zap cleared inode 16908419
unexpected regular file inode 16908420 with metadata flag will zap cleared inode 16908420
- agno = 3
- process newly discovered inodes...

Quota files have been created, but xfs_repair thinks that quotas aren't enabled and trashes the quota files. Looking at the filesystem reveals that the quota accounting flags were indeed persisted to the primary superblock but not the secondary:

 # xfs_db -c 'sb 0' -c 'print qflags' -c 'sb 1' -c 'print qflags' /dev/sdf
 Metadata corruption detected at 0x561c68436080, inode 0x81 dinode
 xfs_db: Failed to load metadir root directory, error 117
 Metadata corruption detected at 0x561c683f7c80, xfs_agf block 0x1/0x200
 xfs_db: cannot init perag data (117). Continuing anyway.
 Metadata CRC error detected at 0x561c6844d1b5, xfs_sb block 0x0/0x200
 qflags = 0x7cf
 qflags = 0

On a metadir filesystem, quota state is supposed to persist across mount cycles if the sysadmin doesn't provide any quota mount options. Therefore, any time we update the quota flags on a metadir filesystem, we should write the same change to the secondary supers so that xfs_repair will find the quota data if it ever has to restore from a secondary.

Fixes d5d9dd5b3026a8 ("xfs: persist quota flags with metadir")
---
 fs/xfs/xfs_mount.c |    9 ++++++++-
 fs/xfs/xfs_qm.c    |   36 +++++++++++++++++++++++++++++++++++-
 fs/xfs/xfs_quota.h |    9 +++++++++
 3 files changed, 52 insertions(+), 2 deletions(-)
fs/xfs/xfs_mount.c +8 -1
@@ -446,6 +446,8 @@ int
 xfs_mount_reset_sbqflags(
 	struct xfs_mount	*mp)
 {
+	int			error;
+
 	mp->m_qflags = 0;
 
 	/* It is OK to look at sb_qflags in the mount path without m_sb_lock. */
@@ -458,7 +460,12 @@ xfs_mount_reset_sbqflags(
 	if (!xfs_fs_writable(mp, SB_FREEZE_WRITE))
 		return 0;
 
-	return xfs_sync_sb(mp, false);
+	error = xfs_sync_sb(mp, false);
+	if (error)
+		return error;
+
+	xfs_qm_update_secondary_sb(mp);
+	return 0;
 }
 
 static const char *const xfs_free_pool_name[] = {
fs/xfs/xfs_qm.c +35 -1
@@ -694,6 +694,32 @@ xfs_qm_create_metadir_qinos(
 }
 
 /*
+ * For metadir filesystems, quota flag state persists across mounts, so update
+ * secondary superblocks in case xfs_repair ever has to recover the primary
+ * from a secondary.  growfs also updates backup supers so lock against that.
+ * Note that the secondary backups are opportunistic, so we log but do not
+ * return write errors.
+ */
+void
+__xfs_qm_update_secondary_sb(
+	struct xfs_mount	*mp,
+	const char		*func)
+{
+	int			error;
+
+	if (!xfs_has_metadir(mp))
+		return;
+
+	mutex_lock(&mp->m_growlock);
+	error = xfs_update_secondary_sbs(mp);
+	mutex_unlock(&mp->m_growlock);
+
+	if (error)
+		xfs_alert(mp, "%s: Secondary super update failed, err=%d!",
+				func, error);
+}
+
+/*
  * Add QUOTABIT to sb_versionnum and initialize qflags in preparation for
  * creating quota files on a metadir filesystem.
  */
@@ -718,7 +744,12 @@ xfs_qm_prep_metadir_sb(
 	spin_unlock(&mp->m_sb_lock);
 	xfs_log_sb(tp);
 
-	return xfs_trans_commit(tp);
+	error = xfs_trans_commit(tp);
+	if (error)
+		return error;
+
+	xfs_qm_update_secondary_sb(mp);
+	return 0;
 }
 
 /*
@@ -1683,6 +1714,9 @@ xfs_qm_mount_quotas(
 			ASSERT(!(XFS_IS_QUOTA_ON(mp)));
 			xfs_alert(mp, "%s: Superblock update failed!",
 				__func__);
+		} else {
+			/* Primary update succeeded, try to write secondary */
+			xfs_qm_update_secondary_sb(mp);
 		}
 	}
 
fs/xfs/xfs_quota.h +9 -0
@@ -151,6 +151,8 @@ void xfs_dqtrx_hook_setup(struct xfs_dqt
 		xfs_trans_mod_dquot((tp), (dqp), (field), (delta))
 # endif /* CONFIG_XFS_LIVE_HOOKS */
 
+void __xfs_qm_update_secondary_sb(struct xfs_mount *mp,
+		const char *func);
 #else
 static inline int
 xfs_qm_vop_dqalloc(struct xfs_inode *ip, kuid_t kuid, kgid_t kgid,
@@ -216,8 +218,15 @@ static inline int xfs_quota_reserve_blkr
 #  define xfs_dqtrx_hook_disable()		((void)0)
 # endif /* CONFIG_XFS_LIVE_HOOKS */
 
+static inline void __xfs_qm_update_secondary_sb(struct xfs_mount *mp,
+		const char *func)
+{
+}
 #endif /* CONFIG_XFS_QUOTA */
 
+#define xfs_qm_update_secondary_sb(mp) \
+	__xfs_qm_update_secondary_sb((mp), __func__)
+
 static inline void
 xfs_quota_unreserve_blkres(struct xfs_inode *ip, uint64_t blocks)
 {
author maintainer
#346 lore raw

PATCH 343/547 xfs: abort directory tree repair whenever dl->aborted is set

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 4582327e7068194d55941b49dd66be211b9e3f90 upstream.

LOLLM observed that if the live update hooks for the directory tree repair code ever fail, they'll set dl->aborted, but then the main repair code path won't check it to exit early. This can cause incorrect repairs, so let's check for hook errors and abort the repair.

Fixes 3f31406aef493b ("xfs: fix corruptions in the directory tree")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/dirtree_repair.c |    9 +++++++++
 1 file changed, 9 insertions(+)
fs/xfs/scrub/dirtree_repair.c +9 -0
@@ -575,6 +575,8 @@ xrep_dirtree_delete_path(
 
 	if (!error && dl->stale)
 		error = -ESTALE;
+	if (!error && dl->aborted)
+		error = -EIO;
 	return error;
 }
 
@@ -720,6 +722,11 @@ xrep_dirtree_adopt(
 		error = -ESTALE;
 		goto out_trans;
 	}
+	if (dl->aborted) {
+		mutex_unlock(&dl->lock);
+		error = -EIO;
+		goto out_trans;
+	}
 	error = xrep_dirtree_create_adoption_path(dl);
 	mutex_unlock(&dl->lock);
 	if (error)
@@ -780,6 +787,8 @@ xrep_dirtree_move_to_orphanage(
 
 	if (!error && dl->stale)
 		error = -ESTALE;
+	if (!error && dl->aborted)
+		error = -EIO;
 	return error;
 }
 
author maintainer
#347 lore raw

PATCH 344/547 xfs: always forget cached ACLs if the attr fork swap succeeds

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 41ee987f53785b9443388a756912b1a0fe3c9592 upstream.

LOLLM complains that xrep_xattr_rebuild_tree omits the xfs_forget_acl call if the attr fork swap succeeds (and hence the acls might have changed) but reaping the old attr fork fails. Fix it so that we always purge the cached acls if the swap succeeds, even if subsequent steps do not. This avoids some cache coherency problems with access controls.

Fixes e47dcf113ae348 ("xfs: repair extended attributes")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/attr_repair.c |    6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
fs/xfs/scrub/attr_repair.c +3 -3
@@ -1491,7 +1491,7 @@ xrep_xattr_rebuild_tree(
 
 	error = xrep_xattr_reset_tempfile_fork(sc);
 	if (error)
-		return error;
+		goto forget_acls;
 
 	/*
 	 * Roll to get a transaction without any inodes joined to it.  Then we
@@ -1500,7 +1500,7 @@ xrep_xattr_rebuild_tree(
 	 */
 	error = xfs_trans_roll(&sc->tp);
 	if (error)
-		return error;
+		goto forget_acls;
 
 	xrep_tempfile_iunlock(sc);
 	xrep_tempfile_iounlock(sc);
@@ -1509,7 +1509,7 @@ forget_acls:
 	/* Invalidate cached ACLs now that we've reloaded all the xattrs. */
 	xfs_forget_acl(VFS_I(sc->ip), SGI_ACL_FILE);
 	xfs_forget_acl(VFS_I(sc->ip), SGI_ACL_DEFAULT);
-	return 0;
+	return error;
 }
 
 /* Tear down all the incore scan stuff we created. */
author maintainer
#348 lore raw

PATCH 345/547 xfs: always report inode repair setup failures

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit ce9098338a7e1a77246684242d10779fc4d4a539 upstream.

LOLLM noticed that xchk_setup_inode silently discards errors being returned by xrep_setup_inode. Fix that, and fix the stub macro so that it actually "returns" a value.

Fixes 2d295fe65776d1 ("xfs: repair inode records")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/inode.c  |    2 +-
 fs/xfs/scrub/repair.h |    2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
fs/xfs/scrub/inode.c +1 -1
@@ -212,7 +212,7 @@ xchk_setup_inode(
 	 * make repairs to the ondisk inode buffer.
 	 */
 	if (xchk_could_repair(sc))
-		xrep_setup_inode(sc, &imap);
+		return xrep_setup_inode(sc, &imap);
 	return 0;
 
 out_cancel:
fs/xfs/scrub/repair.h +1 -1
@@ -239,7 +239,7 @@ xrep_setup_nothing(
 #define xrep_setup_rtrmapbt		xrep_setup_nothing
 #define xrep_setup_rtrefcountbt		xrep_setup_nothing
 
-#define xrep_setup_inode(sc, imap)	((void)0)
+#define xrep_setup_inode(sc, imap)	(0)
 
 static inline int xrep_setup_symlink(struct xfs_scrub *sc, unsigned int *x)
 {
author maintainer
#349 lore raw

PATCH 346/547 xfs: always report scrub errors in tracepoints

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 1ccc8f553d885d49c1bfe141ea1f331511940b3a upstream.

LOLLM complains that the error processing functions in scrub will sometimes zero out *error before recording a tracepoint. This makes diagnosing problems harder, so let's fix that.

Fixes 4700d22980d459 ("xfs: create helpers to record and deal with scrub problems")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/btree.c   |    8 +++++++-
 fs/xfs/scrub/common.c  |    7 +++++--
 fs/xfs/scrub/dabtree.c |    6 +++++-
 3 files changed, 17 insertions(+), 4 deletions(-)
fs/xfs/scrub/btree.c +7 -1
@@ -46,8 +46,14 @@ __xchk_btree_process_error(
 	case -ENODATA:
 		/* Note the badness but don't abort. */
 		sc->sm->sm_flags |= errflag;
+		if (cur->bc_ops->type == XFS_BTREE_TYPE_INODE)
+			trace_xchk_ifork_btree_op_error(sc, cur, level,
+					*error, ret_ip);
+		else
+			trace_xchk_btree_op_error(sc, cur, level,
+					*error, ret_ip);
 		*error = 0;
-		fallthrough;
+		break;
 	default:
 		if (cur->bc_ops->type == XFS_BTREE_TYPE_INODE)
 			trace_xchk_ifork_btree_op_error(sc, cur, level,
fs/xfs/scrub/common.c +5 -2
@@ -107,8 +107,9 @@ __xchk_process_error(
 	case -ENODATA:
 		/* Note the badness but don't abort. */
 		sc->sm->sm_flags |= errflag;
+		trace_xchk_op_error(sc, agno, bno, *error, ret_ip);
 		*error = 0;
-		fallthrough;
+		break;
 	default:
 		trace_xchk_op_error(sc, agno, bno, *error, ret_ip);
 		break;
@@ -183,8 +184,10 @@ __xchk_fblock_process_error(
 	case -ENODATA:
 		/* Note the badness but don't abort. */
 		sc->sm->sm_flags |= errflag;
+		trace_xchk_file_op_error(sc, whichfork, offset, *error,
+				ret_ip);
 		*error = 0;
-		fallthrough;
+		break;
 	default:
 		trace_xchk_file_op_error(sc, whichfork, offset, *error,
 				ret_ip);
fs/xfs/scrub/dabtree.c +5 -1
@@ -49,8 +49,12 @@ xchk_da_process_error(
 	case -ENODATA:
 		/* Note the badness but don't abort. */
 		sc->sm->sm_flags |= XFS_SCRUB_OFLAG_CORRUPT;
+		trace_xchk_file_op_error(sc, ds->dargs.whichfork,
+				xfs_dir2_da_to_db(ds->dargs.geo,
+					ds->state->path.blk[level].blkno),
+				*error, __return_address);
 		*error = 0;
-		fallthrough;
+		break;
 	default:
 		trace_xchk_file_op_error(sc, ds->dargs.whichfork,
 				xfs_dir2_da_to_db(ds->dargs.geo,
author maintainer
#350 lore raw

PATCH 347/547 xfs: always zero the whole shortform header when zeroing attr fork

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 52aa50cea408e27454d206cccecbe4f694a6c1e1 upstream.

LOLLM noticed that xrep_xattr_fork_remove can decide to reset the attr fork contents to an empty shortform header, but then fails to zero the padding byte in the header. Fix that.

Fixes e47dcf113ae348 ("xfs: repair extended attributes")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/attr_repair.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/xfs/scrub/attr_repair.c +1 -1
@@ -970,7 +970,7 @@ xrep_xattr_fork_remove(
 		ifp->if_format = XFS_DINODE_FMT_LOCAL;
 		hdr = xfs_idata_realloc(ip, (int)sizeof(*hdr) - ifp->if_bytes,
 				XFS_ATTR_FORK);
-		hdr->count = 0;
+		memset(hdr, 0, sizeof(*hdr));
 		hdr->totsize = cpu_to_be16(sizeof(*hdr));
 		xfs_trans_log_inode(sc->tp, ip,
 				XFS_ILOG_CORE | XFS_ILOG_ADATA);
author maintainer
#351 lore raw

PATCH 348/547 xfs: bound da-node entry count against the correct geometry

In reply to Greg Kroah-Hartman

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

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

From: Aldo Ariel Panzardo <[email protected]>

commit 3df5e5aaa3bc0913236c48ab29b7df3a785aa29f upstream.

xfs_da3_node_verify() bounds the node entry count against the larger of the directory and attribute geometries because, as a buffer verifier, it cannot tell whether the block belongs to the directory or the attribute tree. When the directory block size exceeds the fs block size (e.g. mkfs.xfs -n size=64k -b size=4k), an attribute node buffer is a single fs block that holds only m_attr_geo->node_ents entries, yet a crafted attr node may claim a count up to m_dir_geo->node_ents and still pass the verifier.

xfs_da3_node_lookup_int() then indexes btree[] up to that count during its binary search -- an out-of-bounds read via getxattr/listxattr on a mounted crafted image.

The buffer verifier is the wrong place to tighten this: it has no fork context, and the transaction-less read path used by getxattr does not run xfs_da3_node_set_type() either. xfs_da3_node_lookup_int(), on the other hand, always runs on that path and holds args->geo, the geometry of the fork actually being searched. Bound the entry count against args->geo->node_ents there, before walking the entries.

Fixes 7ab610f9e0f1 ("xfs: move node entry counts to xfs_da_geometry")
---
 fs/xfs/libxfs/xfs_da_btree.c |   14 ++++++++++++++
 1 file changed, 14 insertions(+)
fs/xfs/libxfs/xfs_da_btree.c +14 -0
@@ -1787,6 +1787,20 @@ xfs_da3_node_lookup_int(
 		} else
 			expected_level--;
 
+		/*
+		 * The node verifier cannot tell whether this block belongs to
+		 * the directory or the attribute tree, so it only bounds the
+		 * entry count against the larger of the two geometries.  Here
+		 * args->geo is the geometry of the fork we are actually
+		 * searching, so reject a count that would walk btree[] off the
+		 * end of this node buffer.
+		 */
+		if (nodehdr.count > args->geo->node_ents) {
+			xfs_buf_mark_corrupt(blk->bp);
+			xfs_da_mark_sick(args);
+			return -EFSCORRUPTED;
+		}
+
 		max = nodehdr.count;
 		blk->hashval = be32_to_cpu(btree[max - 1].hashval);
 
author maintainer
#352 lore raw

PATCH 349/547 xfs: bound inode fork length against the fork size during log recovery

In reply to Greg Kroah-Hartman

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

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

From: Aldo Ariel Panzardo <[email protected]>

commit 9232301894a06e664d8de2da97175cf98419bd16 upstream.

xlog_recover_inode_commit_pass2() copies an inode log item's data/attr fork region into the inode buffer using the on-log region length without bounding it against the fork capacity, e.g.:

	len = item->ri_buf[2].iov_len;
	memcpy(XFS_DFORK_DPTR(dip), src, len);

The only guard is an ASSERT, which is a no-op on production kernels (CONFIG_XFS_DEBUG off), and xfs_dinode_verify() runs only after the copy. A crafted image with a dirty log can therefore drive a heap out-of-bounds write at mount time. The XFS_ILOG_DBROOT sibling already passes XFS_DFORK_DSIZE as a bound; the DDATA/DEXT and ADATA/AEXT memcpy paths did not.

Bound each logged fork region against the destination fork size before copying it, and reject the log item with -EFSCORRUPTED when it does not fit. Because the recovered inode is only verified after the fork data has been copied in, the checks are done up front, before any memcpy into the on-disk inode.

Fixes 658fa68b6f34 ("xfs: refactor log recovery inode item dispatch for pass2 commit functions")
---
 fs/xfs/xfs_inode_item_recover.c |   20 +++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)
fs/xfs/xfs_inode_item_recover.c +19 -1
@@ -507,6 +507,25 @@ xlog_recover_inode_commit_pass2(
 	ASSERT(!(fields & XFS_ILOG_DFORK) ||
 	       (len == xlog_calc_iovec_len(in_f->ilf_dsize)));
 
+	/*
+	 * The recovered inode is verified only after the fork data has been
+	 * copied into it, so bound each logged fork region against the size of
+	 * its fork now, before the memcpy below can overrun the on-disk inode.
+	 * The DBROOT/ABROOT cases already bound their copies against the fork
+	 * size.
+	 */
+	if ((fields & (XFS_ILOG_DDATA | XFS_ILOG_DEXT)) &&
+	    item->ri_buf[2].iov_len > XFS_DFORK_DSIZE(dip, mp)) {
+		error = -EFSCORRUPTED;
+		goto out_release;
+	}
+	if ((fields & (XFS_ILOG_ADATA | XFS_ILOG_AEXT)) &&
+	    item->ri_buf[(fields & XFS_ILOG_DFORK) ? 3 : 2].iov_len >
+	    XFS_DFORK_ASIZE(dip, mp)) {
+		error = -EFSCORRUPTED;
+		goto out_release;
+	}
+
 	switch (fields & XFS_ILOG_DFORK) {
 	case XFS_ILOG_DDATA:
 	case XFS_ILOG_DEXT:
@@ -546,7 +565,6 @@ xlog_recover_inode_commit_pass2(
 		case XFS_ILOG_ADATA:
 		case XFS_ILOG_AEXT:
 			dest = XFS_DFORK_APTR(dip);
-			ASSERT(len <= XFS_DFORK_ASIZE(dip, mp));
 			memcpy(dest, src, len);
 			break;
 
author maintainer
#353 lore raw

PATCH 350/547 xfs: check for fragments when full-extent sharing matches

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 95e213c1ddb40dfb0a8178ed35c9f29992a320e1 upstream.

LOLLM noticed that xchk_refcountbt_process_rmap_fragments returns early if there are enough rmap records that overlap the space referenced by a refcountbt record to match the refcount in that refcountbt record. Unfortunately, it never checks the fragment list in this case, so it won't find the discrepancy between the rmap and refcount btrees.

Fixes dbde19da963706 ("xfs: cross-reference the rmapbt data with the refcountbt")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/refcount.c |    5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
fs/xfs/scrub/refcount.c +4 -1
@@ -173,8 +173,11 @@ xchk_refcountbt_process_rmap_fragments(
 	xfs_nlink_t			target_nr;
 
 	target_nr = refchk->refcount - refchk->seen;
-	if (target_nr == 0)
+	if (target_nr == 0) {
+		if (!list_empty(&refchk->fragments))
+			refchk->seen = 0;
 		return;
+	}
 
 	/*
 	 * There are (refchk->rc.rc_refcount - refchk->nr refcount)
author maintainer
#354 lore raw

PATCH 351/547 xfs: check for termination during rmap btree walk

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 1fc241cdeab276dc6c3ec14840faa706ed7712ff upstream.

LOLLM complains that we should check for a fatal signal *every* time we walk a record in the rmap btree as part of rebuilding the free space btrees. Fix that, and improve responsiveness to ^C of xfs_scrub.

Fixes 4bdfd7d15747b1 ("xfs: repair free space btrees")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/alloc_repair.c |    5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
fs/xfs/scrub/alloc_repair.c +4 -1
@@ -227,7 +227,10 @@ xrep_abt_walk_rmap(
 	void				*priv)
 {
 	struct xrep_abt			*ra = priv;
-	int				error;
+	int				error = 0;
+
+	if (xchk_should_terminate(ra->sc, &error))
+		return error;
 
 	/* Record all the OWN_AG blocks... */
 	if (rec->rm_owner == XFS_RMAP_OWN_AG) {
author maintainer
#355 lore raw

PATCH 352/547 xfs: clarify various parts of the bitmap API

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 00f32fdf54983371d39162efef7df693e2842ffb upstream.

LOLLM pointed out some underspecified parts of the xbitmap{32,64} API. Specifically, the behavior of set/clear/test functions when the length parameter is zero is not well defined, nor is what happens when someone tries to disunion a bitmap with itself. None of these situations are expected, but we'll define zero-length set and clear to be nops, and the rest to be checked by assertions.

Fixes 6ece924b952262 ("xfs: create separate structures and code for u32 bitmaps")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/bitmap.c |   20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)
fs/xfs/scrub/bitmap.c +20 -0
@@ -77,6 +77,9 @@ xbitmap64_clear(
 	struct xbitmap64_node	*new_bn;
 	uint64_t		last = start + len - 1;
 
+	if (!len)
+		return 0;
+
 	while ((bn = xbitmap64_tree_iter_first(&bitmap->xb_root, start, last))) {
 		if (bn->bn_start < start && bn->bn_last > last) {
 			uint64_t	old_last = bn->bn_last;
@@ -127,6 +130,9 @@ xbitmap64_set(
 	uint64_t		last = start + len - 1;
 	int			error;
 
+	if (!len)
+		return 0;
+
 	/* Is this whole range already set? */
 	left = xbitmap64_tree_iter_first(&bitmap->xb_root, start, last);
 	if (left && left->bn_start <= start && left->bn_last >= last)
@@ -223,6 +229,8 @@ xbitmap64_disunion(
 	struct xbitmap64_node	*bn;
 	int			error;
 
+	ASSERT(bitmap != sub);
+
 	if (xbitmap64_empty(bitmap) || xbitmap64_empty(sub))
 		return 0;
 
@@ -287,6 +295,8 @@ xbitmap64_test(
 	struct xbitmap64_node	*bn;
 	uint64_t		last = start + *len - 1;
 
+	ASSERT(*len > 0);
+
 	bn = xbitmap64_tree_iter_first(&bitmap->xb_root, start, last);
 	if (!bn)
 		return false;
@@ -357,6 +367,9 @@ xbitmap32_clear(
 	struct xbitmap32_node	*new_bn;
 	uint32_t		last = start + len - 1;
 
+	if (!len)
+		return 0;
+
 	while ((bn = xbitmap32_tree_iter_first(&bitmap->xb_root, start, last))) {
 		if (bn->bn_start < start && bn->bn_last > last) {
 			uint32_t	old_last = bn->bn_last;
@@ -407,6 +420,9 @@ xbitmap32_set(
 	uint32_t		last = start + len - 1;
 	int			error;
 
+	if (!len)
+		return 0;
+
 	/* Is this whole range already set? */
 	left = xbitmap32_tree_iter_first(&bitmap->xb_root, start, last);
 	if (left && left->bn_start <= start && left->bn_last >= last)
@@ -503,6 +519,8 @@ xbitmap32_disunion(
 	struct xbitmap32_node	*bn;
 	int			error;
 
+	ASSERT(bitmap != sub);
+
 	if (xbitmap32_empty(bitmap) || xbitmap32_empty(sub))
 		return 0;
 
@@ -567,6 +585,8 @@ xbitmap32_test(
 	struct xbitmap32_node	*bn;
 	uint32_t		last = start + *len - 1;
 
+	ASSERT(*len > 0);
+
 	bn = xbitmap32_tree_iter_first(&bitmap->xb_root, start, last);
 	if (!bn)
 		return false;
author maintainer
#356 lore raw

PATCH 353/547 xfs: clear set[ug]id mode bits when zapping attr fork

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit eb20a959760c21e3547cd811d0d9b0b29df98959 upstream.

LOLLM observes that zapping a file's attr fork could result in ACLs being removed from the file. Because we have no idea what we're deleting, we should clear the setuid and setgid bits in addition to the access mode bits so that nobody can access the file.

Fixes e744cef2060559 ("xfs: zap broken inode forks")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/inode_repair.c |    7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
fs/xfs/scrub/inode_repair.c +6 -1
@@ -1307,7 +1307,12 @@ xrep_dinode_zap_afork(
 	 */
 	if (dip->di_format != XFS_DINODE_FMT_BTREE)
 		dip->di_forkoff = 0;
-	dip->di_mode = cpu_to_be16(mode & ~0777);
+
+	/*
+	 * Zapping the attr fork could remove ACLs, so we clear suid/sgid and
+	 * all access mode bits.
+	 */
+	dip->di_mode = cpu_to_be16(mode & ~(S_ISUID | S_ISGID | 0777));
 	dip->di_uid = 0;
 	dip->di_gid = 0;
 }
author maintainer
#357 lore raw

PATCH 354/547 xfs: complain loudly when dirtree checker finds broken links

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit e09438cab72c2c6a32665829d4186155346bfee8 upstream.

LOLLM observed that the directory tree walk code bails out if it finds broken parent pointers along the way. However, it flattens the return code to zero, which means that we can end up in the repair code having not completed the scan. We should never proceed with a repair in this state, so let's mark the scrub incomplete and exit.

Fixes 928b721a11789a ("xfs: teach online scrub to find directory tree structure problems")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/dirtree.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
fs/xfs/scrub/dirtree.c +3 -1
@@ -860,7 +860,8 @@ xchk_dirtree_find_paths_to_root(
 				 * A parent pointer of @sc->ip is bad, don't
 				 * bother continuing.
 				 */
-				break;
+				xchk_set_incomplete(sc);
+				return error;
 			}
 			if (error == -ESTALE) {
 				/* This had better be an invalidation. */
@@ -981,6 +982,7 @@ xchk_dirtree(
 		 * parent pointers are corrupt; this scan cannot be completed
 		 * without full information.
 		 */
+		xchk_set_incomplete(sc);
 		xchk_ip_xref_set_corrupt(sc, sc->ip);
 		error = 0;
 		goto out_scanlock;
author maintainer
#358 lore raw

PATCH 355/547 xfs: dont allow sm_agno for non-group metadir path checking

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 20c5a56bc4f2329872d21561e4a2d4b8576004c9 upstream.

LOLLM noticed that the metadata directory tree path checker accepts non-zero values in the sm_agno field for non-group metadata. Make that case return -EINVAL.

Fixes a74923333d9c3b ("xfs: scrub metadir paths for rtgroup metadata")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/metapath.c |    6 ++++++
 1 file changed, 6 insertions(+)
fs/xfs/scrub/metapath.c +6 -0
@@ -129,6 +129,8 @@ static int
 xchk_setup_metapath_rtdir(
 	struct xfs_scrub	*sc)
 {
+	if (sc->sm->sm_agno)
+		return -EINVAL;
 	if (!sc->mp->m_rtdirip)
 		return -ENOENT;
 
@@ -176,6 +178,8 @@ xchk_setup_metapath_quotadir(
 {
 	struct xfs_quotainfo	*qi = sc->mp->m_quotainfo;
 
+	if (sc->sm->sm_agno)
+		return -EINVAL;
 	if (!qi || !qi->qi_dirip)
 		return -ENOENT;
 
@@ -192,6 +196,8 @@ xchk_setup_metapath_dqinode(
 	struct xfs_quotainfo	*qi = sc->mp->m_quotainfo;
 	struct xfs_inode	*ip = NULL;
 
+	if (sc->sm->sm_agno)
+		return -EINVAL;
 	if (!qi)
 		return -ENOENT;
 
author maintainer
#359 lore raw

PATCH 356/547 xfs: dont clear COWEXTSIZE on directories on reflink filesystems

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 3978b1f3109dfd5c648442bb040f9abd58608226 upstream.

LOLLM noticed that xrep_dinode_flags clears the COWEXTSIZE flag unnecessarily on directories on reflink filesystems. Directories just pass the hint along to new children, so it's valid to leave the flag set.

Fixes 2d295fe65776d1 ("xfs: repair inode records")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/inode_repair.c |    2 ++
 1 file changed, 2 insertions(+)
fs/xfs/scrub/inode_repair.c +2 -0
@@ -563,6 +563,8 @@ xrep_dinode_flags(
 	 */
 	if (xfs_has_reflink(mp) && S_ISREG(mode))
 		flags2 |= XFS_DIFLAG2_REFLINK;
+	else if (xfs_has_reflink(mp) && S_ISDIR(mode))
+		flags2 &= ~XFS_DIFLAG2_REFLINK;
 	else
 		flags2 &= ~(XFS_DIFLAG2_REFLINK | XFS_DIFLAG2_COWEXTSIZE);
 	if (!xfs_has_bigtime(mp))
author maintainer
#360 lore raw

PATCH 357/547 xfs: dont overrun incore inode when cleaning attr forks

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit c28b4b48deac17749ed1ebe4289a4ba73541ddc6 upstream.

LOLLM noticed that xrep_dinode_check_afork doesn't check for a di_forkoff value that is so large that the attr fork would begin after the end of the inode space. This causes afork_{ptr,size} to be nonsense. What we really ought to do here is zap the attr fork.

Fixes e744cef2060559 ("xfs: zap broken inode forks")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/inode_repair.c |    2 ++
 1 file changed, 2 insertions(+)
fs/xfs/scrub/inode_repair.c +2 -0
@@ -1243,6 +1243,8 @@ xrep_dinode_check_afork(
 	if (XFS_DFORK_BOFF(dip) == 0)
 		return dip->di_aformat != XFS_DINODE_FMT_EXTENTS ||
 		       xfs_dfork_attr_extents(dip) != 0;
+	if (XFS_DFORK_BOFF(dip) >= XFS_LITINO(sc->mp))
+		return true;
 
 	afork_size = XFS_DFORK_SIZE(dip, sc->mp, XFS_ATTR_FORK);
 	afork_ptr = XFS_DFORK_PTR(dip, XFS_ATTR_FORK);
author maintainer
#361 lore raw

PATCH 358/547 xfs: dont queue rmap update twice when reaping a fork

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 219ff8a734d8438e24eb346a847c9b1ad9b7ab5d upstream.

LOLLM noticed that xrep_reap_bmapi_iter calls xfs_bmap_unmap_extent and xfs_rmap_unmap_extent to remove a mapping from a file fork and its reverse mapping. However, xfs_bmap_del_extent_real also queues a deferred rmap removal log item, which means that we incorrectly queue two rmap removal operations. Fix that by removing the extra call and updating the comment to mention this subtlety that I forgot, having written the code. :P

Fixes 5befb047b9f4de ("xfs: add the ability to reap entire inode forks")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/reap.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/xfs/scrub/reap.c +2 -2
@@ -1480,12 +1480,12 @@ xrep_reap_bmapi_iter(
 		/*
 		 * t0: Schedule removal of the mapping from the fork.  We use
 		 * deferred log intents in this function to control the exact
-		 * sequence of metadata updates.
+		 * sequence of metadata updates.  The BUI queues a RUI to
+		 * remove the reverse mapping.
 		 */
 		xfs_bmap_unmap_extent(sc->tp, rs->ip, rs->whichfork, imap);
 		xfs_trans_mod_dquot_byino(sc->tp, rs->ip, XFS_TRANS_DQ_BCOUNT,
 				-(int64_t)imap->br_blockcount);
-		xfs_rmap_unmap_extent(sc->tp, rs->ip, rs->whichfork, imap);
 		return 0;
 	}
 
author maintainer
#362 lore raw

PATCH 359/547 xfs: dont rescan ifree and icount when frozen

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 18028768415e3c05ab7edb22d740e2f4dc52836a upstream.

LOLLM points out that it's pointless to rescan the AGs if we've already frozen the filesystem because there won't be any more perturbations. Fix this to mark the scan incomplete and exit.

Fixes 75efa57d0bf5fc ("xfs: add online scrub for superblock counters")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/fscounters.c |    5 +++++
 1 file changed, 5 insertions(+)
fs/xfs/scrub/fscounters.c +5 -0
@@ -384,6 +384,11 @@ retry:
 	 * to maintain ifree <= icount before giving up.
 	 */
 	if (fsc->ifree > fsc->icount) {
+		if (fsc->frozen) {
+			xchk_set_incomplete(sc);
+			return -EFSCORRUPTED;
+		}
+
 		if (tries--)
 			goto retry;
 		return -EDEADLOCK;
author maintainer
#363 lore raw

PATCH 360/547 xfs: dont scan across metadata/regular directory trees for dirents

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 03ce4ca43c00394364493865f417d646e252bac2 upstream.

LOLLM points out that the directory repair code should never scan files in the regular directory tree when fixing a metadata directory and vice-versa. Amend the scan predicate to check this condition.

Fixes 4f3d4dd1b04b2b ("xfs: define the on-disk format for the metadir feature")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/dir_repair.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
fs/xfs/scrub/dir_repair.c +3 -1
@@ -1189,7 +1189,9 @@ xrep_dir_want_scan(
 	struct xrep_dir		*rd,
 	const struct xfs_inode	*ip)
 {
-	return ip != rd->sc->ip && !xrep_is_tempfile(ip);
+	return ip != rd->sc->ip &&
+	       xfs_is_metadir_inode(ip) == xfs_is_metadir_inode(rd->sc->ip) &&
+	       !xrep_is_tempfile(ip);
 }
 
 /*
author maintainer
#364 lore raw

PATCH 361/547 xfs: dont set a metadata directorys parent to sb_rootino

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit c9f98b0f4f70c8cfd617dc2886bf2fc0a36ab9da upstream.

LOLLM complains that it's weird to set a metadata directory's parent inumber to the regular directory tree root. Fix this even if nobody's ever going to notice this because metadata path lookups don't access dotdot.

Fixes 4f3d4dd1b04b2b ("xfs: define the on-disk format for the metadir feature")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/dir_repair.c |    5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
fs/xfs/scrub/dir_repair.c +4 -1
@@ -1674,7 +1674,10 @@ xrep_dir_swap(
 	ASSERT(sc->ilock_flags & XFS_ILOCK_EXCL);
 	if (rd->pscan.parent_ino == NULLFSINO) {
 		rd->needs_adoption = true;
-		rd->pscan.parent_ino = rd->sc->mp->m_sb.sb_rootino;
+		if (xfs_is_metadir_inode(rd->sc->ip))
+			rd->pscan.parent_ino = rd->sc->mp->m_sb.sb_metadirino;
+		else
+			rd->pscan.parent_ino = rd->sc->mp->m_sb.sb_rootino;
 	}
 
 	/*
author maintainer
#365 lore raw

PATCH 362/547 xfs: dont subtract excess usage twice when computing agf_btreeblks

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 4439b626fb5104204952aa2f169451688fb6be26 upstream.

LOLLM noticed that the free space btree repair code calculates agf_btreeblks from the number of blocks we wrote to rebuild the free space btrees (minus the roots). That's correct. However, it observes that we subtract the "excess" reservation, which is not correct. Fix this accounting problem.

Fixes 4bdfd7d15747b1 ("xfs: repair free space btrees")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/alloc_repair.c |    6 +-----
 fs/xfs/scrub/newbt.c        |   13 -------------
 fs/xfs/scrub/newbt.h        |    1 -
 3 files changed, 1 insertion(+), 19 deletions(-)
fs/xfs/scrub/alloc_repair.c +1 -5
@@ -663,15 +663,11 @@ xrep_abt_reset_counters(
 
 	/*
 	 * Compute the contribution to agf_btreeblks for the new free space
-	 * btrees.  This is the computed btree size minus anything we didn't
-	 * use.
+	 * btrees.  This is the computed btree size minus the root block.
 	 */
 	freesp_btreeblks += ra->new_bnobt.bload.nr_blocks - 1;
 	freesp_btreeblks += ra->new_cntbt.bload.nr_blocks - 1;
 
-	freesp_btreeblks -= xrep_newbt_unused_blocks(&ra->new_bnobt);
-	freesp_btreeblks -= xrep_newbt_unused_blocks(&ra->new_cntbt);
-
 	/*
 	 * The AGF header contains extra information related to the free space
 	 * btrees, so we must update those fields here.
fs/xfs/scrub/newbt.c +0 -13
@@ -598,16 +598,3 @@ xrep_newbt_claim_block(
 	/* Relog all the EFIs. */
 	return xrep_defer_finish(xnr->sc);
 }
-
-/* How many reserved blocks are unused? */
-unsigned int
-xrep_newbt_unused_blocks(
-	struct xrep_newbt	*xnr)
-{
-	struct xrep_newbt_resv	*resv;
-	unsigned int		unused = 0;
-
-	list_for_each_entry(resv, &xnr->resv_list, list)
-		unused += resv->len - resv->used;
-	return unused;
-}
fs/xfs/scrub/newbt.h +0 -1
@@ -71,6 +71,5 @@ void xrep_newbt_cancel(struct xrep_newbt
 int xrep_newbt_commit(struct xrep_newbt *xnr);
 int xrep_newbt_claim_block(struct xfs_btree_cur *cur, struct xrep_newbt *xnr,
 		union xfs_btree_ptr *ptr);
-unsigned int xrep_newbt_unused_blocks(struct xrep_newbt *xnr);
 
 #endif /* __XFS_SCRUB_NEWBT_H__ */
author maintainer
#366 lore raw

PATCH 363/547 xfs: dont try to repair rtsummary if the summary file isnt computed

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 6e82b7641889ad0198f3bf17a5e4c6fe7aab0850 upstream.

LOLLM observed that we can erroneously try to repair the rtsummary file if we've not yet computed its contents. That results in a corrupt summary file, so let's add a flag to track whether or not the incore data is complete.

Fixes abf039e2e4afde ("xfs: online repair of realtime summaries")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/rtsummary.c        |    9 ++++++++-
 fs/xfs/scrub/rtsummary.h        |    1 +
 fs/xfs/scrub/rtsummary_repair.c |    2 +-
 3 files changed, 10 insertions(+), 2 deletions(-)
fs/xfs/scrub/rtsummary.c +8 -1
@@ -212,13 +212,20 @@ xchk_rtsum_compute(
 {
 	struct xfs_mount	*mp = sc->mp;
 	struct xfs_rtgroup	*rtg = sc->sr.rtg;
+	struct xchk_rtsummary	*rts = sc->buf;
+	int			error;
 
 	/* If the bitmap size doesn't match the computed size, bail. */
 	if (XFS_FSB_TO_B(mp, xfs_rtbitmap_blockcount(mp)) !=
 	    rtg_bitmap(rtg)->i_disk_size)
 		return -EFSCORRUPTED;
 
-	return xfs_rtalloc_query_all(rtg, sc->tp, xchk_rtsum_record_free, sc);
+	error = xfs_rtalloc_query_all(rtg, sc->tp, xchk_rtsum_record_free, sc);
+	if (error)
+		return error;
+
+	rts->summary_computed = true;
+	return 0;
 }
 
 /* Compare the rtsummary file against the one we computed. */
fs/xfs/scrub/rtsummary.h +1 -0
@@ -17,6 +17,7 @@ struct xchk_rtsummary {
 	xfs_filblks_t		rsumblocks;
 	unsigned int		rsumlevels;
 	unsigned int		resblks;
+	bool			summary_computed;
 
 	/* suminfo position of xfile as we write buffers to disk. */
 	xfs_rtsumoff_t		prep_wordoff;
fs/xfs/scrub/rtsummary_repair.c +1 -1
@@ -122,7 +122,7 @@ xrep_rtsummary(
 		return -EOPNOTSUPP;
 
 	/* Walk away if we disagree on the size of the rt bitmap. */
-	if (rts->rbmblocks != mp->m_sb.sb_rbmblocks)
+	if (rts->rbmblocks != mp->m_sb.sb_rbmblocks || !rts->summary_computed)
 		return 0;
 
 	/* Make sure any problems with the fork are fixed. */
author maintainer
#367 lore raw

PATCH 364/547 xfs: dont try to scrub self-referential dirent in metapath checker

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 1e7337a3ecebab1bb2ba02187d88b94e5146e4f0 upstream.

LOLLM observes that the _ilock_both helper will loop forever trying to double-lock the same inode if mpath->dp == sc->ip. Callers are not supposed to call us with parent == child because that makes no sense. Trigger an assertion, mark the scan incomplete, and return IO error so that this fails noisily.

Fixes b3c03efa5972f0 ("xfs: check metadata directory file path connectivity")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/metapath.c |    7 +++++++
 1 file changed, 7 insertions(+)
fs/xfs/scrub/metapath.c +7 -0
@@ -325,6 +325,13 @@ xchk_metapath(
 		return 0;
 	}
 
+	/* Callers should not set the parent to the child. */
+	if (mpath->dp == sc->ip) {
+		ASSERT(mpath->dp != sc->ip);
+		xchk_set_incomplete(sc);
+		return -EIO;
+	}
+
 	xchk_trans_alloc_empty(sc);
 
 	error = xchk_metapath_ilock_both(mpath);
author maintainer
#368 lore raw

PATCH 365/547 xfs: fix correction of unwritten extents in quota file data fork

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 6f2792720673f569fa3e1f68181b9d6fd26802b5 upstream.

LOLLM noticed a couple of problems with the code that fixes unwritten mappings in the quota file's data fork: first, we should zero the ondisk contents as part of converting them to "unwritten" just in case we crash shortly after the conversion. Second, and more importantly, it noticed that we fail to resynchronize the iext tree cursor after modifying the iext tree. If the tree shape changes, we could be in a world of hurt. Third, we should force a quotacheck if we reset an ondisk dquot. Fix all issues.

Fixes a5b91555403e3a ("xfs: repair quotas")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/quota_repair.c |   25 +++++++++++++++++++++++--
 1 file changed, 23 insertions(+), 2 deletions(-)
fs/xfs/scrub/quota_repair.c +23 -2
@@ -416,7 +416,9 @@ xrep_quota_data_fork(
 	/* Check for data fork problems that apply only to quota files. */
 	max_dqid_off = XFS_DQ_ID_MAX / qi->qi_dqperchunk;
 	ifp = xfs_ifork_ptr(sc->ip, XFS_DATA_FORK);
-	for_each_xfs_iext(ifp, &icur, &irec) {
+	xfs_iext_first(ifp, &icur);
+
+	while (xfs_iext_get_extent(ifp, &icur, &irec)) {
 		if (isnullstartblock(irec.br_startblock)) {
 			error = -EFSCORRUPTED;
 			goto out;
@@ -440,16 +442,35 @@ xrep_quota_data_fork(
 
 			error = xfs_bmapi_write(sc->tp, sc->ip,
 					irec.br_startoff, irec.br_blockcount,
-					XFS_BMAPI_CONVERT, 0, &nrec, &nmap);
+					XFS_BMAPI_CONVERT | XFS_BMAPI_ZERO, 0,
+					&nrec, &nmap);
 			if (error)
 				goto out;
 			ASSERT(nrec.br_startoff == irec.br_startoff);
 			ASSERT(nrec.br_blockcount == irec.br_blockcount);
 
+			/*
+			 * We just zeroed the ondisk dquot, so counts could be
+			 * wrong.  Schedule a quotacheck to fix that.
+			 */
+			xrep_force_quotacheck(sc, dqtype);
 			error = xfs_defer_finish(&sc->tp);
 			if (error)
 				goto out;
+
+			/*
+			 * Set cursor to the next block past the extent we just
+			 * converted because bmapi write could have merged
+			 * records.
+			 */
+			if (!xfs_iext_lookup_extent(sc->ip, ifp,
+					irec.br_startoff + irec.br_blockcount,
+					&icur, &irec))
+				break;
+			continue;
 		}
+
+		xfs_iext_next(ifp, &icur);
 	}
 
 	if (!joined) {
author maintainer
#369 lore raw

PATCH 366/547 xfs: fix data fork block count check in xrep_inode_blockcounts

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 147f9f8300cb284923e08bb8a7b32ba9681c45ed upstream.

LOLLM notices that for non-reflink realtime files, the @count output of xchk_inode_count_blocks includes both the file blocks on the realtime volume and the bmap btree blocks on the data volume. Therefore, we must compare this value to rblocks + dblocks to avoid unnecessary failure.

Fixes 2d295fe65776d1 ("xfs: repair inode records")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/inode_repair.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/xfs/scrub/inode_repair.c +1 -1
@@ -1724,7 +1724,7 @@ xrep_inode_blockcounts(
 		 */
 		;
 	} else if (XFS_IS_REALTIME_INODE(sc->ip)) {
-		if (count >= sc->mp->m_sb.sb_rblocks)
+		if (count >= sc->mp->m_sb.sb_rblocks + sc->mp->m_sb.sb_dblocks)
 			return -EFSCORRUPTED;
 	} else {
 		if (count >= sc->mp->m_sb.sb_dblocks)
author maintainer
#370 lore raw

PATCH 367/547 xfs: init inode number for tracepoint

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit e98643f794d0d7a7fde8b29276d74e09fa0d5d19 upstream.

LOLLM complains that if the xchk_dir_lookup call fails, it won't set ino to anything. ino is then passed into the tracepoint function, which means that it reports random stack garbage. Set it to NULLFSINO instead so that the circumstance is more obvious.

Fixes 0d2c636e489c11 ("xfs: repair metadata directory file path connectivity")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/metapath.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/xfs/scrub/metapath.c +2 -2
@@ -522,7 +522,7 @@ xrep_metapath_try_link(
 	xfs_ino_t		*alleged_child)
 {
 	struct xfs_scrub	*sc = mpath->sc;
-	xfs_ino_t		ino;
+	xfs_ino_t		ino = NULLFSINO;
 	int			error;
 
 	/* Allocate transaction, lock inodes, join to transaction. */
@@ -621,7 +621,7 @@ xrep_metapath_try_unlink(
 {
 	struct xfs_scrub	*sc = mpath->sc;
 	struct xfs_inode	*ip = NULL;
-	xfs_ino_t		ino;
+	xfs_ino_t		ino = NULLFSINO;
 	int			error;
 
 	ASSERT(*alleged_child != I_INO(sc->ip));
author maintainer
#371 lore raw

PATCH 368/547 xfs: never reset the default quota timer

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit ddf4fe30c3fd7d37cf9bad3887ddb69984954cf4 upstream.

LOLLM notices that xrep_quota_fix_timer doesn't check the dquot id, which means that it can inadvertently reset the default quota timer when we really meant to ensure that a (non-root) quota overage timeout has a sane timestamp. Fix that.

Fixes a5b91555403e3a ("xfs: repair quotas")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/quota_repair.c |    3 +++
 1 file changed, 3 insertions(+)
fs/xfs/scrub/quota_repair.c +3 -0
@@ -272,6 +272,9 @@ xrep_quota_fix_timer(
 	time64_t		new_timer;
 	uint32_t		t;
 
+	/* never reset the default quota timer */
+	if (ddq->d_id == 0)
+		return;
 	if (!soft || count <= soft || *timer != 0)
 		return;
 
author maintainer
#372 lore raw

PATCH 369/547 xfs: only written file data blocks can be shared

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 634b63baf05062988456a0bd5df2696c14ea2949 upstream.

LOLLM noticed that xchk_refcountbt_rmap_check (and its rt equivalent) will count any rmap owner towards the shared count. However, the only blocks that can be shared between xfs files are written file data blocks; and the only blocks that can have single-refcount entries are COW staging extents. Fix the checking code.

Fixes dbde19da963706 ("xfs: cross-reference the rmapbt data with the refcountbt")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/refcount.c |   12 ++++++++++++
 1 file changed, 12 insertions(+)
fs/xfs/scrub/refcount.c +12 -0
@@ -129,6 +129,18 @@ xchk_refcountbt_rmap_check(
 		return 0;
 	}
 
+	/*
+	 * The refcount btree should only have records for written file data
+	 * blocks or for COW staging blocks.
+	 */
+	if ((XFS_RMAP_NON_INODE_OWNER(rec->rm_owner) &&
+	     rec->rm_owner != XFS_RMAP_OWN_COW) ||
+	    (rec->rm_flags & (XFS_RMAP_ATTR_FORK | XFS_RMAP_BMBT_BLOCK |
+			      XFS_RMAP_UNWRITTEN))) {
+		xchk_btree_xref_set_corrupt(refchk->sc, cur, 0);
+		return 0;
+	}
+
 	if (rec->rm_startblock <= refchk->bno && rm_last >= rc_last) {
 		/*
 		 * The rmap overlaps the refcount record, so we can confirm
author maintainer
#373 lore raw

PATCH 370/547 xfs: opportunistically skip btree block checks

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 4ce244b234c251963fca6dff9de6edf26a209d08 upstream.

LOLLM notices that both callers of xchk_btree_get_block will return early if *pblock is NULL after a successful return. However, xchk_btree_get_block itself can return 0 after flagging a corruption. There's no point in continuing after we've found a corruption, so null the pointer out.

Fixes cc3e0948d2686f ("xfs: scrub the shape of a metadata btree")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/btree.c |    8 ++++++++
 1 file changed, 8 insertions(+)
fs/xfs/scrub/btree.c +8 -0
@@ -608,6 +608,14 @@ xchk_btree_get_block(
 	xfs_btree_get_block(bs->cur, level, pbp);
 	if (__xfs_btree_check_block(bs->cur, *pblock, level, *pbp)) {
 		xchk_btree_set_corrupt(bs->sc, bs->cur, level);
+		/*
+		 * The btree block fails basic checks, so we know it's corrupt.
+		 * There's no need to continue looking for corruptions, so we
+		 * null out pblock.  If *pbp is non-null then it's also
+		 * attached to the transaction so we won't leak it despite the
+		 * 0 return code.
+		 */
+		*pblock = NULL;
 		return 0;
 	}
 	if (*pbp)
author maintainer
#374 lore raw

PATCH 371/547 xfs: propagate errors while checking null siblings

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit e5bde75a816b3549942f4b09a8bf09006b7ea9de upstream.

LOLLM observes that if xfs_da3_path_shift returns an error here, scrub doesn't handle it the way that it handles most runtime errors. Instead, it drops the error and keeps going, even though that's not how that's supposed to work. Fix that by calling xchk_da_process_error to set corruption flags and then jump out of the flow of execution.

Fixes 7c4a07a424c18d ("xfs: scrub directory/attribute btrees")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/dabtree.c |    5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
fs/xfs/scrub/dabtree.c +3 -2
@@ -257,9 +257,10 @@ xchk_da_btree_block_check_sibling(
 	if (sibling == 0) {
 		error = xfs_da3_path_shift(ds->state, altpath, direction,
 				false, &retval);
-		if (error == 0 && retval == 0)
+		if (!xchk_da_process_error(ds, level, &error))
+			goto out;
+		if (retval == 0)
 			xchk_da_set_corrupt(ds, level);
-		error = 0;
 		goto out;
 	}
 
author maintainer
#375 lore raw

PATCH 372/547 xfs: range-check bc_levels array access in scrub tracepoints

In reply to Greg Kroah-Hartman

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

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

From: Darrick J. Wong <[email protected]>

commit 73b7276b8a4b5eb272f3c3b36ea3042e786f4741 upstream.

LOLLM noticed xchk_btree()'s odd habit of passing cur->bc_nlevels to xchk_btree_ptr_ok when we're checking the pointer to the root block at the start of the btree scan. This enables us to skip checking the pointer for an inode btree's root (since it doesn't have one) but doesn't handle per-AG btrees quite correctly. There isn't a problem for __xfs_btree_check_ptr itself, but the corruption tracepoint naively walks off the end of bc_level[]. Fix that by adding a helper to do an implicit range check.

Fixes 6ca444cfd66354 ("xfs: prepare xfs_btree_cur for dynamic cursor heights")
Assisted-by LOLLM # finding obvious bugs
---
 fs/xfs/scrub/trace.c |   13 +++++++++++++
 fs/xfs/scrub/trace.h |   10 +++++-----
 2 files changed, 18 insertions(+), 5 deletions(-)
fs/xfs/scrub/trace.c +13 -0
@@ -42,6 +42,9 @@ xchk_btree_cur_fsbno(
 	struct xfs_btree_cur	*cur,
 	int			level)
 {
+	if (level < 0)
+		return NULLFSBLOCK;
+
 	if (level < cur->bc_nlevels && cur->bc_levels[level].bp)
 		return XFS_DADDR_TO_FSB(cur->bc_mp,
 				xfs_buf_daddr(cur->bc_levels[level].bp));
@@ -53,6 +56,16 @@ xchk_btree_cur_fsbno(
 	return NULLFSBLOCK;
 }
 
+static inline int
+xchk_btree_cur_ptr(
+	const struct xfs_btree_cur	*cur,
+	int				level)
+{
+	if (level >= 0 && level < cur->bc_nlevels)
+		return cur->bc_levels[level].ptr;
+	return -1;
+}
+
 /*
  * We include this last to have the helpers above available for the trace
  * event implementations.
fs/xfs/scrub/trace.h +5 -5
@@ -577,7 +577,7 @@ TRACE_EVENT(xchk_btree_op_error,
 		__entry->level = level;
 		__entry->agno = XFS_FSB_TO_AGNO(cur->bc_mp, fsbno);
 		__entry->bno = XFS_FSB_TO_AGBNO(cur->bc_mp, fsbno);
-		__entry->ptr = cur->bc_levels[level].ptr;
+		__entry->ptr = xchk_btree_cur_ptr(cur, level);
 		__entry->error = error;
 		__entry->ret_ip = ret_ip;
 	),
@@ -618,7 +618,7 @@ TRACE_EVENT(xchk_ifork_btree_op_error,
 		__entry->type = sc->sm->sm_type;
 		__assign_str(name);
 		__entry->level = level;
-		__entry->ptr = cur->bc_levels[level].ptr;
+		__entry->ptr = xchk_btree_cur_ptr(cur, level);
 		__entry->agno = XFS_FSB_TO_AGNO(cur->bc_mp, fsbno);
 		__entry->bno = XFS_FSB_TO_AGBNO(cur->bc_mp, fsbno);
 		__entry->error = error;
@@ -660,7 +660,7 @@ TRACE_EVENT(xchk_btree_error,
 		__entry->level = level;
 		__entry->agno = XFS_FSB_TO_AGNO(cur->bc_mp, fsbno);
 		__entry->bno = XFS_FSB_TO_AGBNO(cur->bc_mp, fsbno);
-		__entry->ptr = cur->bc_levels[level].ptr;
+		__entry->ptr = xchk_btree_cur_ptr(cur, level);
 		__entry->ret_ip = ret_ip;
 	),
 	TP_printk("dev %d:%d type %s %sbt level %d ptr %d agno 0x%x agbno 0x%x ret_ip %pS",
@@ -700,7 +700,7 @@ TRACE_EVENT(xchk_ifork_btree_error,
 		__entry->level = level;
 		__entry->agno = XFS_FSB_TO_AGNO(cur->bc_mp, fsbno);
 		__entry->bno = XFS_FSB_TO_AGBNO(cur->bc_mp, fsbno);
-		__entry->ptr = cur->bc_levels[level].ptr;
+		__entry->ptr = xchk_btree_cur_ptr(cur, level);
 		__entry->ret_ip = ret_ip;
 	),
 	TP_printk("dev %d:%d ino 0x%llx fork %s type %s %sbt level %d ptr %d agno 0x%x agbno 0x%x ret_ip %pS",
@@ -740,7 +740,7 @@ DECLARE_EVENT_CLASS(xchk_sbtree_class,
 		__entry->bno = XFS_FSB_TO_AGBNO(cur->bc_mp, fsbno);
 		__entry->level = level;
 		__entry->nlevels = cur->bc_nlevels;
-		__entry->ptr = cur->bc_levels[level].ptr;
+		__entry->ptr = xchk_btree_cur_ptr(cur, level);
 	),
 	TP_printk("dev %d:%d type %s %sbt agno 0x%x agbno 0x%x level %d nlevels %d ptr %d",
 		  MAJOR(__entry->dev), MINOR(__entry->dev),