Skip to contentSkip to conversation

6.12.119-rc1 review

PATCH Applied Greg Kroah-Hartman 15 participants 1,795 messages Nov 18 – Nov 20 Page 13 of 14

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

PATCH 1547/1756 bpf: Remove nmi_uaccess_okay() check in bpf_send_signal_common()

In reply to Greg Kroah-Hartman

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

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

From: Aditya Sharma <[email protected]>

[ Upstream commit 93bd472336ac2424f5f3cf05cbb24e02242343b7 ]

nmi_uaccess_okay() takes no task argument and is a statement about current. When commit 6280cf718db0 ("bpf: Implement bpf_send_signal_task() kfunc") made the PF_KTHREAD/PF_EXITING and is_global_init() test the supplied task, nmi_uaccess_okay() was left testing current.

As a result bpf_send_signal_task() returns -EPERM whenever the calling context happens to be a kernel thread, regardless of which task the signal is aimed at. The same call with the same target succeeds or fails depending only on what the CPU was running:

bpf_send_signal_task() from tp_btf/workqueue_execute_start : -EPERM
bpf_send_signal_task() from tp_btf/sys_enter : 0

The check was carried over from bpf_probe_write_user() when bpf_send_signal() was added in commit 8b401f9ed244 ("bpf: implement bpf_send_signal() helper"). There it guards a user memory write, but bpf_send_signal_common() does no user memory access, so the check has nothing to guard here. It is also already a no-op outside x86.

Remove it, and drop the part of the comment above it that described the memory access checks, as none remain.

---
 kernel/trace/bpf_trace.c | 9 +++------
 1 file changed, 3 insertions(+), 6 deletions(-)
kernel/trace/bpf_trace.c +3 -6
index 5abd26d3a8ab8..d6d9ca8c79746 100644
@@ -845,15 +845,12 @@ static int bpf_send_signal_common(u32 sig, enum pid_type type, struct task_struc
 		siginfo = &info;
 	}
 
-	/* Similar to bpf_probe_write_user, task needs to be
-	 * in a sound condition and kernel memory access be
-	 * permitted in order to send signal to the current
-	 * task.
+	/*
+	 * Similar to bpf_probe_write_user, task needs to be
+	 * in a sound condition.
 	 */
 	if (unlikely(task->flags & (PF_KTHREAD | PF_EXITING)))
 		return -EPERM;
-	if (unlikely(!nmi_uaccess_okay()))
-		return -EPERM;
 	/* Task should not be pid=1 to avoid kernel panic. */
 	if (unlikely(is_global_init(task)))
 		return -EPERM;
Signature · 1 line
2.53.0
author maintainer
#1578 lore raw

PATCH 1548/1756 kernel/reboot: avoid potential deadlocks during suspension

In reply to Greg Kroah-Hartman

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

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

From: Edward Adam Davis <[email protected]>

[ Upstream commit 66644b992f25f6a33775788c8b69a8bb3d41ad67 ]

Invoking reboot with LINUX_REBOOT_CMD_SW_SUSPEND causes kernel/reboot.c to acquire system_transition_mutex and invoke hibernate(). hibernate() calls lock_system_sleep(), which sets PF_NOFREEZE on current and attempts to acquire system_transition_mutex again, potentially hitting:

WARNING: possible recursive locking detected
--------------------------------------------
syz.3.5755/5950 is trying to acquire lock:
ffffffff8fc04760 (system_transition_mutex){+.+.}-{4:4}, at: lock_system_sleep+0x49/0x70 kernel/power/main.c:71

but task is already holding lock:
ffffffff8fc04760 (system_transition_mutex){+.+.}-{4:4}, at: __do_sys_reboot kernel/reboot.c:774 [inline] ffffffff8fc04760 (system_transition_mutex){+.+.}-{4:4}, at: __se_sys_reboot+0x223/0x460 kernel/reboot.c:738

other info that might help us debug this:

 Possible unsafe locking scenario:
       CPU0
       ----

lock(system_transition_mutex);
lock(system_transition_mutex);

*** DEADLOCK ***

May be due to missing lock nesting notation

locks held by syz.3.5755/5950: 1, last CPU#0:
#0: ffffffff8fc04760 (system_transition_mutex){+.+.}-{4:4}, at: __do_sys_reboot kernel/reboot.c:774 [inline] #0: ffffffff8fc04760 (system_transition_mutex){+.+.}-{4:4}, at: __se_sys_reboot+0x223/0x460 kernel/reboot.c:738

Call Trace:
 lock_system_sleep+0x49/0x70 kernel/power/main.c:71
 hibernate+0x162/0x680 kernel/power/hibernate.c:784
 __do_sys_reboot kernel/reboot.c:816 [inline]

Move the suspension operation outside the scope protected by lock system_transition_mutex.

---
 kernel/reboot.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/reboot.c +2 -2
index caab5c86c6e29..788aaa4c5be76 100644
@@ -801,8 +801,8 @@ SYSCALL_DEFINE4(reboot, int, magic1, int, magic2, unsigned int, cmd,
 
 #ifdef CONFIG_HIBERNATION
 	case LINUX_REBOOT_CMD_SW_SUSPEND:
-		ret = hibernate();
-		break;
+		mutex_unlock(&system_transition_mutex);
+		return hibernate();
 #endif
 
 	default:
Signature · 1 line
2.53.0
author maintainer
#1579 lore raw

PATCH 1549/1756 profiling: fix sampling step on 64-bit big-endian systems

In reply to Greg Kroah-Hartman

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

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

From: Avi Weiss <[email protected]>

[ Upstream commit b1d68946a08313895f352af5336623d29739c299 ]

read_profile() stores the sampling step in an unsigned long but copies only four bytes to userspace. On 64-bit big-endian systems (not common obviously), this copies the upper 32 bits and discards the rest, causing /proc/profile to report zero for normal shift values.

Cast to unsigned int so we get the correct 4 bytes, while keeping the shift calculation in unsigned long.

A small C reproducer under qemu-s390x reproduced this and proved the fix works for prof_shift=2.

Fixes 2d186afd04d6 ("profiling: fix shift-out-of-bounds bugs")
---
 kernel/profile.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/profile.c +1 -1
index 1fcf1adcf4eb0..e7defa90a34c9 100644
@@ -156,7 +156,7 @@ read_profile(struct file *file, char __user *buf, size_t count, loff_t *ppos)
 	unsigned long p = *ppos;
 	ssize_t read;
 	char *pnt;
-	unsigned long sample_step = 1UL << prof_shift;
+	unsigned int sample_step = (unsigned int)(1UL << prof_shift);
 
 	if (p >= (prof_len+1)*sizeof(unsigned int))
 		return 0;
Signature · 1 line
2.53.0
author maintainer
#1580 lore raw

PATCH 1550/1756 scripts/gdb/radix-tree: add lx-radix-tree-command

In reply to Greg Kroah-Hartman

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

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

From: Ilya Leoshkevich <[email protected]>

[ Upstream commit caa71919a622e3f7d290d4f17ae538b15f5cb6d3 ]

Patch series "scripts/gdb/symbols: make BPF debug info available to GDB", v2.

This series greatly simplifies debugging BPF progs when using QEMU gdbstub by providing symbol names, sizes, and line numbers to GDB.

Patch 1 adds radix tree iteration, which is necessary for parsing prog_idr. Patch 2 is the actual implementation; its description contains some details on how to use this.

This patch (of 2):

Add a function and a command to iterate over radix tree contents. Duplicate the C implementation in Python, but drop support for tagging.

Stable-dep-of: 66d190b072b4 ("scripts/gdb: fix radix tree lookup pointer handling")

---
 scripts/gdb/linux/radixtree.py | 139 +++++++++++++++++++++++++++++++--
 1 file changed, 132 insertions(+), 7 deletions(-)
scripts/gdb/linux/radixtree.py +132 -7
index 074543ac763d2..bc2954e45c327 100644
@@ -30,13 +30,16 @@ def entry_to_node(node):
 def node_maxindex(node):
     return (constants.LX_RADIX_TREE_MAP_SIZE << node['shift']) - 1
 
-def lookup(root, index):
+def resolve_root(root):
+    if root.type == radix_tree_root_type.get_type():
+        return root
     if root.type == radix_tree_root_type.get_type().pointer():
-        node = root.dereference()
-    elif root.type != radix_tree_root_type.get_type():
-        raise gdb.GdbError("must be {} not {}"
-                           .format(radix_tree_root_type.get_type(), root.type))
+        return root.dereference()
+    raise gdb.GdbError("must be {} not {}"
+                       .format(radix_tree_root_type.get_type(), root.type))
 
+def lookup(root, index):
+    root = resolve_root(root)
     node = root['xa_head']
     if node == 0:
         return None
@@ -71,14 +74,120 @@ def lookup(root, index):
 
     return node
 
-class LxRadixTree(gdb.Function):
+def descend(parent, index):
+    offset = (index >> int(parent["shift"])) & constants.LX_RADIX_TREE_MAP_MASK
+    return offset, parent["slots"][offset]
+
+def load_root(root):
+    node = root["xa_head"]
+    nodep = node
+
+    if is_internal_node(node):
+        node = entry_to_node(node)
+        maxindex = node_maxindex(node)
+        return int(node["shift"]) + constants.LX_RADIX_TREE_MAP_SHIFT, \
+               nodep, maxindex
+
+    return 0, nodep, 0
+
+class RadixTreeIter:
+    def __init__(self, start):
+        self.index = 0
+        self.next_index = start
+        self.node = None
+
+def xa_mk_internal(v):
+    return (v << 2) | 2
+
+LX_XA_RETRY_ENTRY = xa_mk_internal(256)
+LX_RADIX_TREE_RETRY = LX_XA_RETRY_ENTRY
+
+def next_chunk(root, iter):
+    mask = (1 << (utils.get_ulong_type().sizeof * 8)) - 1
+
+    index = iter.next_index
+    if index == 0 and iter.index != 0:
+        return None
+
+    restart = True
+    while restart:
+        restart = False
+
+        _, child, maxindex = load_root(root)
+        if index > maxindex:
+            return None
+        if not child:
+            return None
+
+        if not is_internal_node(child):
+            iter.index = index
+            iter.next_index = (maxindex + 1) & mask
+            iter.node = None
+            return root["xa_head"].address
+
+        while True:
+            node = entry_to_node(child)
+            offset, child = descend(node, index)
+
+            if not child:
+                while True:
+                    offset += 1
+                    if offset >= constants.LX_RADIX_TREE_MAP_SIZE:
+                        break
+                    slot = node["slots"][offset]
+                    if slot:
+                        break
+                index &= ~node_maxindex(node)
+                index = (index + (offset << int(node["shift"]))) & mask
+                if index == 0:
+                    return None
+                if offset == constants.LX_RADIX_TREE_MAP_SIZE:
+                    restart = True
+                    break
+                child = node["slots"][offset]
+
+            if not child:
+                restart = True
+                break
+            if child == LX_XA_RETRY_ENTRY:
+                break
+            if not node["shift"] or not is_internal_node(child):
+                break
+
+    iter.index = (index & ~node_maxindex(node)) | offset
+    iter.next_index = ((index | node_maxindex(node)) + 1) & mask
+    iter.node = node
+
+    return node["slots"][offset].address
+
+def next_slot(slot, iter):
+    mask = (1 << (utils.get_ulong_type().sizeof * 8)) - 1
+    for _ in range(iter.next_index - iter.index - 1):
+        slot += 1
+        iter.index = (iter.index + 1) & mask
+        if slot.dereference():
+            return slot
+    return None
+
+def for_each_slot(root, start=0):
+    iter = RadixTreeIter(start)
+    slot = None
+    while True:
+        if not slot:
+            slot = next_chunk(root, iter)
+            if not slot:
+                break
+        yield iter.index, slot
+        slot = next_slot(slot, iter)
+
+class LxRadixTreeLookup(gdb.Function):
     """ Lookup and return a node from a RadixTree.
 
 $lx_radix_tree_lookup(root_node [, index]): Return the node at the given index.
 If index is omitted, the root node is dereference and returned."""
 
     def __init__(self):
-        super(LxRadixTree, self).__init__("lx_radix_tree_lookup")
+        super(LxRadixTreeLookup, self).__init__("lx_radix_tree_lookup")
 
     def invoke(self, root, index=0):
         result = lookup(root, index)
@@ -87,4 +196,20 @@ If index is omitted, the root node is dereference and returned."""
 
         return result
 
+class LxRadixTree(gdb.Command):
+    """Show all values stored in a RadixTree."""
+
+    def __init__(self):
+        super(LxRadixTree, self).__init__("lx-radix-tree", gdb.COMMAND_DATA,
+                                          gdb.COMPLETE_NONE)
+
+    def invoke(self, argument, from_tty):
+        args = gdb.string_to_argv(argument)
+        if len(args) != 1:
+            raise gdb.GdbError("Usage: lx-radix-tree ROOT")
+        root = gdb.parse_and_eval(args[0])
+        for index, slot in for_each_slot(root):
+            gdb.write("[{}] = {}\n".format(index, slot.dereference()))
+
 LxRadixTree()
+LxRadixTreeLookup()
Signature · 1 line
2.53.0
author maintainer
#1581 lore raw

PATCH 1551/1756 scripts/gdb: fix radix tree lookup pointer handling

In reply to Greg Kroah-Hartman

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

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

From: Ting-Han Hou <[email protected]>

[ Upstream commit 66d190b072b4e261aff35debb53872ace9b80628 ]

Patch series "scripts/gdb: fix radix tree lookup and stack depot diagnostic", v2.

Two scripts/gdb fixes.

Patch 1 fixes $lx_radix_tree_lookup(), which dereferenced slot contents as if they were node pointers. v2 also handles the XArray sibling, retry and zero entries that Sashiko pointed out: they carry the internal tag but are not node pointers, and the v1 patch raised a GDB MemoryError on them. Large folios in the page cache make sibling entries common, so this was worth fixing rather than documenting.

Patch 2 is unchanged from v1 apart from being resent with git send-email, since the earlier copy was word-wrapped by the mail client. Sorry about that.

Both patches are tested against standalone GCC-built fixtures that use the kernel struct layouts (details below the --- line of each patch), not against a running kernel.

This patch (of 2):

lookup() casts each slot to a pointer to a node pointer and then dereferences it. Since the slot already contains an entry pointer, this reads the entry's contents as another pointer instead of returning the entry itself. Internal entries also keep their tag bits when descending, so multi-level trees are read from the wrong address and $lx_radix_tree_lookup() fails with a memory error.

Sibling, retry and zero entries carry the same internal tag but are small integers rather than node pointers, so the tag alone must not decide whether to descend. A page cache populated with large folios has a sibling entry in every slot but the first of each folio.

Walk the tree the way xas_load() does: descend only through entries that xa_is_node() would accept, follow sibling entries to the canonical slot of a multi-index entry, and treat retry and zero entries like empty slots since they hold no data. Remove the explicit shift counter, as traversal now follows the entry type.

Fixes b7235d6bb516 ("scripts/gdb: add a Radix Tree Parser")
Assisted-by LLM
Cc Jan Kiszka <[email protected]>
Cc Kieran Bingham <[email protected]>
Cc Kuan-Ying Lee <[email protected]>
---
 scripts/gdb/linux/radixtree.py | 66 ++++++++++++++++++++--------------
 1 file changed, 40 insertions(+), 26 deletions(-)
scripts/gdb/linux/radixtree.py +40 -26
index bc2954e45c327..8ce9936dfa50f 100644
@@ -27,6 +27,24 @@ def entry_to_node(node):
     indirect_ptr = node.cast(long_type) & ~constants.LX_RADIX_TREE_INTERNAL_NODE
     return indirect_ptr.cast(radix_tree_node_type.get_type().pointer())
 
+def is_node(entry):
+    # Like xa_is_node(): internal entries below 4096 are sibling, retry
+    # or zero entries rather than pointers to a struct xa_node.
+    ulong_type = utils.get_ulong_type()
+    return is_internal_node(entry) and entry.cast(ulong_type) > 4096
+
+def is_sibling(entry):
+    # Like xa_is_sibling(): a multi-index entry occupies several slots,
+    # and all but the first hold a sibling entry that encodes the offset
+    # of the first one.
+    ulong_type = utils.get_ulong_type()
+    return is_internal_node(entry) and entry.cast(ulong_type) < \
+        xa_mk_internal(constants.LX_RADIX_TREE_MAP_SIZE - 1)
+
+def sibling_offset(entry):
+    ulong_type = utils.get_ulong_type()
+    return int(entry.cast(ulong_type)) >> 2
+
 def node_maxindex(node):
     return (constants.LX_RADIX_TREE_MAP_SIZE << node['shift']) - 1
 
@@ -40,39 +58,35 @@ def resolve_root(root):
 
 def lookup(root, index):
     root = resolve_root(root)
-    node = root['xa_head']
-    if node == 0:
-        return None
+    entry = root['xa_head']
 
-    if not (is_internal_node(node)):
-        if (index > 0):
+    if is_node(entry):
+        node = entry_to_node(entry)
+        if index > node_maxindex(node):
             return None
-        return node
 
-    node = entry_to_node(node)
-    maxindex = node_maxindex(node)
-
-    if (index > maxindex):
-        return None
-
-    shift = node['shift'] + constants.LX_RADIX_TREE_MAP_SHIFT
-
-    while True:
-        offset = (index >> node['shift']) & constants.LX_RADIX_TREE_MAP_MASK
-        slot = node['slots'][offset]
+        # Walk down the tree like xas_load() does.
+        while True:
+            offset = (index >> node['shift']) & constants.LX_RADIX_TREE_MAP_MASK
+            entry = node['slots'][offset]
 
-        if slot == 0:
-            return None
+            while is_sibling(entry):
+                entry = node['slots'][sibling_offset(entry)]
+                if node['shift'] and is_node(entry):
+                    # xas_descend() turns this into a retry entry.
+                    return None
 
-        node = slot.cast(node.type.pointer()).dereference()
-        if node == 0:
-            return None
+            if not is_node(entry) or node['shift'] == 0:
+                break
+            node = entry_to_node(entry)
+    elif index > 0:
+        return None
 
-        shift -= constants.LX_RADIX_TREE_MAP_SHIFT
-        if (shift <= 0):
-            break
+    # Empty slots and retry or zero entries hold no data.
+    if entry == 0 or is_internal_node(entry):
+        return None
 
-    return node
+    return entry
 
 def descend(parent, index):
     offset = (index >> int(parent["shift"])) & constants.LX_RADIX_TREE_MAP_MASK
Signature · 1 line
2.53.0
author maintainer
#1582 lore raw

PATCH 1552/1756 scripts/gdb: fix stack depot out-of-bounds diagnostic

In reply to Greg Kroah-Hartman

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

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

From: Ting-Han Hou <[email protected]>

[ Upstream commit b6232ca8d194c60ee603586e42b5ea584d4b7be9 ]

The pool_index field was renamed to pool_index_plus_1, but the out-of-bounds diagnostic in stack_depot_fetch() still accesses the old field. Looking up a handle whose pool index is outside stack_pools therefore raises "There is no member named pool_index" instead of printing the diagnostic and returning an empty result.

Use the already decoded pool_index variable in the diagnostic.

Fixes 9d938f40b228 ("scripts/gdb: rename pool_index to pool_index_plus_1")
Assisted-by LLM
Cc Jan Kiszka <[email protected]>
Cc Kieran Bingham <[email protected]>
Cc Kuan-Ying Lee <[email protected]>
---
 scripts/gdb/linux/stackdepot.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
scripts/gdb/linux/stackdepot.py +1 -1
index 37313a5a51a0d..aaa18af25cd12 100644
@@ -39,7 +39,7 @@ def stack_depot_fetch(handle):
 
     pool_index = parts['pool_index_plus_1'] - 1
     if pool_index >= pools_num:
-        gdb.write("pool index %d out of bounds (%d) for stack id 0x%08x\n" % (parts['pool_index'], pools_num, handle))
+        gdb.write("pool index %d out of bounds (%d) for stack id 0x%08x\n" % (pool_index, pools_num, handle))
         return gdb.Value(0), 0
 
     stack_pools = gdb.parse_and_eval('stack_pools')
Signature · 1 line
2.53.0
author maintainer
#1583 lore raw

PATCH 1553/1756 ALSA: us122l: mark hwdep mappings VM_MIXEDMAP

In reply to Greg Kroah-Hartman

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

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

From: Lorenzo Stoakes (ARM) <[email protected]>

[ Upstream commit bbde9d5bdd2d7cf94707b2a8bb466f2e074f9db2 ]

mm has recently moved to a strict model which requires any driver which clears VMA_MAYWRITE_BIT to be mapping non-mm-managed memory (VMA_PFNMAP_BIT or VMA_MIXEDMAP_BIT), failing any such mmap() with an error and a kernel warning - see "mm/vma: only allow mmap to clear VMA_MAYWRITE_BIT if not mm-managed".

However, simultaneous to this, commit 71c610aeb177 ("ALSA: us122l: Prevent write upgrades for read mappings") updated us122l to clear VMA_MAYWRITE_BIT without marking the region with either VMA_PFNMAP_BIT or VMA_MIXEDMAP_BIT.

vm_insert_pages() and friends set this automatically, however this driver maps its pre-allocated pages from a fault handler, so never calls these.

Simply set the flag in usb_stream_hwdep_mmap() to resolve the issue. This correctly marks the mapping as one whose pages core mm does not manage, which has no meaningful impact for this driver beyond preventing the mmap() from failing.

---
 sound/usb/usx2y/us122l.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
sound/usb/usx2y/us122l.c +1 -1
index 8880051927044..1c36db0af160d 100644
@@ -228,7 +228,7 @@ static int usb_stream_hwdep_mmap(struct snd_hwdep *hw,
 	}
 
 	area->vm_ops = &usb_stream_hwdep_vm_ops;
-	vm_flags_set(area, VM_DONTDUMP);
+	vm_flags_set(area, VM_MIXEDMAP | VM_DONTDUMP);
 	if (!read)
 		vm_flags_set(area, VM_DONTEXPAND);
 	area->vm_private_data = us122l;
Signature · 1 line
2.53.0
author maintainer
#1584 lore raw

PATCH 1554/1756 tools/cgroup: sum shrinker object counts across NUMA nodes

In reply to Greg Kroah-Hartman

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

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

From: Ren Tamura <[email protected]>

[ Upstream commit ae2514c95518b39b36fa463d855c74f29c91d064 ]

Each row of a memcg-aware shrinker's debugfs count file contains the cgroup ID followed by one object count per NUMA node. memcg_shrinker.py uses only the first count when sorting and displaying entries.

This undercounts objects on NUMA systems. An entry with counts of 0 and 23 is treated as zero and omitted from the output, even though its total is 23.

Sum all count fields after the cgroup ID so that the displayed totals and sort order account for every node. Single-node input retains the same result.

Fixes d261ea23533b ("tools: add memcg_shrinker.py")
Assisted-by LLM
Cc Roman Gushchin <[email protected]>
---
 tools/cgroup/memcg_shrinker.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/cgroup/memcg_shrinker.py +1 -1
index e81c3017ada96..714772449c6ba 100644
@@ -31,7 +31,7 @@ def scan_shrinkers(shrinker_debugfs):
                     items = line.split(' ')
                     ino = int(items[0])
                     # (count, shrinker, memcg ino)
-                    shrinkers.append((int(items[1]), shrinker, ino))
+                    shrinkers.append((sum(map(int, items[1:])), shrinker, ino))
     return shrinkers
 
 
Signature · 1 line
2.53.0
author maintainer
#1585 lore raw

PATCH 1555/1756 maple_tree: Use kfree_rcu in ma_free_rcu

In reply to Greg Kroah-Hartman

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

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

From: Pedro Falcato <[email protected]>

[ Upstream commit 9b60811cb3b42fe9a8e3f0aa3e007cd9cc814a78 ]

kfree_rcu is an optimized version of call_rcu + kfree. It used to not be possible to call it on non-kmalloc objects, but this restriction was lifted ever since SLOB was dropped from the kernel, and since commit 6c6c47b063b5 ("mm, slab: call kvfree_rcu_barrier() from kmem_cache_destroy()").

Thus, replace call_rcu + mt_free_rcu with kfree_rcu.

Stable-dep-of: baed735a956f ("maple_tree: fix maple_range_64 crashes in RCU mode")

---
 lib/maple_tree.c | 13 +++----------
 1 file changed, 3 insertions(+), 10 deletions(-)
lib/maple_tree.c +3 -10
index c7e3f91fd91c6..41fb935134917 100644
@@ -179,13 +179,6 @@ static inline void mt_free_bulk(size_t size, void __rcu **nodes)
 	kmem_cache_free_bulk(maple_node_cache, size, (void **)nodes);
 }
 
-static void mt_free_rcu(struct rcu_head *head)
-{
-	struct maple_node *node = container_of(head, struct maple_node, rcu);
-
-	kmem_cache_free(maple_node_cache, node);
-}
-
 /*
  * ma_free_rcu() - Use rcu callback to free a maple node
  * @node: The node to free
@@ -196,7 +189,7 @@ static void mt_free_rcu(struct rcu_head *head)
 static void ma_free_rcu(struct maple_node *node)
 {
 	WARN_ON(node->parent != ma_parent_ptr(node));
-	call_rcu(&node->rcu, mt_free_rcu);
+	kfree_rcu(node, rcu);
 }
 
 static void mas_set_height(struct ma_state *mas)
@@ -5301,7 +5294,7 @@ static void mt_free_walk(struct rcu_head *head)
 	mt_free_bulk(node->slot_len, slots);
 
 free_leaf:
-	mt_free_rcu(&node->rcu);
+	mt_free_one(node);
 }
 
 static inline void __rcu **mte_destroy_descend(struct maple_enode **enode,
@@ -5385,7 +5378,7 @@ static void mt_destroy_walk(struct maple_enode *enode, struct maple_tree *mt,
 
 free_leaf:
 	if (free)
-		mt_free_rcu(&node->rcu);
+		mt_free_one(node);
 	else
 		mt_clear_meta(mt, node, node->type);
 }
Signature · 1 line
2.53.0
author maintainer
#1586 lore raw

PATCH 1556/1756 maple_tree: Replace mt_free_one() with kfree()

In reply to Greg Kroah-Hartman

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

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

From: Pedro Falcato <[email protected]>

[ Upstream commit 025f93101bb4e0a0cdc0fc4ee264f7905271ad75 ]

kfree() is a little shorter and works with kmem_cache_alloc'd pointers too. Also lets us remove one more helper.

Stable-dep-of: baed735a956f ("maple_tree: fix maple_range_64 crashes in RCU mode")

---
 lib/maple_tree.c | 13 ++++---------
 1 file changed, 4 insertions(+), 9 deletions(-)
lib/maple_tree.c +4 -9
index 41fb935134917..f18c06c23a0ed 100644
@@ -169,11 +169,6 @@ static inline int mt_alloc_bulk(gfp_t gfp, size_t size, void **nodes)
 	return kmem_cache_alloc_bulk(maple_node_cache, gfp, size, nodes);
 }
 
-static inline void mt_free_one(struct maple_node *node)
-{
-	kmem_cache_free(maple_node_cache, node);
-}
-
 static inline void mt_free_bulk(size_t size, void __rcu **nodes)
 {
 	kmem_cache_free_bulk(maple_node_cache, size, (void **)nodes);
@@ -5294,7 +5289,7 @@ static void mt_free_walk(struct rcu_head *head)
 	mt_free_bulk(node->slot_len, slots);
 
 free_leaf:
-	mt_free_one(node);
+	kfree(node);
 }
 
 static inline void __rcu **mte_destroy_descend(struct maple_enode **enode,
@@ -5378,7 +5373,7 @@ static void mt_destroy_walk(struct maple_enode *enode, struct maple_tree *mt,
 
 free_leaf:
 	if (free)
-		mt_free_one(node);
+		kfree(node);
 	else
 		mt_clear_meta(mt, node, node->type);
 }
@@ -5604,7 +5599,7 @@ void mas_destroy(struct ma_state *mas)
 			mt_free_bulk(count, (void __rcu **)&node->slot[1]);
 			total -= count;
 		}
-		mt_free_one(ma_mnode_ptr(node));
+		kfree(ma_mnode_ptr(node));
 		total--;
 	}
 
@@ -6638,7 +6633,7 @@ static void mas_dup_free(struct ma_state *mas)
 	}
 
 	node = mte_to_node(mas->node);
-	mt_free_one(node);
+	kfree(node);
 }
 
 /*
Signature · 1 line
2.53.0
author maintainer
#1587 lore raw

PATCH 1557/1756 maple_tree: fix maple_range_64 crashes in RCU mode

In reply to Greg Kroah-Hartman

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

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

From: Dimitris Charisis <[email protected]>

[ Upstream commit baed735a956f2a7badb5436bef6810303034f920 ]

Patch series "maple_tree: fix maple_range_64 crashes in RCU mode", v3.

The patch series fixes two RCU destroy path issues on maple_range_64 nodes. Both arising from the fact that a maple_range_64 node repurposes the last slot to hold metadata when the node is not full. Patch 1 addresses the issues, and patch 2 adds a test used to catch them.

Currently there is no in-tree user of maple_range_64 nodes in RCU mode. All in-tree users of MT_FLAGS_USE_RCU also set MT_FLAGS_ALLOC_RANGE which makes the internal nodes maple_arange_64.

Below is the minimal reproducer used during debugging:

static DEFINE_MTREE(tree);
static int __init maple_fix_init(void)

{
        unsigned long i, j;

        for (i = 10; i < 4000; i++) {
                mt_init_flags(&tree, MT_FLAGS_USE_RCU);

                for (j = 0; j < i; j++) {
                        mtree_insert_range(&tree, j * 10, j * 10 + 9,
                                        xa_mk_value(j), GFP_KERNEL);
                }

                mtree_destroy(&tree);
                rcu_barrier();
        }
        return 0;
}

The splat for the first issue addressed by the first patch is shown below. mt_clear_meta() runs after the slots have been rewritten with raw pointers by mte_dead_leaves(), so it cannot recognize a valid last pointer because the type information is stripped. On my 64-bit LE machine, it clears bytes 248 and 249 of the maple_range_64 which are the two least significant bytes of the last pointer. The lowest byte is already zero, since nodes are 256-byte aligned, but zeroing byte 249 corrupts the pointer.

KASAN catches it as a double-free, because that corrupted pointer happens to land on a node that was freed previously. The splat appears at 226 insertions in the reproducer. This is when the tree has a full root node on a 64-bit build.

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

  BUG: KASAN: double-free in mt_free_walk+0x138/0x3a0
  Free of addr ffff0000f3d40000 by task swapper/2/0
  [...]
  Call trace:
   [...]
   kmem_cache_free_bulk+0x5b8/0xc18
   mt_free_walk+0x138/0x3a0
   rcu_core+0x5d0/0x1638
   rcu_core_si+0x18/0x30
   [...]

  Allocated by task 1218:
   [...]
   kmem_cache_alloc_from_sheaf_noprof+0xa8/0x2f0
   dst_setup+0x210/0x630
   mas_wr_split+0x568/0x26e0
   mas_wr_store_entry+0x98c/0x1de0
   mas_insert.isra.0+0x3d0/0x5d8
   mtree_insert_range+0xec/0x1c8
   maple_fix_init+0x94/0xff8 [maple_fix_obj]
   [...]

  Freed by task 0:
   [...]
   __kasan_slab_free+0x88/0xb8
   __rcu_free_sheaf_prepare+0x94/0x360
   rcu_free_sheaf+0x30/0x138
   rcu_core+0x5d0/0x1638
   rcu_core_si+0x18/0x30
   [...]

  The buggy address belongs to the object at ffff0000f3d40000
   which belongs to the cache maple_node of size 256
  The buggy address is located 0 bytes inside of
   256-byte region [ffff0000f3d40000, ffff0000f3d40100)

[...]

  Memory state around the buggy address:
   ffff0000f3d3ff00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
   ffff0000f3d3ff80: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
  >ffff0000f3d40000: fa fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
                     ^
   ffff0000f3d40080: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
   ffff0000f3d40100: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
  ==================================================================

The second issue fixed in the first patch is in the mt_free_walk(). mt_free_walk() descends by checking if the corresponding slot[offset] entry is non-zero. In a maple_range_64 node that has MAPLE_RANGE64_SLOTS-1 valid pointers to child nodes, all slots will be non-zero, since the last slot holds the metadata. Thus, mte_dead_walk() dereferences the metadata as if it were a node and hits the null-ptr-deref as shown in the splat below.

After fixing the first issue, the reproducer reaches this case at 3166 insertions. The affected node is the root on a tree with height 3 and it has 15 valid child nodes on a 64-bit machine. The first fix does not introduce this bug, but it exposes it for the root node because it no longer clears the root metadata. On an unmodified kernel, the same bug exists and is reachable when such a maple_range_64 node appears below the root, where mt_clear_meta() is not called.

Second KASAN splat:

  Unable to handle kernel paging request at virtual address dfff800000000006
  KASAN: null-ptr-deref in range [0x0000000000000030-0x0000000000000037]
  [...]
  Call trace:
   mte_dead_walk+0x78/0x140 (P)
   mt_free_walk+0x1f8/0x3a0
   rcu_core+0x5d0/0x1638
   rcu_core_si+0x18/0x30
   [..]

Both splats are from an arm64 QEMU guest. The test_maple_tree and the userspace suite pass after each patch in the series.

This patch (of 2):

This commit fixes two issues in maple_range_64 nodes under RCU mode. A maple_range_64 node repurposes its last slot to hold metadata whenever the node is not full. Both issues arise from mishandling that last slot.

More specifically the two fixes are:

1. Remove mt_clear_meta() function. mt_clear_meta() decides whether the last slot of a maple_range_64 node holds a child pointer or a struct maple_metadata with the check

        if (unlikely((mte_to_node(next) &&
                      mte_node_type(next))))
                return; /* no metadata, could be node */

The check expects the pointer to be encoded. But the only callsite of mt_clear_meta() is mt_destroy_walk() on the RCU destroy path, and by the time it runs, mte_dead_leaves() has overwritten every slot on a full node with a raw pointer, stripping the type information. Thus, the check above never returns early for a full node as it should. It falls through and then:

           meta->gap = 0;
           meta->end = 0;

zeroes two bytes of a valid child pointer. Later, mt_free_walk() dereferences the corrupted pointer.

Fix this by removing mt_clear_meta() along with its only callsite. mt_clear_meta() is only called for the root of each sub-tree destroyed under RCU. Descendant nodes retain their metadata until they are freed. RCU readers may use the metadata while traversing a node, but do not use cleared metadata to detect that a node has been removed. They detect a dead node via ma_dead_node().

2. Fix invalid memory access in mt_free_walk(). mt_free_walk() descends to the left-most unvisited "parent-of-a-leaf" node by checking the condition:

        if ((offset < mt_slots[type]) &&
            rcu_dereference_protected(slots[offset],
                                      lock_is_held(&rcu_callback_map)))
                slots = mte_dead_walk(&enode, offset);

On a maple_range_64 node with MAPLE_RANGE64_SLOTS-1 children *all* slots are non-NULL. The first MAPLE_RANGE64_SLOTS-1 hold valid pointers to child nodes, and the last slot contains metadata. The above check therefore passes for all offsets, and mte_dead_walk() dereferences the metadata as if it were a node.

To trigger this, a node at least two levels above the leaves has to have exactly MAPLE_RANGE64_SLOTS-1 valid pointers to other nodes. maple_arange_64 nodes cannot hit this since they store the metadata in a separate field.

Fix this by bounding the descent with slot_len which holds the number of children of a dead node.

---
 lib/maple_tree.c | 43 +------------------------------------------
 1 file changed, 1 insertion(+), 42 deletions(-)
lib/maple_tree.c +1 -42
index f18c06c23a0ed..18d99876233e5 100644
@@ -866,43 +866,6 @@ static inline void ma_set_meta(struct maple_node *mn, enum maple_type mt,
 	meta->end = end;
 }
 
-/*
- * mt_clear_meta() - clear the metadata information of a node, if it exists
- * @mt: The maple tree
- * @mn: The maple node
- * @type: The maple node type
- */
-static inline void mt_clear_meta(struct maple_tree *mt, struct maple_node *mn,
-				  enum maple_type type)
-{
-	struct maple_metadata *meta;
-	unsigned long *pivots;
-	void __rcu **slots;
-	void *next;
-
-	switch (type) {
-	case maple_range_64:
-		pivots = mn->mr64.pivot;
-		if (unlikely(pivots[MAPLE_RANGE64_SLOTS - 2])) {
-			slots = mn->mr64.slot;
-			next = mt_slot_locked(mt, slots,
-					      MAPLE_RANGE64_SLOTS - 1);
-			if (unlikely((mte_to_node(next) &&
-				      mte_node_type(next))))
-				return; /* no metadata, could be node */
-		}
-		fallthrough;
-	case maple_arange_64:
-		meta = ma_meta(mn, type);
-		break;
-	default:
-		return;
-	}
-
-	meta->gap = 0;
-	meta->end = 0;
-}
-
 /*
  * ma_meta_end() - Get the data end of a node from the metadata
  * @mn: The maple node
@@ -5278,9 +5241,7 @@ static void mt_free_walk(struct rcu_head *head)
 
 		type = mte_node_type(enode);
 		slots = ma_slots(mte_to_node(enode), type);
-		if ((offset < mt_slots[type]) &&
-		    rcu_dereference_protected(slots[offset],
-					      lock_is_held(&rcu_callback_map)))
+		if (offset < mte_to_node(enode)->slot_len)
 			slots = mte_dead_walk(&enode, offset);
 		node = mte_to_node(enode);
 	} while ((node != start) || (node->slot_len < offset));
@@ -5374,8 +5335,6 @@ static void mt_destroy_walk(struct maple_enode *enode, struct maple_tree *mt,
 free_leaf:
 	if (free)
 		kfree(node);
-	else
-		mt_clear_meta(mt, node, node->type);
 }
 
 /*
Signature · 1 line
2.53.0
author maintainer
#1588 lore raw

PATCH 1558/1756 ALSA: seq: Allow system notification in atomic

In reply to Greg Kroah-Hartman

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

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

From: Takashi Iwai <[email protected]>

[ Upstream commit 10a29de13bbc7ca92ae85184cf2f966c4ce3b69b ]

Currently the system notification helper assumes only the non-atomic delivery. For allowing an event delivery in non-atomic context, add the atomic flag to the helper function.

This is a preliminary change for the support of UMP EP/FB notification.

Stable-dep-of: 9b30046de03a ("ALSA: ump: Drain sequencer callbacks before freeing their client")

---
 sound/core/seq/seq_clientmgr.c |  2 +-
 sound/core/seq/seq_system.c    |  9 +++++----
 sound/core/seq/seq_system.h    | 21 +++++++++++++--------
 3 files changed, 19 insertions(+), 13 deletions(-)
sound/core/seq/seq_clientmgr.c +1 -1
index 4dc5b15029e45..55014bfc02570 100644
@@ -1541,7 +1541,7 @@ int snd_seq_client_notify_subscription(int client, int port,
 	event.data.connect.dest = info->dest;
 	event.data.connect.sender = info->sender;
 
-	return snd_seq_system_notify(client, port, &event);  /* non-atomic */
+	return snd_seq_system_notify(client, port, &event, false);  /* non-atomic */
 }
 
 
sound/core/seq/seq_system.c +5 -4
index 80267290190d0..d8ed05b1705e1 100644
@@ -76,26 +76,27 @@ static int setheader(struct snd_seq_event * ev, int client, int port)
 
 
 /* entry points for broadcasting system events */
-void snd_seq_system_broadcast(int client, int port, int type)
+void snd_seq_system_broadcast(int client, int port, int type, bool atomic)
 {
 	struct snd_seq_event ev;
 	
 	if (setheader(&ev, client, port) < 0)
 		return;
 	ev.type = type;
-	snd_seq_kernel_client_dispatch(sysclient, &ev, 0, 0);
+	snd_seq_kernel_client_dispatch(sysclient, &ev, atomic, 0);
 }
 EXPORT_SYMBOL_GPL(snd_seq_system_broadcast);
 
 /* entry points for broadcasting system events */
-int snd_seq_system_notify(int client, int port, struct snd_seq_event *ev)
+int snd_seq_system_notify(int client, int port, struct snd_seq_event *ev,
+			  bool atomic)
 {
 	ev->flags = SNDRV_SEQ_EVENT_LENGTH_FIXED;
 	ev->source.client = sysclient;
 	ev->source.port = announce_port;
 	ev->dest.client = client;
 	ev->dest.port = port;
-	return snd_seq_kernel_client_dispatch(sysclient, ev, 0, 0);
+	return snd_seq_kernel_client_dispatch(sysclient, ev, atomic, 0);
 }
 
 /* call-back handler for timer events */
sound/core/seq/seq_system.h +13 -8
index 4fe88ad403461..a118f7252b62a 100644
@@ -10,16 +10,21 @@
 
 
 /* entry points for broadcasting system events */
-void snd_seq_system_broadcast(int client, int port, int type);
+void snd_seq_system_broadcast(int client, int port, int type, bool atomic);
 
-#define snd_seq_system_client_ev_client_start(client) snd_seq_system_broadcast(client, 0, SNDRV_SEQ_EVENT_CLIENT_START)
-#define snd_seq_system_client_ev_client_exit(client) snd_seq_system_broadcast(client, 0, SNDRV_SEQ_EVENT_CLIENT_EXIT)
-#define snd_seq_system_client_ev_client_change(client) snd_seq_system_broadcast(client, 0, SNDRV_SEQ_EVENT_CLIENT_CHANGE)
-#define snd_seq_system_client_ev_port_start(client, port) snd_seq_system_broadcast(client, port, SNDRV_SEQ_EVENT_PORT_START)
-#define snd_seq_system_client_ev_port_exit(client, port) snd_seq_system_broadcast(client, port, SNDRV_SEQ_EVENT_PORT_EXIT)
-#define snd_seq_system_client_ev_port_change(client, port) snd_seq_system_broadcast(client, port, SNDRV_SEQ_EVENT_PORT_CHANGE)
+/* normal system notification event broadcast */
+#define notify_event(client, port, type) \
+	snd_seq_system_broadcast(client, port, type, false)
 
-int snd_seq_system_notify(int client, int port, struct snd_seq_event *ev);
+#define snd_seq_system_client_ev_client_start(client) notify_event(client, 0, SNDRV_SEQ_EVENT_CLIENT_START)
+#define snd_seq_system_client_ev_client_exit(client) notify_event(client, 0, SNDRV_SEQ_EVENT_CLIENT_EXIT)
+#define snd_seq_system_client_ev_client_change(client) notify_event(client, 0, SNDRV_SEQ_EVENT_CLIENT_CHANGE)
+#define snd_seq_system_client_ev_port_start(client, port) notify_event(client, port, SNDRV_SEQ_EVENT_PORT_START)
+#define snd_seq_system_client_ev_port_exit(client, port) notify_event(client, port, SNDRV_SEQ_EVENT_PORT_EXIT)
+#define snd_seq_system_client_ev_port_change(client, port) notify_event(client, port, SNDRV_SEQ_EVENT_PORT_CHANGE)
+
+int snd_seq_system_notify(int client, int port, struct snd_seq_event *ev,
+			  bool atomic);
 
 /* register our internal client */
 int snd_seq_system_client_init(void);
Signature · 1 line
2.53.0
author maintainer
#1589 lore raw

PATCH 1559/1756 ALSA: seq: Notify UMP EP and FB changes

In reply to Greg Kroah-Hartman

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

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

From: Takashi Iwai <[email protected]>

[ Upstream commit 3ab4a3199c782eae9b683b952f3ec5a766e4a096 ]

So far we notify the sequencer client and port changes upon UMP FB changes, but those aren't really corresponding to the UMP updates. e.g. when a FB info gets updated, it's not notified but done only when some of sequencer port attribute is changed. This is no ideal behavior.

This patch adds the two new sequencer event types for notifying the UMP EP and FB changes via the announce port. The new event takes snd_seq_ev_ump_notify type data, which is compatible with snd_seq_addr (where the port number is replaced with the block number).

The events are sent when the EP and FB info gets updated explicitly via ioctl, or the backend UMP receives the corresponding UMP messages.

The sequencer protocol version is bumped to 1.0.5 along with it.

Stable-dep-of: 9b30046de03a ("ALSA: ump: Drain sequencer callbacks before freeing their client")

---
 Documentation/sound/designs/midi-2.0.rst |  7 +++++
 include/sound/ump.h                      |  1 +
 include/uapi/sound/asequencer.h          | 12 ++++++-
 sound/core/seq/seq_clientmgr.c           | 10 ++++++
 sound/core/seq/seq_system.h              | 10 ++++++
 sound/core/seq/seq_ump_client.c          | 40 ++++++++++++++++++++++--
 sound/core/ump.c                         | 23 ++++++++++++--
 7 files changed, 97 insertions(+), 6 deletions(-)
Documentation/sound/designs/midi-2.0.rst +7 -0
index d6c17a47c8320..71a343c93fe7d 100644
@@ -388,6 +388,13 @@ Sequencer API Extensions
   announcement to the ALSA sequencer system port, similarly like the
   normal port change notification.
 
+* There are two extended event types for notifying the UMP Endpoint and
+  Function Block changes via the system announcement port:
+  type 68 (`SNDRV_SEQ_EVENT_UMP_EP_CHANGE`) and type 69
+  (`SNDRV_SEQ_EVENT_UMP_BLOCK_CHANGE`). They take the new type,
+  `snd_seq_ev_ump_notify` in the payload, indicating the client number
+  and the FB number that are changed.
+
 
 MIDI2 USB Gadget Function Driver
 ================================
include/sound/ump.h +1 -0
index 532c2c3ea28e3..73f97f88e2ed7 100644
@@ -83,6 +83,7 @@ struct snd_ump_ops {
 struct snd_seq_ump_ops {
 	void (*input_receive)(struct snd_ump_endpoint *ump,
 			      const u32 *data, int words);
+	int (*notify_ep_change)(struct snd_ump_endpoint *ump);
 	int (*notify_fb_change)(struct snd_ump_endpoint *ump,
 				struct snd_ump_block *fb);
 	int (*switch_protocol)(struct snd_ump_endpoint *ump);
include/uapi/sound/asequencer.h +11 -1
index bc30c1f2a1094..a5c41f771e059 100644
@@ -10,7 +10,7 @@
 #include <sound/asound.h>
 
 /** version of the sequencer */
-#define SNDRV_SEQ_VERSION SNDRV_PROTOCOL_VERSION(1, 0, 4)
+#define SNDRV_SEQ_VERSION SNDRV_PROTOCOL_VERSION(1, 0, 5)
 
 /**
  * definition of sequencer event types
@@ -92,6 +92,9 @@
 #define SNDRV_SEQ_EVENT_PORT_SUBSCRIBED	66	/* ports connected */
 #define SNDRV_SEQ_EVENT_PORT_UNSUBSCRIBED 67	/* ports disconnected */
 
+#define SNDRV_SEQ_EVENT_UMP_EP_CHANGE	68	/* UMP EP info has changed */
+#define SNDRV_SEQ_EVENT_UMP_BLOCK_CHANGE 69	/* UMP block info has changed */
+
 /* 70-89:  synthesizer events - obsoleted */
 
 /** user-defined events with fixed length
@@ -253,6 +256,12 @@ struct snd_seq_ev_quote {
 	struct snd_seq_event *event;		/* quoted event */
 } __packed;
 
+	/* UMP info change notify */
+struct snd_seq_ev_ump_notify {
+	unsigned char client;	/**< Client number */
+	unsigned char block;	/**< Block number (optional) */
+};
+
 union snd_seq_event_data { /* event data... */
 	struct snd_seq_ev_note note;
 	struct snd_seq_ev_ctrl control;
@@ -265,6 +274,7 @@ union snd_seq_event_data { /* event data... */
 	struct snd_seq_connect connect;
 	struct snd_seq_result result;
 	struct snd_seq_ev_quote quote;
+	struct snd_seq_ev_ump_notify ump_notify;
 };
 
 	/* sequencer event */
sound/core/seq/seq_clientmgr.c +10 -0
index 55014bfc02570..6d0c0937236da 100644
@@ -2295,6 +2295,16 @@ static int snd_seq_ioctl_client_ump_info(struct snd_seq_client *caller,
  error:
 	mutex_unlock(&cptr->ioctl_mutex);
 	snd_seq_client_unlock(cptr);
+	if (!err && cmd == SNDRV_SEQ_IOCTL_SET_CLIENT_UMP_INFO) {
+		if (type == SNDRV_SEQ_CLIENT_UMP_INFO_ENDPOINT)
+			snd_seq_system_ump_notify(client, 0,
+						  SNDRV_SEQ_EVENT_UMP_EP_CHANGE,
+						  false);
+		else
+			snd_seq_system_ump_notify(client, type - 1,
+						  SNDRV_SEQ_EVENT_UMP_BLOCK_CHANGE,
+						  false);
+	}
 	return err;
 }
 #endif
sound/core/seq/seq_system.h +10 -0
index a118f7252b62a..62e513f748715 100644
@@ -16,6 +16,16 @@ void snd_seq_system_broadcast(int client, int port, int type, bool atomic);
 #define notify_event(client, port, type) \
 	snd_seq_system_broadcast(client, port, type, false)
 
+/* notify UMP EP/FB change event */
+static inline void snd_seq_system_ump_notify(int client, int block, int type,
+					     bool atomic)
+{
+	/* reuse the existing snd_seq_system_broadcast():
+	 * struct snd_seq_ev_ump_notify is compatible with struct snd_seq_addr
+	 */
+	snd_seq_system_broadcast(client, block, type, atomic);
+}
+
 #define snd_seq_system_client_ev_client_start(client) notify_event(client, 0, SNDRV_SEQ_EVENT_CLIENT_START)
 #define snd_seq_system_client_ev_client_exit(client) notify_event(client, 0, SNDRV_SEQ_EVENT_CLIENT_EXIT)
 #define snd_seq_system_client_ev_client_change(client) notify_event(client, 0, SNDRV_SEQ_EVENT_CLIENT_CHANGE)
sound/core/seq/seq_ump_client.c +38 -2
index 0d5d5ade87e68..ad794c22cc420 100644
@@ -401,6 +401,33 @@ static void handle_group_notify(struct work_struct *work)
 	setup_client_group_filter(client);
 }
 
+/* UMP EP change notification */
+static int seq_ump_notify_ep_change(struct snd_ump_endpoint *ump)
+{
+	struct seq_ump_client *client = ump->seq_client;
+	struct snd_seq_client *cptr;
+	int client_id;
+
+	if (!client)
+		return -ENODEV;
+	client_id = client->seq_client;
+	cptr = snd_seq_kernel_client_get(client_id);
+	if (!cptr)
+		return -ENODEV;
+
+	snd_seq_system_ump_notify(client_id, 0, SNDRV_SEQ_EVENT_UMP_EP_CHANGE,
+				  true);
+
+	/* update sequencer client name if needed */
+	if (*ump->core.name && strcmp(ump->core.name, cptr->name)) {
+		strscpy(cptr->name, ump->core.name, sizeof(cptr->name));
+		snd_seq_system_client_ev_client_change(client_id);
+	}
+
+	snd_seq_kernel_client_put(cptr);
+	return 0;
+}
+
 /* UMP FB change notification */
 static int seq_ump_notify_fb_change(struct snd_ump_endpoint *ump,
 				    struct snd_ump_block *fb)
@@ -410,20 +437,29 @@ static int seq_ump_notify_fb_change(struct snd_ump_endpoint *ump,
 	if (!client)
 		return -ENODEV;
 	schedule_work(&client->group_notify_work);
+	snd_seq_system_ump_notify(client->seq_client, fb->info.block_id,
+				  SNDRV_SEQ_EVENT_UMP_BLOCK_CHANGE,
+				  true);
 	return 0;
 }
 
 /* UMP protocol change notification; just update the midi_version field */
 static int seq_ump_switch_protocol(struct snd_ump_endpoint *ump)
 {
-	if (!ump->seq_client)
+	struct seq_ump_client *client = ump->seq_client;
+
+	if (!client)
 		return -ENODEV;
-	setup_client_midi_version(ump->seq_client);
+	setup_client_midi_version(client);
+	snd_seq_system_ump_notify(client->seq_client, 0,
+				  SNDRV_SEQ_EVENT_UMP_EP_CHANGE,
+				  true);
 	return 0;
 }
 
 static const struct snd_seq_ump_ops seq_ump_ops = {
 	.input_receive = seq_ump_input_receive,
+	.notify_ep_change = seq_ump_notify_ep_change,
 	.notify_fb_change = seq_ump_notify_fb_change,
 	.switch_protocol = seq_ump_switch_protocol,
 };
sound/core/ump.c +20 -3
index e35253cc019d2..8ee4350d5ed6e 100644
@@ -695,6 +695,15 @@ static void choose_default_protocol(struct snd_ump_endpoint *ump)
 		ump->info.protocol |= SNDRV_UMP_EP_INFO_PROTO_MIDI1;
 }
 
+/* notify the EP info/name change to sequencer */
+static void seq_notify_ep_change(struct snd_ump_endpoint *ump)
+{
+#if IS_ENABLED(CONFIG_SND_SEQUENCER)
+	if (ump->parsed && ump->seq_ops && ump->seq_ops->notify_ep_change)
+		ump->seq_ops->notify_ep_change(ump);
+#endif
+}
+
 /* handle EP info stream message; update the UMP attributes */
 static int ump_handle_ep_info_msg(struct snd_ump_endpoint *ump,
 				  const union snd_ump_stream_msg *buf)
@@ -719,6 +728,7 @@ static int ump_handle_ep_info_msg(struct snd_ump_endpoint *ump,
 
 	ump->info.protocol &= ump->info.protocol_caps;
 	choose_default_protocol(ump);
+	seq_notify_ep_change(ump);
 
 	return 1; /* finished */
 }
@@ -741,6 +751,7 @@ static int ump_handle_device_info_msg(struct snd_ump_endpoint *ump,
 		ump->info.family_id,
 		ump->info.model_id,
 		ump->info.sw_revision);
+	seq_notify_ep_change(ump);
 	return 1; /* finished */
 }
 
@@ -762,6 +773,7 @@ static int ump_handle_ep_name_msg(struct snd_ump_endpoint *ump,
 	if (ret && ump->parsed) {
 		ump_set_rawmidi_name(ump);
 		ump_legacy_set_rawmidi_name(ump);
+		seq_notify_ep_change(ump);
 	}
 
 	return ret;
@@ -771,9 +783,14 @@ static int ump_handle_ep_name_msg(struct snd_ump_endpoint *ump,
 static int ump_handle_product_id_msg(struct snd_ump_endpoint *ump,
 				     const union snd_ump_stream_msg *buf)
 {
-	return ump_append_string(ump, ump->info.product_id,
-				 sizeof(ump->info.product_id),
-				 buf->raw, 2);
+	int ret;
+
+	ret = ump_append_string(ump, ump->info.product_id,
+				sizeof(ump->info.product_id),
+				buf->raw, 2);
+	if (ret)
+		seq_notify_ep_change(ump);
+	return ret;
 }
 
 /* notify the protocol change to sequencer */
Signature · 1 line
2.53.0
author maintainer
#1590 lore raw

PATCH 1560/1756 ALSA: ump: Drain sequencer callbacks before freeing their client

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit 9b30046de03acb3b3f2135d45af6be7ee0b565b6 ]

seq_ump_client_free() cancels group_notify_work while the endpoint still publishes seq_ops and seq_client. A received Function Block update can enter the sequencer callback after cancellation and queue the work again. Even disabling the work cannot protect a callback that already loaded seq_client and then resumes after the client has been freed.

A USB UMP endpoint can continue receiving while its sequencer binding is removed. The following order uses the same endpoint and client:

Sequencer binding removal UMP input completion
------------------------- --------------------
cancel_work_sync()
load seq_ops and seq_client
delete sequencer client
clear endpoint binding
kfree(client)

                                        schedule group_notify_work
                                        read client->seq_client

Cover all calls through seq_ops with SRCU in the UMP core. Withdraw the operations pointer and wait for those callbacks before canceling work and deleting the client. No producer can then queue work after the final cancellation, and both the client and callback code remain available until the last in-flight callback returns.

Publish seq_ops with release/acquire ordering so the separately stored seq_client is initialized before any callback uses it. Use SRCU because sequencer notification delivery can sleep; no callback needs to change its existing execution context or allocation behavior.

Fixes 4a16a3af0571 ("ALSA: seq: ump: Handle FB info update")
Assisted-by LLM
---
 include/sound/ump.h             |  5 +++
 sound/core/seq/seq_ump_client.c |  5 +--
 sound/core/ump.c                | 59 ++++++++++++++++++++++++++++-----
 3 files changed, 59 insertions(+), 10 deletions(-)
include/sound/ump.h +5 -0
index 73f97f88e2ed7..387143783a9b5 100644
@@ -66,6 +66,7 @@ struct snd_ump_endpoint {
 
 #if IS_ENABLED(CONFIG_SND_SEQUENCER)
 	struct snd_seq_device *seq_dev;
+	/* Published after seq_client; calls are covered by UMP core SRCU. */
 	const struct snd_seq_ump_ops *seq_ops;
 	void *seq_client;
 #endif
@@ -126,6 +127,10 @@ int snd_ump_receive_ump_val(struct snd_ump_endpoint *ump, u32 val);
 int snd_ump_switch_protocol(struct snd_ump_endpoint *ump, unsigned int protocol);
 void snd_ump_update_group_attrs(struct snd_ump_endpoint *ump);
 
+#if IS_ENABLED(CONFIG_SND_SEQUENCER)
+void snd_ump_detach_seq(struct snd_ump_endpoint *ump);
+#endif
+
 /*
  * Some definitions for UMP
  */
sound/core/seq/seq_ump_client.c +3 -2
index ad794c22cc420..73b9af190d585 100644
@@ -346,12 +346,12 @@ static int create_ump_endpoint_port(struct seq_ump_client *client)
 /* release the client resources */
 static void seq_ump_client_free(struct seq_ump_client *client)
 {
+	snd_ump_detach_seq(client->ump);
 	cancel_work_sync(&client->group_notify_work);
 
 	if (client->seq_client >= 0)
 		snd_seq_delete_kernel_client(client->seq_client);
 
-	client->ump->seq_ops = NULL;
 	client->ump->seq_client = NULL;
 
 	kfree(client);
@@ -518,7 +518,8 @@ static int snd_seq_ump_probe(struct device *_dev)
 	snd_seq_kernel_client_put(cptr);
 
 	ump->seq_client = client;
-	ump->seq_ops = &seq_ump_ops;
+	/* Publish the initialized client before callbacks can observe seq_ops. */
+	smp_store_release(&ump->seq_ops, &seq_ump_ops);
 	return 0;
 
  error:
sound/core/ump.c +51 -8

95 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#1591 lore raw

PATCH 1561/1756 ALSA: pcmtest: Reject invalid fill_mode values

In reply to Greg Kroah-Hartman

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

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

From: HyeongJun An <[email protected]>

[ Upstream commit 5deb9c57ba93d28a52871a96f3d8794d2cbed035 ]

The fill_block() function handles only fill_mode 0 (random) and 1 (pattern). With any other value it writes nothing and does not move the buffer position. A capture stream then gets no data, and a read fails with -EIO after the timeout. Nothing in the kernel log says why.

Check the value in a set callback, so a bad value is rejected both when the module is loaded and when the parameter is written.

Fixes 315a3d57c64c ("ALSA: Implement the new Virtual PCM Test Driver")
Assisted-by Claude:claude-opus-5-5
---
 sound/drivers/pcmtest.c | 21 ++++++++++++++++++++-
 1 file changed, 20 insertions(+), 1 deletion(-)
sound/drivers/pcmtest.c +20 -1
index 25f21255b0651..3c85f90c0cc1e 100644
@@ -71,13 +71,32 @@ static u8 playback_capture_test;
 static u8 ioctl_reset_test;
 static struct dentry *driver_debug_dir;
 
+static int fill_mode_set(const char *val, const struct kernel_param *kp)
+{
+	short mode;
+	int err;
+
+	err = kstrtos16(val, 0, &mode);
+	if (err)
+		return err;
+	if (mode != FILL_MODE_RAND && mode != FILL_MODE_PAT)
+		return -EINVAL;
+	fill_mode = mode;
+	return 0;
+}
+
+static const struct kernel_param_ops fill_mode_ops = {
+	.set = fill_mode_set,
+	.get = param_get_short,
+};
+
 module_param(index, int, 0444);
 MODULE_PARM_DESC(index, "Index value for pcmtest soundcard");
 module_param(id, charp, 0444);
 MODULE_PARM_DESC(id, "ID string for pcmtest soundcard");
 module_param(enable, bool, 0444);
 MODULE_PARM_DESC(enable, "Enable pcmtest soundcard.");
-module_param(fill_mode, short, 0600);
+module_param_cb(fill_mode, &fill_mode_ops, &fill_mode, 0600);
 MODULE_PARM_DESC(fill_mode, "Buffer fill mode: rand(0) or pattern(1)");
 module_param(inject_delay, int, 0600);
 MODULE_PARM_DESC(inject_delay, "Inject delays during playback/capture (in jiffies)");
Signature · 1 line
2.53.0
author maintainer
#1592 lore raw

PATCH 1562/1756 netlink: fix out-of-bounds bitmap access clearing stale mc groups

In reply to Greg Kroah-Hartman

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

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

From: Henry Martin <[email protected]>

[ Upstream commit 6430fb7f1cc4e329e386521b7b208df443de92f2 ]

netlink_realloc_groups() sizes nlk->groups to the number of groups that exist at bind/ADD_MEMBERSHIP time. When more multicast groups are registered later (e.g. a new genl family), existing sockets keep their smaller bitmap.

When clearing a multicast group of a departing family, __netlink_clear_multicast_users() runs netlink_update_socket_mc() on each socket on mc_list, which does test_bit()/__assign_bit() on group - 1 with no regard to nlk->ngroups. Skip sockets whose bitmap predates the group: such a socket can never have joined it.

The overflow windows differ per architecture, both needing privileged module (un)loading. On 32-bit kernels the ~54 dynamically allocated genl groups already exceed the initial 32-bit bitmap, so the table can grow there directly. On 64-bit kernels the same in-tree set fits the initial 64-bit bitmap only while allocation stays contiguous:
genl_allocate_reserve_groups() takes the first free contiguous range and unregister does not compact, so an unload/reload sequence can fragment the ~59 free IDs until no fitting range remains, forcing the table past 64 bits and reaching the same stale-bitmap overflow on the next family teardown.

This issue was discovered by Tencent CodeBuddy Security.

Fixes 84659eb529b3 ("[NETLIKN]: Allow removing multicast groups.")
---
 net/netlink/af_netlink.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
net/netlink/af_netlink.c +5 -1
index 7e1c087a98647..fb84eaa63d0ac 100644
@@ -2135,8 +2135,12 @@ void __netlink_clear_multicast_users(struct sock *ksk, unsigned int group)
 	struct netlink_table *tbl = &nl_table[ksk->sk_protocol];
 	struct hlist_node *tmp;
 
-	sk_for_each_bound_safe(sk, tmp, &tbl->mc_list)
+	sk_for_each_bound_safe(sk, tmp, &tbl->mc_list) {
+		/* bitmap predates the group, can't be a member */
+		if (group - 1 >= nlk_sk(sk)->ngroups)
+			continue;
 		netlink_update_socket_mc(nlk_sk(sk), group, 0);
+	}
 }
 
 struct nlmsghdr *
Signature · 1 line
2.53.0
author maintainer
#1593 lore raw

PATCH 1563/1756 ceph: remove unused field `i_cap_migration_resv`

In reply to Greg Kroah-Hartman

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

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

From: Max Kellermann <[email protected]>

[ Upstream commit a200e12135c96893f7c29bdf97f46868132f695d ]

This field was added 17 years ago by commit de57606c23afd ("ceph:
client types") but it was never used.

This reduces the size of struct ceph_inode_info by 8 bytes.

---
 fs/ceph/super.h | 1 -
 1 file changed, 1 deletion(-)
fs/ceph/super.h +0 -1
index 83ddd61e16475..e5c22c833b8ef 100644
@@ -438,7 +438,6 @@ struct ceph_inode_info {
 	wait_queue_head_t i_cap_wq;      /* threads waiting on a capability */
 	unsigned long i_hold_caps_max; /* jiffies */
 	struct list_head i_cap_delay_list;  /* for delayed cap release to mds */
-	struct ceph_cap_reservation i_cap_migration_resv;
 	struct list_head i_cap_snaps;   /* snapped state pending flush to mds */
 	struct ceph_snap_context *i_head_snapc;  /* set if wr_buffer_head > 0 or
 						    dirty|flushing caps */
Signature · 1 line
2.53.0
author maintainer
#1594 lore raw

PATCH 1564/1756 ceph: mark the superblock active after mounting

In reply to Greg Kroah-Hartman

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

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

From: Xiubo Li <[email protected]>

[ Upstream commit 32eacfae3b16f6a9c0c20f946115abf5a091c922 ]

ceph_get_tree() calls sget_fc() directly and so never goes through vfs_get_super(), which is what sets SB_ACTIVE after fill_super for filesystems that use it. Before commit 82995cc6c5ae ("libceph, rbd,
ceph: convert to use the new mount API") the flag used to be set by get_sb_nodev(), which did this for ceph, but the conversion dropped it.

SB_ACTIVE is required for iput_final() to retain an inode on the inode LRU instead of evicting it once its last reference goes away. This has gone unnoticed because ceph sets inode_just_drop() for ->drop_inode, which always asks for eviction, so the retain branch in iput_final() was never reachable. The next patch makes ->drop_inode() able to retain inodes, and that needs the flag to actually work.

Set it once the mount is up, like nfs_get_tree() does.

Fixes 82995cc6c5ae ("libceph, rbd, ceph: convert to use the new mount API")
---
 fs/ceph/super.c | 9 +++++++++
 1 file changed, 9 insertions(+)
fs/ceph/super.c +9 -0
index 96d582f71beaa..bd315aaaff13c 100644
@@ -1348,6 +1348,15 @@ static int ceph_get_tree(struct fs_context *fc)
 	doutc(fsc->client, "root %p inode %p ino %llx.%llx\n", res,
 		    d_inode(res), ceph_vinop(d_inode(res)));
 	fc->root = fsc->sb->s_root;
+
+	/*
+	 * The mount is up.  sget_fc() leaves SB_ACTIVE unset, and, unlike
+	 * filesystems that go through vfs_get_super(), nothing else sets
+	 * it here, so iput_final() would always evict an inode whose
+	 * ->drop_inode() asks to retain it.  Set it like nfs_get_tree()
+	 * does.
+	 */
+	sb->s_flags |= SB_ACTIVE;
 	return 0;
 
 out_splat:
Signature · 1 line
2.53.0
author maintainer
#1595 lore raw

PATCH 1565/1756 ceph: fix page vector leak on encrypted netfs read EIO path

In reply to Greg Kroah-Hartman

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

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

From: Alex Markuze <[email protected]>

[ Upstream commit 00a0d7f377f6af59bc559b2e07dffff63eaa5544 ]

ceph_netfs_issue_read() pins pages with iov_iter_get_pages_alloc2() for encrypted inodes and attaches them with own_pages=false. If ceph_inc_osd_stopping_blocker() then fails, the request is dropped without calling finish_netfs_read(), so the page array and the references taken on those pages leak: ceph_osd_data_release() only frees pages when own_pages is true, and __free_pages() would be the wrong destructor for GUP-pinned pages.

Release the vector with put_page() and kvfree() on that error path, matching finish_netfs_read(). Unencrypted ITER reads are unaffected.

Fixes 1464de9f813e ("ceph: wait for OSD requests' callbacks to finish when unmounting")
---
 fs/ceph/addr.c | 11 +++++++++++
 1 file changed, 11 insertions(+)
fs/ceph/addr.c +11 -0
index 63ead85dff268..0c2abc4adea67 100644
@@ -432,6 +432,17 @@ static void ceph_netfs_issue_read(struct netfs_io_subrequest *subreq)
 		osd_req_op_extent_osd_iter(req, 0, &subreq->io_iter);
 	}
 	if (!ceph_inc_osd_stopping_blocker(fsc->mdsc)) {
+		struct ceph_osd_data *osd_data =
+			osd_req_op_extent_osd_data(req, 0);
+
+		if (osd_data->type == CEPH_OSD_DATA_TYPE_PAGES) {
+			int num_pages = calc_pages_for(osd_data->alignment,
+						       osd_data->length);
+
+			for (int i = 0; i < num_pages; i++)
+				put_page(osd_data->pages[i]);
+			kvfree(osd_data->pages);
+		}
 		err = -EIO;
 		goto out;
 	}
Signature · 1 line
2.53.0
author maintainer
#1596 lore raw

PATCH 1566/1756 ceph: fix generic/421 test failure

In reply to Greg Kroah-Hartman

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

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

From: Viacheslav Dubeyko <[email protected]>

[ Upstream commit fd7449d937e7fb3144770592927cf452bf66dbd3 ]

The generic/421 fails to finish because of the issue:

Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.894678] INFO: task kworker/u48:0:11 blocked for more than 122 seconds. Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.895403] Not tainted 6.13.0-rc5+ #1
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.895867] "echo 0 > /proc/sys/kernel/hung_task_timeout_secs" disables this message. Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.896633] task:kworker/u48:0 state:D stack:0 pid:11 tgid:11 ppid:2 flags:0x00004000 Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.896641] Workqueue: writeback wb_workfn (flush-ceph-24)
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897614] Call Trace:
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897620] <TASK>
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897629] __schedule+0x443/0x16b0
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897637] schedule+0x2b/0x140
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897640] io_schedule+0x4c/0x80
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897643] folio_wait_bit_common+0x11b/0x310
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897646] ? _raw_spin_unlock_irq+0xe/0x50
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897652] ? __pfx_wake_page_function+0x10/0x10
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897655] __folio_lock+0x17/0x30
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897658] ceph_writepages_start+0xca9/0x1fb0
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897663] ? fsnotify_remove_queued_event+0x2f/0x40
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897668] do_writepages+0xd2/0x240
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897672] __writeback_single_inode+0x44/0x350
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897675] writeback_sb_inodes+0x25c/0x550
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897680] wb_writeback+0x89/0x310
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897683] ? finish_task_switch.isra.0+0x97/0x310
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897687] wb_workfn+0xb5/0x410
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897689] process_one_work+0x188/0x3d0
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897692] worker_thread+0x2b5/0x3c0
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897694] ? __pfx_worker_thread+0x10/0x10
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897696] kthread+0xe1/0x120
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897699] ? __pfx_kthread+0x10/0x10
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897701] ret_from_fork+0x43/0x70
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897705] ? __pfx_kthread+0x10/0x10
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897707] ret_from_fork_asm+0x1a/0x30
Jan 3 14:25:27 ceph-testing-0001 kernel: [ 369.897711] </TASK>

There are several issues here:
(1) ceph_kill_sb() doesn't wait ending of flushing all dirty folios/pages because of racy nature of mdsc->stopping_blockers. As a result, mdsc->stopping becomes CEPH_MDSC_STOPPING_FLUSHED too early.
(2) The ceph_inc_osd_stopping_blocker(fsc->mdsc) fails to increment mdsc->stopping_blockers. Finally, already locked folios/pages are never been unlocked and the logic tries to lock the same page second time.
(3) The folio_batch with found dirty pages by filemap_get_folios_tag() is not processed properly. And this is why some number of dirty pages simply never processed and we have dirty folios/pages after unmount anyway.

This patch fixes the issues by means of:
(1) introducing dirty_folios counter and flush_end_wq waiting queue in struct ceph_mds_client;
(2) ceph_dirty_folio() increments the dirty_folios counter;
(3) writepages_finish() decrements the dirty_folios counter and wake up all waiters on the queue if dirty_folios counter is equal or lesser than zero;
(4) adding in ceph_kill_sb() method the logic of checking the value of dirty_folios counter and waiting if it is bigger than zero;
(5) adding ceph_inc_osd_stopping_blocker() call in the beginning of the ceph_writepages_start() and ceph_dec_osd_stopping_blocker() at the end of the ceph_writepages_start() with the goal to resolve the racy nature of mdsc->stopping_blockers.

sudo ./check generic/421

FSTYP         -- ceph
PLATFORM      -- Linux/x86_64 ceph-testing-0001 6.13.0+ #137 SMP PREEMPT_DYNAMIC Mon Feb  3 20:30:08 UTC 2025
MKFS_OPTIONS  -- 127.0.0.1:40551:/scratch

MOUNT_OPTIONS -- -o name=fs,secret=<secret>,ms_mode=crc,nowsync,copyfrom 127.0.0.1:40551:/scratch /mnt/scratch

generic/421 7s ... 4s
Ran: generic/421
Passed all 1 tests

Stable-dep-of: ad67b498de17 ("ceph: fix error handling when the OSD client is stopping in ceph_submit_write()")

---
 fs/ceph/addr.c       | 20 +++++++++++++++++++-
 fs/ceph/mds_client.c |  2 ++
 fs/ceph/mds_client.h |  3 +++
 fs/ceph/super.c      | 11 +++++++++++
 4 files changed, 35 insertions(+), 1 deletion(-)
fs/ceph/addr.c +19 -1
index 0c2abc4adea67..9e3706e0a06f6 100644
@@ -82,6 +82,7 @@ static bool ceph_dirty_folio(struct address_space *mapping, struct folio *folio)
 {
 	struct inode *inode = mapping->host;
 	struct ceph_client *cl = ceph_inode_to_client(inode);
+	struct ceph_mds_client *mdsc = ceph_sb_to_mdsc(inode->i_sb);
 	struct ceph_inode_info *ci;
 	struct ceph_snap_context *snapc;
 
@@ -92,6 +93,8 @@ static bool ceph_dirty_folio(struct address_space *mapping, struct folio *folio)
 		return false;
 	}
 
+	atomic64_inc(&mdsc->dirty_folios);
+
 	ci = ceph_inode(inode);
 
 	/* dirty the head */
@@ -899,6 +902,7 @@ static void writepages_finish(struct ceph_osd_request *req)
 	struct ceph_snap_context *snapc = req->r_snapc;
 	struct address_space *mapping = inode->i_mapping;
 	struct ceph_fs_client *fsc = ceph_inode_to_fs_client(inode);
+	struct ceph_mds_client *mdsc = ceph_sb_to_mdsc(inode->i_sb);
 	unsigned int len = 0;
 	bool remove_page;
 
@@ -954,6 +958,12 @@ static void writepages_finish(struct ceph_osd_request *req)
 
 			ceph_put_snap_context(detach_page_private(page));
 			end_page_writeback(page);
+
+			if (atomic64_dec_return(&mdsc->dirty_folios) <= 0) {
+				wake_up_all(&mdsc->flush_end_wq);
+				WARN_ON(atomic64_read(&mdsc->dirty_folios) < 0);
+			}
+
 			doutc(cl, "unlocking %p\n", page);
 
 			if (remove_page)
@@ -1667,13 +1677,18 @@ static int ceph_writepages_start(struct address_space *mapping,
 
 	ceph_init_writeback_ctl(mapping, wbc, &ceph_wbc);
 
+	if (!ceph_inc_osd_stopping_blocker(fsc->mdsc)) {
+		rc = -EIO;
+		goto out;
+	}
+
 retry:
 	rc = ceph_define_writeback_range(mapping, wbc, &ceph_wbc);
 	if (rc == -ENODATA) {
 		/* hmm, why does writepages get called when there
 		   is no dirty data? */
 		rc = 0;
-		goto out;
+		goto dec_osd_stopping_blocker;
 	}
 
 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
@@ -1762,6 +1777,9 @@ static int ceph_writepages_start(struct address_space *mapping,
 	if (wbc->range_cyclic || (ceph_wbc.range_whole && wbc->nr_to_write > 0))
 		mapping->writeback_index = ceph_wbc.index;
 
+dec_osd_stopping_blocker:
+	ceph_dec_osd_stopping_blocker(fsc->mdsc);
+
 out:
 	ceph_put_snap_context(ceph_wbc.last_snapc);
 	doutc(cl, "%llx.%llx dend - startone, rc = %d\n", ceph_vinop(inode),
fs/ceph/mds_client.c +2 -0
index 69f716e162190..14c307df2b981 100644
@@ -5679,6 +5679,8 @@ int ceph_mdsc_init(struct ceph_fs_client *fsc)
 	spin_lock_init(&mdsc->stopping_lock);
 	atomic_set(&mdsc->stopping_blockers, 0);
 	init_completion(&mdsc->stopping_waiter);
+	atomic64_set(&mdsc->dirty_folios, 0);
+	init_waitqueue_head(&mdsc->flush_end_wq);
 	init_waitqueue_head(&mdsc->session_close_wq);
 	INIT_LIST_HEAD(&mdsc->waiting_for_map);
 	mdsc->quotarealms_inodes = RB_ROOT;
fs/ceph/mds_client.h +3 -0
index a1629e61e75bf..5a5600b15cee4 100644
@@ -458,6 +458,9 @@ struct ceph_mds_client {
 	atomic_t                stopping_blockers;
 	struct completion	stopping_waiter;
 
+	atomic64_t		dirty_folios;
+	wait_queue_head_t	flush_end_wq;
+
 	atomic64_t		quotarealms_count; /* # realms with quota */
 	/*
 	 * We keep a list of inodes we don't see in the mountpoint but that we
fs/ceph/super.c +11 -0
index bd315aaaff13c..45425700a7bd7 100644
@@ -1559,6 +1559,17 @@ static void ceph_kill_sb(struct super_block *s)
 	 */
 	sync_filesystem(s);
 
+	if (atomic64_read(&mdsc->dirty_folios) > 0) {
+		wait_queue_head_t *wq = &mdsc->flush_end_wq;
+		long timeleft = wait_event_killable_timeout(*wq,
+					atomic64_read(&mdsc->dirty_folios) <= 0,
+					fsc->client->options->mount_timeout);
+		if (!timeleft) /* timed out */
+			pr_warn_client(cl, "umount timed out, %ld\n", timeleft);
+		else if (timeleft < 0) /* killed */
+			pr_warn_client(cl, "umount was killed, %ld\n", timeleft);
+	}
+
 	spin_lock(&mdsc->stopping_lock);
 	mdsc->stopping = CEPH_MDSC_STOPPING_FLUSHING;
 	wait = !!atomic_read(&mdsc->stopping_blockers);
Signature · 1 line
2.53.0
author maintainer
#1597 lore raw

PATCH 1567/1756 ceph: fix error handling when the OSD client is stopping in ceph_submit_write()

In reply to Greg Kroah-Hartman

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

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

From: Tal Zussman <[email protected]>

[ Upstream commit ad67b498de17b709f050d7ebf84749b1fc6a242d ]

When ceph_inc_osd_stopping_blocker() fails, ceph_submit_write() redirties and unlocks the folios remaining in ceph_wbc->fbatch. However, none of those folios are locked at this point: locked folios were moved to ceph_wbc->pages[] and removed from the fbatch by ceph_process_folio_batch(). Unlocking them triggers VM_BUG_ON_FOLIO(!folio_test_locked(folio)) in folio_unlock(), or unlocks a folio locked by another task.

This error path also returns -EIO without fully cleaning up the folios in ceph_wbc->pages[]: their references are never dropped, fscrypt bounce pages are never freed, the writeback congestion count is never decremented, and the pages array is leaked. ceph_wbc->locked_pages is also left non-zero, so ceph_writepages_start() loops back around and hits BUG_ON(ceph_wbc.locked_pages).

Leave the fbatch folios alone, as ceph_writepages_start() drops their references when releasing the batch, and unwind ceph_wbc->pages[] the same way writepages_finish() would have. Abort writeback in ceph_writepages_start() instead of continuing, matching the handling of ceph_inc_osd_stopping_blocker() failure on entry, as the OSD client is being torn down and further writeback cannot make progress.

An LLM was used to verify that the cleanup was comprehensive, and suggested aborting the writeback instead of continuing.

---
 fs/ceph/addr.c | 37 ++++++++++++++++++++++---------------
 1 file changed, 22 insertions(+), 15 deletions(-)
fs/ceph/addr.c +22 -15
index 9e3706e0a06f6..e9fa0b9afcc13 100644
@@ -1478,26 +1478,30 @@ int ceph_submit_write(struct address_space *mapping,
 	BUG_ON(len < ceph_fscrypt_page_offset(page) + thp_size(page) - offset);
 
 	if (!ceph_inc_osd_stopping_blocker(fsc->mdsc)) {
-		for (i = 0; i < folio_batch_count(&ceph_wbc->fbatch); i++) {
-			struct folio *folio = ceph_wbc->fbatch.folios[i];
+		for (i = 0; i < ceph_wbc->locked_pages; i++) {
+			page = ceph_wbc->pages[i];
+			if (fscrypt_is_bounce_page(page)) {
+				page = fscrypt_pagecache_page(page);
+				fscrypt_free_bounce_page(ceph_wbc->pages[i]);
+			}
 
-			if (!folio)
-				continue;
+			if (atomic_long_dec_return(&fsc->writeback_count) <
+			    CONGESTION_OFF_THRESH(fsc->mount_options->congestion_kb))
+				fsc->write_congested = false;
 
-			page = &folio->page;
 			redirty_page_for_writepage(wbc, page);
 			unlock_page(page);
+			put_page(page);
 		}
 
-		for (i = 0; i < ceph_wbc->locked_pages; i++) {
-			page = ceph_fscrypt_pagecache_page(ceph_wbc->pages[i]);
-
-			if (!page)
-				continue;
-
-			redirty_page_for_writepage(wbc, page);
-			unlock_page(page);
+		if (ceph_wbc->from_pool) {
+			mempool_free(ceph_wbc->pages, ceph_wb_pagevec_pool);
+			ceph_wbc->from_pool = false;
+		} else {
+			kfree(ceph_wbc->pages);
 		}
+		ceph_wbc->pages = NULL;
+		ceph_wbc->locked_pages = 0;
 
 		ceph_osdc_put_request(req);
 		return -EIO;
@@ -1731,8 +1735,11 @@ static int ceph_writepages_start(struct address_space *mapping,
 		}
 
 		rc = ceph_submit_write(mapping, wbc, &ceph_wbc);
-		if (rc)
-			goto release_folios;
+		if (rc) {
+			/* the OSD client is being torn down, don't retry */
+			folio_batch_release(&ceph_wbc.fbatch);
+			goto dec_osd_stopping_blocker;
+		}
 
 		ceph_wbc.locked_pages = 0;
 		ceph_wbc.strip_unit_end = 0;
Signature · 1 line
2.53.0
author maintainer
#1598 lore raw

PATCH 1568/1756 ceph: Convert ceph_move_dirty_page_in_page_array() to move_dirty_folio_in_page_array()

In reply to Greg Kroah-Hartman

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

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

From: Matthew Wilcox (Oracle) <[email protected]>

[ Upstream commit ad49fe2b3d54fe657756e1dbf0acb5ed9cf5c576 ]

Shorten the name of this internal function by dropping the 'ceph_' prefix and pass in a folio instead of a page.

Stable-dep-of: 7807710d88ad ("ceph: fix writeback_count leak when a bounce page allocation fails")

---
 fs/ceph/addr.c | 16 +++++++---------
 1 file changed, 7 insertions(+), 9 deletions(-)
fs/ceph/addr.c +7 -9
index e9fa0b9afcc13..cb791f468d376 100644
@@ -1267,11 +1267,9 @@ bool is_write_congestion_happened(struct ceph_fs_client *fsc)
 		CONGESTION_ON_THRESH(fsc->mount_options->congestion_kb);
 }
 
-static inline
-int ceph_move_dirty_page_in_page_array(struct address_space *mapping,
-					struct writeback_control *wbc,
-					struct ceph_writeback_ctl *ceph_wbc,
-					struct page *page)
+static inline int move_dirty_folio_in_page_array(struct address_space *mapping,
+		struct writeback_control *wbc,
+		struct ceph_writeback_ctl *ceph_wbc, struct folio *folio)
 {
 	struct inode *inode = mapping->host;
 	struct ceph_fs_client *fsc = ceph_inode_to_fs_client(inode);
@@ -1281,7 +1279,7 @@ int ceph_move_dirty_page_in_page_array(struct address_space *mapping,
 	gfp_t gfp_flags = ceph_wbc->locked_pages ? GFP_NOWAIT : GFP_NOFS;
 
 	if (IS_ENCRYPTED(inode)) {
-		pages[index] = fscrypt_encrypt_pagecache_blocks(page,
+		pages[index] = fscrypt_encrypt_pagecache_blocks(&folio->page,
 								PAGE_SIZE,
 								0,
 								gfp_flags);
@@ -1300,7 +1298,7 @@ int ceph_move_dirty_page_in_page_array(struct address_space *mapping,
 			return err;
 		}
 	} else {
-		pages[index] = page;
+		pages[index] = &folio->page;
 	}
 
 	ceph_wbc->locked_pages++;
@@ -1391,8 +1389,8 @@ int ceph_process_folio_batch(struct address_space *mapping,
 
 		fsc->write_congested = is_write_congestion_happened(fsc);
 
-		rc = ceph_move_dirty_page_in_page_array(mapping, wbc,
-							ceph_wbc, &folio->page);
+		rc = move_dirty_folio_in_page_array(mapping, wbc, ceph_wbc,
+				folio);
 		if (rc) {
 			/* Did we just begin a new contiguous op? Nevermind! */
 			if (ceph_wbc->len == 0)
Signature · 1 line
2.53.0
author maintainer
#1599 lore raw

PATCH 1569/1756 ceph: fix writeback_count leak when a bounce page allocation fails

In reply to Greg Kroah-Hartman

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

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

From: Tal Zussman <[email protected]>

[ Upstream commit 7807710d88ad03e7ca9b5f79f518f040db2a4e09 ]

ceph_process_folio_batch() calls is_write_congestion_happened(), which increments fsc->writeback_count, before calling move_dirty_folio_in_page_array(). If the fscrypt bounce page allocation there fails, the folio is redirtied and never makes it into the page array, but the count is never dropped.

write_congested is only cleared when a decrement falls below CONGESTION_OFF_THRESH, so the leaked counts set congestion early and eventually leave write_congested set for good. Every WB_SYNC_NONE writeback then returns 0 and background writeback stops entirely.

Bump the count only once the folio is in the page array.

Fixes d55207717ded ("ceph: add encryption support to writepage and writepages")
Assisted-by Claude:fable-5.1
---
 fs/ceph/addr.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/ceph/addr.c +2 -2
index cb791f468d376..3edb0f7097aab 100644
@@ -1387,8 +1387,6 @@ int ceph_process_folio_batch(struct address_space *mapping,
 		doutc(cl, "%llx.%llx will write folio %p idx %lu\n",
 		      ceph_vinop(inode), folio, folio->index);
 
-		fsc->write_congested = is_write_congestion_happened(fsc);
-
 		rc = move_dirty_folio_in_page_array(mapping, wbc, ceph_wbc,
 				folio);
 		if (rc) {
@@ -1401,6 +1399,8 @@ int ceph_process_folio_batch(struct address_space *mapping,
 			break;
 		}
 
+		fsc->write_congested = is_write_congestion_happened(fsc);
+
 		ceph_wbc->fbatch.folios[i] = NULL;
 		ceph_wbc->len += folio_size(folio);
 	}
Signature · 1 line
2.53.0
author maintainer
#1600 lore raw

PATCH 1570/1756 ceph: dont clear write_congested when collecting folios

In reply to Greg Kroah-Hartman

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

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

From: Tal Zussman <[email protected]>

[ Upstream commit 77ff2ba4630b9e9e9f73bbaaeb675638b2c20dd0 ]

ceph_process_folio_batch() assigns the result of is_write_congestion_happened() to fsc->write_congested for every folio it collects. The code it replaced only ever set write_congested to true here, leaving the decrement paths to clear it once writeback_count drops below CONGESTION_OFF_THRESH. The unconditional assignment means that a sync writeback that runs while the count sits between the off and on thresholds clears the flag on its first folio, and background writeback resumes early.

Only set the flag here, as before.

Fixes ce80b76dd327 ("ceph: introduce ceph_process_folio_batch() method")
Assisted-by Claude:fable-5.1
---
 fs/ceph/addr.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
fs/ceph/addr.c +2 -1
index 3edb0f7097aab..947932a51aa0f 100644
@@ -1399,7 +1399,8 @@ int ceph_process_folio_batch(struct address_space *mapping,
 			break;
 		}
 
-		fsc->write_congested = is_write_congestion_happened(fsc);
+		if (is_write_congestion_happened(fsc))
+			fsc->write_congested = true;
 
 		ceph_wbc->fbatch.folios[i] = NULL;
 		ceph_wbc->len += folio_size(folio);
Signature · 1 line
2.53.0
author maintainer
#1601 lore raw

PATCH 1571/1756 ceph: fix off-by-one NUL termination in decode_encrypted_symlink()

In reply to Greg Kroah-Hartman

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

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

From: Xiang Mei <[email protected]>

[ Upstream commit 4da259ea8bf4bd6a91a63f33630a26592d2353f8 ]

decode_encrypted_symlink() allocates enclen + 1 bytes but writes the NUL terminator at sym[declen + 1] instead of sym[declen]. A malicious MDS can report symlink_len == 0 for an encrypted inode, and base64_decode() returns 0 for a zero-length input, so the store lands one byte past a kmalloc(1) allocation.

Terminate at sym[declen], which is always within the allocation.

  BUG: KASAN: slab-out-of-bounds in ceph_fill_inode (fs/ceph/inode.c:996)
  Write of size 1 at addr ffff888020aad361 by task kworker/0:0/9
  Workqueue: ceph-msgr ceph_con_workfn
  Call Trace:
   kasan_report (mm/kasan/report.c:595)
   ceph_fill_inode (fs/ceph/inode.c:996 fs/ceph/inode.c:1277)
   ceph_fill_trace (fs/ceph/inode.c:1716)
   ceph_con_process_message (net/ceph/messenger.c:1424)
   ceph_con_v1_try_read (net/ceph/messenger_v1.c:1430)
   ceph_con_workfn (net/ceph/messenger.c:1576)
   ...
  The buggy address belongs to the object at ffff888020aad360
   which belongs to the cache kmalloc-8 of size 8
  The buggy address is located 0 bytes to the right of
   allocated 1-byte region [ffff888020aad360, ffff888020aad361)
Fixes 79f2f6ad878c ("ceph: create symlinks with encrypted and base64-encoded targets")
Reported-by [email protected]
Assisted-by LLM
---
 fs/ceph/inode.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/ceph/inode.c +1 -1
index 32f612934f839..933ef43371eb9 100644
@@ -965,7 +965,7 @@ static int decode_encrypted_symlink(struct ceph_mds_client *mdsc,
 		kfree(sym);
 		return -EIO;
 	}
-	sym[declen + 1] = '\0';
+	sym[declen] = '\0';
 	*decsym = sym;
 	return declen;
 }
Signature · 1 line
2.53.0
author maintainer
#1602 lore raw

PATCH 1572/1756 ceph: dont keep a mon_addr string that failed to parse

In reply to Greg Kroah-Hartman

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

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

From: Yogesh Gaur <[email protected]>

[ Upstream commit 6c82bff8561f4c20dc0113f81cb2f6e6e2b4cf70 ]

ceph_parse_mon_addr() stores the string in fsopt->mon_addr before handing it to ceph_parse_mon_ips(), and then returns that function's error. So after a mon_addr= that does not parse, fsconfig() reports the failure but the mount context keeps the rejected string.

That matters because ceph_get_tree() uses fsopt->mon_addr as the "monitor addresses were supplied" test:

	if (fsopt->new_dev_syntax && !fsopt->mon_addr)
		return invalfc(fc, "No monitor address");

Userspace is free to ignore the error from fsconfig(FSCONFIG_SET_STRING) and go straight to FSCONFIG_CMD_CREATE. The check then passes on a value that was rejected, and the mount continues with ceph_options::num_mon still 0 - which is how syzbot reached the BUG_ON() in pick_new_mon() fixed by the previous patch.

Parse first and commit only on success. A failed mon_addr= now leaves any previously accepted value in place instead of replacing it with one that does not parse.

Fixes 7b19b4db5add ("ceph: new device mount syntax")
Reported-by [email protected]
Assisted-by Cursor
---
 fs/ceph/super.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
fs/ceph/super.c +7 -2
index 45425700a7bd7..2ce9386c5d6b7 100644
@@ -388,13 +388,18 @@ static int ceph_parse_mon_addr(struct fs_parameter *param,
 {
 	struct ceph_parse_opts_ctx *pctx = fc->fs_private;
 	struct ceph_mount_options *fsopt = pctx->opts;
+	int ret;
+
+	ret = ceph_parse_mon_ips(param->string, strlen(param->string),
+				 pctx->copts, fc->log.log, '/');
+	if (ret)
+		return ret;
 
 	kfree(fsopt->mon_addr);
 	fsopt->mon_addr = param->string;
 	param->string = NULL;
 
-	return ceph_parse_mon_ips(fsopt->mon_addr, strlen(fsopt->mon_addr),
-				  pctx->copts, fc->log.log, '/');
+	return 0;
 }
 
 static int ceph_parse_mount_param(struct fs_context *fc,
Signature · 1 line
2.53.0
author maintainer
#1603 lore raw

PATCH 1573/1756 libceph: reject bad connect_seq in msgr1 READY reply

In reply to Greg Kroah-Hartman

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

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

From: Nguyen Ngoc Thang <[email protected]>

[ Upstream commit 6dfc1b1a99da4909aee07a906352be5c3fc9baba ]

process_connect() WARN_ON()s when the peer's READY/SEQ reply carries a connect_seq other than ours + 1. That value comes off the wire, so a misbehaving or malicious server can trigger the warning at will (and panic machines running with panic_on_warn).

Check it before touching connection state and fail the connection with a protocol error instead, like the other bad-reply cases here.

---
 net/ceph/messenger_v1.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
net/ceph/messenger_v1.c +6 -2
index 0cb61c76b9b87..d3a9d08b59d84 100644
@@ -891,6 +891,12 @@ static int process_connect(struct ceph_connection *con)
 			return -1;
 		}
 
+		if (le32_to_cpu(con->v1.in_reply.connect_seq) !=
+		    con->v1.connect_seq + 1) {
+			con->error_msg = "protocol error, bad connect_seq";
+			return -1;
+		}
+
 		WARN_ON(con->state != CEPH_CON_S_V1_CONNECT_MSG);
 		con->state = CEPH_CON_S_OPEN;
 		con->v1.auth_retry = 0;    /* we authenticated; clear flag */
@@ -902,8 +908,6 @@ static int process_connect(struct ceph_connection *con)
 		     con->v1.peer_global_seq,
 		     le32_to_cpu(con->v1.in_reply.connect_seq),
 		     con->v1.connect_seq);
-		WARN_ON(con->v1.connect_seq !=
-			le32_to_cpu(con->v1.in_reply.connect_seq));
 
 		if (con->v1.in_reply.flags & CEPH_MSG_CONNECT_LOSSY)
 			ceph_con_flag_set(con, CEPH_CON_F_LOSSYTX);
Signature · 1 line
2.53.0
author maintainer
#1604 lore raw

PATCH 1574/1756 cgroup/cpuset: Make sure compute_partition_effective_cpumask() is only called for valid partition

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit 356a3aa7404e420e6f19c5ed42db7b8bd0c7ee9f ]

With visual inspection to make sure that compute_partition_effective_cpumask() is only called for valid partition root, it was found that the function can be called for an invalidated partition near the end of cpuset_hotplug_update_tasks(). When partcmd is set, update_parent_effective_cpumask() is called to either invalidate a valid partition or with partcmd_update to check if an invalid partition can be switched back to valid. In both cases, cpuset_force_rebuild() should be invoked. However, compute_partition_effective_cpumask() should only be called when an invalid partition is switched back to valid. When a partition is invalidated, compute_effective_cpumask() should be called instead.

Also add a WARN_ON_ONCE() in compute_partition_effective_cpumask() to ensure that a valid partition root is passed in.

Fixes 72c6303acfa1 ("cgroup/cpuset: Take isolated CPUs out of workqueue unbound cpumask")
---
 kernel/cgroup/cpuset.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
kernel/cgroup/cpuset.c +6 -1
index e11c70729e0a4..3662acc2cff89 100644
@@ -1988,6 +1988,8 @@ static void compute_partition_effective_cpumask(struct cpuset *cs,
 	struct cpuset *child;
 	bool populated = partition_is_populated(cs, NULL);
 
+	WARN_ON_ONCE(!is_partition_valid(cs));
+
 	/*
 	 * Check child partition roots to see if they should be
 	 * invalidated when
@@ -3879,9 +3881,12 @@ static void cpuset_hotplug_update_tasks(struct cpuset *cs, struct tmpmasks *tmp)
 
 	if (partcmd >= 0) {
 		update_parent_effective_cpumask(cs, partcmd, NULL, tmp);
-		if ((partcmd == partcmd_invalidate) || is_partition_valid(cs)) {
+		if (is_partition_valid(cs)) {
 			compute_partition_effective_cpumask(cs, &new_cpus);
 			cpuset_force_rebuild();
+		} else if (partcmd == partcmd_invalidate) {
+			compute_effective_cpumask(&new_cpus, cs, parent);
+			cpuset_force_rebuild();
 		}
 	}
 
Signature · 1 line
2.53.0
author maintainer
#1605 lore raw

PATCH 1575/1756 block: advance iterator after copy-in for SG_DXFER_TO_FROM_DEV

In reply to Greg Kroah-Hartman

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

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

From: TJ Adams <[email protected]>

[ Upstream commit 82e72ea18d0af724914c31a1f274c1aef452aad0 ]

When a passthrough request uses transfer direction SG_DXFER_TO_FROM_DEV, bio_copy_user_iov() sets up a temporary iterator iter2 with data_source = ITER_SOURCE to copy user data into the bio pages before execution.

bio_copy_from_iter(bio, &iter2) copies the data and advances iter2, but the original iter is never advanced. Consequently, iov_iter_count(&i) remains non-zero in the caller loop in blk_rq_map_user_iov():

	i = *iter;
	do {
		if (copy)
			ret = bio_copy_user_iov(rq, map_data, &i, gfp_mask);
...
	} while (iov_iter_count(&i));

Because i is never advanced, blk_rq_map_user_iov() loops indefinitely, continually allocating bios and consuming map_data pages until it exhausts pages and fails with -EINVAL.

Fix this by calling iov_iter_advance(iter, bio->bi_iter.bi_size) in the map_data && map_data->from_user branch after bio_copy_from_iter().

Fixes 13f3956eb568 ("block: Fix WARNING in _copy_from_iter")
Assisted-by LLM
---
 block/blk-map.c | 1 +
 1 file changed, 1 insertion(+)
block/blk-map.c +1 -0
index b5fd1d8574615..12c586b29e75f 100644
@@ -218,6 +218,7 @@ static int bio_copy_user_iov(struct request *rq, struct rq_map_data *map_data,
 		ret = bio_copy_from_iter(bio, &iter2);
 		if (ret)
 			goto cleanup;
+		iov_iter_advance(iter, bio->bi_iter.bi_size);
 	} else {
 		if (bmd->is_our_pages)
 			zero_fill_bio(bio);
Signature · 1 line
2.53.0
author maintainer
#1606 lore raw

PATCH 1576/1756 selftests: fix ARCH normalization to handle command-line argument

In reply to Greg Kroah-Hartman

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

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

From: Aleksei Oladko <[email protected]>

[ Upstream commit 5a1292137e89c8c4b12076b17427eb00f788a4ed ]

Several selftests Makefiles (e.g. prctl, breakpoints, etc) attempt to normalize the ARCH variable by converting x86_64 and i.86 to x86. However, it uses the conditional assignment operator '?='.

When ARCH is passed as a command-line argument (e.g., during an rpmbuild process), the '?=' operator ignores the shell command and the sed transformation. This leads to an incorrect ARCH value being used, which causes build failures

  # make -C tools/testing/selftests TARGETS=prctl ARCH=x86_64
  make: Entering directory '/build/tools/testing/selftests'
  make[1]: Entering directory '/build/tools/testing/selftests/prctl'
  make[1]: *** No targets.  Stop.
  make[1]: Leaving directory '/build/tools/testing/selftests/prctl'
  make: *** [Makefile:197: all] Error 2

Change the assignment to use 'override' and ':=' to ensure the normalization logic is applied regardless of how the ARCH variable was initially defined.

Stable-dep-of: ff4194e54f84 ("selftests/thermal: allow cross builds of the Intel tests")

---
 tools/testing/selftests/breakpoints/Makefile              | 4 ++--
 tools/testing/selftests/ipc/Makefile                      | 8 ++++----
 tools/testing/selftests/prctl/Makefile                    | 4 ++--
 tools/testing/selftests/sparc64/Makefile                  | 4 ++--
 .../testing/selftests/thermal/intel/power_floor/Makefile  | 4 ++--
 .../selftests/thermal/intel/workload_hint/Makefile        | 4 ++--
 6 files changed, 14 insertions(+), 14 deletions(-)
tools/testing/selftests/breakpoints/Makefile +2 -2
index 9ec2c78de8caa..0b8f5acf7c78f 100644
@@ -1,7 +1,7 @@
 # SPDX-License-Identifier: GPL-2.0
 # Taken from perf makefile
-uname_M := $(shell uname -m 2>/dev/null || echo not)
-ARCH ?= $(shell echo $(uname_M) | sed -e s/i.86/x86/ -e s/x86_64/x86/)
+ARCH ?= $(shell uname -m 2>/dev/null || echo not)
+override ARCH := $(shell echo $(ARCH) | sed -e s/i.86/x86/ -e s/x86_64/x86/)
 
 TEST_GEN_PROGS := step_after_suspend_test
 
tools/testing/selftests/ipc/Makefile +4 -4
index 50e9c299fc4ae..fad10f2bb57b0 100644
@@ -1,12 +1,12 @@
 # SPDX-License-Identifier: GPL-2.0
-uname_M := $(shell uname -m 2>/dev/null || echo not)
-ARCH ?= $(shell echo $(uname_M) | sed -e s/i.86/i386/)
+ARCH ?= $(shell uname -m 2>/dev/null || echo not)
+override ARCH := $(shell echo $(ARCH) | sed -e s/i.86/i386/)
 ifeq ($(ARCH),i386)
-        ARCH := x86
+        override ARCH := x86
 	CFLAGS := -DCONFIG_X86_32 -D__i386__
 endif
 ifeq ($(ARCH),x86_64)
-	ARCH := x86
+        override ARCH := x86
 	CFLAGS := -DCONFIG_X86_64 -D__x86_64__
 endif
 
tools/testing/selftests/prctl/Makefile +2 -2
index 01dc90fbb5094..e770e86fad9ac 100644
@@ -1,7 +1,7 @@
 # SPDX-License-Identifier: GPL-2.0
 ifndef CROSS_COMPILE
-uname_M := $(shell uname -m 2>/dev/null || echo not)
-ARCH ?= $(shell echo $(uname_M) | sed -e s/i.86/x86/ -e s/x86_64/x86/)
+ARCH ?= $(shell uname -m 2>/dev/null || echo not)
+override ARCH := $(shell echo $(ARCH) | sed -e s/i.86/x86/ -e s/x86_64/x86/)
 
 ifeq ($(ARCH),x86)
 TEST_PROGS := disable-tsc-ctxt-sw-stress-test disable-tsc-on-off-stress-test \
tools/testing/selftests/sparc64/Makefile +2 -2
index a19531dba4dc3..88f7be76f962d 100644
@@ -1,6 +1,6 @@
 # SPDX-License-Identifier: GPL-2.0
-uname_M := $(shell uname -m 2>/dev/null || echo not)
-ARCH ?= $(shell echo $(uname_M) | sed -e s/x86_64/x86/)
+ARCH ?= $(shell uname -m 2>/dev/null || echo not)
+override ARCH := $(shell echo $(ARCH) | sed -e s/x86_64/x86/)
 
 ifneq ($(ARCH),sparc64)
 nothing:
tools/testing/selftests/thermal/intel/power_floor/Makefile +2 -2
index 9b88e57dbba5a..07463c2160e09 100644
@@ -1,7 +1,7 @@
 # SPDX-License-Identifier: GPL-2.0
 ifndef CROSS_COMPILE
-uname_M := $(shell uname -m 2>/dev/null || echo not)
-ARCH ?= $(shell echo $(uname_M) | sed -e s/i.86/x86/ -e s/x86_64/x86/)
+ARCH ?= $(shell uname -m 2>/dev/null || echo not)
+override ARCH := $(shell echo $(ARCH) | sed -e s/i.86/x86/ -e s/x86_64/x86/)
 
 ifeq ($(ARCH),x86)
 TEST_GEN_PROGS := power_floor_test
tools/testing/selftests/thermal/intel/workload_hint/Makefile +2 -2
index 37ff3286283b6..49e3bc2b20f9d 100644
@@ -1,7 +1,7 @@
 # SPDX-License-Identifier: GPL-2.0
 ifndef CROSS_COMPILE
-uname_M := $(shell uname -m 2>/dev/null || echo not)
-ARCH ?= $(shell echo $(uname_M) | sed -e s/i.86/x86/ -e s/x86_64/x86/)
+ARCH ?= $(shell uname -m 2>/dev/null || echo not)
+override ARCH := $(shell echo $(ARCH) | sed -e s/i.86/x86/ -e s/x86_64/x86/)
 
 ifeq ($(ARCH),x86)
 TEST_GEN_PROGS := workload_hint_test
Signature · 1 line
2.53.0
author maintainer
#1607 lore raw

PATCH 1577/1756 selftests/thermal: allow cross builds of the Intel tests

In reply to Greg Kroah-Hartman

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

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

[ Upstream commit ff4194e54f840b4df4eb2489c63ee88283895efc ]

The power_floor and workload_hint Makefiles build nothing when CROSS_COMPILE is set, even for an x86 target, and they include lib.mk only on x86. Other architectures therefore have no install or emit_tests rules for these suites, and their installation fails with a missing target.

Select the x86 tests from the target ARCH when it is given and from the host's SUBARCH otherwise, and include lib.mk unconditionally so that the suites install and emit an empty runlist on other architectures. Use a private ARCH_PROCESSED instead of the ARCH override added by commit 5a1292137e89 ("selftests: fix ARCH normalization to handle command-line argument"): the override changed the value lib.mk uses to pick the clang target, whereas leaving ARCH unset lets lib.mk use the compiler's native triple. A command-line ARCH such as x86_64 is still normalized for the selection, while an ARCH spelling that lib.mk does not know, such as i686 with LLVM=1, is rejected as in other selftests.

Fixes 27801542b2b8 ("selftests/thermel/intel: Add test to read workload hint")
Fixes d4d27e5a1a88 ("selftests/thermel/intel: Add test to read power floor status")
---
 .../selftests/thermal/intel/power_floor/Makefile     | 12 +++++-------
 .../selftests/thermal/intel/workload_hint/Makefile   | 12 +++++-------
 2 files changed, 10 insertions(+), 14 deletions(-)
tools/testing/selftests/thermal/intel/power_floor/Makefile +5 -7
index 07463c2160e09..16d26eab55652 100644
@@ -1,12 +1,10 @@
 # SPDX-License-Identifier: GPL-2.0
-ifndef CROSS_COMPILE
-ARCH ?= $(shell uname -m 2>/dev/null || echo not)
-override ARCH := $(shell echo $(ARCH) | sed -e s/i.86/x86/ -e s/x86_64/x86/)
+top_srcdir = ../../../../../..
+include $(top_srcdir)/scripts/subarch.include
+ARCH_PROCESSED := $(shell echo $(or $(ARCH),$(SUBARCH)) | sed -e s/i.86/x86/ -e s/x86_64/x86/)
 
-ifeq ($(ARCH),x86)
+ifeq ($(ARCH_PROCESSED),x86)
 TEST_GEN_PROGS := power_floor_test
+endif
 
 include ../../../lib.mk
-
-endif
-endif
tools/testing/selftests/thermal/intel/workload_hint/Makefile +5 -7
index 49e3bc2b20f9d..e53d6ecd9f8de 100644
@@ -1,12 +1,10 @@
 # SPDX-License-Identifier: GPL-2.0
-ifndef CROSS_COMPILE
-ARCH ?= $(shell uname -m 2>/dev/null || echo not)
-override ARCH := $(shell echo $(ARCH) | sed -e s/i.86/x86/ -e s/x86_64/x86/)
+top_srcdir = ../../../../../..
+include $(top_srcdir)/scripts/subarch.include
+ARCH_PROCESSED := $(shell echo $(or $(ARCH),$(SUBARCH)) | sed -e s/i.86/x86/ -e s/x86_64/x86/)
 
-ifeq ($(ARCH),x86)
+ifeq ($(ARCH_PROCESSED),x86)
 TEST_GEN_PROGS := workload_hint_test
+endif
 
 include ../../../lib.mk
-
-endif
-endif
Signature · 1 line
2.53.0
author maintainer
#1608 lore raw

PATCH 1578/1756 thermal: Fix CPU mask truncation in power limit trace event

In reply to Greg Kroah-Hartman

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

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

From: Hungyu Lin <[email protected]>

[ Upstream commit 82c9c94f54a444a686e926c872dae4b198d1036f ]

num_possible_cpus() counts CPUs, but CPU IDs need not be contiguous. Using it to size the thermal_power_cpu_limit bitmap can omit CPUs with higher IDs. For example, possible CPUs 0 and 64 produce an eight-byte bitmap on a 64-bit system, dropping CPU 64.

Use nr_cpumask_bits for both sizing and copying the bitmap.

Fixes 6828a4711f99 ("thermal: add trace events to the power allocator governor")
---
 drivers/thermal/thermal_trace.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/thermal/thermal_trace.h +2 -2
index df8f4edd6068a..2f953fd8289dd 100644
@@ -119,7 +119,7 @@ TRACE_EVENT(thermal_power_cpu_limit,
 	TP_ARGS(cpus, freq, cdev_state, power),
 
 	TP_STRUCT__entry(
-		__bitmask(cpumask, num_possible_cpus())
+		__bitmask(cpumask, nr_cpumask_bits)
 		__field(unsigned int,  freq      )
 		__field(unsigned long, cdev_state)
 		__field(u32,           power     )
@@ -127,7 +127,7 @@ TRACE_EVENT(thermal_power_cpu_limit,
 
 	TP_fast_assign(
 		__assign_bitmask(cpumask, cpumask_bits(cpus),
-				num_possible_cpus());
+				nr_cpumask_bits);
 		__entry->freq = freq;
 		__entry->cdev_state = cdev_state;
 		__entry->power = power;
Signature · 1 line
2.53.0
author maintainer
#1609 lore raw

PATCH 1579/1756 ASoC: codecs: wsa884x: disable runtime PM on unbind

In reply to Greg Kroah-Hartman

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

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

From: Srinivas Kandagatla <[email protected]>

[ Upstream commit 54c121eaeed8ee7751935db8100b6b5c57124db9 ]

Probe enables runtime PM but nothing disables it on unbind. The pending autosuspend then runs wsa884x_runtime_suspend() after the devm-managed regmap is freed, and dereferences NULL:

  Unable to handle kernel NULL pointer dereference at virtual address 0000000000000020
  pc : regcache_cache_only+0x18/0x80
  lr : wsa884x_runtime_suspend+0x24/0x40 [snd_soc_wsa884x]

Use devm_pm_runtime_enable() so runtime PM is disabled before the regmap is freed.

Fixes aa21a7d4f68a ("ASoC: codecs: wsa884x: Add WSA884x family of speakers")
---
 sound/soc/codecs/wsa884x.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
sound/soc/codecs/wsa884x.c +3 -1
index 1e42093849742..1fb9f11ba2a9c 100644
@@ -2128,7 +2128,9 @@ static int wsa884x_probe(struct sdw_slave *pdev,
 	pm_runtime_use_autosuspend(dev);
 	pm_runtime_mark_last_busy(dev);
 	pm_runtime_set_active(dev);
-	pm_runtime_enable(dev);
+	ret = devm_pm_runtime_enable(dev);
+	if (ret)
+		return ret;
 
 	return devm_snd_soc_register_component(dev,
 					       &wsa884x_component_drv,
Signature · 1 line
2.53.0
author maintainer
#1610 lore raw

PATCH 1580/1756 ASoC: codecs: wsa883x: disable runtime PM on unbind

In reply to Greg Kroah-Hartman

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

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

From: Srinivas Kandagatla <[email protected]>

[ Upstream commit ea63182d71956dc33c6f08dc4171f1052f8409a9 ]

Probe enables runtime PM but nothing disables it on unbind, or when registering the component fails. A pending autosuspend can then run wsa883x_runtime_suspend() after the devm-managed regmap is freed, and dereference NULL, as seen on wsa884x.

Use devm_pm_runtime_enable() so runtime PM is disabled before the regmap is freed.

Fixes 43b8c7dc85a1 ("ASoC: codecs: add wsa883x amplifier support")
---
 sound/soc/codecs/wsa883x.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
sound/soc/codecs/wsa883x.c +3 -1
index 8d1393041de48..491a2131bb598 100644
@@ -1437,7 +1437,9 @@ static int wsa883x_probe(struct sdw_slave *pdev,
 	pm_runtime_use_autosuspend(dev);
 	pm_runtime_mark_last_busy(dev);
 	pm_runtime_set_active(dev);
-	pm_runtime_enable(dev);
+	ret = devm_pm_runtime_enable(dev);
+	if (ret)
+		goto err;
 
 	ret = devm_snd_soc_register_component(dev,
 					      &wsa883x_component_drv,
Signature · 1 line
2.53.0
author maintainer
#1611 lore raw

PATCH 1581/1756 ASoC: codecs: wsa884x: Fix VI sense port channel count

In reply to Greg Kroah-Hartman

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

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

From: Ravi Hothi <[email protected]>

[ Upstream commit a6093f98cbfc4a717ef3d1048b0e38fb2035be98 ]

The VI sense port carries both the voltage and the current sense data of the speaker, but it is described with max_ch = 1 and, since commit 060fac202eb8 ("ASoC: codecs: wsa884x: Correct VI sense channel mask"), a channel mask of 0x1, so only half of the V/I pair is transferred.

Describe the port as two channels and set the channel mask back to 0x3.

Fixes 060fac202eb8 ("ASoC: codecs: wsa884x: Correct VI sense channel mask")
Cc Krzysztof Kozlowski <[email protected]>
---
 sound/soc/codecs/wsa884x.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
sound/soc/codecs/wsa884x.c +2 -2
index 1fb9f11ba2a9c..78e40d9569cff 100644
@@ -859,7 +859,7 @@ static struct sdw_dpn_prop wsa884x_sink_dpn_prop[WSA884X_MAX_SWR_PORTS] = {
 		.num = WSA884X_PORT_VISENSE + 1,
 		.type = SDW_DPN_SIMPLE,
 		.min_ch = 1,
-		.max_ch = 1,
+		.max_ch = 2,
 		.simple_ch_prep_sm = true,
 		.read_only_wordlength = true,
 	},
@@ -892,7 +892,7 @@ static const struct sdw_port_config wsa884x_pconfig[WSA884X_MAX_SWR_PORTS] = {
 	},
 	[WSA884X_PORT_VISENSE] = {
 		.num = WSA884X_PORT_VISENSE + 1,
-		.ch_mask = 0x1,
+		.ch_mask = 0x3,
 	},
 	[WSA884X_PORT_CPS] = {
 		.num = WSA884X_PORT_CPS + 1,
Signature · 1 line
2.53.0
author maintainer
#1612 lore raw

PATCH 1582/1756 ASoC: codecs: wsa883x: Fix VI sense port channel count

In reply to Greg Kroah-Hartman

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

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

From: Ravi Hothi <[email protected]>

[ Upstream commit 9728b328d7adf228d5f691d0ec43bb7a6d07e44b ]

The VI sense port carries both the voltage and the current sense data of the speaker, but it is described with max_ch = 1 and, since commit ed3b274abc40 ("ASoC: codecs: wsa883x: Correct VI sense channel mask"), a channel mask of 0x1, so only half of the V/I pair is transferred.

Describe the port as two channels and set the channel mask back to 0x3.

Fixes ed3b274abc40 ("ASoC: codecs: wsa883x: Correct VI sense channel mask")
Cc Krzysztof Kozlowski <[email protected]>
---
 sound/soc/codecs/wsa883x.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
sound/soc/codecs/wsa883x.c +2 -2
index 491a2131bb598..075c90357776d 100644
@@ -509,7 +509,7 @@ static struct sdw_dpn_prop wsa_sink_dpn_prop[WSA883X_MAX_SWR_PORTS] = {
 		.num = WSA883X_PORT_VISENSE + 1,
 		.type = SDW_DPN_SIMPLE,
 		.min_ch = 1,
-		.max_ch = 1,
+		.max_ch = 2,
 		.simple_ch_prep_sm = true,
 		.read_only_wordlength = true,
 	}
@@ -530,7 +530,7 @@ static const struct sdw_port_config wsa883x_pconfig[WSA883X_MAX_SWR_PORTS] = {
 	},
 	[WSA883X_PORT_VISENSE] = {
 		.num = WSA883X_PORT_VISENSE + 1,
-		.ch_mask = 0x1,
+		.ch_mask = 0x3,
 	},
 };
 
Signature · 1 line
2.53.0
author maintainer
#1613 lore raw

PATCH 1583/1756 ASoC: codecs: es*: Modify the registers related to ALC RECOVERY

In reply to Greg Kroah-Hartman

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

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

From: Zhang Yi <[email protected]>

[ Upstream commit dd64271fe1b935252cf454a72a558cbdb7be57c5 ]

The register related to "ALC Capture Recovery Level" is ES8326_ALC_RECOVERY, not ES8326_ALC_LEVEL.

Fixes 5c439937775d ("ASoC: codecs: add support for ES8326")
---
 sound/soc/codecs/es8326.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
sound/soc/codecs/es8326.c +1 -1
index caaacde8b59e3..ea65f32e22698 100644
@@ -247,7 +247,7 @@ static const struct snd_kcontrol_new es8326_snd_controls[] = {
 	SOC_SINGLE_TLV("ADC PGA Gain Volume", ES8326_PGAGAIN, 0, 10, 0, adc_analog_pga_tlv),
 	SOC_SINGLE_TLV("ADC Ramp Rate", ES8326_ADC_RAMPRATE, 0, 0x0f, 0, softramp_rate),
 	SOC_SINGLE("ALC Capture Switch", ES8326_ALC_RECOVERY, 3, 1, 0),
-	SOC_SINGLE_TLV("ALC Capture Recovery Level", ES8326_ALC_LEVEL,
+	SOC_SINGLE_TLV("ALC Capture Recovery Level", ES8326_ALC_RECOVERY,
 			0, 4, 0, drc_recovery_tlv),
 	SOC_ENUM("ALC Capture Winsize", alc_winsize),
 	SOC_SINGLE_TLV("ALC Capture Target Level", ES8326_ALC_LEVEL,
Signature · 1 line
2.53.0
author maintainer
#1614 lore raw

PATCH 1584/1756 net/sched: gred: keep the qdisc lock while updating the table

In reply to Greg Kroah-Hartman

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

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

From: Dudu Lu <[email protected]>

[ Upstream commit 306f788134a21a3d60c1eb872d0ec0ce7c7e09bc ]

gred_change_table_def() publishes table->DPs/def/red_flags under sch_tree_lock(), drops the lock, and then keeps writing state the datapath reads without it:

- gred_enable_rio_mode()/gred_disable_rio_mode()/gred_disable_wred_mode()

    set/clear table->flags;

- the red_flags_changed loop writes table->tab[i]->red_flags;
- the shadowed-VQ loop frees table->tab[i] and clears the slot.

gred_enqueue() and gred_dequeue() read those same fields (test_bit on table->flags, q->red_flags, t->tab[]/t->DPs) under the same root lock on another CPU, so the post-unlock writes race with the enqueue path:

  BUG: KCSAN: data-race in gred_change_table_def [sch_gred] / gred_enqueue [sch_gred]
  read (marked) to 0xffff000007ad3b00 of 8 bytes by task 110 on cpu 0:
   gred_enqueue+0x88/0xc60 [sch_gred]
   dev_qdisc_enqueue+0x4c/0x19c
   __dev_queue_xmit+0x10a4/0x1ea4

The comment justifying the early unlock only covers the DP-vs-DPs check, which the shadowed-VQ free loop relies on; it does not cover the scalar mode bits and per-VQ red_flags written afterwards. Move the unlock below those updates so everything the datapath reads is published under the lock that protects it.

Fixes 6639607ed9de ("[PKT_SCHED]: GRED: Use a central table definition change procedure")
---
 net/sched/sch_gred.c | 16 +++++++++-------
 1 file changed, 9 insertions(+), 7 deletions(-)
net/sched/sch_gred.c +9 -7
index 26103178a4ce4..839cbd5d91dbd 100644
@@ -442,13 +442,6 @@ static int gred_change_table_def(struct Qdisc *sch, struct nlattr *dps,
 	red_flags_changed = table->red_flags != sopt->flags;
 	table->red_flags = sopt->flags;
 
-	/*
-	 * Every entry point to GRED is synchronized with the above code
-	 * and the DP is checked against DPs, i.e. shadowed VQs can no
-	 * longer be found so we can unlock right here.
-	 */
-	sch_tree_unlock(sch);
-
 	if (sopt->grio) {
 		gred_enable_rio_mode(table);
 		gred_disable_wred_mode(table);
@@ -474,6 +467,15 @@ static int gred_change_table_def(struct Qdisc *sch, struct nlattr *dps,
 		}
 	}
 
+	/*
+	 * Keep the lock until every field the datapath reads (the
+	 * RIO/WRED mode bits, the per-VQ red_flags and the tab[] slots)
+	 * has been updated: gred_enqueue()/gred_dequeue() read them under
+	 * the same lock, so publishing them after the unlock races with
+	 * the enqueue path.
+	 */
+	sch_tree_unlock(sch);
+
 	gred_offload(sch, TC_GRED_REPLACE);
 	return 0;
 }
Signature · 1 line
2.53.0
author maintainer
#1615 lore raw

PATCH 1585/1756 net/sched: act_api: inherit filter offload flags only on new actions

In reply to Greg Kroah-Hartman

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

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

From: Alexandre Cassen <[email protected]>

[ Upstream commit 9463e8d8c6922a5aa87f7e4fe6deb4f16925d498 ]

tcf_action_init() gives the skip_sw and skip_hw flags of a filter to the actions it binds. An action that another filter created gets them too, they then apply to every filter that uses this action. When a skip_sw filter reuses the action of a software filter, the software filter silently stops running it. This happens even when the filter add fails on a later action. A skip_hw filter likewise prevents a later filter without flags from reusing the action.

Give the flags only to the actions that the filter creates. The mismatch check still rejects a filter that reuses an action with a flag that the filter does not have.

Discovered by manual code inspection after the Sashiko AI review [1] of a tunnel_key patch questioned how actions get the filter flags. Reproduced on netdevsim without kernel changes. The egress filter below runs in software only, since netdevsim offloads only ingress filters. Once the skip_sw filter reuses its drop action, the last command shows skip_sw on this action and the egress filter stops dropping packets:

ethtool -K eth0 hw-tc-offload on
tc qdisc add dev eth0 clsact
tc filter add dev eth0 egress protocol ip flower dst_ip 192.0.2.1 \
action gact drop index 1
tc filter add dev eth0 ingress protocol ip flower skip_sw \

     dst_ip 192.0.2.2 action gact drop index 1

tc actions get action gact index 1

Tested with the reproducer and the tc-testing action, matchall and flower tests.

---
 net/sched/act_api.c | 3 +++
 1 file changed, 3 insertions(+)
net/sched/act_api.c +3 -0
index 22f840ed11326..3ba2af867a104 100644
@@ -1524,6 +1524,9 @@ int tcf_action_init(struct net *net, struct tcf_proto *tp, struct nlattr *nla,
 					err = -EINVAL;
 					goto err;
 				}
+				/* Other filters share an existing action */
+				if (init_res[i - 1] != ACT_P_CREATED)
+					continue;
 				if (skip_sw)
 					act->tcfa_flags |= TCA_ACT_FLAGS_SKIP_SW;
 				if (skip_hw)
Signature · 1 line
2.53.0
author maintainer
#1616 lore raw

PATCH 1586/1756 net/sched: taprio: unwind the netdevice notifier if register_qdisc() fails

In reply to Greg Kroah-Hartman

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

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

From: Dudu Lu <[email protected]>

[ Upstream commit c5234f89d7cb311880ef218cb7a969794a106678 ]

taprio_module_init() registers taprio_device_notifier and then returns register_qdisc()'s error directly. When register_qdisc() fails the notifier stays registered, but the loader's failure path frees the module image without ever calling the __exit function, so netdev_chain is left pointing at taprio_device_notifier.notifier_call -- a function pointer that lives in text that has just been freed.

register_qdisc() has two failure returns: -EEXIST (duplicate .id) and -EINVAL (malformed cl_ops). taprio_class_ops satisfies every checked implication, so -EINVAL is unreachable and -EEXIST is the only reachable failure; it needs a pre-existing "taprio" entry in qdisc_base. In-tree that is reachable only through bpf_qdisc_reg() (CONFIG_NET_SCH_BPF); a module calling the exported register_qdisc() reaches it as well.

Once the notifier is left dangling, the next netdevice event that walks netdev_chain calls through the stale pointer:

  BUG: KASAN: vmalloc-out-of-bounds in notifier_call_chain+0x650/0xb5c
  Read of size 8 at addr ffff80001fc5ab08 by task ip/110
   notifier_call_chain+0x650/0xb5c
   raw_notifier_call_chain+0x34/0x64
   call_netdevice_notifiers_info+0xa8/0x198
   __dev_close_many+0xe0/0x800
   ...
  >ffff80001fc5ab00: f8 f8 f8 f8 f8 f8 f8 f8 f8 f8 f8 f8 f8 f8 f8 f8

The shadow row is all f8 (KASAN_VMALLOC_INVALID): the read lands in vmalloc memory that was poisoned when the module image was freed, and the indirect call is unguarded because the only check, func_ptr_is_kernel_text(), is compiled out unless CONFIG_DEBUG_NOTIFIERS.

Mirror the sibling sch_cbs.c and act_mirred.c, which unwind the notifier on this failure path.

Fixes 7b9eba7ba0c1 ("net/sched: taprio: fix picos_per_byte miscalculation")
---
 net/sched/sch_taprio.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
net/sched/sch_taprio.c +5 -1
index 54d0136dfe6c5..152bca7f55612 100644
@@ -2573,7 +2573,11 @@ static int __init taprio_module_init(void)
 	if (err)
 		return err;
 
-	return register_qdisc(&taprio_qdisc_ops);
+	err = register_qdisc(&taprio_qdisc_ops);
+	if (err)
+		unregister_netdevice_notifier(&taprio_device_notifier);
+
+	return err;
 }
 
 static void __exit taprio_module_exit(void)
Signature · 1 line
2.53.0
author maintainer
#1617 lore raw

PATCH 1587/1756 net: stmmac: fix rx checksum offload with extended descriptors

In reply to Greg Kroah-Hartman

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

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

From: alex todadze <[email protected]>

[ Upstream commit 72ee27b97986f4d331fe1c26e4333f12738d982f ]

With extended descriptors, bit 0 of RDES0 is the Extended Status Available flag. enh_desc_get_rx_status() still reads it as the payload checksum error bit of the checksum offload table, so every IP frame that has extended status is reported as csum_none and its checksum is verified again in software.

When extended status is available, take the result from RDES4 instead. A TCP, UDP or ICMP payload with no IP header error, no payload error and no checksum bypass is a good frame. Everything else keeps the status from RDES0. Since RDES4 now decides the checksum status, read it after the own bit with dma_rmb(). While at it, fix the IP payload type mask, which covered bits 6:2 instead of 2:0 and had no users.

Tested on a Siflower SF19A2890 (GMAC 3.70) with the board as the iperf3 endpoint. TCP receive goes from 326 to 378 Mbit/s with one stream and from 259 to 329 Mbit/s with four, and CPU use while receiving 200 Mbit/s drops from 26.6% to 21.5%. In stmmac_rx(), frames with a bad TCP, UDP or ICMP checksum, over IPv4 and IPv6 and including fragmented UDP, are still passed up as CHECKSUM_NONE and dropped by the stack.

Fixes c24602ef8664 ("stmmac: support extend descriptors")
---
 drivers/net/ethernet/stmicro/stmmac/descs.h   |  6 ++++-
 .../net/ethernet/stmicro/stmmac/enh_desc.c    | 25 +++++++++++++++++--
 drivers/net/ethernet/stmicro/stmmac/hwif.h    |  6 ++---
 .../net/ethernet/stmicro/stmmac/stmmac_main.c | 19 ++++++++++----
 4 files changed, 45 insertions(+), 11 deletions(-)
drivers/net/ethernet/stmicro/stmmac/descs.h +5 -1
index 49d6a866244f4..4fc5f69aeaa98 100644
@@ -123,7 +123,7 @@
 #define	ETDES1_BUFFER2_SIZE_SHIFT	16
 
 /* Extended Receive descriptor definitions */
-#define	ERDES4_IP_PAYLOAD_TYPE_MASK	GENMASK(6, 2)
+#define	ERDES4_IP_PAYLOAD_TYPE_MASK	GENMASK(2, 0)
 #define	ERDES4_IP_HDR_ERR		BIT(3)
 #define	ERDES4_IP_PAYLOAD_ERR		BIT(4)
 #define	ERDES4_IP_CSUM_BYPASSED		BIT(5)
@@ -154,6 +154,10 @@
 #define RDES_PTP_SIGNALING		0xa
 #define RDES_PTP_PKT_RESERVED_TYPE	0xf
 
+#define RDES_EXT_PAYLOAD_UDP		0x1
+#define RDES_EXT_PAYLOAD_TCP		0x2
+#define RDES_EXT_PAYLOAD_ICMP		0x3
+
 /* Basic descriptor structure for normal and alternate descriptors */
 struct dma_desc {
 	__le32 des0;
drivers/net/ethernet/stmicro/stmmac/enh_desc.c +23 -2
index 937b7a0466fca..963579518405c 100644
@@ -114,8 +114,25 @@ static int enh_desc_coe_rdes0(int ipc_err, int type, int payload_err)
 	return ret;
 }
 
-static void enh_desc_get_ext_status(struct stmmac_extra_stats *x,
-				    struct dma_extended_desc *p)
+static int enh_desc_ext_rx_csum(u32 rdes0, u32 rdes4, int status)
+{
+	u32 type = FIELD_GET(ERDES4_IP_PAYLOAD_TYPE_MASK, rdes4);
+
+	if (status != csum_none || !(rdes0 & RDES0_FRAME_TYPE))
+		return status;
+	if (!(rdes4 & (ERDES4_IPV4_PKT_RCVD | ERDES4_IPV6_PKT_RCVD)) ||
+	    (rdes4 & (ERDES4_IP_HDR_ERR | ERDES4_IP_PAYLOAD_ERR |
+		      ERDES4_IP_CSUM_BYPASSED)))
+		return status;
+	if (type != RDES_EXT_PAYLOAD_UDP && type != RDES_EXT_PAYLOAD_TCP &&
+	    type != RDES_EXT_PAYLOAD_ICMP)
+		return status;
+
+	return good_frame;
+}
+
+static int enh_desc_get_ext_status(struct stmmac_extra_stats *x,
+				   struct dma_extended_desc *p, int status)
 {
 	unsigned int rdes0 = le32_to_cpu(p->basic.des0);
 	unsigned int rdes4 = le32_to_cpu(p->des4);
@@ -175,7 +192,11 @@ static void enh_desc_get_ext_status(struct stmmac_extra_stats *x,
 			x->l4_filter_match++;
 		if ((rdes4 & ERDES4_L3_L4_FILT_NO_MATCH_MASK) >> 26)
 			x->l3_l4_filter_no_match++;
+
+		status = enh_desc_ext_rx_csum(rdes0, rdes4, status);
 	}
+
+	return status;
 }
 
 static int enh_desc_get_rx_status(struct stmmac_extra_stats *x,
drivers/net/ethernet/stmicro/stmmac/hwif.h +3 -3
index 4376d61db969f..c0fc126d3a3ee 100644
@@ -75,8 +75,8 @@ struct stmmac_desc_ops {
 	/* Return the reception status looking at the RDES1 */
 	int (*rx_status)(struct stmmac_extra_stats *x,
 			 struct dma_desc *p);
-	void (*rx_extended_status)(struct stmmac_extra_stats *x,
-				   struct dma_extended_desc *p);
+	int (*rx_extended_status)(struct stmmac_extra_stats *x,
+				  struct dma_extended_desc *p, int status);
 	/* Set tx timestamp enable bit */
 	void (*enable_tx_timestamp) (struct dma_desc *p);
 	/* get tx timestamp status */
@@ -139,7 +139,7 @@ struct stmmac_desc_ops {
 #define stmmac_rx_status(__priv, __args...) \
 	stmmac_do_callback(__priv, desc, rx_status, __args)
 #define stmmac_rx_extended_status(__priv, __args...) \
-	stmmac_do_void_callback(__priv, desc, rx_extended_status, __args)
+	stmmac_do_callback(__priv, desc, rx_extended_status, __args)
 #define stmmac_enable_tx_timestamp(__priv, __args...) \
 	stmmac_do_void_callback(__priv, desc, enable_tx_timestamp, __args)
 #define stmmac_get_tx_timestamp_status(__priv, __args...) \
drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +14 -5
index adb530635f30b..d8988ca3d163f 100644
@@ -5380,9 +5380,13 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue)
 		if (!buf->xdp)
 			break;
 
-		if (priv->extend_desc)
-			stmmac_rx_extended_status(priv, &priv->xstats,
-						  rx_q->dma_erx + entry);
+		if (priv->extend_desc) {
+			/* Read the extended status after the own bit */
+			dma_rmb();
+			status = stmmac_rx_extended_status(priv, &priv->xstats,
+							   &rx_q->dma_erx[entry],
+							   status);
+		}
 		if (unlikely(status == discard_frame)) {
 			xsk_buff_free(buf->xdp);
 			buf->xdp = NULL;
@@ -5574,8 +5578,13 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue)
 
 		prefetch(np);
 
-		if (priv->extend_desc)
-			stmmac_rx_extended_status(priv, &priv->xstats, rx_q->dma_erx + entry);
+		if (priv->extend_desc) {
+			/* Read the extended status after the own bit */
+			dma_rmb();
+			status = stmmac_rx_extended_status(priv, &priv->xstats,
+							   &rx_q->dma_erx[entry],
+							   status);
+		}
 		if (unlikely(status == discard_frame)) {
 			page_pool_recycle_direct(rx_q->page_pool, buf->page);
 			buf->page = NULL;
Signature · 1 line
2.53.0
author maintainer
#1618 lore raw

PATCH 1588/1756 ipmr: clear skb->cb[] in reg_vif_xmit()

In reply to Greg Kroah-Hartman

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

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

From: Eric Dumazet <[email protected]>

[ Upstream commit 389952e8776a4663044df2ae3e8987a9e81964cf ]

reg_vif_xmit() hands the skb to ipmr_cache_report() as an IGMPMSG_WHOLEPKT report. When the mroute socket has IP_PKTINFO enabled, ipmr_cache_report() calls ipv4_pktinfo_prepare() on the original skb, which reads skb->cb[] as IPCB.

By the time the pimreg device transmits the packet, skb->cb[] is not IPCB anymore: qdisc_pkt_len_init() overwrites IPCB(skb)->iif with qdisc_skb_cb(skb)->pkt_len, and any qdisc installed on the device or a tc BPF program writing skb->cb[] fills the area holding the IP options and IPCB(skb)->flags.

For locally generated packets routed out pimreg (they carry an rtable dst), the mroute socket can therefore receive a bogus ipi_ifindex (the packet length), and the l3mdev slave test in ipv4_pktinfo_prepare() is driven by stale qdisc data.

Clear IPCB before building the report, as done for IPv6 in commit 238164201431 ("ip6mr: clear skb->cb[] in reg_vif_xmit()"). The skb is freed right after, so nothing else depends on its control block.

---
 net/ipv4/ipmr.c | 5 +++++
 1 file changed, 5 insertions(+)
net/ipv4/ipmr.c +5 -0
index f9cec6b2bc1a3..560c4cd60c609 100644
@@ -530,6 +530,11 @@ static netdev_tx_t reg_vif_xmit(struct sk_buff *skb, struct net_device *dev)
 	DEV_STATS_ADD(dev, tx_bytes, skb->len);
 	DEV_STATS_INC(dev, tx_packets);
 
+	/* skb->cb[] holds qdisc/tc state at this point, not IPCB.
+	 * ipmr_cache_report() reads it as IPCB to build IP_PKTINFO.
+	 */
+	memset(IPCB(skb), 0, sizeof(*IPCB(skb)));
+
 	/* Pairs with WRITE_ONCE() in vif_add() and vif_delete() */
 	ipmr_cache_report(mrt, skb, READ_ONCE(mrt->mroute_reg_vif_num),
 			  IGMPMSG_WHOLEPKT);
Signature · 1 line
2.53.0
author maintainer
#1619 lore raw

PATCH 1589/1756 clk: lmk04832: Handle reset GPIO lookup errors

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit 5c7c0cbf81bba69695efa12e451f0f2ecd4b92a5 ]

devm_gpiod_get_optional() may return -EPROBE_DEFER or other errors, but lmk04832_probe() currently ignores them.

Check the return value and propagate errors from the reset GPIO lookup.

---
 drivers/clk/clk-lmk04832.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/clk/clk-lmk04832.c +3 -0
index c997e74919961..8c51cbe44ac53 100644
@@ -1413,6 +1413,9 @@ static int lmk04832_probe(struct spi_device *spi)
 
 	lmk->reset_gpio = devm_gpiod_get_optional(&spi->dev, "reset",
 						  GPIOD_OUT_LOW);
+	if (IS_ERR(lmk->reset_gpio))
+		return dev_err_probe(lmk->dev, PTR_ERR(lmk->reset_gpio),
+				     "failed to get reset GPIO\n");
 
 	lmk->dclk = devm_kcalloc(lmk->dev, info->num_channels >> 1,
 				 sizeof(struct lmk_dclk), GFP_KERNEL);
Signature · 1 line
2.53.0
author maintainer
#1620 lore raw

PATCH 1590/1756 clk: cdce925: Size the PLL child name buffer for any int

In reply to Greg Kroah-Hartman

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

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

From: Jerome Brunet <[email protected]>

[ Upstream commit e9e6b4dc303dff637ef725aca4f4968d7600798b ]

The PLL child node name is built from "PLL%d" in a 6 byte stack buffer. The PLL index is bounded by the chip's num_plls, at most 4, but GCC cannot see that bound and, with W=1, warns that the formatted string may not fit.

Make the buffer large enough to hold any int and use snprintf() with sizeof() so the size stays tied to the declaration.

---
 drivers/clk/clk-cdce925.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
drivers/clk/clk-cdce925.c +7 -2
index e48be7a6c0e2b..50634618c75af 100644
@@ -617,7 +617,12 @@ static int cdce925_probe(struct i2c_client *client)
 	int i;
 	int err;
 	struct device_node *np_output;
-	char child_name[6];
+	/*
+	 * The PLL number isn't a compile time constant so GCC can't infer
+	 * the number. Make the stack buffer large enough to hold any int
+	 * so Wformat-truncation does not complain.
+	 */
+	char child_name[15];
 	struct regmap_config config = {
 		.name = "configuration0",
 		.reg_bits = 8,
@@ -689,7 +694,7 @@ static int cdce925_probe(struct i2c_client *client)
 			dev_err(&client->dev, "Failed register PLL %d\n", i);
 			goto error;
 		}
-		sprintf(child_name, "PLL%d", i+1);
+		snprintf(child_name, sizeof(child_name), "PLL%d", i + 1);
 		np_output = of_get_child_by_name(node, child_name);
 		if (!np_output)
 			continue;
Signature · 1 line
2.53.0
author maintainer
#1621 lore raw

PATCH 1591/1756 tipc: fix refcount panic in tipc_rcv() when receiving shared skb

In reply to Greg Kroah-Hartman

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

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

From: Tung Nguyen <[email protected]>

[ Upstream commit 5308a2049b764aa55513c90c68933abf596c51d2 ]

TIPC assumes that the received skb is not shared with other users. However, syzbot reports a bug triggered by receiving a shared skb:

...

RIP: 0010:pskb_expand_head+0x135a/0x13a0 net/core/skbuff.c:2308
__pskb_pull_tail+0x111/0x1870 net/core/skbuff.c:2890
skb_cow_data+0x2ed/0xc50 net/core/skbuff.c:5398
tipc_aead_decrypt net/tipc/crypto.c:892 [inline]
tipc_crypto_rcv+0x346/0x23d0 net/tipc/crypto.c:1843
tipc_rcv+0x4b7/0x1040 net/tipc/node.c:2119
tipc_l2_rcv_msg+0x2d9/0x470 net/tipc/bearer.c:669
deliver_ptype_list_skb net/core/dev.c:2533 [inline]

...

The root cause is that local delivery hooks in the kernel (e.g., deliver_skb()) may increment the skb's reference count (users) before TIPC processes it on ingress.

Fix this by calling skb_share_check() to ensure exclusive ownership before passing the skb to tipc_rcv(). As TIPC needs to modify the skb's data, the cloned skb needs to be uncloned when needed. This can be addressed in separate patch.

---
 net/tipc/bearer.c | 4 ++++
 1 file changed, 4 insertions(+)
net/tipc/bearer.c +4 -0
index 8866a3d713132..24dcb8aa32330 100644
@@ -659,6 +659,10 @@ static int tipc_l2_rcv_msg(struct sk_buff *skb, struct net_device *dev,
 {
 	struct tipc_bearer *b;
 
+	skb = skb_share_check(skb, GFP_ATOMIC);
+	if (!skb)
+		return NET_RX_DROP;
+
 	rcu_read_lock();
 	b = rcu_dereference(dev->tipc_ptr) ?:
 		rcu_dereference(orig_dev->tipc_ptr);
Signature · 1 line
2.53.0
author maintainer
#1622 lore raw

PATCH 1592/1756 pppoe: drop discovery frames with no MAC header

In reply to Greg Kroah-Hartman

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

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

From: Qingfang Deng <[email protected]>

[ Upstream commit 406bf2dc8d6d3e93fdae0b66d2ae99b6b62e479c ]

Commit 8540827ebac6 ("pppoe: fix reception of frames with no mac header") drops PPPoE session frames with no MAC header to avoid reading uninitialized memory.

Apply the same to PPPoE discovery frames, as both functions read eth_hdr(skb)->h_source.

Found by LLM static analysis, and reproduced using the same TUN injection as described in the mentioned commit.

Fixes 8540827ebac6 ("pppoe: fix reception of frames with no mac header")
---
 drivers/net/ppp/pppoe.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/net/ppp/pppoe.c +3 -0
index 293b6fb1c1e98..97eb18dbc312e 100644
@@ -496,6 +496,9 @@ static int pppoe_disc_rcv(struct sk_buff *skb, struct net_device *dev,
 	if (skb->pkt_type != PACKET_HOST)
 		goto abort;
 
+	if (skb_mac_header_len(skb) < ETH_HLEN)
+		goto abort;
+
 	if (!pskb_may_pull(skb, sizeof(struct pppoe_hdr)))
 		goto abort;
 
Signature · 1 line
2.53.0
author maintainer
#1623 lore raw

PATCH 1593/1756 gtp: hold RCU in gtp_genl_send_echo_req()

In reply to Greg Kroah-Hartman

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

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

From: Paolo Abeni <[email protected]>

[ Upstream commit a204e9c001dfafe83cac01b16508b1cf5c953355 ]

Such function is invoked in process context, performs an RCU device lookup and dereference the found device with no additional protection.

=============================
WARNING: suspicious RCU usage
7.3.0-virtme #7 Not tainted
-----------------------------
net/core/dev.c:1047 RCU-list traversed in non-reader section!!

other info that might help us debug this:

rcu_scheduler_active = 2, debug_locks = 1
locks held by python3/233: 2, last CPU#5:
#0: ffffffffbab93268 (cb_lock){++++}-{4:4}, at: genl_rcv+0x19/0x40 #1: ffffffffbab93320 (genl_mutex){+.+.}-{4:4}, at:

                                                genl_rcv_msg+0x12c/0x160

  stack backtrace:
  CPU: 5 UID: 0 PID: 233 Comm: python3 Not tainted 7.3.0#7 PREEMPT(full)
  Hardware name: Bochs, BIOS Bochs 01/01/2011
  Call Trace:
   <TASK>
   dump_stack_lvl+0x6f/0xb0
   lockdep_rcu_suspicious.cold+0x37/0x8e
   dev_get_by_index_rcu+0x135/0x180
   gtp_find_dev+0xe7/0x360 [gtp]
   gtp_genl_send_echo_req+0x298/0xb30 [gtp]
   genl_family_rcv_msg_doit+0x20f/0x310
   genl_family_rcv_msg+0x3a8/0x640
   genl_rcv_msg+0xbb/0x160
   netlink_rcv_skb+0x154/0x3a0
   genl_rcv+0x28/0x40
   netlink_unicast+0x54b/0x860
   netlink_sendmsg+0x7fb/0xf60
   __sys_sendto+0x3d6/0x450
   __x64_sys_sendto+0xe4/0x1f0
   do_syscall_64+0xff/0x530
   entry_SYSCALL_64_after_hwframe+0x77/0x7f
  RIP: 0033:0x7ffa43b0256e
  Code: 4d 89 d8 e8 d4 bd 00 00 4c 8b 5d f8 41 8b 93 08 03 00 00 59 5e 48 83
   f8 fc 74 11 c9 c3 0f 1f 80 00 00 00 00 48 8b 45 10 0f 05 <c9> c3 83 e2 39
   83 fa 08 75 e7 e8 03 ff ff ff 0f 1f 00 f3 0f 1e fa
  RSP: 002b:00007ffd3b8828d0 EFLAGS: 00000202 ORIG_RAX: 000000000000002c
  RAX: ffffffffffffffda RBX: 00007ffd3b8829e0 RCX: 00007ffa43b0256e
  RDX: 0000000000000034 RSI: 00007ffa3519d0d0 RDI: 0000000000000006
  RBP: 00007ffd3b8828e0 R08: 0000000000000000 R09: 0000000000000000
  R10: 0000000000000000 R11: 0000000000000202 R12: 00007ffa351cc0c0
  R13: 00007ffd3b8829e0 R14: 00007ffa354ca130 R15: 00007ffa4433d498
   </TASK>

Add the missing RCU guards and keep it for the whole function body, while the RCU-protected device is used.

Found by code inspection, validated explicitly testing the relevant code path.

---
 drivers/net/gtp.c | 44 ++++++++++++++++++++++++++++++--------------
 1 file changed, 30 insertions(+), 14 deletions(-)
drivers/net/gtp.c +30 -14
index 2551f17cbf14e..0d29d766511bc 100644
@@ -2356,9 +2356,9 @@ static int gtp_genl_send_echo_req(struct sk_buff *skb, struct genl_info *info)
 	struct gtp_dev *gtp;
 	struct flowi4 fl4;
 	struct rtable *rt;
+	int len, ret = 0;
 	struct sock *sk;
 	__be16 port;
-	int len;
 
 	if (!info->attrs[GTPA_VERSION] ||
 	    !info->attrs[GTPA_LINK] ||
@@ -2370,14 +2370,21 @@ static int gtp_genl_send_echo_req(struct sk_buff *skb, struct genl_info *info)
 	dst_ip = nla_get_be32(info->attrs[GTPA_PEER_ADDRESS]);
 	src_ip = nla_get_be32(info->attrs[GTPA_MS_ADDRESS]);
 
+	rcu_read_lock();
 	gtp = gtp_find_dev(sock_net(skb->sk), info->attrs);
-	if (!gtp)
-		return -ENODEV;
+	if (!gtp) {
+		ret = -ENODEV;
+		goto unlock;
+	}
 
-	if (!gtp->sk_created)
-		return -EOPNOTSUPP;
-	if (!(gtp->dev->flags & IFF_UP))
-		return -ENETDOWN;
+	if (!gtp->sk_created) {
+		ret = -EOPNOTSUPP;
+		goto unlock;
+	}
+	if (!(gtp->dev->flags & IFF_UP)) {
+		ret = -ENETDOWN;
+		goto unlock;
+	}
 
 	if (version == GTP_V0) {
 		struct gtp0_header *gtp0_h;
@@ -2386,8 +2393,10 @@ static int gtp_genl_send_echo_req(struct sk_buff *skb, struct genl_info *info)
 			sizeof(struct iphdr) + sizeof(struct udphdr);
 
 		skb_to_send = netdev_alloc_skb_ip_align(gtp->dev, len);
-		if (!skb_to_send)
-			return -ENOMEM;
+		if (!skb_to_send) {
+			ret = -ENOMEM;
+			goto unlock;
+		}
 
 		sk = gtp->sk0;
 		port = htons(GTP0_PORT);
@@ -2403,8 +2412,10 @@ static int gtp_genl_send_echo_req(struct sk_buff *skb, struct genl_info *info)
 			sizeof(struct iphdr) + sizeof(struct udphdr);
 
 		skb_to_send = netdev_alloc_skb_ip_align(gtp->dev, len);
-		if (!skb_to_send)
-			return -ENOMEM;
+		if (!skb_to_send) {
+			ret = -ENOMEM;
+			goto unlock;
+		}
 
 		sk = gtp->sk1u;
 		port = htons(GTP1U_PORT);
@@ -2414,7 +2425,8 @@ static int gtp_genl_send_echo_req(struct sk_buff *skb, struct genl_info *info)
 		memset(gtp1u_h, 0, sizeof(struct gtp1_header_long));
 		gtp1u_build_echo_msg(gtp1u_h, GTP_ECHO_REQ);
 	} else {
-		return -ENODEV;
+		ret = -ENODEV;
+		goto unlock;
 	}
 
 	rt = ip4_route_output_gtp(&fl4, sk, dst_ip, src_ip);
@@ -2422,7 +2434,8 @@ static int gtp_genl_send_echo_req(struct sk_buff *skb, struct genl_info *info)
 		netdev_dbg(gtp->dev, "no route for echo request to %pI4\n",
 			   &dst_ip);
 		kfree_skb(skb_to_send);
-		return -ENODEV;
+		ret = -ENODEV;
+		goto unlock;
 	}
 
 	local_bh_disable();
@@ -2436,7 +2449,10 @@ static int gtp_genl_send_echo_req(struct sk_buff *skb, struct genl_info *info)
 				    dev_net(gtp->dev)),
 			    false);
 	local_bh_enable();
-	return 0;
+
+unlock:
+	rcu_read_unlock();
+	return ret;
 }
 
 static const struct nla_policy gtp_genl_policy[GTPA_MAX + 1] = {
Signature · 1 line
2.53.0
author maintainer
#1624 lore raw

PATCH 1594/1756 net: atlantic: Unregister before clearing RXNFC rules

In reply to Greg Kroah-Hartman

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

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

From: Binbin Deng <[email protected]>

[ Upstream commit 13b364c765e69db1f8446399d8db0b331c23b50c ]

aq_pci_remove() clears the driver's RXNFC rule list before unregistering the netdevice. Until unregister_netdev() returns, ethtool operations can still call aq_get_rxnfc_rule(), aq_get_rxnfc_all_rules(), aq_add_rxnfc_rule(), or aq_del_rxnfc_rule(). Those paths traverse the same unlocked hlist that aq_clear_rxnfc_all_rules() is mutating and freeing.

The race is reachable by issuing RXNFC ethtool commands concurrently with PCI device removal or driver unbind. A reader can dereference a node that has just been freed, and two writers can corrupt the list or free the same rule more than once, causing KASAN reports, list corruption, or a kernel panic.

Reverse the removal order: unregister the netdevice first, then clear the RXNFC rules. After unregister_netdev() returns, ethtool can no longer enter the driver, while the PCI device is still available for the rule-clearing routine to issue hardware commands.

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

Fixes 8d0bcb012f57 ("net: aquantia: add infrastructure for ntuple rules")
---
 drivers/net/ethernet/aquantia/atlantic/aq_pci_func.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/ethernet/aquantia/atlantic/aq_pci_func.c +1 -1
index eb22531be554c..5e444a887283d 100644
@@ -343,9 +343,9 @@ static void aq_pci_remove(struct pci_dev *pdev)
 	struct aq_nic_s *self = pci_get_drvdata(pdev);
 
 	if (self->ndev) {
-		aq_clear_rxnfc_all_rules(self);
 		if (self->ndev->reg_state == NETREG_REGISTERED)
 			unregister_netdev(self->ndev);
+		aq_clear_rxnfc_all_rules(self);
 
 #if IS_ENABLED(CONFIG_MACSEC)
 		aq_macsec_free(self);
Signature · 1 line
2.53.0
author maintainer
#1625 lore raw

PATCH 1595/1756 net: usb: cdc_ncm: dont enable BHs in tx_fixup under netpoll

In reply to Greg Kroah-Hartman

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

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

From: Nicolai Buchwitz <[email protected]>

[ Upstream commit 108ca34cf4b453f6375a70079e32b11866b02601 ]

netpoll holds the txq lock and calls ndo_start_xmit() with IRQs off but BHs on. The spin_unlock_bh() in cdc_ncm_tx_fixup() then runs pending softirqs. If one of them transmits, it spins on the txq lock that netpoll holds. With netconsole on a cdc_ncm device this ends in a soft or hard lockup.

Every caller of cdc_ncm_tx_fixup() holds the txq lock with BHs or IRQs off, so the softirq user of ctx->mtx cannot interrupt it. Use plain spin_lock().

---
 drivers/net/usb/cdc_ncm.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
drivers/net/usb/cdc_ncm.c +5 -2
index c00699cd3e350..65a156ffdde96 100644
@@ -1536,14 +1536,17 @@ cdc_ncm_tx_fixup(struct usbnet *dev, struct sk_buff *skb, gfp_t flags)
 	if (ctx == NULL)
 		goto error;
 
-	spin_lock_bh(&ctx->mtx);
+	/* BHs or IRQs are always off here. netpoll only disables IRQs, and
+	 * spin_unlock_bh() would then run softirqs with the txq lock held.
+	 */
+	spin_lock(&ctx->mtx);
 
 	if (ctx->is_ndp16)
 		skb_out = cdc_ncm_fill_tx_frame(dev, skb, cpu_to_le32(USB_CDC_NCM_NDP16_NOCRC_SIGN));
 	else
 		skb_out = cdc_ncm_fill_tx_frame(dev, skb, cpu_to_le32(USB_CDC_NCM_NDP32_NOCRC_SIGN));
 
-	spin_unlock_bh(&ctx->mtx);
+	spin_unlock(&ctx->mtx);
 	return skb_out;
 
 error:
Signature · 1 line
2.53.0
author maintainer
#1626 lore raw

PATCH 1596/1756 net: usb: cdc_mbim: dont enable BHs in tx_fixup under netpoll

In reply to Greg Kroah-Hartman

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

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

From: Nicolai Buchwitz <[email protected]>

[ Upstream commit bfd7ced012c7857b5ab5edf7e416c2789b652702 ]

cdc_mbim_tx_fixup() has the same spin_unlock_bh() as cdc_ncm_tx_fixup(). Under netpoll it runs pending softirqs while the txq lock is held, and a transmit from one of them spins on that lock.

Use plain spin_lock() as in cdc_ncm.

Fixes 9bf211a30b3f ("net: cdc_mbim: adding MBIM driver")
---
 drivers/net/usb/cdc_mbim.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/net/usb/cdc_mbim.c +3 -2
index 917c8637533b2..3571c4f37b9d6 100644
@@ -290,9 +290,10 @@ static struct sk_buff *cdc_mbim_tx_fixup(struct usbnet *dev, struct sk_buff *skb
 		}
 	}
 
-	spin_lock_bh(&ctx->mtx);
+	/* BHs or IRQs are always off here, see cdc_ncm_tx_fixup() */
+	spin_lock(&ctx->mtx);
 	skb_out = cdc_ncm_fill_tx_frame(dev, skb, sign);
-	spin_unlock_bh(&ctx->mtx);
+	spin_unlock(&ctx->mtx);
 	return skb_out;
 
 error:
Signature · 1 line
2.53.0
author maintainer
#1627 lore raw

PATCH 1597/1756 ALSA: pcmtest: Honor the enable parameter

In reply to Greg Kroah-Hartman

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

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

From: HyeongJun An <[email protected]>

[ Upstream commit fe3b45a0875a8b0944d2adee3ca62283d876edc0 ]

The enable module parameter is declared and documented as "Enable pcmtest soundcard.", but nothing reads it. Loading the module with enable=0 still creates the card.

Return -ENODEV from mod_init() when enable is false, as the pcsp driver does.

Fixes 315a3d57c64c ("ALSA: Implement the new Virtual PCM Test Driver")
---
 sound/drivers/pcmtest.c | 3 +++
 1 file changed, 3 insertions(+)
sound/drivers/pcmtest.c +3 -0
index 3c85f90c0cc1e..0376fe17365a8 100644
@@ -762,6 +762,9 @@ static int __init mod_init(void)
 {
 	int err = 0;
 
+	if (!enable)
+		return -ENODEV;
+
 	buf_allocated = setup_patt_bufs();
 	if (!buf_allocated)
 		return -ENOMEM;
Signature · 1 line
2.53.0
author maintainer
#1628 lore raw

PATCH 1598/1756 ALSA: usb-audio: Add correct datainterval in the quirks-table for Microbook II

In reply to Greg Kroah-Hartman

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

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

From: Sally Marcher <[email protected]>

[ Upstream commit a09c2f3b267e47767b8937f65930567edbb88d44 ]

This patch fixes playback issues on the Microbook II. The correct value was in the older driver for this device
(https://github.com/manuel-rhdt/snd-microbookii/blob/dd304c097bb6a9d52276ac29c6969fa02bc7674a/audio.c#L914).

Datainterval needs to be set explicitly.

Fixes a634090a0f24 ("ALSA: usb-audio: Add quirk for MOTU MicroBook II")
---
 sound/usb/quirks-table.h | 2 ++
 1 file changed, 2 insertions(+)
sound/usb/quirks-table.h +2 -0
index 5dcbd85a25112..9e7f29d099818 100644
@@ -2753,6 +2753,7 @@ YAMAHA_DEVICE(0x7010, "UB99"),
 					.rates = SNDRV_PCM_RATE_96000,
 					.ep_attr = USB_ENDPOINT_XFER_ISOC |
 						   USB_ENDPOINT_SYNC_ASYNC,
+					.datainterval = 1,
 					.rate_min = 96000,
 					.rate_max = 96000,
 					.nr_rates = 1,
@@ -2775,6 +2776,7 @@ YAMAHA_DEVICE(0x7010, "UB99"),
 					.rates = SNDRV_PCM_RATE_96000,
 					.ep_attr = USB_ENDPOINT_XFER_ISOC |
 						   USB_ENDPOINT_SYNC_ASYNC,
+					.datainterval = 1,
 					.rate_min = 96000,
 					.rate_max = 96000,
 					.nr_rates = 1,
Signature · 1 line
2.53.0
author maintainer
#1629 lore raw

PATCH 1599/1756 net: tun: hold napi_mutex when deleting NAPI in tun_detach_all()

In reply to Greg Kroah-Hartman

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

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

From: Cheng Yongkang <[email protected]>

[ Upstream commit 6c799b4998c87bb44574bb090b8728bb3b3dbc47 ]

With IFF_NAPI_FRAGS, tun_get_user() takes tfile->napi_mutex, gets the skb from napi_get_frags() and copies the user data into it before it enters the RCU read-side section around napi_gro_frags().

tun_detach_all() waits with synchronize_net() and then calls tun_napi_del() without napi_mutex. netif_napi_del() frees napi->skb through napi_free_frags(). A writer that is still copying has not yet entered its RCU section, so synchronize_net() does not wait for it, and deleting the device frees the skb while the writer is using it:

  BUG: KASAN: slab-use-after-free in skb_copy_datagram_from_iter+0x175/0x720
  Read of size 8 at addr ffff888077def990 by task br029-poc/9406
  Call Trace:
   skb_copy_datagram_from_iter+0x175/0x720
   tun_get_user+0xb42/0x3d00
   tun_chr_write_iter+0x113/0x200
  ...
  Freed by task 9405:
   kmem_cache_free+0x184/0x670
   __netif_napi_del_locked+0x2bb/0x3c0
   tun_net_uninit+0x566/0xa70
   unregister_netdevice_many_notify+0x1a26/0x2090
   rtnl_dellink+0x514/0x710

__tun_detach() also calls tun_napi_del() without the mutex, but only from tun_chr_close(), when no write on that file can be in flight.

Take napi_mutex around tun_napi_del() in tun_detach_all() for both attached and disabled queues.

Fixes 90e33d459407 ("tun: enable napi_gro_frags() for TUN/TAP driver")
---
 drivers/net/tun.c | 4 ++++
 1 file changed, 4 insertions(+)
drivers/net/tun.c +4 -0
index 78a8f1e8eb855..479108e87e3d8 100644
@@ -736,14 +736,18 @@ static void tun_detach_all(struct net_device *dev)
 	synchronize_net();
 	for (i = 0; i < n; i++) {
 		tfile = rtnl_dereference(tun->tfiles[i]);
+		mutex_lock(&tfile->napi_mutex);
 		tun_napi_del(tfile);
+		mutex_unlock(&tfile->napi_mutex);
 		/* Drop read queue */
 		tun_queue_purge(tfile);
 		xdp_rxq_info_unreg(&tfile->xdp_rxq);
 		sock_put(&tfile->sk);
 	}
 	list_for_each_entry_safe(tfile, tmp, &tun->disabled, next) {
+		mutex_lock(&tfile->napi_mutex);
 		tun_napi_del(tfile);
+		mutex_unlock(&tfile->napi_mutex);
 		tun_enable_queue(tfile);
 		tun_queue_purge(tfile);
 		xdp_rxq_info_unreg(&tfile->xdp_rxq);
Signature · 1 line
2.53.0
author maintainer
#1630 lore raw

PATCH 1600/1756 net/rds: do not fail init when CONFIG_SYSCTL=n

In reply to Greg Kroah-Hartman

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

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

From: Allison Henderson <[email protected]>

[ Upstream commit fbea154a86641d2543a871aa19f7c77a366de542 ]

With CONFIG_SYSCTL=n, register_net_sysctl() and register_net_sysctl_sz() are inline stubs that return NULL. rds_sysctl_init(), rds_ib_sysctl_init() and rds_tcp_init_net() all treat that NULL as -ENOMEM, so RDS refuses to initialize at all even though every tunable has a sane compiled-in default.

When RDS is built in, that is worse than a missing feature: the failed rds_init() destroys rds_wq, but the rds_rdma initcall still runs, and when rds_ib_sysctl_init() fails the same way, the error path in rds_ib_init() flushes the already freed workqueue:

  BUG: KASAN: slab-use-after-free in touch_wq_lockdep_map
  ...
   __flush_workqueue
   rds_ib_init
   rds_rdma_init
  ...
  Allocated by task 1:
   alloc_workqueue_noprof
   rds_threads_init
   rds_init
  ...
  Freed by task 0:
   kfree
   rcu_do_batch

Only treat the NULL return as a failure when sysctl support is actually compiled in. The exit paths need no change: unregister_net_sysctl_table() is an empty stub with CONFIG_SYSCTL=n and already tolerates a NULL header otherwise.

The underlying problem of built-in transports initializing after rds_init() has failed is independent of sysctl and is addressed separately.

Fixes 3e5048495c85 ("RDS: sysctls")
Fixes e6babe4cc4ce ("RDS/IB: Stats and sysctls")
Fixes c6a58ffed536 ("RDS: TCP: Add sysctl tunables for sndbuf/rcvbuf on rds-tcp socket")
---
 net/rds/ib_sysctl.c | 2 +-
 net/rds/sysctl.c    | 2 +-
 net/rds/tcp.c       | 2 +-
 3 files changed, 3 insertions(+), 3 deletions(-)
net/rds/ib_sysctl.c +1 -1
index 2af678e71e3c6..bc97a3eecad69 100644
@@ -114,7 +114,7 @@ void rds_ib_sysctl_exit(void)
 int rds_ib_sysctl_init(void)
 {
 	rds_ib_sysctl_hdr = register_net_sysctl(&init_net, "net/rds/ib", rds_ib_sysctl_table);
-	if (!rds_ib_sysctl_hdr)
+	if (!rds_ib_sysctl_hdr && IS_ENABLED(CONFIG_SYSCTL))
 		return -ENOMEM;
 	return 0;
 }
net/rds/sysctl.c +1 -1
index 025f518a43495..968d6279bbd36 100644
@@ -103,7 +103,7 @@ int rds_sysctl_init(void)
 
 	rds_sysctl_reg_table =
 		register_net_sysctl(&init_net, "net/rds", rds_sysctl_rds_table);
-	if (!rds_sysctl_reg_table)
+	if (!rds_sysctl_reg_table && IS_ENABLED(CONFIG_SYSCTL))
 		return -ENOMEM;
 	return 0;
 }
net/rds/tcp.c +1 -1
index eab960d10ab08..7fae00350b404 100644
@@ -643,7 +643,7 @@ static __net_init int rds_tcp_init_net(struct net *net)
 	tbl[RDS_TCP_RCVBUF].data = &rtn->rcvbuf_size;
 	rtn->rds_tcp_sysctl = register_net_sysctl_sz(net, "net/rds/tcp", tbl,
 						     ARRAY_SIZE(rds_tcp_sysctl_table));
-	if (!rtn->rds_tcp_sysctl) {
+	if (!rtn->rds_tcp_sysctl && IS_ENABLED(CONFIG_SYSCTL)) {
 		pr_warn("could not register sysctl\n");
 		err = -ENOMEM;
 		goto fail;
Signature · 1 line
2.53.0
author maintainer
#1631 lore raw

PATCH 1601/1756 net/rds: do not initialize transports after rds_init() failed

In reply to Greg Kroah-Hartman

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

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

From: Allison Henderson <[email protected]>

[ Upstream commit ffbbc315b8b883a1c0e131fb3186b9428d2812aa ]

rds, rds_rdma and rds_tcp each have their own module_init(). When they are built in, those run in link order, so rds_init() goes first, but do_initcalls() does not stop when it fails. The transports then initialize against a core that has already been torn down: rds_wq has been destroyed, yet rds_ib_dev_put(), rds_ib_unregister_client() and rds_tcp_accept_work() still queue onto or flush it, and rds_trans_register() hands the transports to a core whose socket family may never have been registered.

This was seen with CONFIG_SYSCTL=n, where rds_sysctl_init() failed and rds_ib_init()'s error path then flushed the freed rds_wq [1], but any rds_init() failure after rds_threads_init() has the same effect.

Record whether rds_init() succeeded and have rds_rdma_init() and rds_tcp_init() bail out with -ENODEV otherwise. Modular builds are
unaffected: the transports need symbols exported by rds.ko, so they cannot be loaded unless rds_init() succeeded.

[1] https://lore.kernel.org/oe-lkp/[email protected]

Fixes 55b7ed0b582f ("RDS: Common RDMA transport code")
Fixes 70041088e3b9 ("RDS: Add TCP transport to RDS")
---
 net/rds/af_rds.c         | 14 ++++++++++++++
 net/rds/rdma_transport.c |  3 +++
 net/rds/rds.h            |  1 +
 net/rds/tcp.c            |  3 +++
 4 files changed, 21 insertions(+)
net/rds/af_rds.c +14 -0
index 63b6d6e6b035d..942ee11c67a9f 100644
@@ -921,8 +921,11 @@ static void rds6_sock_info(struct socket *sock, unsigned int len,
 }
 #endif
 
+static bool rds_initialized;
+
 static void rds_exit(void)
 {
+	rds_initialized = false;
 	sock_unregister(rds_family_ops.family);
 	proto_unregister(&rds_proto);
 	rds_conn_exit();
@@ -943,6 +946,16 @@ module_exit(rds_exit);
 
 u32 rds_gen_num;
 
+/* When RDS is built in, a failed rds_init() does not stop the rds_rdma
+ * and rds_tcp initcalls from running against a core that has already
+ * been torn down (rds_wq in particular).  Let them bail out early.
+ */
+bool rds_is_initialized(void)
+{
+	return rds_initialized;
+}
+EXPORT_SYMBOL_GPL(rds_is_initialized);
+
 static int __init rds_init(void)
 {
 	int ret;
@@ -979,6 +992,7 @@ static int __init rds_init(void)
 	rds_info_register_func(RDS6_INFO_SOCKETS, rds6_sock_info);
 	rds_info_register_func(RDS6_INFO_RECV_MESSAGES, rds6_sock_inc_info);
 #endif
+	rds_initialized = true;
 
 	goto out;
 
net/rds/rdma_transport.c +3 -0
index 7be38be1228ec..cc6a7d29791ae 100644
@@ -325,6 +325,9 @@ static int __init rds_rdma_init(void)
 {
 	int ret;
 
+	if (!rds_is_initialized())
+		return -ENODEV;
+
 	ret = rds_ib_init();
 	if (ret)
 		goto out;
net/rds/rds.h +1 -0
index 5a1789ace8fbf..9396eda4c3ff7 100644
@@ -1008,6 +1008,7 @@ extern unsigned int  rds_sysctl_trace_level;
 int rds_threads_init(void);
 void rds_threads_exit(void);
 extern struct workqueue_struct *rds_wq;
+bool rds_is_initialized(void);
 void rds_queue_reconnect(struct rds_conn_path *cp);
 void rds_connect_worker(struct work_struct *);
 void rds_shutdown_worker(struct work_struct *);
net/rds/tcp.c +3 -0
index 7fae00350b404..73b587660b3ac 100644
@@ -819,6 +819,9 @@ static int __init rds_tcp_init(void)
 {
 	int ret;
 
+	if (!rds_is_initialized())
+		return -ENODEV;
+
 	rds_tcp_conn_slab = KMEM_CACHE(rds_tcp_connection, 0);
 	if (!rds_tcp_conn_slab) {
 		ret = -ENOMEM;
Signature · 1 line
2.53.0
author maintainer
#1632 lore raw

PATCH 1602/1756 net: xps: bound the cleanup loop by the old maps num_tc

In reply to Greg Kroah-Hartman

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

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

From: Dudu Lu <[email protected]>

[ Upstream commit 6d5a2cb0b7d6caf170d37ae7ac74738d592d2a05 ]

__netif_set_xps_queue() walks the OLD dev_maps to free its entries. The per-row trip count uses the NEW num_tc while the row stride uses the OLD dev_maps->num_tc, so when dev->num_tc was raised without rebuilding the XPS map the last row indexes attr_map[] past the allocation:

  BUG: KASAN: slab-out-of-bounds in __netif_set_xps_queue+0x1458/0x1ee8
  Read of size 8 at addr ffff000014f69458 by task insmod/112

The loop frees entries in dev_maps, so both the trip count and the stride must come from dev_maps->num_tc. The map is sized XPS_CPU_DEV_MAPS_SIZE(old num_tc)/XPS_RXQ_DEV_MAPS_SIZE(old num_tc, ...), so iterating the new (larger) num_tc reads past the end.

---
 net/core/dev.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/core/dev.c +1 -1
index f42ec2837143e..857d195bef231 100644
@@ -2788,7 +2788,7 @@ int __netif_set_xps_queue(struct net_device *dev, const unsigned long *mask,
 		goto out_no_old_maps;
 
 	for (j = 0; j < dev_maps->nr_ids; j++) {
-		for (i = num_tc, tci = j * dev_maps->num_tc; i--; tci++) {
+		for (i = dev_maps->num_tc, tci = j * dev_maps->num_tc; i--; tci++) {
 			map = xmap_dereference(dev_maps->attr_map[tci]);
 			if (!map)
 				continue;
Signature · 1 line
2.53.0
author maintainer
#1633 lore raw

PATCH 1603/1756 net: lan966x: do not inject uninitialised bytes past skb->len

In reply to Greg Kroah-Hartman

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

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

From: Daniel Machon <[email protected]>

[ Upstream commit b4a7180558eb3cd8affa1e240b22171425bdfcb4 ]

lan966x_port_ifh_xmit() writes the frame to the injection FIFO one 32-bit word at a time, and pads frames shorter than 60 bytes with zero words.

Before this patch, the last word is loaded whole even when skb->len is not a multiple of four, so 1 to 3 bytes past the end of the frame are read. For a frame shorter than 60 bytes those bytes are also transmitted, as VLD_BYTES marks the whole last word valid and the padding starts at the next word.

Write the trailing bytes from a zeroed word. The number of words written and VLD_BYTES are unchanged.

Found by an AI code review agent. Reproduced on a lan9668 board with register injection, by sending a
57 byte frame and capturing it on the link partner: byte 57 of the padded frame was not zero. With the fix all padding bytes are zero.

---
 .../ethernet/microchip/lan966x/lan966x_main.c | 19 ++++++++++++++++---
 1 file changed, 16 insertions(+), 3 deletions(-)
drivers/net/ethernet/microchip/lan966x/lan966x_main.c +16 -3
index 9acba25a30586..300f0751c707a 100644
@@ -253,9 +253,8 @@ static int lan966x_port_ifh_xmit(struct sk_buff *skb,
 		lan_wr((__force u32)ifh[i], lan966x, QS_INJ_WR(grp));
 	}
 
-	/* Write frame */
-	count = DIV_ROUND_UP(skb->len, 4);
-	last = skb->len % 4;
+	/* Write the whole words of the frame */
+	count = skb->len / 4;
 	for (i = 0; i < count; ++i) {
 		/* Wait until the fifo is ready */
 		err = lan966x_port_inj_ready(lan966x, grp);
@@ -265,6 +264,20 @@ static int lan966x_port_ifh_xmit(struct sk_buff *skb,
 		lan_wr(((u32 *)skb->data)[i], lan966x, QS_INJ_WR(grp));
 	}
 
+	/* Write the last 1 to 3 bytes, zero padded to a whole word */
+	last = skb->len % 4;
+	if (last) {
+		/* Wait until the fifo is ready */
+		err = lan966x_port_inj_ready(lan966x, grp);
+		if (err)
+			goto err;
+
+		val = 0;
+		memcpy(&val, skb->data + count * 4, last);
+		lan_wr(val, lan966x, QS_INJ_WR(grp));
+		++i;
+	}
+
 	/* Add padding */
 	while (i < (LAN966X_BUFFER_MIN_SZ / 4)) {
 		/* Wait until the fifo is ready */
Signature · 1 line
2.53.0
author maintainer
#1634 lore raw

PATCH 1604/1756 net: lan966x: do not warn on MAC entries that are not port destined

In reply to Greg Kroah-Hartman

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

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

From: Daniel Machon <[email protected]>

[ Upstream commit 2cffcf1aeabb187e4f08fe4f5363128a3c45d786 ]

lan966x_mac_irq_handler() scans the rows of the MAC table that the analyzer reports as changed, reads back all four columns of each row and treats ANA_MACACCESS.DEST_IDX as a port number.

Before this patch, a destination index above num_phys_ports hits a WARN_ON(). The driver installs such entries itself:
lan966x_mac_cpu_learn() uses PGID_CPU, and L2 multicast entries use a general-purpose PGID. A row holding one of them is read back whenever another entry in the same row is learned or aged out, so the scan warns in normal operation, repeatedly once the MAC table is busy.

Skipping such a column is already the right behaviour. Drop the WARN_ON() and keep the bounds check as a plain filter.

Found by an AI code review agent. Reproduced on a lan9668 board by bridging two ports with a 10 s ageing time and sending three rounds of 2048 new source MACs: the base kernel warned 42 times from lan966x_mac_irq_process(), the fixed kernel did not warn.

Fixes 5ccd66e01cbe ("net: lan966x: add support for interrupts from analyzer")
---
 drivers/net/ethernet/microchip/lan966x/lan966x_mac.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/net/ethernet/microchip/lan966x/lan966x_mac.c +2 -2
index baa3a30c039f4..96bb0a16ac08d 100644
@@ -447,7 +447,7 @@ static void lan966x_mac_irq_process(struct lan966x *lan966x, u32 row,
 
 			lan966x_mac_process_raw_entry(&raw_entries[column],
 						      mac, &vid, &dest_idx);
-			if (WARN_ON(dest_idx >= lan966x->num_phys_ports))
+			if (dest_idx >= lan966x->num_phys_ports)
 				continue;
 
 			/* If the entry in SW is found, then there is nothing
@@ -501,7 +501,7 @@ static void lan966x_mac_irq_process(struct lan966x *lan966x, u32 row,
 
 		lan966x_mac_process_raw_entry(&raw_entries[column],
 					      mac, &vid, &dest_idx);
-		if (WARN_ON(dest_idx >= lan966x->num_phys_ports))
+		if (dest_idx >= lan966x->num_phys_ports)
 			continue;
 
 		spin_lock(&lan966x->mac_lock);
Signature · 1 line
2.53.0
author maintainer
#1635 lore raw

PATCH 1605/1756 x86_energy_perf_policy: Fix optarg keyword matching

In reply to Greg Kroah-Hartman

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

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

From: Len Brown <[email protected]>

[ Upstream commit 0177067d195a4757149f6702af191987377c71c3 ]

Replace strncmp() with strcmp() for exact string matching in parse_optarg_string(). Exact keyword matching is safer and clearer. This prevents accidental matches with longer strings
like "performance-foo".

Fixes 4beec1d75196 ("tools/power x86_energy_perf_policy: support HWP.EPP")
Assisted-by GitHub-Copilot:Claude-Sonnet-4.6
---
 .../x86_energy_perf_policy/x86_energy_perf_policy.c  | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
tools/power/x86/x86_energy_perf_policy/x86_energy_perf_policy.c +6 -6
index 891738116c8b2..2545f64d5f43b 100644
@@ -312,22 +312,22 @@ int parse_optarg_string(char *s)
 	int i;
 	char *endptr;
 
-	if (!strncmp(s, "default", 7))
+	if (strcmp(s, "default") == 0)
 		return OPTARG_NORMAL;
 
-	if (!strncmp(s, "normal", 6))
+	if (strcmp(s, "normal") == 0)
 		return OPTARG_NORMAL;
 
-	if (!strncmp(s, "power", 9))
+	if (strcmp(s, "power") == 0)
 		return OPTARG_POWER;
 
-	if (!strncmp(s, "balance-power", 17))
+	if (strcmp(s, "balance-power") == 0)
 		return OPTARG_BALANCE_POWER;
 
-	if (!strncmp(s, "balance-performance", 19))
+	if (strcmp(s, "balance-performance") == 0)
 		return OPTARG_BALANCE_PERFORMANCE;
 
-	if (!strncmp(s, "performance", 11))
+	if (strcmp(s, "performance") == 0)
 		return OPTARG_PERFORMANCE;
 
 	i = strtol(s, &endptr, 0);
Signature · 1 line
2.53.0
author maintainer
#1636 lore raw

PATCH 1606/1756 x86_energy_perf_policy: Cleanup: Check fseek() in VM path

In reply to Greg Kroah-Hartman

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

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

From: Len Brown <[email protected]>

[ Upstream commit 2778dc35d40e7e84c134ca4cab1376fa58208f80 ]

Add return value validation for fseek() and ensure consistent resource cleanup on all error paths in err_on_hypervisor().

Fixes 0936cdfbb527 ("tools/power x86_energy_perf_policy: Input/output error in a VM")
Assisted-by GitHub-Copilot:Claude-Sonnet-4.6
---
 .../x86/x86_energy_perf_policy/x86_energy_perf_policy.c     | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
tools/power/x86/x86_energy_perf_policy/x86_energy_perf_policy.c +5 -1
index 2545f64d5f43b..f26c6dd0d6c14 100644
@@ -661,7 +661,11 @@ void err_on_hypervisor(void)
 
 	flags = strstr(buffer, "flags");
 	rewind(cpuinfo);
-	fseek(cpuinfo, flags - buffer, SEEK_SET);
+	if (fseek(cpuinfo, flags - buffer, SEEK_SET) != 0) {
+		fclose(cpuinfo);
+		free(buffer);
+		err(1, "Failed to seek in /proc/cpuinfo");
+	}
 	if (!fgets(buffer, 4096, cpuinfo)) {
 		fclose(cpuinfo);
 		free(buffer);
Signature · 1 line
2.53.0
author maintainer
#1637 lore raw

PATCH 1607/1756 perf mmap: Use the head selected by read_init

In reply to Greg Kroah-Hartman

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

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

From: Paul Moses <[email protected]>

[ Upstream commit 022c64992af554cfd8c564bff86100fb5ed98678 ]

perf_mmap__push() reads the producer head before calling perf_mmap__read_init(), which reads it again to select the range to copy.

If the producer advances between those reads, push() copies through the newer head but stores the earlier head in prev. The next drain starts at that earlier position and can write the same records to perf.data again.

Use the head selected by read_init(): end for forward buffers and start for overwrite buffers. Save it before the copy loop advances start so prev matches the range that was copied.

Fixes 8872481bd04850b1 ("perf mmap: Introduce perf_mmap__read_init()")
Cc Adrian Hunter <[email protected]>
Cc Alexander Shishkin <[email protected]>
Cc Ian Rogers <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc James Clark <[email protected]>
Cc Jiri Olsa <[email protected]>
Cc Kan Liang <[email protected]>
Cc Kan Liang <[email protected]>
Cc Mark Rutland <[email protected]>
Cc Namhyung Kim <[email protected]>
Cc Peter Zijlstra <[email protected]>
---
 tools/perf/util/mmap.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
tools/perf/util/mmap.c +2 -1
index 43b02293f1d2d..3033b454643b4 100644
@@ -319,7 +319,7 @@ int mmap__mmap(struct mmap *map, struct mmap_params *mp, int fd, struct perf_cpu
 int perf_mmap__push(struct mmap *md, void *to,
 		    int push(struct mmap *map, void *to, void *buf, size_t size))
 {
-	u64 head = perf_mmap__read_head(&md->core);
+	u64 head;
 	unsigned char *data = md->core.base + page_size;
 	unsigned long size;
 	void *buf;
@@ -329,6 +329,7 @@ int perf_mmap__push(struct mmap *md, void *to,
 	if (rc < 0)
 		return (rc == -EAGAIN) ? 1 : -1;
 
+	head = md->core.overwrite ? md->core.start : md->core.end;
 	size = md->core.end - md->core.start;
 
 	if ((md->core.start & md->core.mask) + size != (md->core.end & md->core.mask)) {
Signature · 1 line
2.53.0
author maintainer
#1638 lore raw

PATCH 1608/1756 perf mmap: Preserve the consumed cursor in forward mode

In reply to Greg Kroah-Hartman

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

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

From: Paul Moses <[email protected]>

[ Upstream commit 1e826983ceef421d7047ed76581840b778294ad4 ]

perf_mmap__read_event() updates prev as it consumes forward-buffer records. perf_mmap__read_done() then overwrites prev with a fresh producer head, even when unread records remain.

perf_kvm__mmap_read_idx() stops after 25 records per mmap and calls read_done(). If more records are pending, prev advances past them. The next drain starts at that new position and skips the unread remainder.

An event arriving after the last empty read_event() and before read_done() can also be skipped. read_done() does not itself update the kernel's data_tail.

Only refresh prev for overwrite buffers, which need the current head as the end of the next backward read. Leave the forward cursor at the consumed position.

Fixes 53172f9057e92c9b ("perf kvm: Switch to new perf_mmap__read_event() interface")
Cc Adrian Hunter <[email protected]>
Cc Alexander Shishkin <[email protected]>
Cc Ian Rogers <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc James Clark <[email protected]>
Cc Jiri Olsa <[email protected]>
Cc Kan Liang <[email protected]>
Cc Mark Rutland <[email protected]>
Cc Namhyung Kim <[email protected]>
Cc Peter Zijlstra <[email protected]>
---
 tools/lib/perf/mmap.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/lib/perf/mmap.c +1 -1
index c1a51d925e0e0..52b806e799a4b 100644
@@ -200,7 +200,7 @@ void perf_mmap__read_done(struct perf_mmap *map)
 	/*
 	 * Check if event was unmapped due to a POLLHUP/POLLERR.
 	 */
-	if (!refcount_read(&map->refcnt))
+	if (!refcount_read(&map->refcnt) || !map->overwrite)
 		return;
 
 	map->prev = perf_mmap__read_head(map);
Signature · 1 line
2.53.0
author maintainer
#1639 lore raw

PATCH 1609/1756 perf print_insn: Include sys/types.h for ssize_t

In reply to Greg Kroah-Hartman

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

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

From: Florian Fainelli <[email protected]>

[ Upstream commit e0e4470aa53c0022418290fb551c21da4bd50209 ]

print_insn.h declares fprintf_insn_asm() with an ssize_t return type but does not include the header defining that type. This causes builds where stdio.h does not provide ssize_t to fail when compiling util/print_insn.c:

util/print_insn.h:21:1: error: unknown type name 'ssize_t'

Include sys/types.h so the header provides its own dependency for ssize_t.

Fixes 218c200f677d8af4 ("perf script: Consolidate capstone print functions")
Cc Adrian Hunter <[email protected]>
Cc Alexander Shishkin <[email protected]>
Cc Andi Kleen <[email protected]>
Cc Ian Rogers <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc Jiri Olsa <[email protected]>
Cc Mark Rutland <[email protected]>
Cc Namhyung Kim <[email protected]>
Cc Peter Zijlstra <[email protected]>
---
 tools/perf/util/print_insn.h | 1 +
 1 file changed, 1 insertion(+)
tools/perf/util/print_insn.h +1 -0
index 07d11af3fc1cb..e4eb55e8b8a2f 100644
@@ -4,6 +4,7 @@
 
 #include <stddef.h>
 #include <stdio.h>
+#include <sys/types.h>
 
 struct perf_sample;
 struct thread;
Signature · 1 line
2.53.0
author maintainer
#1640 lore raw

PATCH 1610/1756 drm/amdgpu: re-enable GFXOFF for compute on GFX12

In reply to Greg Kroah-Hartman

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

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

From: Harkirat Gill <[email protected]>

[ Upstream commit 6a1dbb006056ad1ce6df0d6d5f2155767c20f410 ]

Commit 2affe2bbc997 ("drm/amdgpu: disable gfxoff with the compute workload on gfx12") disabled GFXOFF whenever a user-mode compute queue exists, as a workaround for an OpenCL test failure. The MES firmware issue behind that failure has since been addressed, so the workaround is no longer required.

Without this change, idle inference servers that hold a context for hours never let the graphics block power down, costing roughly 3-4% reported GPU activity and ~3 W per GPU at idle.

Measured on gfx1200 with an idle HIP process holding one stream and two resident KFD queues:

before: VDDGFX 695 mV, GPU load 2%, ~9-10 W
after: VDDGFX 35 mV, GPU load 0%, ~8 W (idle baseline)

The resident queue count is unchanged in both cases; only GFXOFF availability differs. The ocltst runtime suite (40 tests) passes with and without this change.

Fixes 2affe2bbc997 ("drm/amdgpu: disable gfxoff with the compute workload on gfx12")
(cherry picked from commit f6d97ecb68b8623da2f83997a9c8c57a1a9649f9)
---
 drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.c +2 -3
index 2de2895e3850b..3e946b61df152 100644
@@ -737,9 +737,8 @@ int amdgpu_amdkfd_submit_ib(struct amdgpu_device *adev,
 void amdgpu_amdkfd_set_compute_idle(struct amdgpu_device *adev, bool idle)
 {
 	enum amd_powergating_state state = idle ? AMD_PG_STATE_GATE : AMD_PG_STATE_UNGATE;
-	if ((IP_VERSION_MAJ(amdgpu_ip_version(adev, GC_HWIP, 0)) == 11 &&
-	    ((adev->mes.kiq_version & AMDGPU_MES_VERSION_MASK) <= 64)) ||
-		(IP_VERSION_MAJ(amdgpu_ip_version(adev, GC_HWIP, 0)) == 12)) {
+	if (IP_VERSION_MAJ(amdgpu_ip_version(adev, GC_HWIP, 0)) == 11 &&
+	    ((adev->mes.kiq_version & AMDGPU_MES_VERSION_MASK) <= 64)) {
 		pr_debug("GFXOFF is %s\n", idle ? "enabled" : "disabled");
 		amdgpu_gfx_off_ctrl(adev, idle);
 	} else if ((IP_VERSION_MAJ(amdgpu_ip_version(adev, GC_HWIP, 0)) == 9) &&
Signature · 1 line
2.53.0
author maintainer
#1641 lore raw

PATCH 1611/1756 net: lan966x: fix the DB dataptr of frames from ndo_xdp_xmit

In reply to Greg Kroah-Hartman

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

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

From: Daniel Machon <[email protected]>

[ Upstream commit ce3192e0dafa829e76edefecc16a32589b53c875 ]

lan966x_fdma_xmit_xdpf() transmits both XDP_TX frames and xdp_frames from ndo_xdp_xmit, and builds the DB with lan966x_fdma_xdp_tx_dataptr_cb(), which adds XDP_PACKET_HEADROOM to the stored DMA address.

Before this patch, the headroom is also added for xdp_frames. For XDP_TX the stored address is the start of the page pool page, but for an xdp_frame it is the mapping of the IFH placed in front of the frame data, so frames from ndo_xdp_xmit are read from XDP_PACKET_HEADROOM bytes after their IFH.

Use the plain tx dataptr callback for xdp_frames.

Found by an AI code review agent. Reproduced on a lan9668 board with an XDP program redirecting frames from one port to another: none of the 20 frames arrived intact on the link partner. With the fix all 20 did.

---
 drivers/net/ethernet/microchip/lan966x/lan966x_fdma.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/net/ethernet/microchip/lan966x/lan966x_fdma.c +2 -1
index b13c60438b978..4e9f347a1387c 100644
@@ -686,7 +686,8 @@ int lan966x_fdma_xmit_xdpf(struct lan966x_port *port, void *ptr, u32 len)
 		       FDMA_DCB_STATUS_BLOCKO(0) |
 		       FDMA_DCB_STATUS_BLOCKL(next_dcb_buf->len),
 		       &fdma_nextptr_cb,
-		       &lan966x_fdma_xdp_tx_dataptr_cb);
+		       len ? &lan966x_fdma_xdp_tx_dataptr_cb :
+			     &lan966x_fdma_tx_dataptr_cb);
 
 	/* Start the transmission */
 	lan966x_fdma_tx_start(tx);
Signature · 1 line
2.53.0
author maintainer
#1642 lore raw

PATCH 1612/1756 net: lan966x: release the in-flight slot of a stale TX skb

In reply to Greg Kroah-Hartman

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

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

From: Daniel Machon <[email protected]>

[ Upstream commit 074caa30a62726c0ee959e8b8ccb64cda0b26ae5 ]

lan966x_ptp_txtstamp_request() counts every two step TX skb waiting for its timestamp in lan966x->ptp_skbs, and refuses new ones once LAN966X_MAX_PTP_ID are in flight. lan966x_ptp_txtstamp_old_release() frees the skbs that have waited longer than LAN966X_PTP_TIMEOUT.

Before this patch, old_release() does not decrement ptp_skbs, so every skb whose timestamp never arrives, for example because the switch discarded the frame, keeps its slot forever. Once LAN966X_MAX_PTP_ID slots are lost, two step frames fail to transmit on every port of the switch.

Return the number of released skbs from old_release() and subtract it from ptp_skbs in txtstamp_request(), under the ptp_ts_id_lock it already takes.

This fixes the accounting only. A port's stale skbs are still aged out only when that port sends a two step frame, so a port that stops sending them keeps its stale skbs, and their slots, until it sends one again. That behaviour is unchanged by this patch.

Found by an AI code review agent. Reproduced on a lan9668 board.

---
 drivers/net/ethernet/microchip/lan966x/lan966x_ptp.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
drivers/net/ethernet/microchip/lan966x/lan966x_ptp.c +8 -2
index 84f5b4410e48e..fd213d5b57e69 100644
@@ -376,9 +376,10 @@ static void lan966x_ptp_classify(struct lan966x_port *port, struct sk_buff *skb,
 	*rew_op = IFH_REW_OP_TWO_STEP_PTP;
 }
 
-static void lan966x_ptp_txtstamp_old_release(struct lan966x_port *port)
+static unsigned int lan966x_ptp_txtstamp_old_release(struct lan966x_port *port)
 {
 	struct sk_buff *skb, *skb_tmp;
+	unsigned int purged = 0;
 	unsigned long flags;
 
 	spin_lock_irqsave(&port->tx_skbs.lock, flags);
@@ -389,14 +390,18 @@ static void lan966x_ptp_txtstamp_old_release(struct lan966x_port *port)
 
 		__skb_unlink(skb, &port->tx_skbs);
 		dev_kfree_skb_any(skb);
+		purged++;
 	}
 	spin_unlock_irqrestore(&port->tx_skbs.lock, flags);
+
+	return purged;
 }
 
 int lan966x_ptp_txtstamp_request(struct lan966x_port *port,
 				 struct sk_buff *skb)
 {
 	struct lan966x *lan966x = port->lan966x;
+	unsigned int purged;
 	unsigned long flags;
 	u8 pdu_type;
 	u8 rew_op;
@@ -408,9 +413,10 @@ int lan966x_ptp_txtstamp_request(struct lan966x_port *port,
 	if (rew_op != IFH_REW_OP_TWO_STEP_PTP)
 		return 0;
 
-	lan966x_ptp_txtstamp_old_release(port);
+	purged = lan966x_ptp_txtstamp_old_release(port);
 
 	spin_lock_irqsave(&lan966x->ptp_ts_id_lock, flags);
+	lan966x->ptp_skbs -= purged;
 	if (lan966x->ptp_skbs == LAN966X_MAX_PTP_ID) {
 		spin_unlock_irqrestore(&lan966x->ptp_ts_id_lock, flags);
 		return -EBUSY;
Signature · 1 line
2.53.0
author maintainer
#1643 lore raw

PATCH 1613/1756 net: microchip: fdma: use little-endian types for descriptor fields

In reply to Greg Kroah-Hartman

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

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

From: Daniel Machon <[email protected]>

[ Upstream commit 9786c387b299bda5277eed98284a6f6fa7331fb9 ]

The FDMA engine reads and writes the DCB and DB descriptors in little-endian byte order. So far the descriptors have only been produced by the little-endian SoC itself, so plain u64 fields were fine. With the PCIe FDMA path, the descriptors live in host memory and are written by the host CPU, which may be big-endian.

Change the descriptor fields to __le64 and convert at the library
boundary: in __fdma_db_add() and __fdma_dcb_add() on write, and in the fdma_db_*() accessors on read. The dataptr and nextptr callbacks keep their u64 signatures, so their implementations are unchanged. Add fdma_db_dataptr_get(), and convert the lan966x sites that read the descriptor fields directly to use the accessors.

No functional change on little-endian hosts.

Stable-dep-of: 573a6d4c7a21 ("net: microchip: fdma: fix DCB corruption under sustained load")

---
 .../net/ethernet/microchip/fdma/fdma_api.c    | 21 ++++++++++++++-----
 .../net/ethernet/microchip/fdma/fdma_api.h    | 20 +++++++++++-------
 .../ethernet/microchip/lan966x/lan966x_fdma.c |  9 ++++----
 3 files changed, 34 insertions(+), 16 deletions(-)
drivers/net/ethernet/microchip/fdma/fdma_api.c +16 -5
index e78c3590da9e6..6dfe36f58d67a 100644
@@ -12,10 +12,18 @@ static int __fdma_db_add(struct fdma *fdma, int dcb_idx, int db_idx, u64 status,
 				   int db_idx, u64 *dataptr))
 {
 	struct fdma_db *db = fdma_db_get(fdma, dcb_idx, db_idx);
+	u64 dataptr;
+	int err;
 
-	db->status = status;
+	db->status = cpu_to_le64(status);
 
-	return cb(fdma, dcb_idx, db_idx, &db->dataptr);
+	err = cb(fdma, dcb_idx, db_idx, &dataptr);
+	if (unlikely(err))
+		return err;
+
+	db->dataptr = cpu_to_le64(dataptr);
+
+	return 0;
 }
 
 /* Add a DB to a DCB, using the callback set in the fdma_ops struct. */
@@ -35,6 +43,7 @@ int __fdma_dcb_add(struct fdma *fdma, int dcb_idx, u64 info, u64 status,
 				u64 *dataptr))
 {
 	struct fdma_dcb *dcb = fdma_dcb_get(fdma, dcb_idx);
+	u64 nextptr;
 	int i, err;
 
 	for (i = 0; i < fdma->n_dbs; i++) {
@@ -43,14 +52,16 @@ int __fdma_dcb_add(struct fdma *fdma, int dcb_idx, u64 info, u64 status,
 			return err;
 	}
 
-	err = dcb_cb(fdma, dcb_idx, &fdma->last_dcb->nextptr);
+	err = dcb_cb(fdma, dcb_idx, &nextptr);
 	if (unlikely(err))
 		return err;
 
+	fdma->last_dcb->nextptr = cpu_to_le64(nextptr);
+
 	fdma->last_dcb = dcb;
 
-	dcb->nextptr = FDMA_DCB_INVALID_DATA;
-	dcb->info = info;
+	dcb->nextptr = cpu_to_le64(FDMA_DCB_INVALID_DATA);
+	dcb->info = cpu_to_le64(info);
 
 	return 0;
 }
drivers/net/ethernet/microchip/fdma/fdma_api.h +13 -7
index d91affe8bd988..a1bd7b8a75c16 100644
@@ -64,13 +64,13 @@
 struct fdma;
 
 struct fdma_db {
-	u64 dataptr;
-	u64 status;
+	__le64 dataptr;
+	__le64 status;
 };
 
 struct fdma_dcb {
-	u64 nextptr;
-	u64 info;
+	__le64 nextptr;
+	__le64 info;
 	struct fdma_db db[FDMA_DB_MAX];
 };
 
@@ -140,19 +140,25 @@ static inline bool fdma_dcb_is_reusable(struct fdma *fdma)
 /* Check if the FDMA has marked this DB as done. */
 static inline bool fdma_db_is_done(struct fdma_db *db)
 {
-	return db->status & FDMA_DCB_STATUS_DONE;
+	return le64_to_cpu(db->status) & FDMA_DCB_STATUS_DONE;
 }
 
 /* Get the length of a DB. */
 static inline int fdma_db_len_get(struct fdma_db *db)
 {
-	return FDMA_DCB_STATUS_BLOCKL(db->status);
+	return FDMA_DCB_STATUS_BLOCKL(le64_to_cpu(db->status));
+}
+
+/* Get the dataptr of a DB. */
+static inline u64 fdma_db_dataptr_get(struct fdma_db *db)
+{
+	return le64_to_cpu(db->dataptr);
 }
 
 /* Set the length of a DB. */
 static inline void fdma_dcb_len_set(struct fdma_dcb *dcb, u32 len)
 {
-	dcb->info = FDMA_DCB_INFO_DATAL(len);
+	dcb->info = cpu_to_le64(FDMA_DCB_INFO_DATAL(len));
 }
 
 /* Get a DB by index. */
drivers/net/ethernet/microchip/lan966x/lan966x_fdma.c +5 -4
index 4e9f347a1387c..e6638cf4f805b 100644
@@ -406,8 +406,9 @@ static int lan966x_fdma_rx_check_frame(struct lan966x_rx *rx, u64 *src_port)
 		return FDMA_ERROR;
 
 	dma_sync_single_for_cpu(lan966x->dev,
-				(dma_addr_t)db->dataptr + XDP_PACKET_HEADROOM,
-				FDMA_DCB_STATUS_BLOCKL(db->status),
+				(dma_addr_t)fdma_db_dataptr_get(db) +
+				XDP_PACKET_HEADROOM,
+				fdma_db_len_get(db),
 				DMA_FROM_DEVICE);
 
 	lan966x_ifh_get_src_port(page_address(page) + XDP_PACKET_HEADROOM,
@@ -419,7 +420,7 @@ static int lan966x_fdma_rx_check_frame(struct lan966x_rx *rx, u64 *src_port)
 	if (!lan966x_xdp_port_present(port))
 		return FDMA_PASS;
 
-	return lan966x_xdp_run(port, page, FDMA_DCB_STATUS_BLOCKL(db->status));
+	return lan966x_xdp_run(port, page, fdma_db_len_get(db));
 }
 
 static struct sk_buff *lan966x_fdma_rx_get_frame(struct lan966x_rx *rx,
@@ -443,7 +444,7 @@ static struct sk_buff *lan966x_fdma_rx_get_frame(struct lan966x_rx *rx,
 	skb_mark_for_recycle(skb);
 
 	skb_reserve(skb, XDP_PACKET_HEADROOM);
-	skb_put(skb, FDMA_DCB_STATUS_BLOCKL(db->status));
+	skb_put(skb, fdma_db_len_get(db));
 
 	lan966x_ifh_get_timestamp(skb->data, &timestamp);
 
Signature · 1 line
2.53.0
author maintainer
#1644 lore raw

PATCH 1614/1756 net: microchip: fdma: fix DCB corruption under sustained load

In reply to Greg Kroah-Hartman

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

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

From: Daniel Machon <[email protected]>

[ Upstream commit 573a6d4c7a21e34d7a2174b8d3c7ca67a5e850b6 ]

__fdma_dcb_add() prepares a DCB and links it into a channel's chain by writing its address to the NEXT_PTR of the current last DCB. The FDMA may be processing the chain while this happens.

Before this patch, the link is written before the new DCB's own nextptr and info fields, so the FDMA can follow it to a DCB that hasn't been fully prepared yet. Under sustained load this stalls the FDMA.

Prepare the new DCB fully before linking it, and update the previous DCB's NEXT_PTR using the two-step sequence from the datasheet (poison the LSB and flush, then clear it) so the FDMA never observes a partially-updated pointer.

Reported by a customer running iperf3 --bidir against a lan969x board.

Reproduced on lan969x with iperf3, throughput collapsing to zero:

  [  5]   1.00-2.00   sec  73.9 MBytes   620 Mbits/sec    0    305 KBytes
  [  5]   2.00-3.00   sec  73.9 MBytes   620 Mbits/sec    0    305 KBytes
  [  5]   3.00-4.00   sec  13.9 MBytes   116 Mbits/sec    2   1.41 KBytes
  [  5]   4.00-5.00   sec  0.00 Bytes  0.00 bits/sec    1   1.41 KBytes
  [  5]   5.00-6.00   sec  0.00 Bytes  0.00 bits/sec    0   1.41 KBytes
  [  5]   6.00-7.00   sec  0.00 Bytes  0.00 bits/sec    1   1.41 KBytes

The race is timing-dependent: across three reproductions the stall appeared anywhere from ~400s to ~3000s into the run.

---
 .../net/ethernet/microchip/fdma/fdma_api.c    | 30 ++++++++++++++++---
 1 file changed, 26 insertions(+), 4 deletions(-)
drivers/net/ethernet/microchip/fdma/fdma_api.c +26 -4
index 6dfe36f58d67a..a85dcb492829d 100644
@@ -43,9 +43,19 @@ int __fdma_dcb_add(struct fdma *fdma, int dcb_idx, u64 info, u64 status,
 				u64 *dataptr))
 {
 	struct fdma_dcb *dcb = fdma_dcb_get(fdma, dcb_idx);
+	struct fdma_dcb *prev = fdma->last_dcb;
 	u64 nextptr;
 	int i, err;
 
+	/* Per the FDMA datasheet, adding a DCB to an active channel takes
+	 * three steps:
+	 * 1) Write NEXT_PTR of the current last DCB with the LSB forced to
+	 *    FDMA_DCB_INVALID_DATA, and flush that write.
+	 * 2) Clear the LSB to complete the link.
+	 * 3) Reload the channel (FDMA_CH_RELOAD); this is done by the caller
+	 *    once the chain has been extended.
+	 */
+
 	for (i = 0; i < fdma->n_dbs; i++) {
 		err = __fdma_db_add(fdma, dcb_idx, i, status, db_cb);
 		if (unlikely(err))
@@ -56,13 +66,25 @@ int __fdma_dcb_add(struct fdma *fdma, int dcb_idx, u64 info, u64 status,
 	if (unlikely(err))
 		return err;
 
-	fdma->last_dcb->nextptr = cpu_to_le64(nextptr);
-
-	fdma->last_dcb = dcb;
-
 	dcb->nextptr = cpu_to_le64(FDMA_DCB_INVALID_DATA);
 	dcb->info = cpu_to_le64(info);
 
+	/* On the first DCB of fdma_dcbs_init() prev is the DCB itself;
+	 * don't link it to itself.
+	 */
+	if (prev != dcb) {
+		/* Write NEXT_PTR of the current last DCB with the LSB forced
+		 * to FDMA_DCB_INVALID_DATA, and flush that write.
+		 */
+		prev->nextptr = cpu_to_le64(nextptr | FDMA_DCB_INVALID_DATA);
+		dma_wmb();
+
+		/* Clear the LSB to complete the link. */
+		prev->nextptr = cpu_to_le64(nextptr);
+	}
+
+	fdma->last_dcb = dcb;
+
 	return 0;
 }
 EXPORT_SYMBOL_GPL(__fdma_dcb_add);
Signature · 1 line
2.53.0
author maintainer
#1645 lore raw

PATCH 1615/1756 devlink: region: fix snapshot id leak on kernel-allocated ids

In reply to Greg Kroah-Hartman

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

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

From: Fernando Fernandez Mancera <[email protected]>

[ Upstream commit ef8f0a1d888e0280452792f6d4edad237c934a51 ]

When DEVLINK_CMD_REGION_NEW is issued without a snapshot id, the kernel allocates one with __devlink_region_snapshot_id_get(). That helper counts the caller as a user of the id, and the caller must release this hold once it is done.

devlink_nl_region_new_doit() never drops it. The refcount of the id goes 1 (allocation) -> 2 (snapshot created) and stays at 2. When the snapshot is deleted the count only drops to 1, so the id is never erased from the snapshot_ids xarray. The id then stays in use for the lifetime of the devlink instance: requesting a snapshot with that explicit id fails with -EEXIST, and there is no snapshot left to delete to clean it up.

Reproducer steps:

  # devlink region new pci/0000:13:00.0/device-caps
  pci/0000:13:00.0/device-caps: snapshot 0
  # devlink region del pci/0000:13:00.0/device-caps snapshot 0
  # devlink region new pci/0000:13:00.0/device-caps snapshot 0
  kernel answers: File exists

Drop the caller's reference right after the snapshot has been created, as the snapshot then holds its own.

---
 net/devlink/region.c | 5 +++++
 1 file changed, 5 insertions(+)
net/devlink/region.c +5 -0
index 7319127c5913f..2bd000d878367 100644
@@ -721,6 +721,11 @@ int devlink_nl_region_new_doit(struct sk_buff *skb, struct genl_info *info)
 	if (!snapshot_id_attr) {
 		struct sk_buff *msg;
 
+		/* Drop the allocation reference, the snapshot
+		 * now holds its own.
+		 */
+		__devlink_snapshot_id_decrement(devlink, snapshot_id);
+
 		snapshot = devlink_region_snapshot_get_by_id(region,
 							     snapshot_id);
 		if (WARN_ON(!snapshot)) {
Signature · 1 line
2.53.0
author maintainer
#1646 lore raw

PATCH 1616/1756 net: lan966x: dont disable hardirqs in fdma tx clear path

In reply to Greg Kroah-Hartman

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

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

From: Daniel Machon <[email protected]>

[ Upstream commit b2e17432e7ee75997657f99862eb83be0c78a6c1 ]

lan966x_fdma_tx_clear_buf() runs from the NAPI poll and frees the buffers of completed tx DCBs with napi_consume_skb(), page_pool_recycle_direct() and xdp_return_frame_bulk(), under lan966x->tx_lock.

Before this patch, the lock is taken with spin_lock_irqsave(), so the buffers are freed with hardirqs disabled. RX skbs are marked for page_pool recycling, so when such an skb is forwarded back out and its tx completion frees it here, the free path reaches __page_pool_put_page(), which warns via lockdep_assert_no_hardirq().

Take tx_lock with a plain spin_lock(), as the other tx_lock users, lan966x_port_xmit() and lan966x_fdma_xmit_xdpf(), already do. tx_clear_buf() runs from the NAPI poll, so disabling hardirqs there is not needed.

Found with lockdep enabled (CONFIG_PROVE_LOCKING), which the assert depends on. Reproduced on a lan9668 board by redirecting received frames out of another port with tc mirred.

---
 drivers/net/ethernet/microchip/lan966x/lan966x_fdma.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
drivers/net/ethernet/microchip/lan966x/lan966x_fdma.c +2 -3
index e6638cf4f805b..11a341fc45779 100644
@@ -337,14 +337,13 @@ static void lan966x_fdma_tx_clear_buf(struct lan966x *lan966x, int weight)
 	struct lan966x_tx_dcb_buf *dcb_buf;
 	struct fdma *fdma = &tx->fdma;
 	struct xdp_frame_bulk bq;
-	unsigned long flags;
 	bool clear = false;
 	struct fdma_db *db;
 	int i;
 
 	xdp_frame_bulk_init(&bq);
 
-	spin_lock_irqsave(&lan966x->tx_lock, flags);
+	spin_lock(&lan966x->tx_lock);
 	for (i = 0; i < fdma->n_dcbs; ++i) {
 		dcb_buf = &tx->dcbs_buf[i];
 
@@ -389,7 +388,7 @@ static void lan966x_fdma_tx_clear_buf(struct lan966x *lan966x, int weight)
 	if (clear)
 		lan966x_fdma_wakeup_netdev(lan966x);
 
-	spin_unlock_irqrestore(&lan966x->tx_lock, flags);
+	spin_unlock(&lan966x->tx_lock);
 }
 
 static int lan966x_fdma_rx_check_frame(struct lan966x_rx *rx, u64 *src_port)
Signature · 1 line
2.53.0
author maintainer
#1647 lore raw

PATCH 1617/1756 net: dsa: mv88e6xxx: fix 6351 family statistics snapshot

In reply to Greg Kroah-Hartman

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

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

From: Florian Fainelli <[email protected]>

[ Upstream commit 9663edfa71e8807890203578dab6db60c6b548c4 ]

The 88E6171, 88E6175, 88E6350 and 88E6351 take the port number in the low bits of the statistics operation register. The 6320 snapshot helper instead encodes the port as (port + 1) << 5. On an EA4500 with an 88E6171, this causes ethtool -S to return physical port 0's MIB counters for every user port. Traffic on other ports does not update their reported hardware counters.

Before the snapshot operation was moved into the chip operations, only the 6320 and 6352 families used the shifted encoding. The refactoring incorrectly assigned that encoding to all four 6351 family chips.

Use the unshifted snapshot helper for the entire 6351 family. This matches the Marvell DSDT statsCapture() implementation, which uses the raw port number for chips outside DEV_RMON_PORT_BITS, including these four chips.

The original 88E6171 change was tested on an EA4500: pings through different switch ports updated only the corresponding port's hardware counters. The other three chips have not been hardware tested.

---
 drivers/net/dsa/mv88e6xxx/chip.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
drivers/net/dsa/mv88e6xxx/chip.c +4 -4
index 63d40a40ad0c1..29dc1ecb5eebd 100644
@@ -4613,7 +4613,7 @@ static const struct mv88e6xxx_ops mv88e6171_ops = {
 	.port_disable_pri_override = mv88e6xxx_port_disable_pri_override,
 	.port_get_cmode = mv88e6352_port_get_cmode,
 	.port_setup_message_port = mv88e6xxx_setup_message_port,
-	.stats_snapshot = mv88e6320_g1_stats_snapshot,
+	.stats_snapshot = mv88e6xxx_g1_stats_snapshot,
 	.stats_set_histogram = mv88e6095_g1_stats_set_histogram,
 	.stats_get_sset_count = mv88e6095_stats_get_sset_count,
 	.stats_get_strings = mv88e6095_stats_get_strings,
@@ -4715,7 +4715,7 @@ static const struct mv88e6xxx_ops mv88e6175_ops = {
 	.port_disable_pri_override = mv88e6xxx_port_disable_pri_override,
 	.port_get_cmode = mv88e6352_port_get_cmode,
 	.port_setup_message_port = mv88e6xxx_setup_message_port,
-	.stats_snapshot = mv88e6320_g1_stats_snapshot,
+	.stats_snapshot = mv88e6xxx_g1_stats_snapshot,
 	.stats_set_histogram = mv88e6095_g1_stats_set_histogram,
 	.stats_get_sset_count = mv88e6095_stats_get_sset_count,
 	.stats_get_strings = mv88e6095_stats_get_strings,
@@ -5375,7 +5375,7 @@ static const struct mv88e6xxx_ops mv88e6350_ops = {
 	.port_disable_pri_override = mv88e6xxx_port_disable_pri_override,
 	.port_get_cmode = mv88e6352_port_get_cmode,
 	.port_setup_message_port = mv88e6xxx_setup_message_port,
-	.stats_snapshot = mv88e6320_g1_stats_snapshot,
+	.stats_snapshot = mv88e6xxx_g1_stats_snapshot,
 	.stats_set_histogram = mv88e6095_g1_stats_set_histogram,
 	.stats_get_sset_count = mv88e6095_stats_get_sset_count,
 	.stats_get_strings = mv88e6095_stats_get_strings,
@@ -5421,7 +5421,7 @@ static const struct mv88e6xxx_ops mv88e6351_ops = {
 	.port_disable_pri_override = mv88e6xxx_port_disable_pri_override,
 	.port_get_cmode = mv88e6352_port_get_cmode,
 	.port_setup_message_port = mv88e6xxx_setup_message_port,
-	.stats_snapshot = mv88e6320_g1_stats_snapshot,
+	.stats_snapshot = mv88e6xxx_g1_stats_snapshot,
 	.stats_set_histogram = mv88e6095_g1_stats_set_histogram,
 	.stats_get_sset_count = mv88e6095_stats_get_sset_count,
 	.stats_get_strings = mv88e6095_stats_get_strings,
Signature · 1 line
2.53.0
author maintainer
#1648 lore raw

PATCH 1618/1756 usbnet: fix EVENT_RX_PAUSED race in usbnet_skb_return()

In reply to Greg Kroah-Hartman

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

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

From: Ömer Mete Kaya <[email protected]>

[ Upstream commit 67ae1b80cf73f592b35e4b5e5001a24d6d6c8637 ]

On SMP, usbnet_skb_return() can observe EVENT_RX_PAUSED as set on CPU0 while usbnet_resume_rx() clears the flag and drains rxq_pause on CPU1. The skb can then be queued after the drain has completed and remain stranded until the next MTU change or device stop.

Synchronize the EVENT_RX_PAUSED state transition and paused-queue dequeue operations with rxq_pause.lock. In usbnet_resume_rx() splice the paused queue into a local queue under the lock, then drain the local queue lock-free. In usbnet_skb_return() use a double-check pattern under rxq_pause.lock on the slow path, keeping the normal RX fast path lock-free. Use spin_lock_irqsave() to match the lockdep class shared with other sk_buff_head locks taken from hardirq context in defer_bh().

Discovered by Sashiko, not triggered, not tested on real hardware.

---
 drivers/net/usb/usbnet.c | 20 ++++++++++++++++----
 1 file changed, 16 insertions(+), 4 deletions(-)
drivers/net/usb/usbnet.c +16 -4
index 2ca0808398bf5..e50b5cd426980 100644
@@ -332,9 +332,14 @@ void usbnet_skb_return (struct usbnet *dev, struct sk_buff *skb)
 	unsigned long flags;
 	int	status;
 
-	if (test_bit(EVENT_RX_PAUSED, &dev->flags)) {
-		skb_queue_tail(&dev->rxq_pause, skb);
-		return;
+	if (unlikely(test_bit(EVENT_RX_PAUSED, &dev->flags))) {
+		spin_lock_irqsave(&dev->rxq_pause.lock, flags);
+		if (test_bit(EVENT_RX_PAUSED, &dev->flags)) {
+			__skb_queue_tail(&dev->rxq_pause, skb);
+			spin_unlock_irqrestore(&dev->rxq_pause.lock, flags);
+			return;
+		}
+		spin_unlock_irqrestore(&dev->rxq_pause.lock, flags);
 	}
 
 	/* only update if unset to allow minidriver rx_fixup override */
@@ -701,13 +706,20 @@ EXPORT_SYMBOL_GPL(usbnet_pause_rx);
 
 void usbnet_resume_rx(struct usbnet *dev)
 {
+	struct sk_buff_head q;
 	struct sk_buff *skb;
+	unsigned long flags;
 	int num = 0;
 
+	__skb_queue_head_init(&q);
+
 	local_bh_disable();
+	spin_lock_irqsave(&dev->rxq_pause.lock, flags);
 	clear_bit(EVENT_RX_PAUSED, &dev->flags);
+	skb_queue_splice_init(&dev->rxq_pause, &q);
+	spin_unlock_irqrestore(&dev->rxq_pause.lock, flags);
 
-	while ((skb = skb_dequeue(&dev->rxq_pause)) != NULL) {
+	while ((skb = __skb_dequeue(&q))) {
 		usbnet_skb_return(dev, skb);
 		num++;
 	}
Signature · 1 line
2.53.0
author maintainer
#1649 lore raw

PATCH 1619/1756 bpf: Fix out-of-bounds btf->types write for split BTF

In reply to Greg Kroah-Hartman

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

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

From: Feng Yang <[email protected]>

[ Upstream commit 6c476d2b73056ed151c3f8b884c627c75999ed7c ]

btf_add_type() stores the types of a BTF in btf->types[], which can hold at most BTF_MAX_TYPE entries. The types of a split BTF get IDs start_id .. start_id + nr_types - 1, so only BTF_MAX_TYPE - start_id of them fit, but neither the limit check nor the size used to grow the array accounts for
start_id: the check is an equality test against BTF_MAX_TYPE ('start_id + btf->types_size == BTF_MAX_TYPE') and the new size is clamped to BTF_MAX_TYPE.

The check therefore only fires if the array happens to grow to exactly BTF_MAX_TYPE - start_id entries. Otherwise, if the module has more than BTF_MAX_TYPE types, the array is filled up to BTF_MAX_TYPE entries. The next type that needs to be added reallocates the array to the same size, after which btf->types_size no longer equals btf->nr_types and the growth path is not taken anymore, so every following type is written past the end of the array:

  BUG: unable to handle page fault for address: ffffc90006200000
  RIP: 0010:btf_add_type+0x74/0x270
  Call Trace:
   btf_check_all_metas
   btf_parse_module

Bound both the array size and the limit check by BTF_MAX_TYPE - start_id. Base BTF (start_id == 0) is unaffected.

---
 kernel/bpf/btf.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
kernel/bpf/btf.c +4 -3
index 8956f2fd0c57d..e152b4d9113f8 100644
@@ -1600,15 +1600,16 @@ static int btf_add_type(struct btf_verifier_env *env, struct btf_type *t)
 		/* Expand 'types' array */
 
 		struct btf_type **new_types;
-		u32 expand_by, new_size;
+		u32 expand_by, new_size, max_size;
 
-		if (btf->start_id + btf->types_size == BTF_MAX_TYPE) {
+		if (btf->start_id + btf->types_size >= BTF_MAX_TYPE) {
 			btf_verifier_log(env, "Exceeded max num of types");
 			return -E2BIG;
 		}
 
+		max_size = BTF_MAX_TYPE - btf->start_id;
 		expand_by = max_t(u32, btf->types_size >> 2, 16);
-		new_size = min_t(u32, BTF_MAX_TYPE,
+		new_size = min_t(u32, max_size,
 				 btf->types_size + expand_by);
 
 		new_types = kvcalloc(new_size, sizeof(*new_types),
Signature · 1 line
2.53.0
author maintainer
#1650 lore raw

PATCH 1620/1756 net/mlx4: always create the eth and ib auxiliary devices

In reply to Greg Kroah-Hartman

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

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

From: Peter Morrow <[email protected]>

[ Upstream commit 557d80138618b9d17407733d4ec25b33d3971d60 ]

Since commit 7d22b1cb9d84 ("mlx4: Connect the infiniband part to the auxiliary bus"), mlx4_core creates the "ib" auxiliary device only for an IB port or a device that advertises IBoE. Before it, each mlx4 interface was offered every device and decided in its own add callback. mlx4_ib_add() accepted Ethernet ports without IBoE and registered them for raw packet QPs only.

ConnectX-3 VFs on Azure have an Ethernet port and no IBoE, so since v6.6 they get no RDMA device. DPDK's mlx4 PMD, which needs only raw packet QPs, then cannot open them:

net_mlx4: cannot access device, is mlx4_ib loaded?

Restore the old behaviour by creating both auxiliary devices for every device and letting mlx4_en and mlx4_ib decide in probe, as their add callbacks did. mlx4_ib_probe() returns -ENODEV when there are no usable ports, and mlx4_en_probe() binds a device without Ethernet ports but creates no netdevs, as mlx4_en_add() did.

Tested on 6.12.111 on an Azure VM with two ConnectX-3 VFs: each gets an eth and an ib auxiliary device, and DPDK attaches both VFs and passes traffic through them.

---
 drivers/net/ethernet/mellanox/mlx4/intf.c | 15 ++-------------
 1 file changed, 2 insertions(+), 13 deletions(-)
drivers/net/ethernet/mellanox/mlx4/intf.c +2 -13
index a371b970ac1e2..5bb6272968148 100644
@@ -43,23 +43,12 @@ static DEFINE_IDA(mlx4_adev_ida);
 
 static bool is_eth_supported(struct mlx4_dev *dev)
 {
-	for (int port = 1; port <= dev->caps.num_ports; port++)
-		if (dev->caps.port_type[port] == MLX4_PORT_TYPE_ETH)
-			return true;
-
-	return false;
+	return true;
 }
 
 static bool is_ib_supported(struct mlx4_dev *dev)
 {
-	for (int port = 1; port <= dev->caps.num_ports; port++)
-		if (dev->caps.port_type[port] == MLX4_PORT_TYPE_IB)
-			return true;
-
-	if (dev->caps.flags & MLX4_DEV_CAP_FLAG_IBOE)
-		return true;
-
-	return false;
+	return true;
 }
 
 static const struct mlx4_adev_device {
Signature · 1 line
2.53.0
author maintainer
#1651 lore raw

PATCH 1621/1756 nfp: flower: fix use-after-free in neighbour update work

In reply to Greg Kroah-Hartman

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

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

From: Sicong Huang <[email protected]>

[ Upstream commit 083aaafd453c3fb14411519d6ada9a8917573fdb ]

The netevent notifier handles neighbour updates and redirects by queuing nfp_tun_neigh_update() on system_highpri_wq. Each work item holds a reference to the neighbour, but only stores a pointer to the flower app.

During device removal, nfp_tunnel_config_stop() unregisters the notifier. This waits for notifier callbacks to return, but does not wait for the work they queued. The teardown then frees app->priv and app without waiting for these work items. Flushing cmsg_work in nfp_flower_clean() does not cover the neighbour update work.

A pending work item can therefore run after the app has been freed. Its call to nfp_flower_get_port_id_from_netdev() can then access freed memory while checking whether the neighbour's device can be offloaded. Even notifications for unrelated devices can reach this check. The same problem affects shutdown and probe error paths that tear down the app after the netevent notifier has been registered.

One possible interleaving is shown below. The neighbour belongs to another network device that remains registered.

CPU0 (remove) CPU1 (notifier / kworker)

                                  nfp_tun_neigh_event_handler()
                                    queue_work(system_highpri_wq, ...)
                                    return
                                  /* Work has not run yet. */
  nfp_tunnel_config_stop()
    unregister_netevent_notifier()
    /* Notifier callbacks have finished, but work may be pending. */
  nfp_flower_clean()
    vfree(app->priv)
    app->priv = NULL
  nfp_app_free()
    kfree(app)
                                  nfp_tun_neigh_update()
                                    app = update_work->app
                                    nfp_flower_get_port_id_from_netdev()
                                      app->priv  /* use-after-free */

The work items are allocated per event and free themselves, so they cannot be cancelled individually, and flushing system_highpri_wq is not allowed. Use a dedicated workqueue for neighbour updates instead. In nfp_tunnel_config_stop(), unregister the notifier and destroy the workqueue before cleaning up the tunnel state. This prevents new work from being queued and waits for pending and running work to finish while the app and its resources are still valid.

Found by code inspection.

Fixes 0ad722bd9ee3 ("nfp: flower: fix for take a mutex lock in soft irq context and rcu lock")
---
 .../net/ethernet/netronome/nfp/flower/main.h  |  2 ++
 .../netronome/nfp/flower/tunnel_conf.c        | 24 ++++++++++++++-----
 2 files changed, 20 insertions(+), 6 deletions(-)
drivers/net/ethernet/netronome/nfp/flower/main.h +2 -0
index 2b7c947ff4f2a..bd4399758ed4d 100644
@@ -94,6 +94,7 @@ struct nfp_fl_stats_id {
  * @ipv6_off_lock:	Lock for the IPv6 address list
  * @mac_off_ids:	IDA to manage id assignment for offloaded MACs
  * @neigh_nb:		Notifier to monitor neighbour state
+ * @neigh_wq:		Workqueue for neighbour updates
  */
 struct nfp_fl_tunnel_offloads {
 	struct rhashtable offloaded_macs;
@@ -103,6 +104,7 @@ struct nfp_fl_tunnel_offloads {
 	struct mutex ipv6_off_lock;
 	struct ida mac_off_ids;
 	struct notifier_block neigh_nb;
+	struct workqueue_struct *neigh_wq;
 };
 
 /**
drivers/net/ethernet/netronome/nfp/flower/tunnel_conf.c +18 -6
index 0d7d138d6e0d7..bc7f6d25eca5e 100644
@@ -742,7 +742,7 @@ nfp_tun_neigh_event_handler(struct notifier_block *nb, unsigned long event,
 	if (!update_work)
 		return NOTIFY_DONE;
 
-	queue_work(system_highpri_wq, &update_work->work);
+	queue_work(app_priv->tun.neigh_wq, &update_work->work);
 
 	return NOTIFY_DONE;
 }
@@ -1516,6 +1516,13 @@ int nfp_tunnel_config_start(struct nfp_app *app)
 	if (err)
 		return err;
 
+	priv->tun.neigh_wq = alloc_workqueue("nfp-flower-neigh",
+					     WQ_HIGHPRI | WQ_PERCPU, 0);
+	if (!priv->tun.neigh_wq) {
+		err = -ENOMEM;
+		goto err_free_macs;
+	}
+
 	ida_init(&priv->tun.mac_off_ids);
 
 	/* Initialise priv data for IPv4/v6 offloading. */
@@ -1528,13 +1535,17 @@ int nfp_tunnel_config_start(struct nfp_app *app)
 	priv->tun.neigh_nb.notifier_call = nfp_tun_neigh_event_handler;
 
 	err = register_netevent_notifier(&priv->tun.neigh_nb);
-	if (err) {
-		rhashtable_free_and_destroy(&priv->tun.offloaded_macs,
-					    nfp_check_rhashtable_empty, NULL);
-		return err;
-	}
+	if (err)
+		goto err_destroy_neigh_wq;
 
 	return 0;
+
+err_destroy_neigh_wq:
+	destroy_workqueue(priv->tun.neigh_wq);
+err_free_macs:
+	rhashtable_free_and_destroy(&priv->tun.offloaded_macs,
+				    nfp_check_rhashtable_empty, NULL);
+	return err;
 }
 
 void nfp_tunnel_config_stop(struct nfp_app *app)
@@ -1544,6 +1555,7 @@ void nfp_tunnel_config_stop(struct nfp_app *app)
 	struct list_head *ptr, *storage;
 
 	unregister_netevent_notifier(&priv->tun.neigh_nb);
+	destroy_workqueue(priv->tun.neigh_wq);
 
 	ida_destroy(&priv->tun.mac_off_ids);
 
Signature · 1 line
2.53.0
author maintainer
#1652 lore raw

PATCH 1622/1756 ASoC: xilinx: formatter_pcm: Fix read-modify-write of AUD_CTRL in hw_params

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit 3b54e739273752b370e49b09976da152fa3b802c ]

xlnx_formatter_pcm_hw_params() does a read-modify-write on XLNX_AUD_CTRL but only ORs in the new data width and active channel values without clearing the old ones. If hw_params is called more than once on an open stream, these fields may retain bits from the previous configuration, resulting in an incorrect sample width or channel count.

Clear both fields before writing the new values, and use FIELD_PREP() so the values cannot spill into neighbouring bits.

Fixes 6f6c3c36f091 ("ASoC: xlnx: add pcm formatter platform driver")
---
 sound/soc/xilinx/xlnx_formatter_pcm.c | 18 ++++++++++--------
 1 file changed, 10 insertions(+), 8 deletions(-)
sound/soc/xilinx/xlnx_formatter_pcm.c +10 -8
index 4d90e96a677c9..0f7cb911eb4e3 100644
@@ -6,6 +6,7 @@
 //
 // Author: Maruthi Srinivas Bayyavarapu <[email protected]>
 
+#include <linux/bitfield.h>
 #include <linux/clk.h>
 #include <linux/io.h>
 #include <linux/module.h>
@@ -57,8 +58,8 @@
 #define CFG_S2MM_XFER_SHIFT	29
 #define CFG_S2MM_PKG_MASK	BIT(28)
 
-#define AUD_CTRL_DATA_WIDTH_SHIFT	16
-#define AUD_CTRL_ACTIVE_CH_SHIFT	19
+#define AUD_CTRL_DATA_WIDTH_MASK	GENMASK(18, 16)
+#define AUD_CTRL_ACTIVE_CH_MASK		GENMASK(22, 19)
 #define PERIOD_CFG_PERIODS_SHIFT	16
 
 #define PERIODS_MIN		2
@@ -509,28 +510,29 @@ static int xlnx_formatter_pcm_hw_params(struct snd_soc_component *component,
 	writel(high, stream_data->mmio + XLNX_AUD_BUFF_ADDR_MSB);
 
 	val = readl(stream_data->mmio + XLNX_AUD_CTRL);
+	val &= ~(AUD_CTRL_DATA_WIDTH_MASK | AUD_CTRL_ACTIVE_CH_MASK);
 	bits_per_sample = params_width(params);
 	switch (bits_per_sample) {
 	case 8:
-		val |= (BIT_DEPTH_8 << AUD_CTRL_DATA_WIDTH_SHIFT);
+		val |= FIELD_PREP(AUD_CTRL_DATA_WIDTH_MASK, BIT_DEPTH_8);
 		break;
 	case 16:
-		val |= (BIT_DEPTH_16 << AUD_CTRL_DATA_WIDTH_SHIFT);
+		val |= FIELD_PREP(AUD_CTRL_DATA_WIDTH_MASK, BIT_DEPTH_16);
 		break;
 	case 20:
-		val |= (BIT_DEPTH_20 << AUD_CTRL_DATA_WIDTH_SHIFT);
+		val |= FIELD_PREP(AUD_CTRL_DATA_WIDTH_MASK, BIT_DEPTH_20);
 		break;
 	case 24:
-		val |= (BIT_DEPTH_24 << AUD_CTRL_DATA_WIDTH_SHIFT);
+		val |= FIELD_PREP(AUD_CTRL_DATA_WIDTH_MASK, BIT_DEPTH_24);
 		break;
 	case 32:
-		val |= (BIT_DEPTH_32 << AUD_CTRL_DATA_WIDTH_SHIFT);
+		val |= FIELD_PREP(AUD_CTRL_DATA_WIDTH_MASK, BIT_DEPTH_32);
 		break;
 	default:
 		return -EINVAL;
 	}
 
-	val |= active_ch << AUD_CTRL_ACTIVE_CH_SHIFT;
+	val |= FIELD_PREP(AUD_CTRL_ACTIVE_CH_MASK, active_ch);
 	writel(val, stream_data->mmio + XLNX_AUD_CTRL);
 
 	val = (params_periods(params) << PERIOD_CFG_PERIODS_SHIFT)
Signature · 1 line
2.53.0
author maintainer
#1653 lore raw

PATCH 1623/1756 nvmet: zns: reject a NUMD whose byte count wraps

In reply to Greg Kroah-Hartman

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

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

From: Andrea Parri <[email protected]>

[ Upstream commit 12740bec646dafe009a7d9a4d22d3495ef1ea5cd ]

Zone Management Receive computes its buffer size as (numd + 1) << 2 in u32, in nvmet_bdev_validate_zone_mgmt_recv(), nvmet_bdev_zone_zmgmt_recv_work() and nvmet_bdev_execute_zone_mgmt_recv(). NUMD is a 32-bit dword count, so any NUMD from 0x3fffffff up wraps.

The data length check in nvmet_bdev_execute_zone_mgmt_recv() sees the same wrapped value, so such a command can pass it. A data length that does not match the wrapped size is already rejected by that check, with Data SGL Length Invalid.

Every site agrees on the wrapped size, so the target zeroes and fills only that many bytes and nothing leaks, but it answers a command whose NUMD asks for 4 GiB or more.

Reject a NUMD from U32_MAX / 4 up with Invalid Field at the start of nvmet_bdev_execute_zone_mgmt_recv(), before this handler or its work item computes the byte count. A size_t computation would still wrap on 32-bit kernels, where nvmet_check_transfer_len() and req->transfer_len are 32 bits wide.

nvmet_io_cmd_transfer_len() in core.c, which the pci-epf transport uses to size its buffer, computes the same expression before this handler runs. Return 0 there for such a NUMD, so pci-epf allocates no buffer and the handler then rejects the command.

Tested over the loop, tcp, rdma and fc transports with a zoned null_blk namespace: a wrapping NUMD, sent with a data length that matches the wrapped size, was accepted before this patch and now fails with Invalid Field, while ordinary NUMD values still succeed. The core.c change only affects pci-epf and is build-tested only.

Fixes aaf2e048af27 ("nvmet: add ZBD over ZNS backend support")
---
 drivers/nvme/target/core.c |  3 +++
 drivers/nvme/target/zns.c  | 12 ++++++++++--
 2 files changed, 13 insertions(+), 2 deletions(-)
drivers/nvme/target/core.c +3 -0
index 849cd6a5b4219..e2ebc699ae6c4 100644
@@ -912,6 +912,9 @@ static u32 nvmet_io_cmd_transfer_len(struct nvmet_req *req)
 	case nvme_cmd_dsm:
 		return nvmet_dsm_len(req);
 	case nvme_cmd_zone_mgmt_recv:
+		/* The handler rejects a NUMD whose byte count would wrap. */
+		if (le32_to_cpu(req->cmd->zmr.numd) >= U32_MAX / 4)
+			return 0;
 		return (le32_to_cpu(req->cmd->zmr.numd) + 1) << 2;
 	default:
 		return 0;
drivers/nvme/target/zns.c +10 -2
index 497e75a292f75..0041791145476 100644
@@ -319,9 +319,17 @@ static void nvmet_bdev_zone_zmgmt_recv_work(struct work_struct *w)
 
 void nvmet_bdev_execute_zone_mgmt_recv(struct nvmet_req *req)
 {
-	u32 out_bufsize = (le32_to_cpu(req->cmd->zmr.numd) + 1) << 2;
+	u32 numd = le32_to_cpu(req->cmd->zmr.numd);
+
+	/* From U32_MAX / 4 up, (numd + 1) << 2 wraps here and in the work. */
+	if (numd >= U32_MAX / 4) {
+		req->error_loc = offsetof(struct nvme_zone_mgmt_recv_cmd, numd);
+		nvmet_req_complete(req,
+				   NVME_SC_INVALID_FIELD | NVME_STATUS_DNR);
+		return;
+	}
 
-	if (!nvmet_check_transfer_len(req, out_bufsize))
+	if (!nvmet_check_transfer_len(req, (numd + 1) << 2))
 		return;
 
 	INIT_WORK(&req->z.zmgmt_work, nvmet_bdev_zone_zmgmt_recv_work);
Signature · 1 line
2.53.0
author maintainer
#1654 lore raw

PATCH 1624/1756 nvmet: prevent double-free after metadata SGL allocation failure

In reply to Greg Kroah-Hartman

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

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

From: Avi Weiss <[email protected]>

[ Upstream commit 2f61b9d1d54edf75a352c43eebe3804144b5d44e ]

If metadata SGL allocation fails, nvmet_req_alloc_sgls() frees req->sg without clearing it. The RDMA error completion path later frees the same scatterlist again.

Use nvmet_req_free_sgls() instead so that the scatterlist pointers and counts are cleared before response cleanup.

Fixes c6e3f13398123 ("nvmet: add metadata support for block devices")
---
 drivers/nvme/target/core.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/nvme/target/core.c +1 -1
index e2ebc699ae6c4..c4a4af8a0547c 100644
@@ -1136,7 +1136,7 @@ int nvmet_req_alloc_sgls(struct nvmet_req *req)
 
 	return 0;
 out_free:
-	sgl_free(req->sg);
+	nvmet_req_free_sgls(req);
 out:
 	return -ENOMEM;
 }
Signature · 1 line
2.53.0
author maintainer
#1655 lore raw

PATCH 1625/1756 nvmet: protect nvmet_ports_list with nvmet_config_sem

In reply to Greg Kroah-Hartman

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

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

From: Qing Zhang <[email protected]>

[ Upstream commit cead6beb89256ae7145b65fbe8e8a5fedba4a47c ]

Readers of nvmet_ports_list (e.g. nvmet_subsys_disc_changed()) hold nvmet_config_sem and assert it via lockdep. The writers -- nvmet_ports_make() and nvmet_port_release() -- do not take the lock; they rely on the parent directory's VFS inode lock for serialization, which is an implementation detail of configfs and not a guaranteed contract. Align the writers with the lock the readers already require.

Also move list_add() in nvmet_ports_make() to after the port is fully
initialized: the old position published the port on the global list before INIT_LIST_HEAD(&port->subsystems), so a concurrent reader could traverse uninitialized list heads.

flush_workqueue() in nvmet_port_release() stays outside the semaphore to avoid a lock dependency on nvmet_wq.

Fixes b662a078576e ("nvmet: enable Discovery Controller AENs")
---
 drivers/nvme/target/configfs.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
drivers/nvme/target/configfs.c +6 -2
index 0e12f800beb3f..7b0c04a3faf62 100644
@@ -1921,7 +1921,9 @@ static void nvmet_port_release(struct config_item *item)
 
 	/* Let inflight controllers teardown complete */
 	flush_workqueue(nvmet_wq);
+	down_write(&nvmet_config_sem);
 	list_del(&port->global_entry);
+	up_write(&nvmet_config_sem);
 
 	key_put(port->keyring);
 	kfree(port->ana_state);
@@ -1989,8 +1991,6 @@ static struct config_group *nvmet_ports_make(struct config_group *group,
 			port->ana_state[i] = NVME_ANA_INACCESSIBLE;
 	}
 
-	list_add(&port->global_entry, &nvmet_ports_list);
-
 	INIT_LIST_HEAD(&port->entry);
 	INIT_LIST_HEAD(&port->subsystems);
 	INIT_LIST_HEAD(&port->referrals);
@@ -2022,6 +2022,10 @@ static struct config_group *nvmet_ports_make(struct config_group *group,
 	configfs_add_default_group(&port->ana_default_group.group,
 			&port->ana_groups_group);
 
+	down_write(&nvmet_config_sem);
+	list_add(&port->global_entry, &nvmet_ports_list);
+	up_write(&nvmet_config_sem);
+
 	return &port->group;
 }
 
Signature · 1 line
2.53.0
author maintainer
#1656 lore raw

PATCH 1626/1756 nvmet: use the enabled transport when disabling a port

In reply to Greg Kroah-Hartman

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

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

From: Rongzheng Wang <[email protected]>

[ Upstream commit 60385038754ed9fb05dab127b35f88c702252505 ]

nvmet_disable_port() looks up the transport from the current disc_addr.trtype, while nvmet_enable_port() records the transport in port->tr_ops. If trtype is changed while a port is being enabled, the port can be removed through a different transport, passing the private data of the original transport to the wrong ->remove_port().

The same mismatch is reachable with loop and RDMA: loop add_port() leaves port->priv NULL, and RDMA remove_port() dereferences it.

Use port->tr_ops for removal and serialize trtype changes with nvmet_config_sem in nvmet_addr_trtype_store(), so the transport that added the port is also the one that removes it.

---
 drivers/nvme/target/configfs.c | 16 ++++++++++++----
 drivers/nvme/target/core.c     |  8 +++++---
 2 files changed, 17 insertions(+), 7 deletions(-)
drivers/nvme/target/configfs.c +12 -4
index 7b0c04a3faf62..e6e359ae8b806 100644
@@ -358,10 +358,15 @@ static ssize_t nvmet_addr_trtype_store(struct config_item *item,
 		const char *page, size_t count)
 {
 	struct nvmet_port *port = to_nvmet_port(item);
+	ssize_t ret = count;
 	int i;
 
-	if (nvmet_is_port_enabled(port, __func__))
-		return -EACCES;
+	down_write(&nvmet_config_sem);
+
+	if (nvmet_is_port_enabled(port, __func__)) {
+		ret = -EACCES;
+		goto out;
+	}
 
 	for (i = 0; i < ARRAY_SIZE(nvmet_transport); i++) {
 		if (sysfs_streq(page, nvmet_transport[i].name))
@@ -369,7 +374,8 @@ static ssize_t nvmet_addr_trtype_store(struct config_item *item,
 	}
 
 	pr_err("Invalid value '%s' for trtype\n", page);
-	return -EINVAL;
+	ret = -EINVAL;
+	goto out;
 
 found:
 	memset(&port->disc_addr.tsas, 0, NVMF_TSAS_SIZE);
@@ -378,7 +384,9 @@ static ssize_t nvmet_addr_trtype_store(struct config_item *item,
 		nvmet_port_init_tsas_rdma(port);
 	else if (port->disc_addr.trtype == NVMF_TRTYPE_TCP)
 		nvmet_port_init_tsas_tcp(port, NVMF_TCP_SECTYPE_NONE);
-	return count;
+out:
+	up_write(&nvmet_config_sem);
+	return ret;
 }
 
 CONFIGFS_ATTR(nvmet_, addr_trtype);
drivers/nvme/target/core.c +5 -3
index c4a4af8a0547c..6fe67b3d708ec 100644
@@ -381,11 +381,13 @@ void nvmet_disable_port(struct nvmet_port *port)
 
 	lockdep_assert_held(&nvmet_config_sem);
 
-	port->enabled = false;
-	port->tr_ops = NULL;
+	if (!port->enabled)
+		return;
 
-	ops = nvmet_transports[port->disc_addr.trtype];
+	ops = port->tr_ops;
+	port->enabled = false;
 	ops->remove_port(port);
+	port->tr_ops = NULL;
 	module_put(ops->owner);
 }
 
Signature · 1 line
2.53.0
author maintainer
#1657 lore raw

PATCH 1627/1756 kdb: unify CMD_BUFLEN definition into kdb_private.h

In reply to Greg Kroah-Hartman

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

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

From: Naveen Kumar Chaudhary <[email protected]>

[ Upstream commit 2a052074582d976bfa81e41a0337d8ae6dd1dc65 ]

CMD_BUFLEN was defined separately in kdb_io.c (256) and kdb_main.c (200), causing kdb_main.c to use the wrong size when formatting the prompt string into kdb_prompt_str (which is 256 bytes).

Move CMD_BUFLEN (256) into kdb_private.h so all users share a single consistent definition, and remove the local definitions from both files.

---
 kernel/debug/kdb/kdb_io.c      | 1 -
 kernel/debug/kdb/kdb_main.c    | 6 ++----
 kernel/debug/kdb/kdb_private.h | 3 ++-
 3 files changed, 4 insertions(+), 6 deletions(-)
kernel/debug/kdb/kdb_io.c +0 -1
index 6a77f1c779c4c..a84517f48cd68 100644
@@ -25,7 +25,6 @@
 #include <linux/kallsyms.h>
 #include "kdb_private.h"
 
-#define CMD_BUFLEN 256
 char kdb_prompt_str[CMD_BUFLEN];
 
 int kdb_trap_printk;
kernel/debug/kdb/kdb_main.c +2 -4
index f5f7d7fb5936f..c4dbbd2d04ef6 100644
@@ -854,8 +854,6 @@ static int kdb_exec_defcmd(int argc, const char **argv)
 
 /* Command history */
 #define KDB_CMD_HISTORY_COUNT	32
-#define CMD_BUFLEN		200	/* kdb_printf: max printline
-					 * size == 256 */
 static unsigned int cmd_head, cmd_tail;
 static unsigned int cmdptr;
 static char cmd_hist[KDB_CMD_HISTORY_COUNT][CMD_BUFLEN];
@@ -1336,8 +1334,8 @@ static int kdb_local(kdb_reason_t reason, int error, struct pt_regs *regs,
 
 do_full_getstr:
 		/* PROMPT can only be set if we have MEM_READ permission. */
-		snprintf(kdb_prompt_str, CMD_BUFLEN, kdbgetenv("PROMPT"),
-			 raw_smp_processor_id());
+		snprintf(kdb_prompt_str, CMD_BUFLEN,
+			 kdbgetenv("PROMPT"), raw_smp_processor_id());
 
 		/*
 		 * Fetch command from keyboard
kernel/debug/kdb/kdb_private.h +2 -1
index d2520d72b1f56..483ebb9a62cdd 100644
@@ -223,7 +223,8 @@ extern void kdb_kbd_cleanup_state(void);
 #define kdb_kbd_cleanup_state()
 #endif /* ! CONFIG_KDB_KEYBOARD */
 
-extern char kdb_prompt_str[];
+#define CMD_BUFLEN 256
+extern char kdb_prompt_str[CMD_BUFLEN];
 
 #define	KDB_WORD_SIZE	((int)sizeof(unsigned long))
 
Signature · 1 line
2.53.0
author maintainer
#1658 lore raw

PATCH 1628/1756 nvmet: ignore discard return value

In reply to Greg Kroah-Hartman

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

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

From: Chaitanya Kulkarni <[email protected]>

[ Upstream commit 38d12f15c4772b5383b1249b2afb0d206a430f0f ]

__blkdev_issue_discard() always returns 0, making the error checking in nvmet_bdev_discard_range() dead code.

Kill the function nvmet_bdev_discard_range() and call __blkdev_issue_discard() directly from nvmet_bdev_execute_discard(), since no error handling is needed anymore for __blkdev_issue_discard() call.

Stable-dep-of: 424bd0e98ca4 ("nvmet: don't truncate the length of big discards")

---
 drivers/nvme/target/io-cmd-bdev.c | 28 +++++++---------------------
 1 file changed, 7 insertions(+), 21 deletions(-)
drivers/nvme/target/io-cmd-bdev.c +7 -21
index 3b081f421c81d..fea45ce033d3e 100644
@@ -357,29 +357,14 @@ u16 nvmet_bdev_flush(struct nvmet_req *req)
 	return 0;
 }
 
-static u16 nvmet_bdev_discard_range(struct nvmet_req *req,
-		struct nvme_dsm_range *range, struct bio **bio)
-{
-	struct nvmet_ns *ns = req->ns;
-	int ret;
-
-	ret = __blkdev_issue_discard(ns->bdev,
-			nvmet_lba_to_sect(ns, range->slba),
-			le32_to_cpu(range->nlb) << (ns->blksize_shift - 9),
-			GFP_KERNEL, bio);
-	if (ret && ret != -EOPNOTSUPP) {
-		req->error_slba = le64_to_cpu(range->slba);
-		return errno_to_nvme_status(req, ret);
-	}
-	return NVME_SC_SUCCESS;
-}
-
 static void nvmet_bdev_execute_discard(struct nvmet_req *req)
 {
+	struct nvmet_ns *ns = req->ns;
 	struct nvme_dsm_range range;
 	struct bio *bio = NULL;
+	sector_t nr_sects;
 	int i;
-	u16 status;
+	u16 status = NVME_SC_SUCCESS;
 
 	for (i = 0; i <= le32_to_cpu(req->cmd->dsm.nr); i++) {
 		status = nvmet_copy_from_sgl(req, i * sizeof(range), &range,
@@ -387,9 +372,10 @@ static void nvmet_bdev_execute_discard(struct nvmet_req *req)
 		if (status)
 			break;
 
-		status = nvmet_bdev_discard_range(req, &range, &bio);
-		if (status)
-			break;
+		nr_sects = le32_to_cpu(range.nlb) << (ns->blksize_shift - 9);
+		__blkdev_issue_discard(ns->bdev,
+				nvmet_lba_to_sect(ns, range.slba), nr_sects,
+				GFP_KERNEL, &bio);
 	}
 
 	if (bio) {
Signature · 1 line
2.53.0
author maintainer
#1659 lore raw

PATCH 1629/1756 nvmet: dont truncate the length of big discards

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 424bd0e98ca4f227d424c3543166a9982ca45819 ]

nvmet_bdev_execute_discard() shifts the 32-bit nlb of a DSM range into sectors before widening it to sector_t, so on a 4k namespace the top bits are lost. A 3 TiB range discards 1 TiB, a 2 TiB range discards nothing, and both complete with success. The target announces no DMRSL, and hosts other than Linux (and nvme dsm passthrough) do send ranges that big.

Widen before the shift.

Fixes a07b4970f464 ("nvmet: add a generic NVMe target")
Cc Christoph Hellwig <[email protected]>
Cc Sagi Grimberg <[email protected]>
Cc Chaitanya Kulkarni <[email protected]>
---
 drivers/nvme/target/io-cmd-bdev.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/nvme/target/io-cmd-bdev.c +2 -1
index fea45ce033d3e..0ccc7d69655bd 100644
@@ -372,7 +372,8 @@ static void nvmet_bdev_execute_discard(struct nvmet_req *req)
 		if (status)
 			break;
 
-		nr_sects = le32_to_cpu(range.nlb) << (ns->blksize_shift - 9);
+		nr_sects = (sector_t)le32_to_cpu(range.nlb) <<
+			   (ns->blksize_shift - 9);
 		__blkdev_issue_discard(ns->bdev,
 				nvmet_lba_to_sect(ns, range.slba), nr_sects,
 				GFP_KERNEL, &bio);
Signature · 1 line
2.53.0
author maintainer
#1660 lore raw

PATCH 1630/1756 nvmet-auth: take only AUTH_Negotiate for a negotiation

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 7dd1d31e2e3124f331056d68af9a48c501b37e02 ]

nvmet_execute_auth_send() hands a common-type message to nvmet_auth_negotiate() if its ID is AUTH_Negotiate or matches the step the queue is in. The second case is wrong: the only other common-type message a host sends is AUTH_Failure2, and no queue waits in that step. A host can name the step on purpose though, and its message is then treated as a new AUTH_Negotiate without the work that goes with a new transaction, like reloading the keys on the admin queue.

Fail every other common-type message, as AUTH_Failure2 already is.

Fixes db1312dd9548 ("nvmet: implement basic In-Band Authentication")
Cc Hannes Reinecke <[email protected]>
Cc Christoph Hellwig <[email protected]>
Cc Sagi Grimberg <[email protected]>
Cc Chaitanya Kulkarni <[email protected]>
---
 drivers/nvme/target/fabrics-cmd-auth.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/nvme/target/fabrics-cmd-auth.c +2 -1
index 0569f0e120c75..fbf445ddb077a 100644
@@ -299,8 +299,9 @@ void nvmet_execute_auth_send(struct nvmet_req *req)
 			}
 			req->sq->dhchap_step =
 				NVME_AUTH_DHCHAP_MESSAGE_NEGOTIATE;
-		} else if (data->auth_id != req->sq->dhchap_step)
+		} else {
 			goto done_failure1;
+		}
 		/* Validate negotiation parameters */
 		dhchap_status = nvmet_auth_negotiate(req, d, tl);
 		if (dhchap_status == 0)
Signature · 1 line
2.53.0
author maintainer
#1661 lore raw

PATCH 1631/1756 nvmet-tcp: stop listening when a port is removed

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit ece0f4e67f08792c8572080fb0fcc231554f08ca ]

nvmet_tcp_accept_work() accepts until there's nothing left. A connection that is already dead when accepted is torn down right there, which takes a few ms, and more can arrive meanwhile. nvmet_tcp_remove_port() waits for the work with cancel_work_sync(), so someone opening and closing connections in a loop keeps the removal from finishing. It holds nvmet_config_sem for writing, so nothing can be configured and no port answers a Connect until the flood stops. No secret needed, just an admin removing the port at the wrong time.

Shut the listening socket down first. Pending connections are dropped, as they were on release, and the next kernel_accept() fails and ends the work.

Fixes 872d26a391da ("nvmet-tcp: add NVMe over TCP target driver")
Cc Christoph Hellwig <[email protected]>
Cc Sagi Grimberg <[email protected]>
Cc Chaitanya Kulkarni <[email protected]>
---
 drivers/nvme/target/tcp.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/nvme/target/tcp.c +2 -0
index fcb1a3dbff011..3c38646d97e44 100644
@@ -2208,6 +2208,8 @@ static void nvmet_tcp_remove_port(struct nvmet_port *nport)
 	port->sock->sk->sk_data_ready = port->data_ready;
 	port->sock->sk->sk_user_data = NULL;
 	write_unlock_bh(&port->sock->sk->sk_callback_lock);
+	/* The accept work goes on for as long as there is something to accept */
+	kernel_sock_shutdown(port->sock, SHUT_RDWR);
 	cancel_work_sync(&port->accept_work);
 	/*
 	 * Destroy the remaining queues, which are not belong to any
Signature · 1 line
2.53.0
author maintainer
#1662 lore raw

PATCH 1632/1756 nvmet: fix NULL dereference in debugfs host_traddr

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 81ce4d9bbe8cf47d4b023e932ee29b22367545e6 ]

The host_traddr callbacks of tcp, rdma and fc take the host address from the transport queue around ctrl->sqs[0], which nvmet_sq_destroy() clears when the admin queue goes away while the controller lives on with its I/O queues. A host that closes the admin connection and keeps an I/O queue leaves such a controller behind, and reading its host_traddr in debugfs dereferences a near-NULL pointer:

  BUG: kernel NULL pointer dereference, address: 00000000000002e0
  RIP: 0010:nvmet_tcp_host_port_addr+0x19/0x50 [nvmet_tcp]

Don't ask the transport if there's no admin queue. Nothing holds the queue for debugfs, so a reader that's past the check when the queue goes away is still on its own.

Fixes 7e5c3de3f2f2 ("nvmet: add 'host_traddr' callback for debugfs")
Cc Christoph Hellwig <[email protected]>
Cc Sagi Grimberg <[email protected]>
Cc Chaitanya Kulkarni <[email protected]>
---
 drivers/nvme/target/core.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/nvme/target/core.c +3 -0
index 6fe67b3d708ec..3b90a88e1207b 100644
@@ -1597,6 +1597,9 @@ ssize_t nvmet_ctrl_host_traddr(struct nvmet_ctrl *ctrl,
 {
 	if (!ctrl->ops->host_traddr)
 		return -EOPNOTSUPP;
+	/* They all take the address from the admin queue */
+	if (!ctrl->sqs[0])
+		return -ENOTCONN;
 	return ctrl->ops->host_traddr(ctrl, traddr, traddr_len);
 }
 
Signature · 1 line
2.53.0
author maintainer
#1663 lore raw

PATCH 1633/1756 nvmet-tcp: dont read a removed port at Connect time

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 3f98ce65a87979e881343dcf082c9595ec90ddc7 ]

nvmet_tcp_alloc_cmd() takes the nvmet port of a command from queue->port, and the commands of a queue are allocated from the io work when the Connect arrives. nvmet_tcp_remove_port() shuts down the queues that have no controller yet and frees the port without waiting for them, they're released later from a work. An io work handling a Connect at that moment reads the freed port for every command of the queue and hands the result to the core.

Note the nvmet port in the queue at allocation. It outlives the transport port.

Fixes 872d26a391da ("nvmet-tcp: add NVMe over TCP target driver")
Cc Christoph Hellwig <[email protected]>
Cc Sagi Grimberg <[email protected]>
Cc Chaitanya Kulkarni <[email protected]>
---
 drivers/nvme/target/tcp.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/nvme/target/tcp.c +4 -1
index 3c38646d97e44..afcc55d5af661 100644
@@ -150,6 +150,7 @@ enum nvmet_tcp_queue_state {
 struct nvmet_tcp_queue {
 	struct socket		*sock;
 	struct nvmet_tcp_port	*port;
+	struct nvmet_port	*nport;
 	struct work_struct	io_work;
 	struct nvmet_cq		nvme_cq;
 	struct nvmet_sq		nvme_sq;
@@ -1557,7 +1558,7 @@ static int nvmet_tcp_alloc_cmd(struct nvmet_tcp_queue *queue,
 	u8 hdgst = nvmet_tcp_hdgst_len(queue);
 
 	c->queue = queue;
-	c->req.port = queue->port->nport;
+	c->req.port = queue->nport;
 
 	c->cmd_pdu = page_frag_alloc(&queue->pf_cache,
 			sizeof(*c->cmd_pdu) + hdgst, GFP_KERNEL | __GFP_ZERO);
@@ -1988,6 +1989,8 @@ static void nvmet_tcp_alloc_queue(struct nvmet_tcp_port *port,
 	kref_init(&queue->kref);
 	queue->sock = newsock;
 	queue->port = port;
+	/* The port may be gone when the commands are allocated */
+	queue->nport = port->nport;
 	queue->nr_cmds = 0;
 	spin_lock_init(&queue->state_lock);
 	if (queue->port->nport->disc_addr.tsas.tcp.sectype ==
Signature · 1 line
2.53.0
author maintainer
#1664 lore raw

PATCH 1634/1756 nvme-loop: dont BUG() if a scan runs beside a reset

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 64e21d782020e267ca57765a30216c38b34f296d ]

A reset sets queue_count to 1 while it destroys the I/O queues and counts it back up when the new ones are made, and it doesn't stop the scan work. A new namespace found in that window trips the check in nvme_loop_init_hctx() for every hctx but the first:

kernel BUG at drivers/nvme/target/loop.c:224!

   nvme_loop_init_hctx+0x7d/0x80
   __blk_mq_realloc_hw_ctxs+0x3af/0xa80
   nvme_alloc_ns+0x1a2/0x22f0

The check protects nothing. ctrl->queues has nr_io_queues + 1 entries for the life of the controller, the tag set never has more hardware queues than that, and nvme_loop_queue_rq() rejects requests until the controller is live again.

Remove it.

Fixes 3a85a5de29ea ("nvme-loop: add a NVMe loopback host driver")
Cc Christoph Hellwig <[email protected]>
Cc Sagi Grimberg <[email protected]>
Cc Chaitanya Kulkarni <[email protected]>
---
 drivers/nvme/target/loop.c | 2 --
 1 file changed, 2 deletions(-)
drivers/nvme/target/loop.c +0 -2
index a9d112d34d4f4..8bb3e01d9ba00 100644
@@ -221,8 +221,6 @@ static int nvme_loop_init_hctx(struct blk_mq_hw_ctx *hctx, void *data,
 	struct nvme_loop_ctrl *ctrl = to_loop_ctrl(data);
 	struct nvme_loop_queue *queue = &ctrl->queues[hctx_idx + 1];
 
-	BUG_ON(hctx_idx >= ctrl->ctrl.queue_count);
-
 	/*
 	 * flush_end_io() can be called recursively for us, so use our own
 	 * lock class key for avoiding lockdep possible recursive locking,
Signature · 1 line
2.53.0
author maintainer
#1665 lore raw

PATCH 1635/1756 nvmet-rdma: flush nvmet-wq on module exit

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

[ Upstream commit 2b646788ee24d895b8862514e12a95ce5d72d6cc ]

nvmet_rdma_exit() relies on ib_unregister_client() to flush nvmet-wq through nvmet_rdma_remove_one(), but since commit a3dd7d0022c3 that returns at once for a device no longer on device_list. The release work of the last queue takes the device off the list in nvmet_rdma_free_dev() and still has to drop the mutex, free the struct and return through nvmet_rdma_release_queue_work(), so an rmmod in that window frees the module code it's running.

Flush nvmet-wq after ib_unregister_client(). No release work can be queued after that point.

Fixes a3dd7d0022c3 ("nvmet-rdma: Don't flush system_wq by default during remove_one")
Cc Christoph Hellwig <[email protected]>
Cc Sagi Grimberg <[email protected]>
Cc Chaitanya Kulkarni <[email protected]>
---
 drivers/nvme/target/rdma.c | 6 ++++++
 1 file changed, 6 insertions(+)
drivers/nvme/target/rdma.c +6 -0
index 290b51fef0b98..4c16cc9aaaa00 100644
@@ -2146,6 +2146,12 @@ static void __exit nvmet_rdma_exit(void)
 {
 	nvmet_unregister_transport(&nvmet_rdma_ops);
 	ib_unregister_client(&nvmet_rdma_ib_client);
+	/*
+	 * nvmet_rdma_remove_one() does not flush for a device that has left
+	 * device_list, and the release work that took it off still has to
+	 * return from nvmet_rdma_free_dev().
+	 */
+	flush_workqueue(nvmet_wq);
 	WARN_ON_ONCE(!list_empty(&nvmet_rdma_queue_list));
 	ida_destroy(&nvmet_rdma_queue_ida);
 }
Signature · 1 line
2.53.0
author maintainer
#1666 lore raw

PATCH 1636/1756 nvmet-rdma: disable interrupts under rsp_wr_wait_lock

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

[ Upstream commit 14e4e09443ac2b5cd90c1e313ee3c0bdd4928e0d ]

rsp_wr_wait_lock protects the list of commands waiting for room in the send queue, and it's taken with plain spin_lock(). But nvmet_rdma_queue_response() calls nvmet_rdma_release_rsp() directly if ib_post_send() fails, and that processes the wait list. The call chain starts in nvmet_req_complete(), which for a block device namespace runs from the bio end_io callback, which can be in hard interrupt context. An interrupt that completes a command on a CPU holding the lock for the same queue spins forever. Lockdep over siw with a null_blk namespace:

inconsistent {HARDIRQ-ON-W} -> {IN-HARDIRQ-W} usage

Use spin_lock_irqsave() for both takers. The processing loop still drops the lock, and restores the caller's interrupt state, around nvmet_rdma_execute_command().

Fixes 8f000cac6e7a ("nvmet-rdma: add a NVMe over Fabrics RDMA target driver")
Cc Christoph Hellwig <[email protected]>
Cc Sagi Grimberg <[email protected]>
Cc Chaitanya Kulkarni <[email protected]>
---
 drivers/nvme/target/rdma.c | 15 +++++++++------
 1 file changed, 9 insertions(+), 6 deletions(-)
drivers/nvme/target/rdma.c +9 -6
index 4c16cc9aaaa00..9a336cee93a4f 100644
@@ -513,7 +513,9 @@ static int nvmet_rdma_post_recv(struct nvmet_rdma_device *ndev,
 
 static void nvmet_rdma_process_wr_wait_list(struct nvmet_rdma_queue *queue)
 {
-	spin_lock(&queue->rsp_wr_wait_lock);
+	unsigned long flags;
+
+	spin_lock_irqsave(&queue->rsp_wr_wait_lock, flags);
 	while (!list_empty(&queue->rsp_wr_wait_list)) {
 		struct nvmet_rdma_rsp *rsp;
 		bool ret;
@@ -522,16 +524,16 @@ static void nvmet_rdma_process_wr_wait_list(struct nvmet_rdma_queue *queue)
 				struct nvmet_rdma_rsp, wait_list);
 		list_del(&rsp->wait_list);
 
-		spin_unlock(&queue->rsp_wr_wait_lock);
+		spin_unlock_irqrestore(&queue->rsp_wr_wait_lock, flags);
 		ret = nvmet_rdma_execute_command(rsp);
-		spin_lock(&queue->rsp_wr_wait_lock);
+		spin_lock_irqsave(&queue->rsp_wr_wait_lock, flags);
 
 		if (!ret) {
 			list_add(&rsp->wait_list, &queue->rsp_wr_wait_list);
 			break;
 		}
 	}
-	spin_unlock(&queue->rsp_wr_wait_lock);
+	spin_unlock_irqrestore(&queue->rsp_wr_wait_lock, flags);
 }
 
 static u16 nvmet_rdma_check_pi_status(struct ib_mr *sig_mr)
@@ -977,6 +979,7 @@ static bool nvmet_rdma_execute_command(struct nvmet_rdma_rsp *rsp)
 static void nvmet_rdma_handle_command(struct nvmet_rdma_queue *queue,
 		struct nvmet_rdma_rsp *cmd)
 {
+	unsigned long flags;
 	u16 status;
 
 	ib_dma_sync_single_for_cpu(queue->dev->device,
@@ -995,9 +998,9 @@ static void nvmet_rdma_handle_command(struct nvmet_rdma_queue *queue,
 		goto out_err;
 
 	if (unlikely(!nvmet_rdma_execute_command(cmd))) {
-		spin_lock(&queue->rsp_wr_wait_lock);
+		spin_lock_irqsave(&queue->rsp_wr_wait_lock, flags);
 		list_add_tail(&cmd->wait_list, &queue->rsp_wr_wait_list);
-		spin_unlock(&queue->rsp_wr_wait_lock);
+		spin_unlock_irqrestore(&queue->rsp_wr_wait_lock, flags);
 	}
 
 	return;
Signature · 1 line
2.53.0
author maintainer
#1667 lore raw

PATCH 1637/1756 nvmet-rdma: fix double puts after a failed RDMA WRITE

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

[ Upstream commit f1dac2a2e75260d1466d9f03ccf0944d6d0449a4 ]

For a read with T10-PI the RDMA WRITE is posted alone and nvmet_rdma_write_data_done() posts the SEND once the metadata check result is known. By then the request has been completed and its references put: __nvmet_req_complete() put ns->ref and the pc_ref, and nvmet_req_complete() sq->ref, right after queuing the response. The error branch of nvmet_rdma_write_data_done() copies the one from nvmet_rdma_read_data_done() and calls nvmet_req_uninit(), which puts all three again. A WRITE fails whenever the connection ends with reads in flight, which is up to the host. Depending on timing the sq->ref count goes to zero early and the queue is freed under the remaining completions, or never reaches zero and nvmet_sq_destroy() sleeps forever, or percpu_ref_put() dereferences NULL after percpu_ref_exit(). ns->ref stays too low for good, so disabling the namespace hangs too. Reproduced with KASAN over rxe with a test patch forcing the PI path.

Drop the nvmet_req_uninit(). The branch still releases the RDMA context and the response, which is all the request owns at that point.

Fixes b09160c3996c ("nvmet-rdma: add metadata/T10-PI support")
Cc Christoph Hellwig <[email protected]>
Cc Sagi Grimberg <[email protected]>
Cc Chaitanya Kulkarni <[email protected]>
---
 drivers/nvme/target/rdma.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/nvme/target/rdma.c +4 -1
index 9a336cee93a4f..7e715d0436f8b 100644
@@ -803,7 +803,10 @@ static void nvmet_rdma_write_data_done(struct ib_cq *cq, struct ib_wc *wc)
 
 	if (unlikely(wc->status != IB_WC_SUCCESS)) {
 		nvmet_rdma_rw_ctx_destroy(rsp);
-		nvmet_req_uninit(&rsp->req);
+		/*
+		 * Unlike in nvmet_rdma_read_data_done(), the request has been
+		 * completed and its references are put: no nvmet_req_uninit().
+		 */
 		nvmet_rdma_release_rsp(rsp);
 		if (wc->status != IB_WC_WR_FLUSH_ERR) {
 			pr_info("RDMA WRITE for CQE failed with status %s (%d).\n",
Signature · 1 line
2.53.0
author maintainer
#1668 lore raw

PATCH 1638/1756 nvmet: dont clear sq->ctrl for a Connect with sqsize 0

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

[ Upstream commit 89480d137bf0d943a82c64f86ae2407a15276b5e ]

nvmet_install_queue() checks sqsize first and jumps to err on zero, where sq->ctrl is set to NULL. Since commit b71df12605ca the cmpxchg() that sets sq->ctrl comes after the checks, so err now undoes a bind that this call never made. Over RDMA a host can send two Connects together and the second is parsed before the first executes, so a second Connect with sqsize 0 clears the sq->ctrl the first one set. The reference it held is never dropped and the controller leaks, with its cntlid, until reboot. The discovery subsystem lets any host do that, 20 connections leak around 10 controllers. A pending AER on such a queue hangs nvmet_sq_destroy() forever, and a queue can keep its "authenticated" mark across a rebind.

Return the status directly, as the two checks after it do, so err is only reached after this call's cmpxchg() succeeded.

Fixes b71df12605ca ("nvmet: avoid duplicate qid in connect cmd")
Cc Christoph Hellwig <[email protected]>
Cc Sagi Grimberg <[email protected]>
Cc Chaitanya Kulkarni <[email protected]>
---
 drivers/nvme/target/fabrics-cmd.c | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
drivers/nvme/target/fabrics-cmd.c +1 -2
index 66d0dbf7ac733..9fcd4158c2663 100644
@@ -179,8 +179,7 @@ static u16 nvmet_install_queue(struct nvmet_ctrl *ctrl, struct nvmet_req *req)
 		pr_warn("queue size zero!\n");
 		req->error_loc = offsetof(struct nvmf_connect_command, sqsize);
 		req->cqe->result.u32 = IPO_IATTR_CONNECT_SQE(sqsize);
-		ret = NVME_SC_CONNECT_INVALID_PARAM | NVME_STATUS_DNR;
-		goto err;
+		return NVME_SC_CONNECT_INVALID_PARAM | NVME_STATUS_DNR;
 	}
 
 	if (ctrl->sqs[qid] != NULL) {
Signature · 1 line
2.53.0
author maintainer
#1669 lore raw

PATCH 1639/1756 blk-throttle: dont truncate the cgroup v1 iops limits

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 7d96874ba80ba7a2ab578ea9139c2af79c353b88 ]

tg_set_conf() parses the limit into a u64 and stores the iops ones through an unsigned int, so anything above UINT_MAX is truncated and a multiple of 2^32 becomes a limit of 0. The next IO of the group then divides by it in tg_within_iops_limit().

Clamp to UINT_MAX, which means no limit, like tg_set_limit() does on the default hierarchy.

Fixes af133ceb2610 ("blkcg: move blkio_group_conf->iops and ->bps to blk-throttle")
Cc Tejun Heo <[email protected]>
---
 block/blk-throttle.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
block/blk-throttle.c +2 -1
index 7a29eeb7b6957..c15dfb3100ee9 100644
@@ -1282,7 +1282,8 @@ static ssize_t tg_set_conf(struct kernfs_open_file *of,
 	if (is_u64)
 		*(u64 *)((void *)tg + of_cft(of)->private) = v;
 	else
-		*(unsigned int *)((void *)tg + of_cft(of)->private) = v;
+		*(unsigned int *)((void *)tg + of_cft(of)->private) =
+			min_t(u64, v, UINT_MAX);
 
 	tg_conf_updated(tg, false);
 	ret = 0;
Signature · 1 line
2.53.0
author maintainer
#1670 lore raw

PATCH 1640/1756 blk-cgroup: fix root io.stat byte counts on 32-bit

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit e335b853d919f2c6246ca0993115285742a2acc1 ]

blkcg_fill_root_iostats() shifts the unsigned long sector counts by 9 before adding them to the u64 byte counts, so on 32-bit the contribution of a CPU wraps every 4GB. Widen before the shift.

Fixes ef45fe470e1e ("blk-cgroup: show global disk stats in root cgroup io.stat")
Cc Tejun Heo <[email protected]>
---
 block/blk-cgroup.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
block/blk-cgroup.c +3 -3
index 06de4024a9a25..18b52ece07e82 100644
@@ -1118,11 +1118,11 @@ static void blkcg_fill_root_iostats(void)
 				cpu_dkstats->ios[STAT_DISCARD];
 			// convert sectors to bytes
 			tmp.bytes[BLKG_IOSTAT_READ] +=
-				cpu_dkstats->sectors[STAT_READ] << 9;
+				(u64)cpu_dkstats->sectors[STAT_READ] << 9;
 			tmp.bytes[BLKG_IOSTAT_WRITE] +=
-				cpu_dkstats->sectors[STAT_WRITE] << 9;
+				(u64)cpu_dkstats->sectors[STAT_WRITE] << 9;
 			tmp.bytes[BLKG_IOSTAT_DISCARD] +=
-				cpu_dkstats->sectors[STAT_DISCARD] << 9;
+				(u64)cpu_dkstats->sectors[STAT_DISCARD] << 9;
 		}
 
 		flags = u64_stats_update_begin_irqsave(&blkg->iostat.sync);
Signature · 1 line
2.53.0
author maintainer
#1671 lore raw

PATCH 1641/1756 blk-cgroup: dont free a blkg with its punt work queued

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 4def096314cf29fb6940b74c087a0b923185580e ]

blkg_async_bio_workfn() relies on the bios on the list pinning the blkg. But blkcg_punt_bio_submit() can call queue_work() after a running instance already took and completed the bio, and queue_work() succeeds on an empty list for the same reason. Nothing holds the blkg then, and free_work shares its memory with async_bio_work on top of that.

Hold a reference across blkcg_punt_bio_submit(), give the two works memory of their own, and cancel async_bio_work in blkg_free_workfn().

---
 block/blk-cgroup.c | 13 ++++++++++++-
 block/blk-cgroup.h |  6 ++----
 2 files changed, 14 insertions(+), 5 deletions(-)
block/blk-cgroup.c +12 -1
index 18b52ece07e82..d1f3d3491bd36 100644
@@ -118,6 +118,11 @@ static void blkg_free_workfn(struct work_struct *work)
 	struct request_queue *q = blkg->q;
 	int i;
 
+#ifdef CONFIG_BLK_CGROUP_PUNT_BIO
+	/* It may have been queued for bios which an earlier run has taken */
+	cancel_work_sync(&blkg->async_bio_work);
+#endif
+
 	/*
 	 * pd_free_fn() can also be called from blkcg_deactivate_policy(),
 	 * in order to make sure pd_free_fn() is called in order, the deletion
@@ -212,7 +217,7 @@ static void blkg_async_bio_workfn(struct work_struct *work)
 	struct blk_plug plug;
 	bool need_plug = false;
 
-	/* as long as there are pending bios, @blkg can't go away */
+	/* blkg_free_workfn() waits for us */
 	spin_lock(&blkg->async_bio_lock);
 	bio_list_merge_init(&bios, &blkg->async_bios);
 	spin_unlock(&blkg->async_bio_lock);
@@ -239,10 +244,16 @@ void blkcg_punt_bio_submit(struct bio *bio)
 	struct blkcg_gq *blkg = bio->bi_blkg;
 
 	if (blkg->parent) {
+		/*
+		 * Once it is on the list, a run which is under way can submit
+		 * @bio, and its reference goes when it completes.
+		 */
+		blkg_get(blkg);
 		spin_lock(&blkg->async_bio_lock);
 		bio_list_add(&blkg->async_bios, bio);
 		spin_unlock(&blkg->async_bio_lock);
 		queue_work(blkcg_punt_bio_wq, &blkg->async_bio_work);
+		blkg_put(blkg);
 	} else {
 		/* never bounce for the root cgroup */
 		submit_bio(bio);
block/blk-cgroup.h +2 -4
index 270e58e5f38af..8189b275496fc 100644
@@ -76,11 +76,9 @@ struct blkcg_gq {
 #ifdef CONFIG_BLK_CGROUP_PUNT_BIO
 	spinlock_t			async_bio_lock;
 	struct bio_list			async_bios;
+	struct work_struct		async_bio_work;
 #endif
-	union {
-		struct work_struct	async_bio_work;
-		struct work_struct	free_work;
-	};
+	struct work_struct		free_work;
 
 	atomic_t			use_delay;
 	atomic64_t			delay_nsec;
Signature · 1 line
2.53.0
author maintainer
#1672 lore raw

PATCH 1642/1756 blk-iolatency: flush enable_work after going offline

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 020f61242d6ebeba5f8f2ef6e429aeffdd63f1c1 ]

blkcg_iolatency_exit() flushes enable_work before it deactivates the policy, but iolatency_pd_offline() schedules it again for the last group with a target, so the blk_iolatency is freed with the work queued. Flush it after the deactivation.

Fixes 8a177a36da6c ("blk-iolatency: Fix inflight count imbalances and IO hangs on offline")
Cc Tejun Heo <[email protected]>
---
 block/blk-iolatency.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
block/blk-iolatency.c +2 -1
index 6be1c5e020ac9..a82ee8c408c2f 100644
@@ -645,8 +645,9 @@ static void blkcg_iolatency_exit(struct rq_qos *rqos)
 	struct blk_iolatency *blkiolat = BLKIOLATENCY(rqos);
 
 	timer_shutdown_sync(&blkiolat->timer);
-	flush_work(&blkiolat->enable_work);
 	blkcg_deactivate_policy(rqos->disk, &blkcg_policy_iolatency);
+	/* iolatency_pd_offline() schedules it for the last group with a target */
+	flush_work(&blkiolat->enable_work);
 	kfree(blkiolat);
 }
 
Signature · 1 line
2.53.0
author maintainer
#1673 lore raw

PATCH 1643/1756 block: flush all throttled bios when deleting the cgroup

In reply to Greg Kroah-Hartman

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

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

From: Li Lingfeng <[email protected]>

[ Upstream commit 919b5139bd1d557a4d4cd4b2466e2440dda65484 ]

When a process migrates to another cgroup and the original cgroup is deleted, the restrictions of throttled bios cannot be removed. If the restrictions are set too low, it will take a long time to complete these bios.

Refer to the process of deleting a disk to remove the restrictions and issue bios when deleting the cgroup.

This makes difference on the behavior of throttled bios:
Before: the limit of the throttled bios can't be changed and the bios will complete under this limit;
Now: the limit will be canceled and the throttled bios will be flushed immediately.

References:
[1] https://lore.kernel.org/r/[email protected]
[2] https://lore.kernel.org/all/[email protected]/

Stable-dep-of: 587edb931fdd ("blk-throttle: pass the I/O counts of a dead group on")

---
 block/blk-throttle.c | 68 ++++++++++++++++++++++++++++----------------
 1 file changed, 44 insertions(+), 24 deletions(-)
block/blk-throttle.c +44 -24
index c15dfb3100ee9..83b5390be11d6 100644
@@ -1527,6 +1527,42 @@ static void throtl_shutdown_wq(struct request_queue *q)
 	cancel_work_sync(&td->dispatch_work);
 }
 
+static void tg_flush_bios(struct throtl_grp *tg)
+{
+	struct throtl_service_queue *sq = &tg->service_queue;
+
+	if (tg->flags & THROTL_TG_CANCELING)
+		return;
+	/*
+	 * Set the flag to make sure throtl_pending_timer_fn() won't
+	 * stop until all throttled bios are dispatched.
+	 */
+	tg->flags |= THROTL_TG_CANCELING;
+
+	/*
+	 * Do not dispatch cgroup without THROTL_TG_PENDING or cgroup
+	 * will be inserted to service queue without THROTL_TG_PENDING
+	 * set in tg_update_disptime below. Then IO dispatched from
+	 * child in tg_dispatch_one_bio will trigger double insertion
+	 * and corrupt the tree.
+	 */
+	if (!(tg->flags & THROTL_TG_PENDING))
+		return;
+
+	/*
+	 * Update disptime after setting the above flag to make sure
+	 * throtl_select_dispatch() won't exit without dispatching.
+	 */
+	tg_update_disptime(tg);
+
+	throtl_schedule_pending_timer(sq, jiffies + 1);
+}
+
+static void throtl_pd_offline(struct blkg_policy_data *pd)
+{
+	tg_flush_bios(pd_to_tg(pd));
+}
+
 struct blkcg_policy blkcg_policy_throtl = {
 	.dfl_cftypes		= throtl_files,
 	.legacy_cftypes		= throtl_legacy_files,
@@ -1534,6 +1570,7 @@ struct blkcg_policy blkcg_policy_throtl = {
 	.pd_alloc_fn		= throtl_pd_alloc,
 	.pd_init_fn		= throtl_pd_init,
 	.pd_online_fn		= throtl_pd_online,
+	.pd_offline_fn		= throtl_pd_offline,
 	.pd_free_fn		= throtl_pd_free,
 };
 
@@ -1554,32 +1591,15 @@ void blk_throtl_cancel_bios(struct gendisk *disk)
 	 */
 	rcu_read_lock();
 	blkg_for_each_descendant_post(blkg, pos_css, q->root_blkg) {
-		struct throtl_grp *tg = blkg_to_tg(blkg);
-		struct throtl_service_queue *sq = &tg->service_queue;
-
-		/*
-		 * Set the flag to make sure throtl_pending_timer_fn() won't
-		 * stop until all throttled bios are dispatched.
-		 */
-		tg->flags |= THROTL_TG_CANCELING;
-
 		/*
-		 * Do not dispatch cgroup without THROTL_TG_PENDING or cgroup
-		 * will be inserted to service queue without THROTL_TG_PENDING
-		 * set in tg_update_disptime below. Then IO dispatched from
-		 * child in tg_dispatch_one_bio will trigger double insertion
-		 * and corrupt the tree.
+		 * disk_release will call pd_offline_fn to cancel bios.
+		 * However, disk_release can't be called if someone get
+		 * the refcount of device and issued bios which are
+		 * inflight after del_gendisk.
+		 * Cancel bios here to ensure no bios are inflight after
+		 * del_gendisk.
 		 */
-		if (!(tg->flags & THROTL_TG_PENDING))
-			continue;
-
-		/*
-		 * Update disptime after setting the above flag to make sure
-		 * throtl_select_dispatch() won't exit without dispatching.
-		 */
-		tg_update_disptime(tg);
-
-		throtl_schedule_pending_timer(sq, jiffies + 1);
+		tg_flush_bios(blkg_to_tg(blkg));
 	}
 	rcu_read_unlock();
 	spin_unlock_irq(&q->queue_lock);
Signature · 1 line
2.53.0
author maintainer
#1674 lore raw

PATCH 1644/1756 blk-throttle: pass the I/O counts of a dead group on

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 587edb931fdda032bcd63fdfb0db4ded75159ee9 ]

The recursive io_service_bytes and io_serviced files sum up the online groups plus what dead descendants left in aux_cnt. That worked while the counters lived in the blkg. Since commit 7ca464383aec they're in the throtl_grp and nobody passes them up, so the files go backwards when a child is removed. Add them to the parent in throtl_pd_offline().

Fixes 7ca464383aec ("blk-throtl: stop using blkg->stat_bytes and ->stat_ios")
Cc Tejun Heo <[email protected]>
---
 block/blk-throttle.c | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)
block/blk-throttle.c +12 -1
index 83b5390be11d6..75326b8d4868a 100644
@@ -1560,7 +1560,18 @@ static void tg_flush_bios(struct throtl_grp *tg)
 
 static void throtl_pd_offline(struct blkg_policy_data *pd)
 {
-	tg_flush_bios(pd_to_tg(pd));
+	struct throtl_grp *tg = pd_to_tg(pd);
+	struct throtl_grp *parent = blkg_to_tg(tg_to_blkg(tg)->parent);
+
+	tg_flush_bios(tg);
+
+	/* the recursive files of the ancestors go on counting what it did */
+	if (parent) {
+		blkg_rwstat_add_aux(&parent->stat_bytes, &tg->stat_bytes);
+		blkg_rwstat_add_aux(&parent->stat_ios, &tg->stat_ios);
+		blkg_rwstat_reset(&tg->stat_bytes);
+		blkg_rwstat_reset(&tg->stat_ios);
+	}
 }
 
 struct blkcg_policy blkcg_policy_throtl = {
Signature · 1 line
2.53.0
author maintainer
#1675 lore raw

PATCH 1645/1756 blk-throttle: make blkio.reset_stats reset I/O counts

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit ac81a07a0bd5e75e8edc0eb5be563be1b2d56554 ]

blkio.throttle.io_service_bytes and io_serviced were reset by blkcg_reset_stats() while the counters were part of the blkg. Now that they live in the throtl_grp, add a pd_reset_stats_fn for them.

Fixes 7ca464383aec ("blk-throtl: stop using blkg->stat_bytes and ->stat_ios")
Cc Tejun Heo <[email protected]>
---
 block/blk-throttle.c | 9 +++++++++
 1 file changed, 9 insertions(+)
block/blk-throttle.c +9 -0
index 75326b8d4868a..35b35b34cad5f 100644
@@ -1574,6 +1574,14 @@ static void throtl_pd_offline(struct blkg_policy_data *pd)
 	}
 }
 
+static void throtl_pd_reset_stats(struct blkg_policy_data *pd)
+{
+	struct throtl_grp *tg = pd_to_tg(pd);
+
+	blkg_rwstat_reset(&tg->stat_bytes);
+	blkg_rwstat_reset(&tg->stat_ios);
+}
+
 struct blkcg_policy blkcg_policy_throtl = {
 	.dfl_cftypes		= throtl_files,
 	.legacy_cftypes		= throtl_legacy_files,
@@ -1583,6 +1591,7 @@ struct blkcg_policy blkcg_policy_throtl = {
 	.pd_online_fn		= throtl_pd_online,
 	.pd_offline_fn		= throtl_pd_offline,
 	.pd_free_fn		= throtl_pd_free,
+	.pd_reset_stats_fn	= throtl_pd_reset_stats,
 };
 
 void blk_throtl_cancel_bios(struct gendisk *disk)
Signature · 1 line
2.53.0
author maintainer
#1676 lore raw

PATCH 1646/1756 net: bcmgenet: remove dma_ctrl argument

In reply to Greg Kroah-Hartman

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

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

From: Doug Berger <[email protected]>

[ Upstream commit 8b031d4e9baaa33e1b0abd09b9a98a84576a21f0 ]

Since the individual queues manage their own DMA enables there is no need to return dma_ctrl from bcmgenet_dma_disable() and pass it back to bcmgenet_enable_dma().

Stable-dep-of: 1c1f51c3ee9c ("net: bcmgenet: recover from a failed resume")

---
 .../net/ethernet/broadcom/genet/bcmgenet.c    | 21 +++++++------------
 1 file changed, 8 insertions(+), 13 deletions(-)
drivers/net/ethernet/broadcom/genet/bcmgenet.c +8 -13
index 0402e8f69c6fa..0b9c7deab10de 100644
@@ -3224,8 +3224,7 @@ static void bcmgenet_get_hw_addr(struct bcmgenet_priv *priv,
 	put_unaligned_be16(addr_tmp, &addr[4]);
 }
 
-/* Returns a reusable dma control register value */
-static u32 bcmgenet_dma_disable(struct bcmgenet_priv *priv, bool flush_rx)
+static void bcmgenet_dma_disable(struct bcmgenet_priv *priv, bool flush_rx)
 {
 	unsigned int i;
 	u32 reg;
@@ -3257,20 +3256,18 @@ static u32 bcmgenet_dma_disable(struct bcmgenet_priv *priv, bool flush_rx)
 		bcmgenet_rbuf_ctrl_set(priv, reg);
 		udelay(10);
 	}
-
-	return dma_ctrl;
 }
 
-static void bcmgenet_enable_dma(struct bcmgenet_priv *priv, u32 dma_ctrl)
+static void bcmgenet_enable_dma(struct bcmgenet_priv *priv)
 {
 	u32 reg;
 
 	reg = bcmgenet_rdma_readl(priv, DMA_CTRL);
-	reg |= dma_ctrl;
+	reg |= DMA_EN;
 	bcmgenet_rdma_writel(priv, reg, DMA_CTRL);
 
 	reg = bcmgenet_tdma_readl(priv, DMA_CTRL);
-	reg |= dma_ctrl;
+	reg |= DMA_EN;
 	bcmgenet_tdma_writel(priv, reg, DMA_CTRL);
 }
 
@@ -3297,7 +3294,6 @@ static void bcmgenet_netif_start(struct net_device *dev)
 static int bcmgenet_open(struct net_device *dev)
 {
 	struct bcmgenet_priv *priv = netdev_priv(dev);
-	unsigned long dma_ctrl;
 	int ret;
 
 	netif_dbg(priv, ifup, dev, "bcmgenet_open\n");
@@ -3327,7 +3323,7 @@ static int bcmgenet_open(struct net_device *dev)
 	bcmgenet_hfb_init(priv);
 
 	/* Disable RX/TX DMA and flush TX and RX queues */
-	dma_ctrl = bcmgenet_dma_disable(priv, true);
+	bcmgenet_dma_disable(priv, true);
 
 	/* Reinitialize TDMA and RDMA and SW housekeeping */
 	ret = bcmgenet_init_dma(priv);
@@ -3336,7 +3332,7 @@ static int bcmgenet_open(struct net_device *dev)
 		goto err_clk_disable;
 	}
 
-	bcmgenet_enable_dma(priv, dma_ctrl);
+	bcmgenet_enable_dma(priv);
 
 	ret = request_irq(priv->irq0, bcmgenet_isr0, IRQF_SHARED,
 			  dev->name, priv);
@@ -4183,7 +4179,6 @@ static int bcmgenet_resume(struct device *d)
 	struct net_device *dev = dev_get_drvdata(d);
 	struct bcmgenet_priv *priv = netdev_priv(dev);
 	struct bcmgenet_rxnfc_rule *rule;
-	unsigned long dma_ctrl;
 	int ret;
 
 	if (!netif_running(dev))
@@ -4209,7 +4204,7 @@ static int bcmgenet_resume(struct device *d)
 			bcmgenet_hfb_create_rxnfc_filter(priv, rule);
 
 	/* Disable RX/TX DMA and flush TX queues */
-	dma_ctrl = bcmgenet_dma_disable(priv, false);
+	bcmgenet_dma_disable(priv, false);
 
 	/* Reinitialize TDMA and RDMA and SW housekeeping */
 	ret = bcmgenet_init_dma(priv);
@@ -4218,7 +4213,7 @@ static int bcmgenet_resume(struct device *d)
 		goto out_clk_disable;
 	}
 
-	bcmgenet_enable_dma(priv, dma_ctrl);
+	bcmgenet_enable_dma(priv);
 
 	if (!device_may_wakeup(d))
 		phy_resume(dev->phydev);
Signature · 1 line
2.53.0
author maintainer
#1677 lore raw

PATCH 1647/1756 net: bcmgenet: consolidate dma initialization

In reply to Greg Kroah-Hartman

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

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

From: Doug Berger <[email protected]>

[ Upstream commit 58affb23b66793033f95cb4e9a57a388e0485edb ]

The functions bcmgenet_dma_disable and bcmgenet_enable_dma are only used as part of dma initialization. Their functionality is moved inside bcmgenet_init_dma and the functions are removed.

Since the dma is always disabled inside of bcmgenet_init_dma, the initialization functions bcmgenet_init_rx_queues and bcmgenet_init_tx_queues no longer need to attempt to manage its state.

Stable-dep-of: 1c1f51c3ee9c ("net: bcmgenet: recover from a failed resume")

---
 .../net/ethernet/broadcom/genet/bcmgenet.c    | 150 +++++++-----------
 1 file changed, 54 insertions(+), 96 deletions(-)
drivers/net/ethernet/broadcom/genet/bcmgenet.c +54 -96
index 0b9c7deab10de..d02473abf9bb8 100644
@@ -2809,17 +2809,7 @@ static void bcmgenet_init_tx_queues(struct net_device *dev)
 {
 	struct bcmgenet_priv *priv = netdev_priv(dev);
 	unsigned int start = 0, end = GENET_Q0_TX_BD_CNT;
-	u32 i, dma_enable;
-	u32 dma_ctrl, ring_cfg;
-	u32 dma_priority[3] = {0, 0, 0};
-
-	dma_ctrl = bcmgenet_tdma_readl(priv, DMA_CTRL);
-	dma_enable = dma_ctrl & DMA_EN;
-	dma_ctrl &= ~DMA_EN;
-	bcmgenet_tdma_writel(priv, dma_ctrl, DMA_CTRL);
-
-	dma_ctrl = 0;
-	ring_cfg = 0;
+	u32 i, ring_mask, dma_priority[3] = {0, 0, 0};
 
 	/* Enable Weighted Round-Robin arbiter mode */
 	bcmgenet_tdma_writel(priv, DMA_ARBITER_WRR, DMA_ARB_CTRL);
@@ -2829,8 +2819,6 @@ static void bcmgenet_init_tx_queues(struct net_device *dev)
 		bcmgenet_init_tx_ring(priv, i, end - start, start, end);
 		start = end;
 		end += priv->hw_params->tx_bds_per_q;
-		ring_cfg |= (1 << i);
-		dma_ctrl |= (1 << (i + DMA_RING_BUF_EN_SHIFT));
 		dma_priority[DMA_PRIO_REG_INDEX(i)] |=
 			(i ? GENET_Q1_WEIGHT : GENET_Q0_WEIGHT)
 			<< DMA_PRIO_REG_SHIFT(i);
@@ -2841,13 +2829,13 @@ static void bcmgenet_init_tx_queues(struct net_device *dev)
 	bcmgenet_tdma_writel(priv, dma_priority[1], DMA_PRIORITY_1);
 	bcmgenet_tdma_writel(priv, dma_priority[2], DMA_PRIORITY_2);
 
-	/* Enable Tx queues */
-	bcmgenet_tdma_writel(priv, ring_cfg, DMA_RING_CFG);
+	/* Configure Tx queues as descriptor rings */
+	ring_mask = (1 << (priv->hw_params->tx_queues + 1)) - 1;
+	bcmgenet_tdma_writel(priv, ring_mask, DMA_RING_CFG);
 
-	/* Enable Tx DMA */
-	if (dma_enable)
-		dma_ctrl |= DMA_EN;
-	bcmgenet_tdma_writel(priv, dma_ctrl, DMA_CTRL);
+	/* Enable Tx rings */
+	ring_mask <<= DMA_RING_BUF_EN_SHIFT;
+	bcmgenet_tdma_writel(priv, ring_mask, DMA_CTRL);
 }
 
 static void bcmgenet_enable_rx_napi(struct bcmgenet_priv *priv)
@@ -2896,17 +2884,9 @@ static int bcmgenet_init_rx_queues(struct net_device *dev)
 {
 	struct bcmgenet_priv *priv = netdev_priv(dev);
 	unsigned int start = 0, end = GENET_Q0_RX_BD_CNT;
-	u32 i, dma_enable, dma_ctrl = 0, ring_cfg = 0;
+	u32 i, ring_mask;
 	int ret;
 
-	dma_ctrl = bcmgenet_rdma_readl(priv, DMA_CTRL);
-	dma_enable = dma_ctrl & DMA_EN;
-	dma_ctrl &= ~DMA_EN;
-	bcmgenet_rdma_writel(priv, dma_ctrl, DMA_CTRL);
-
-	dma_ctrl = 0;
-	ring_cfg = 0;
-
 	/* Initialize Rx priority queues */
 	for (i = 0; i <= priv->hw_params->rx_queues; i++) {
 		ret = bcmgenet_init_rx_ring(priv, i, end - start, start, end);
@@ -2915,17 +2895,15 @@ static int bcmgenet_init_rx_queues(struct net_device *dev)
 
 		start = end;
 		end += priv->hw_params->rx_bds_per_q;
-		ring_cfg |= (1 << i);
-		dma_ctrl |= (1 << (i + DMA_RING_BUF_EN_SHIFT));
 	}
 
 	/* Configure Rx queues as descriptor rings */
-	bcmgenet_rdma_writel(priv, ring_cfg, DMA_RING_CFG);
+	ring_mask = (1 << (priv->hw_params->rx_queues + 1)) - 1;
+	bcmgenet_rdma_writel(priv, ring_mask, DMA_RING_CFG);
 
 	/* Enable Rx rings */
-	if (dma_enable)
-		dma_ctrl |= DMA_EN;
-	bcmgenet_rdma_writel(priv, dma_ctrl, DMA_CTRL);
+	ring_mask <<= DMA_RING_BUF_EN_SHIFT;
+	bcmgenet_rdma_writel(priv, ring_mask, DMA_CTRL);
 
 	return 0;
 }
@@ -3016,14 +2994,42 @@ static void bcmgenet_fini_dma(struct bcmgenet_priv *priv)
 }
 
 /* init_edma: Initialize DMA control register */
-static int bcmgenet_init_dma(struct bcmgenet_priv *priv)
+static int bcmgenet_init_dma(struct bcmgenet_priv *priv, bool flush_rx)
 {
-	int ret;
-	unsigned int i;
 	struct enet_cb *cb;
+	u32 reg, dma_ctrl;
+	unsigned int i;
+	int ret;
 
 	netif_dbg(priv, hw, priv->dev, "%s\n", __func__);
 
+	/* Disable RX/TX DMA and flush TX queues */
+	dma_ctrl = 1 << (DESC_INDEX + DMA_RING_BUF_EN_SHIFT) | DMA_EN;
+	for (i = 0; i < priv->hw_params->tx_queues; i++)
+		dma_ctrl |= (1 << (i + DMA_RING_BUF_EN_SHIFT));
+	reg = bcmgenet_tdma_readl(priv, DMA_CTRL);
+	reg &= ~dma_ctrl;
+	bcmgenet_tdma_writel(priv, reg, DMA_CTRL);
+
+	dma_ctrl = 1 << (DESC_INDEX + DMA_RING_BUF_EN_SHIFT) | DMA_EN;
+	for (i = 0; i < priv->hw_params->rx_queues; i++)
+		dma_ctrl |= (1 << (i + DMA_RING_BUF_EN_SHIFT));
+	reg = bcmgenet_rdma_readl(priv, DMA_CTRL);
+	reg &= ~dma_ctrl;
+	bcmgenet_rdma_writel(priv, reg, DMA_CTRL);
+
+	bcmgenet_umac_writel(priv, 1, UMAC_TX_FLUSH);
+	udelay(10);
+	bcmgenet_umac_writel(priv, 0, UMAC_TX_FLUSH);
+
+	if (flush_rx) {
+		reg = bcmgenet_rbuf_ctrl_get(priv);
+		bcmgenet_rbuf_ctrl_set(priv, reg | BIT(0));
+		udelay(10);
+		bcmgenet_rbuf_ctrl_set(priv, reg);
+		udelay(10);
+	}
+
 	/* Initialize common Rx ring structures */
 	priv->rx_bds = priv->base + priv->hw_params->rdma_offset;
 	priv->num_rx_bds = TOTAL_DESC;
@@ -3073,6 +3079,15 @@ static int bcmgenet_init_dma(struct bcmgenet_priv *priv)
 	/* Initialize Tx queues */
 	bcmgenet_init_tx_queues(priv->dev);
 
+	/* Enable RX/TX DMA */
+	reg = bcmgenet_rdma_readl(priv, DMA_CTRL);
+	reg |= DMA_EN;
+	bcmgenet_rdma_writel(priv, reg, DMA_CTRL);
+
+	reg = bcmgenet_tdma_readl(priv, DMA_CTRL);
+	reg |= DMA_EN;
+	bcmgenet_tdma_writel(priv, reg, DMA_CTRL);
+
 	return 0;
 }
 
@@ -3224,53 +3239,6 @@ static void bcmgenet_get_hw_addr(struct bcmgenet_priv *priv,
 	put_unaligned_be16(addr_tmp, &addr[4]);
 }
 
-static void bcmgenet_dma_disable(struct bcmgenet_priv *priv, bool flush_rx)
-{
-	unsigned int i;
-	u32 reg;
-	u32 dma_ctrl;
-
-	/* disable DMA */
-	dma_ctrl = DMA_EN;
-	for (i = 0; i <= priv->hw_params->tx_queues; i++)
-		dma_ctrl |= (1 << (i + DMA_RING_BUF_EN_SHIFT));
-	reg = bcmgenet_tdma_readl(priv, DMA_CTRL);
-	reg &= ~dma_ctrl;
-	bcmgenet_tdma_writel(priv, reg, DMA_CTRL);
-
-	dma_ctrl = DMA_EN;
-	for (i = 0; i <= priv->hw_params->rx_queues; i++)
-		dma_ctrl |= (1 << (i + DMA_RING_BUF_EN_SHIFT));
-	reg = bcmgenet_rdma_readl(priv, DMA_CTRL);
-	reg &= ~dma_ctrl;
-	bcmgenet_rdma_writel(priv, reg, DMA_CTRL);
-
-	bcmgenet_umac_writel(priv, 1, UMAC_TX_FLUSH);
-	udelay(10);
-	bcmgenet_umac_writel(priv, 0, UMAC_TX_FLUSH);
-
-	if (flush_rx) {
-		reg = bcmgenet_rbuf_ctrl_get(priv);
-		bcmgenet_rbuf_ctrl_set(priv, reg | BIT(0));
-		udelay(10);
-		bcmgenet_rbuf_ctrl_set(priv, reg);
-		udelay(10);
-	}
-}
-
-static void bcmgenet_enable_dma(struct bcmgenet_priv *priv)
-{
-	u32 reg;
-
-	reg = bcmgenet_rdma_readl(priv, DMA_CTRL);
-	reg |= DMA_EN;
-	bcmgenet_rdma_writel(priv, reg, DMA_CTRL);
-
-	reg = bcmgenet_tdma_readl(priv, DMA_CTRL);
-	reg |= DMA_EN;
-	bcmgenet_tdma_writel(priv, reg, DMA_CTRL);
-}
-
 static void bcmgenet_netif_start(struct net_device *dev)
 {
 	struct bcmgenet_priv *priv = netdev_priv(dev);
@@ -3322,18 +3290,13 @@ static int bcmgenet_open(struct net_device *dev)
 	/* HFB init */
 	bcmgenet_hfb_init(priv);
 
-	/* Disable RX/TX DMA and flush TX and RX queues */
-	bcmgenet_dma_disable(priv, true);
-
 	/* Reinitialize TDMA and RDMA and SW housekeeping */
-	ret = bcmgenet_init_dma(priv);
+	ret = bcmgenet_init_dma(priv, true);
 	if (ret) {
 		netdev_err(dev, "failed to initialize DMA\n");
 		goto err_clk_disable;
 	}
 
-	bcmgenet_enable_dma(priv);
-
 	ret = request_irq(priv->irq0, bcmgenet_isr0, IRQF_SHARED,
 			  dev->name, priv);
 	if (ret < 0) {
@@ -4203,18 +4166,13 @@ static int bcmgenet_resume(struct device *d)
 		if (rule->state != BCMGENET_RXNFC_STATE_UNUSED)
 			bcmgenet_hfb_create_rxnfc_filter(priv, rule);
 
-	/* Disable RX/TX DMA and flush TX queues */
-	bcmgenet_dma_disable(priv, false);
-
 	/* Reinitialize TDMA and RDMA and SW housekeeping */
-	ret = bcmgenet_init_dma(priv);
+	ret = bcmgenet_init_dma(priv, false);
 	if (ret) {
 		netdev_err(dev, "failed to initialize DMA\n");
 		goto out_clk_disable;
 	}
 
-	bcmgenet_enable_dma(priv);
-
 	if (!device_may_wakeup(d))
 		phy_resume(dev->phydev);
 
Signature · 1 line
2.53.0
author maintainer
#1678 lore raw

PATCH 1648/1756 net: bcmgenet: introduce bcmgenet_[r|t]dma_disable

In reply to Greg Kroah-Hartman

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

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

From: Doug Berger <[email protected]>

[ Upstream commit 791f349d02f73aa5c11e84994447adcaf76a92a4 ]

The bcmgenet_rdma_disable and bcmgenet_tdma_disable functions are introduced to provide a common method for disabling each dma and the code is simplified.

Stable-dep-of: 1c1f51c3ee9c ("net: bcmgenet: recover from a failed resume")

---
 .../net/ethernet/broadcom/genet/bcmgenet.c    | 123 +++++++++---------
 1 file changed, 62 insertions(+), 61 deletions(-)
drivers/net/ethernet/broadcom/genet/bcmgenet.c +62 -61
index d02473abf9bb8..44bee231caab8 100644
@@ -2789,6 +2789,52 @@ static void bcmgenet_fini_tx_napi(struct bcmgenet_priv *priv)
 	}
 }
 
+static int bcmgenet_tdma_disable(struct bcmgenet_priv *priv)
+{
+	int timeout = 0;
+	u32 reg, mask;
+
+	reg = bcmgenet_tdma_readl(priv, DMA_CTRL);
+	mask = (1 << (priv->hw_params->tx_queues + 1)) - 1;
+	mask = (mask << DMA_RING_BUF_EN_SHIFT) | DMA_EN;
+	reg &= ~mask;
+	bcmgenet_tdma_writel(priv, reg, DMA_CTRL);
+
+	/* Check DMA status register to confirm DMA is disabled */
+	while (timeout++ < DMA_TIMEOUT_VAL) {
+		reg = bcmgenet_tdma_readl(priv, DMA_STATUS);
+		if ((reg & mask) == mask)
+			return 0;
+
+		udelay(1);
+	}
+
+	return -ETIMEDOUT;
+}
+
+static int bcmgenet_rdma_disable(struct bcmgenet_priv *priv)
+{
+	int timeout = 0;
+	u32 reg, mask;
+
+	reg = bcmgenet_rdma_readl(priv, DMA_CTRL);
+	mask = (1 << (priv->hw_params->rx_queues + 1)) - 1;
+	mask = (mask << DMA_RING_BUF_EN_SHIFT) | DMA_EN;
+	reg &= ~mask;
+	bcmgenet_rdma_writel(priv, reg, DMA_CTRL);
+
+	/* Check DMA status register to confirm DMA is disabled */
+	while (timeout++ < DMA_TIMEOUT_VAL) {
+		reg = bcmgenet_rdma_readl(priv, DMA_STATUS);
+		if ((reg & mask) == mask)
+			return 0;
+
+		udelay(1);
+	}
+
+	return -ETIMEDOUT;
+}
+
 /* Initialize Tx queues
  *
  * Queues 1-4 are the priority queues, each one has 32 descriptors.
@@ -2911,26 +2957,9 @@ static int bcmgenet_init_rx_queues(struct net_device *dev)
 static int bcmgenet_dma_teardown(struct bcmgenet_priv *priv)
 {
 	int ret = 0;
-	int timeout = 0;
-	u32 reg;
-	u32 dma_ctrl;
-	int i;
 
 	/* Disable TDMA to stop add more frames in TX DMA */
-	reg = bcmgenet_tdma_readl(priv, DMA_CTRL);
-	reg &= ~DMA_EN;
-	bcmgenet_tdma_writel(priv, reg, DMA_CTRL);
-
-	/* Check TDMA status register to confirm TDMA is disabled */
-	while (timeout++ < DMA_TIMEOUT_VAL) {
-		reg = bcmgenet_tdma_readl(priv, DMA_STATUS);
-		if (reg & DMA_DISABLED)
-			break;
-
-		udelay(1);
-	}
-
-	if (timeout == DMA_TIMEOUT_VAL) {
+	if (-ETIMEDOUT == bcmgenet_tdma_disable(priv)) {
 		netdev_warn(priv->dev, "Timed out while disabling TX DMA\n");
 		ret = -ETIMEDOUT;
 	}
@@ -2939,39 +2968,11 @@ static int bcmgenet_dma_teardown(struct bcmgenet_priv *priv)
 	usleep_range(10000, 20000);
 
 	/* Disable RDMA */
-	reg = bcmgenet_rdma_readl(priv, DMA_CTRL);
-	reg &= ~DMA_EN;
-	bcmgenet_rdma_writel(priv, reg, DMA_CTRL);
-
-	timeout = 0;
-	/* Check RDMA status register to confirm RDMA is disabled */
-	while (timeout++ < DMA_TIMEOUT_VAL) {
-		reg = bcmgenet_rdma_readl(priv, DMA_STATUS);
-		if (reg & DMA_DISABLED)
-			break;
-
-		udelay(1);
-	}
-
-	if (timeout == DMA_TIMEOUT_VAL) {
+	if (-ETIMEDOUT == bcmgenet_rdma_disable(priv)) {
 		netdev_warn(priv->dev, "Timed out while disabling RX DMA\n");
 		ret = -ETIMEDOUT;
 	}
 
-	dma_ctrl = 0;
-	for (i = 0; i <= priv->hw_params->rx_queues; i++)
-		dma_ctrl |= (1 << (i + DMA_RING_BUF_EN_SHIFT));
-	reg = bcmgenet_rdma_readl(priv, DMA_CTRL);
-	reg &= ~dma_ctrl;
-	bcmgenet_rdma_writel(priv, reg, DMA_CTRL);
-
-	dma_ctrl = 0;
-	for (i = 0; i <= priv->hw_params->tx_queues; i++)
-		dma_ctrl |= (1 << (i + DMA_RING_BUF_EN_SHIFT));
-	reg = bcmgenet_tdma_readl(priv, DMA_CTRL);
-	reg &= ~dma_ctrl;
-	bcmgenet_tdma_writel(priv, reg, DMA_CTRL);
-
 	return ret;
 }
 
@@ -2997,27 +2998,27 @@ static void bcmgenet_fini_dma(struct bcmgenet_priv *priv)
 static int bcmgenet_init_dma(struct bcmgenet_priv *priv, bool flush_rx)
 {
 	struct enet_cb *cb;
-	u32 reg, dma_ctrl;
 	unsigned int i;
 	int ret;
+	u32 reg;
 
 	netif_dbg(priv, hw, priv->dev, "%s\n", __func__);
 
-	/* Disable RX/TX DMA and flush TX queues */
-	dma_ctrl = 1 << (DESC_INDEX + DMA_RING_BUF_EN_SHIFT) | DMA_EN;
-	for (i = 0; i < priv->hw_params->tx_queues; i++)
-		dma_ctrl |= (1 << (i + DMA_RING_BUF_EN_SHIFT));
-	reg = bcmgenet_tdma_readl(priv, DMA_CTRL);
-	reg &= ~dma_ctrl;
-	bcmgenet_tdma_writel(priv, reg, DMA_CTRL);
+	/* Disable TX DMA */
+	ret = bcmgenet_tdma_disable(priv);
+	if (ret) {
+		netdev_err(priv->dev, "failed to halt Tx DMA\n");
+		return ret;
+	}
 
-	dma_ctrl = 1 << (DESC_INDEX + DMA_RING_BUF_EN_SHIFT) | DMA_EN;
-	for (i = 0; i < priv->hw_params->rx_queues; i++)
-		dma_ctrl |= (1 << (i + DMA_RING_BUF_EN_SHIFT));
-	reg = bcmgenet_rdma_readl(priv, DMA_CTRL);
-	reg &= ~dma_ctrl;
-	bcmgenet_rdma_writel(priv, reg, DMA_CTRL);
+	/* Disable RX DMA */
+	ret = bcmgenet_rdma_disable(priv);
+	if (ret) {
+		netdev_err(priv->dev, "failed to halt Rx DMA\n");
+		return ret;
+	}
 
+	/* Flush TX queues */
 	bcmgenet_umac_writel(priv, 1, UMAC_TX_FLUSH);
 	udelay(10);
 	bcmgenet_umac_writel(priv, 0, UMAC_TX_FLUSH);
Signature · 1 line
2.53.0
author maintainer
#1679 lore raw

PATCH 1649/1756 net: bcmgenet: revise suspend/resume

In reply to Greg Kroah-Hartman

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

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

From: Doug Berger <[email protected]>

[ Upstream commit 254f3239dd070e469f45c3ca8b6ac38e47d6c730 ]

If the network interface is configured for Wake-on-LAN we should avoid bringing the interface down and up since it slows the time to reestablish network traffic on resume.

Redundant calls to phy_suspend() and phy_resume() are removed since they are already invoked from within phy_stop() and phy_start() called from bcmgenet_netif_stop() and bcmgenet_netif_start().

Stable-dep-of: 1c1f51c3ee9c ("net: bcmgenet: recover from a failed resume")

---
 .../net/ethernet/broadcom/genet/bcmgenet.c    | 100 +++++++++++++++---
 .../net/ethernet/broadcom/genet/bcmgenet.h    |   2 +
 .../ethernet/broadcom/genet/bcmgenet_wol.c    |  69 ++++++------
 3 files changed, 119 insertions(+), 52 deletions(-)
drivers/net/ethernet/broadcom/genet/bcmgenet.c +85 -15
index 44bee231caab8..9280f94641d74 100644
@@ -2616,7 +2616,7 @@ static void init_umac(struct bcmgenet_priv *priv)
 
 	/* Enable MDIO interrupts on GENET v3+ */
 	if (bcmgenet_has_mdio_intr(priv))
-		int0_enable |= (UMAC_IRQ_MDIO_DONE | UMAC_IRQ_MDIO_ERROR);
+		int0_enable |= UMAC_IRQ_MDIO_EVENT;
 
 	bcmgenet_intrl2_0_writel(priv, int0_enable, INTRL2_CPU_MASK_CLEAR);
 
@@ -3183,10 +3183,8 @@ static irqreturn_t bcmgenet_isr0(int irq, void *dev_id)
 	netif_dbg(priv, intr, priv->dev,
 		  "IRQ=0x%x\n", status);
 
-	if (bcmgenet_has_mdio_intr(priv) &&
-		status & (UMAC_IRQ_MDIO_DONE | UMAC_IRQ_MDIO_ERROR)) {
+	if (bcmgenet_has_mdio_intr(priv) && status & UMAC_IRQ_MDIO_EVENT)
 		wake_up(&priv->wq);
-	}
 
 	/* all other interested interrupts handled in bottom half */
 	status &= (UMAC_IRQ_LINK_EVENT | UMAC_IRQ_PHY_DET_R);
@@ -3344,19 +3342,21 @@ static void bcmgenet_netif_stop(struct net_device *dev, bool stop_phy)
 {
 	struct bcmgenet_priv *priv = netdev_priv(dev);
 
-	bcmgenet_disable_tx_napi(priv);
 	netif_tx_disable(dev);
 
 	/* Disable MAC receive */
+	bcmgenet_hfb_reg_writel(priv, 0, HFB_CTRL);
 	umac_enable_set(priv, CMD_RX_EN, false);
 
+	if (stop_phy)
+		phy_stop(dev->phydev);
+
 	bcmgenet_dma_teardown(priv);
 
 	/* Disable MAC transmit. TX DMA disabled must be done before this */
 	umac_enable_set(priv, CMD_TX_EN, false);
 
-	if (stop_phy)
-		phy_stop(dev->phydev);
+	bcmgenet_disable_tx_napi(priv);
 	bcmgenet_disable_rx_napi(priv);
 	bcmgenet_intr_disable(priv);
 
@@ -4121,7 +4121,10 @@ static int bcmgenet_resume_noirq(struct device *d)
 			pm_wakeup_event(&priv->pdev->dev, 0);
 
 		/* From WOL-enabled suspend, switch to regular clock */
-		bcmgenet_power_up(priv, GENET_POWER_WOL_MAGIC);
+		if (!bcmgenet_power_up(priv, GENET_POWER_WOL_MAGIC))
+			return 0;
+
+		/* Failed so fall through to reset MAC */
 	}
 
 	/* If this is an internal GPHY, power it back on now, before UniMAC is
@@ -4133,8 +4136,6 @@ static int bcmgenet_resume_noirq(struct device *d)
 	/* take MAC out of reset */
 	bcmgenet_umac_reset(priv);
 
-	bcmgenet_intrl2_0_writel(priv, UMAC_IRQ_WAKE_EVENT, INTRL2_CPU_CLEAR);
-
 	return 0;
 }
 
@@ -4144,10 +4145,46 @@ static int bcmgenet_resume(struct device *d)
 	struct bcmgenet_priv *priv = netdev_priv(dev);
 	struct bcmgenet_rxnfc_rule *rule;
 	int ret;
+	u32 reg;
 
 	if (!netif_running(dev))
 		return 0;
 
+	if (device_may_wakeup(d) && priv->wolopts) {
+		reg = bcmgenet_umac_readl(priv, UMAC_CMD);
+		if (reg & CMD_RX_EN) {
+			/* Successfully exited WoL, just resume data flows */
+			list_for_each_entry(rule, &priv->rxnfc_list, list)
+				if (rule->state == BCMGENET_RXNFC_STATE_ENABLED)
+					bcmgenet_hfb_enable_filter(priv,
+							rule->fs.location + 1);
+			bcmgenet_hfb_enable_filter(priv, 0);
+			bcmgenet_set_rx_mode(dev);
+			bcmgenet_enable_rx_napi(priv);
+
+			/* Reinitialize Tx flows */
+			bcmgenet_tdma_disable(priv);
+			bcmgenet_init_tx_queues(priv->dev);
+			reg = bcmgenet_tdma_readl(priv, DMA_CTRL);
+			reg |= DMA_EN;
+			bcmgenet_tdma_writel(priv, reg, DMA_CTRL);
+			bcmgenet_enable_tx_napi(priv);
+
+			bcmgenet_link_intr_enable(priv);
+			phy_start_machine(dev->phydev);
+
+			netif_device_attach(dev);
+			enable_irq(priv->irq1);
+			return 0;
+		}
+		/* MAC was reset so complete bcmgenet_netif_stop() */
+		umac_enable_set(priv, CMD_RX_EN | CMD_TX_EN, false);
+		bcmgenet_rdma_disable(priv);
+		bcmgenet_intr_disable(priv);
+		bcmgenet_fini_dma(priv);
+		enable_irq(priv->irq1);
+	}
+
 	init_umac(priv);
 
 	phy_init_hw(dev->phydev);
@@ -4194,19 +4231,52 @@ static int bcmgenet_suspend(struct device *d)
 {
 	struct net_device *dev = dev_get_drvdata(d);
 	struct bcmgenet_priv *priv = netdev_priv(dev);
+	struct bcmgenet_rxnfc_rule *rule;
+	u32 reg, hfb_enable = 0;
 
 	if (!netif_running(dev))
 		return 0;
 
 	netif_device_detach(dev);
 
-	bcmgenet_netif_stop(dev, true);
+	if (device_may_wakeup(d) && priv->wolopts) {
+		netif_tx_disable(dev);
+
+		/* Suspend non-wake Rx data flows */
+		if (priv->wolopts & WAKE_FILTER)
+			list_for_each_entry(rule, &priv->rxnfc_list, list)
+				if (rule->fs.ring_cookie == RX_CLS_FLOW_WAKE &&
+				    rule->state == BCMGENET_RXNFC_STATE_ENABLED)
+					hfb_enable |= 1 << rule->fs.location;
+		reg = bcmgenet_hfb_reg_readl(priv, HFB_CTRL);
+		if (GENET_IS_V1(priv) || GENET_IS_V2(priv)) {
+			reg &= ~RBUF_HFB_FILTER_EN_MASK;
+			reg |= hfb_enable << (RBUF_HFB_FILTER_EN_SHIFT + 1);
+		} else {
+			bcmgenet_hfb_reg_writel(priv, hfb_enable << 1,
+						HFB_FLT_ENABLE_V3PLUS + 4);
+		}
+		if (!hfb_enable)
+			reg &= ~RBUF_HFB_EN;
+		bcmgenet_hfb_reg_writel(priv, reg, HFB_CTRL);
+
+		/* Clear any old filter matches so only new matches wake */
+		bcmgenet_intrl2_0_writel(priv, 0xFFFFFFFF, INTRL2_CPU_MASK_SET);
+		bcmgenet_intrl2_0_writel(priv, 0xFFFFFFFF, INTRL2_CPU_CLEAR);
 
-	if (!device_may_wakeup(d))
-		phy_suspend(dev->phydev);
+		if (-ETIMEDOUT == bcmgenet_tdma_disable(priv))
+			netdev_warn(priv->dev,
+				    "Timed out while disabling TX DMA\n");
 
-	/* Disable filtering */
-	bcmgenet_hfb_reg_writel(priv, 0, HFB_CTRL);
+		bcmgenet_disable_tx_napi(priv);
+		bcmgenet_disable_rx_napi(priv);
+		disable_irq(priv->irq1);
+		bcmgenet_tx_reclaim_all(dev);
+		bcmgenet_fini_tx_napi(priv);
+	} else {
+		/* Teardown the interface */
+		bcmgenet_netif_stop(dev, true);
+	}
 
 	return 0;
 }
drivers/net/ethernet/broadcom/genet/bcmgenet.h +2 -0
index 532a4ea04c6e6..4f18193a6bd09 100644
@@ -295,6 +295,8 @@ struct bcmgenet_rx_stats64 {
 /* Only valid for GENETv3+ */
 #define UMAC_IRQ_MDIO_DONE		(1 << 23)
 #define UMAC_IRQ_MDIO_ERROR		(1 << 24)
+#define UMAC_IRQ_MDIO_EVENT		(UMAC_IRQ_MDIO_DONE | \
+					 UMAC_IRQ_MDIO_ERROR)
 
 /* INTRL2 instance 1 definitions */
 #define UMAC_IRQ1_TX_INTR_MASK		0xFFFF
drivers/net/ethernet/broadcom/genet/bcmgenet_wol.c +32 -37

129 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#1680 lore raw

PATCH 1650/1756 net: bcmgenet: recover from a failed resume

In reply to Greg Kroah-Hartman

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

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

From: Nicolai Buchwitz <[email protected]>

[ Upstream commit 1c1f51c3ee9ccf86462e36548291ed44fecd5355 ]

A resume that fails in bcmgenet_init_dma() returns with the interface still IFF_UP and the datapath gone. The next ifdown runs the teardown a second time and napi_disable() waits for a NAPI_STATE_SCHED bit that nothing will clear:

task:ip state:D

    usleep_range_state+0xec/0x158
    napi_disable_locked+0x254/0x318
    napi_disable+0x3c/0x68
    bcmgenet_netif_stop+0x1c8/0x318
    bcmgenet_close+0x24/0xd0
    __dev_close_many+0x18c/0x310

RTNL is held across the wait, so everything else blocks behind it.

The same resume gates the clock and detaches the device. Close releases the clock a second time and ifup fails with -ENODEV. The hardware filters stay armed, so the next WoL suspend wakes on any frame. That suspend sets CMD_RX_EN for magic packet detection, so the WoL resume reuses rings that are gone.

A failed resume should leave a state the ordinary paths can handle. Clear rx_cbs and tx_cbs as they are freed so they answer whether a datapath exists, and leave the clock alone so close and suspend release it once. The WoL resume rebuilds instead, so stop the PHY first, phy_start() only takes PHY_READY or PHY_HALTED.

Flagged in a sashiko review and reproduced on a CM4 by forcing the resume allocation to fail.

Fixes b6e978e50444 ("net: bcmgenet: add suspend/resume callbacks")
Fixes 254f3239dd07 ("net: bcmgenet: revise suspend/resume") # for the WoL parts
---
 .../net/ethernet/broadcom/genet/bcmgenet.c    | 92 +++++++++++++------
 1 file changed, 62 insertions(+), 30 deletions(-)
drivers/net/ethernet/broadcom/genet/bcmgenet.c +62 -30
index 9280f94641d74..608dd03c6fe69 100644
@@ -2991,7 +2991,9 @@ static void bcmgenet_fini_dma(struct bcmgenet_priv *priv)
 
 	bcmgenet_free_rx_buffers(priv);
 	kfree(priv->rx_cbs);
+	priv->rx_cbs = NULL;
 	kfree(priv->tx_cbs);
+	priv->tx_cbs = NULL;
 }
 
 /* init_edma: Initialize DMA control register */
@@ -3051,6 +3053,7 @@ static int bcmgenet_init_dma(struct bcmgenet_priv *priv, bool flush_rx)
 			       GFP_KERNEL);
 	if (!priv->tx_cbs) {
 		kfree(priv->rx_cbs);
+		priv->rx_cbs = NULL;
 		return -ENOMEM;
 	}
 
@@ -3069,7 +3072,9 @@ static int bcmgenet_init_dma(struct bcmgenet_priv *priv, bool flush_rx)
 		netdev_err(priv->dev, "failed to initialize Rx queues\n");
 		bcmgenet_free_rx_buffers(priv);
 		kfree(priv->rx_cbs);
+		priv->rx_cbs = NULL;
 		kfree(priv->tx_cbs);
+		priv->tx_cbs = NULL;
 		return ret;
 	}
 
@@ -3377,7 +3382,9 @@ static int bcmgenet_close(struct net_device *dev)
 
 	netif_dbg(priv, ifdown, dev, "bcmgenet_close\n");
 
-	bcmgenet_netif_stop(dev, false);
+	/* A failed resume has torn the datapath down already */
+	if (priv->tx_cbs)
+		bcmgenet_netif_stop(dev, false);
 
 	/* Really kill the PHY state machine and disconnect from it */
 	phy_disconnect(dev->phydev);
@@ -3385,6 +3392,9 @@ static int bcmgenet_close(struct net_device *dev)
 	free_irq(priv->irq0, priv);
 	free_irq(priv->irq1, priv);
 
+	/* A failed resume left the device detached, __dev_open() refuses that */
+	netif_device_attach(dev);
+
 	if (priv->internal_phy)
 		ret = bcmgenet_power_down(priv, GENET_POWER_PASSIVE);
 
@@ -4152,7 +4162,11 @@ static int bcmgenet_resume(struct device *d)
 
 	if (device_may_wakeup(d) && priv->wolopts) {
 		reg = bcmgenet_umac_readl(priv, UMAC_CMD);
-		if (reg & CMD_RX_EN) {
+
+		/* The WoL power down sets CMD_RX_EN itself, so the bit
+		 * alone does not mean the rings survived
+		 */
+		if (priv->tx_cbs && (reg & CMD_RX_EN)) {
 			/* Successfully exited WoL, just resume data flows */
 			list_for_each_entry(rule, &priv->rxnfc_list, list)
 				if (rule->state == BCMGENET_RXNFC_STATE_ENABLED)
@@ -4182,6 +4196,9 @@ static int bcmgenet_resume(struct device *d)
 		bcmgenet_rdma_disable(priv);
 		bcmgenet_intr_disable(priv);
 		bcmgenet_fini_dma(priv);
+		if (phy_is_started(dev->phydev) ||
+		    dev->phydev->state == PHY_ERROR)
+			phy_stop(dev->phydev);
 		enable_irq(priv->irq1);
 	}
 
@@ -4207,8 +4224,9 @@ static int bcmgenet_resume(struct device *d)
 	/* Reinitialize TDMA and RDMA and SW housekeeping */
 	ret = bcmgenet_init_dma(priv, false);
 	if (ret) {
+		/* Leave the block clocked, close and suspend tear it down */
 		netdev_err(dev, "failed to initialize DMA\n");
-		goto out_clk_disable;
+		return ret;
 	}
 
 	if (!device_may_wakeup(d))
@@ -4219,50 +4237,64 @@ static int bcmgenet_resume(struct device *d)
 	netif_device_attach(dev);
 
 	return 0;
+}
 
-out_clk_disable:
-	if (priv->internal_phy)
-		bcmgenet_power_down(priv, GENET_POWER_PASSIVE);
-	clk_disable_unprepare(priv->clk);
-	return ret;
+/* Arm the configured wake filters and drop the rest, then clear old
+ * matches so that only a new one wakes the system
+ */
+static void bcmgenet_wol_arm_filters(struct bcmgenet_priv *priv)
+{
+	struct bcmgenet_rxnfc_rule *rule;
+	u32 reg, hfb_enable = 0;
+
+	if (priv->wolopts & WAKE_FILTER)
+		list_for_each_entry(rule, &priv->rxnfc_list, list)
+			if (rule->fs.ring_cookie == RX_CLS_FLOW_WAKE &&
+			    rule->state == BCMGENET_RXNFC_STATE_ENABLED)
+				hfb_enable |= 1 << rule->fs.location;
+
+	reg = bcmgenet_hfb_reg_readl(priv, HFB_CTRL);
+	if (GENET_IS_V1(priv) || GENET_IS_V2(priv)) {
+		reg &= ~RBUF_HFB_FILTER_EN_MASK;
+		reg |= hfb_enable << (RBUF_HFB_FILTER_EN_SHIFT + 1);
+	} else {
+		bcmgenet_hfb_reg_writel(priv, hfb_enable << 1,
+					HFB_FLT_ENABLE_V3PLUS + 4);
+	}
+	if (!hfb_enable)
+		reg &= ~RBUF_HFB_EN;
+	bcmgenet_hfb_reg_writel(priv, reg, HFB_CTRL);
+
+	bcmgenet_intrl2_0_writel(priv, 0xFFFFFFFF, INTRL2_CPU_MASK_SET);
+	bcmgenet_intrl2_0_writel(priv, 0xFFFFFFFF, INTRL2_CPU_CLEAR);
 }
 
 static int bcmgenet_suspend(struct device *d)
 {
 	struct net_device *dev = dev_get_drvdata(d);
 	struct bcmgenet_priv *priv = netdev_priv(dev);
-	struct bcmgenet_rxnfc_rule *rule;
-	u32 reg, hfb_enable = 0;
 
 	if (!netif_running(dev))
 		return 0;
 
+	/* A failed resume has torn the datapath down already. Resume still
+	 * enables irq1 on the WoL path, so it has to be disabled here.
+	 */
+	if (!priv->tx_cbs) {
+		if (device_may_wakeup(d) && priv->wolopts) {
+			bcmgenet_wol_arm_filters(priv);
+			disable_irq(priv->irq1);
+		}
+		return 0;
+	}
+
 	netif_device_detach(dev);
 
 	if (device_may_wakeup(d) && priv->wolopts) {
 		netif_tx_disable(dev);
 
 		/* Suspend non-wake Rx data flows */
-		if (priv->wolopts & WAKE_FILTER)
-			list_for_each_entry(rule, &priv->rxnfc_list, list)
-				if (rule->fs.ring_cookie == RX_CLS_FLOW_WAKE &&
-				    rule->state == BCMGENET_RXNFC_STATE_ENABLED)
-					hfb_enable |= 1 << rule->fs.location;
-		reg = bcmgenet_hfb_reg_readl(priv, HFB_CTRL);
-		if (GENET_IS_V1(priv) || GENET_IS_V2(priv)) {
-			reg &= ~RBUF_HFB_FILTER_EN_MASK;
-			reg |= hfb_enable << (RBUF_HFB_FILTER_EN_SHIFT + 1);
-		} else {
-			bcmgenet_hfb_reg_writel(priv, hfb_enable << 1,
-						HFB_FLT_ENABLE_V3PLUS + 4);
-		}
-		if (!hfb_enable)
-			reg &= ~RBUF_HFB_EN;
-		bcmgenet_hfb_reg_writel(priv, reg, HFB_CTRL);
-
-		/* Clear any old filter matches so only new matches wake */
-		bcmgenet_intrl2_0_writel(priv, 0xFFFFFFFF, INTRL2_CPU_MASK_SET);
-		bcmgenet_intrl2_0_writel(priv, 0xFFFFFFFF, INTRL2_CPU_CLEAR);
+		bcmgenet_wol_arm_filters(priv);
 
 		if (-ETIMEDOUT == bcmgenet_tdma_disable(priv))
 			netdev_warn(priv->dev,
Signature · 1 line
2.53.0
author maintainer
#1681 lore raw

PATCH 1651/1756 net: bcmgenet: restore the Tx coalescing setting when the rings are rebuilt

In reply to Greg Kroah-Hartman

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

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

From: Nicolai Buchwitz <[email protected]>

[ Upstream commit ff8a7c0c06762a2a2333fbd6148d637bbd3d5090 ]

bcmgenet_set_coalesce() writes tx_max_coalesced_frames straight into DMA_MBUF_DONE_THRESH and keeps no copy of it, while bcmgenet_init_tx_ring() programs a fixed 1. An ifdown and ifup or a resume then puts the Tx coalescing back to one frame per interrupt.

Rx keeps its value per ring and reapplies it on init. Do the same for Tx.

---
 drivers/net/ethernet/broadcom/genet/bcmgenet.c | 10 ++++++++--
 drivers/net/ethernet/broadcom/genet/bcmgenet.h |  1 +
 2 files changed, 9 insertions(+), 2 deletions(-)
drivers/net/ethernet/broadcom/genet/bcmgenet.c +8 -2
index 608dd03c6fe69..8be9b18ed7fa1 100644
@@ -895,10 +895,13 @@ static int bcmgenet_set_coalesce(struct net_device *dev,
 	/* Program all TX queues with the same values, as there is no
 	 * ethtool knob to do coalescing on a per-queue basis
 	 */
-	for (i = 0; i <= priv->hw_params->tx_queues; i++)
+	for (i = 0; i <= priv->hw_params->tx_queues; i++) {
+		priv->tx_rings[i].tx_max_coalesced_frames =
+			ec->tx_max_coalesced_frames;
 		bcmgenet_tdma_ring_writel(priv, i,
 					  ec->tx_max_coalesced_frames,
 					  DMA_MBUF_DONE_THRESH);
+	}
 
 	for (i = 0; i <= priv->hw_params->rx_queues; i++)
 		bcmgenet_set_ring_rx_coalesce(&priv->rx_rings[i], ec);
@@ -2682,7 +2685,8 @@ static void bcmgenet_init_tx_ring(struct bcmgenet_priv *priv,
 
 	bcmgenet_tdma_ring_writel(priv, index, 0, TDMA_PROD_INDEX);
 	bcmgenet_tdma_ring_writel(priv, index, 0, TDMA_CONS_INDEX);
-	bcmgenet_tdma_ring_writel(priv, index, 1, DMA_MBUF_DONE_THRESH);
+	bcmgenet_tdma_ring_writel(priv, index, ring->tx_max_coalesced_frames,
+				  DMA_MBUF_DONE_THRESH);
 	/* Disable rate control for now */
 	bcmgenet_tdma_ring_writel(priv, index, flow_period_val,
 				  TDMA_FLOW_PERIOD);
@@ -4060,6 +4064,8 @@ static int bcmgenet_probe(struct platform_device *pdev)
 		priv->rx_rings[i].index = i;
 		priv->rx_rings[i].rx_max_coalesced_frames = 1;
 	}
+	for (i = 0; i <= priv->hw_params->tx_queues; i++)
+		priv->tx_rings[i].tx_max_coalesced_frames = 1;
 
 	/* Initialize u64 stats seq counter for 32bit machines */
 	for (i = 0; i <= GENET_MAX_MQ_CNT; i++) {
drivers/net/ethernet/broadcom/genet/bcmgenet.h +1 -0
index 4f18193a6bd09..46d1a9340f154 100644
@@ -547,6 +547,7 @@ struct bcmgenet_tx_ring {
 	unsigned int	prod_index;	/* Tx ring producer index SW copy */
 	unsigned int	cb_ptr;		/* Tx ring initial CB ptr */
 	unsigned int	end_ptr;	/* Tx ring end CB ptr */
+	unsigned int	tx_max_coalesced_frames;
 	struct bcmgenet_priv *priv;
 };
 
Signature · 1 line
2.53.0
author maintainer
#1682 lore raw

PATCH 1652/1756 net: dcb: initialize PFC value before calling getpfccfg

In reply to Greg Kroah-Hartman

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

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

From: Joas Antonio dos Santos <[email protected]>

[ Upstream commit ca87a2dffbb550fc934647d5e8d1c4ae85590132 ]

dcbnl_getpfccfg() and dcbnl_cee_fill() pass the address of an uninitialized stack u8 to the driver's getpfccfg() op and then put it into the netlink reply unconditionally. The op returns void, so the core cannot tell whether the driver wrote the value.

i40e_dcbnl_get_pfc_cfg() and ice_dcbnl_get_pfc_cfg() return without writing *setting unless the DCBX agent is host managed and in CEE mode. Both drivers normally run with firmware managed DCBX (DCB_CAP_DCBX_LLD_MANAGED), and i40e with FW LLDP disabled runs host managed in IEEE mode, so on a DCB capable i40e/ice port the PFC values in DCB_CMD_PFC_GCFG and DCB_CMD_CEE_GET replies, and in the CEE part of RTNLGRP_DCB notifications, come from uninitialized stack. The same u8 is reused for all eight priorities, so this is one byte per reply.

dcb_doit() only requires CAP_NET_ADMIN for RTM_SETDCB, so the GET commands are available to unprivileged users.

Set the value to 0 before each call, like the PG config path already presets its outputs to DCB_ATTR_VALUE_UNDEFINED. 0 is also what the reply contains today on kernels built with CONFIG_INIT_STACK_ALL_ZERO, so nothing changes for those.

Found by code inspection, compile-tested only (W=1). I don't have i40e/ice hardware to check the reply.

Fixes b94b013eb626 ("ice: Implement DCBNL support")
Fixes 5effa78e7c94 ("i40e: Add netlink callbacks support for software based DCB")
---
 net/dcb/dcbnl.c | 2 ++
 1 file changed, 2 insertions(+)
net/dcb/dcbnl.c +2 -0
index 2e6b8c8fd2ded..1d82a9cbc2c4c 100644
@@ -281,6 +281,7 @@ static int dcbnl_getpfccfg(struct net_device *netdev, struct nlmsghdr *nlh,
 		if (!getall && !data[i])
 			continue;
 
+		value = 0;
 		netdev->dcbnl_ops->getpfccfg(netdev, i - DCB_PFC_UP_ATTR_0,
 		                             &value);
 		ret = nla_put_u8(skb, i, value);
@@ -1396,6 +1397,7 @@ static int dcbnl_cee_fill(struct sk_buff *skb, struct net_device *netdev)
 			goto nla_put_failure;
 
 		for (i = DCB_PFC_UP_ATTR_0; i <= DCB_PFC_UP_ATTR_7; i++) {
+			value = 0;
 			ops->getpfccfg(netdev, i - DCB_PFC_UP_ATTR_0, &value);
 			if (nla_put_u8(skb, i, value))
 				goto nla_put_failure;
Signature · 1 line
2.53.0
author maintainer
#1683 lore raw

PATCH 1653/1756 ice: set in_use only after preparing Tx timestamp index

In reply to Greg Kroah-Hartman

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

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

From: Jacob Keller <[email protected]>

[ Upstream commit 50870d62116038e6f1e17a6aedcf2a95cec37ec7 ]

The ice_ptp_request_ts() function is used to request a timestamp index for use with a packet. When reserving an index, it sets the start time and saves a pointer to the skb into the appropriate index. The function marks the in_use bit first before doing any of these steps. The IRQ handler which clears the timestamps reads the in_use bits uses a lockless flow for reading the in_use bits to determine which ones are in-use. This is necessary as actually processing a complete timestamp must be able to sleep so we cannot hold the timestamp tracker lock over the entire sequence. Additionally, blocking the Tx hotpath with such a lock indefinitely would be problematic.

However, the existing flow now has a very narrow window where the IRQ handler could see a timestamp as in-use but read a stale value for its "start" time.

Fix this by ordering the sequence to mark the in_use bit last, and add a memory barrier to prevent re-ordering of the previous writes to setup the index.

This was found and reported by Sashiko while reviewing an unrelated change.

---
 drivers/net/ethernet/intel/ice/ice_ptp.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
drivers/net/ethernet/intel/ice/ice_ptp.c +10 -2
index f0dab91ce831e..9587b807e6648 100644
@@ -724,6 +724,12 @@ static void ice_ptp_process_tx_tstamp(struct ice_ptp_tx *tx)
 		bool drop_ts = !link_up;
 		struct sk_buff *skb;
 
+		/* Paired with smp_mb__before_atomic() in ice_ptp_request_ts()
+		 * to ensure ordering the in_use bitmap and the indexed fields
+		 * in the tstamps array.
+		 */
+		smp_rmb();
+
 		/* Drop packets which have waited for more than 2 seconds */
 		if (time_is_before_jiffies(tx->tstamps[idx].start + 2 * HZ)) {
 			drop_ts = true;
@@ -2642,11 +2648,13 @@ s8 ice_ptp_request_ts(struct ice_ptp_tx *tx, struct sk_buff *skb)
 		 * a reference to the skb and the start time to allow discarding old
 		 * requests.
 		 */
-		set_bit(idx, tx->in_use);
-		clear_bit(idx, tx->stale);
 		tx->tstamps[idx].start = jiffies;
 		tx->tstamps[idx].skb = skb_get(skb);
 		skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS;
+		clear_bit(idx, tx->stale);
+		/* Ensure index is setup before marking it as used */
+		smp_mb__before_atomic();
+		set_bit(idx, tx->in_use);
 		ice_trace(tx_tstamp_request, skb, idx);
 	}
 
Signature · 1 line
2.53.0
author maintainer
#1684 lore raw

PATCH 1654/1756 ice: E822: keep Tx timestamps disabled during offset calibration

In reply to Greg Kroah-Hartman

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

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

From: Karol Kolacinski <[email protected]>

[ Upstream commit 56af436b90acce7eaa7531189c827773983f7d07 ]

Do not clear the tx.calibrating flag immediately after starting the PHY timer in ice_ptp_port_phy_restart(). Instead, keep Tx timestamps disabled until the offset verification work (ice_ptp_wait_for_offsets) has confirmed that the Tx PHY offset is properly configured.

Previously, tx.calibrating was set to true, then immediately back to false right after ice_start_phy_timer_e82x() returned. This allowed Tx timestamp requests to be served during the window where offset verification was still pending. Timestamps produced during this window should have their valid bit cleared, but it is better to prevent requests until the driver has confirmed calibration is complete.

Rename the tx.calibrating field to tx.disabled, and change where it is cleared. Only clear it in ice_ptp_wait_for_offsets(), and only after Tx offset configuration has completed successfully. This ensures that new Tx timestamp requests are only accepted after the PHY has properly calibrated the Tx offset.

If ice_start_phy_timer_e82x() fails, do not restore disabled to false. The device is in a state where timestamps cannot succeed properly anyways. A dev_err message is already logged on failure to start the timer at the end of the function.

Renaming the field improves clarity and will better reflect the nature of the flag in a future change that also applies disabling Tx timestamps in software in a following commit.

Log a debug message while offset calibration is still pending, including the specific Tx/Rx error codes to aid debugging stalled calibration. This path is expected on every routine link-up: ov_work is first queued with no delay and the vernier offset cannot be computed until at least one packet has been transmitted, so the first several invocations normally land here. Use dev_dbg() rather than a rate-limited warning to avoid emitting KERN_WARNING on every link-up during normal operation. Log a debug message when calibration completes successfully.

Note that sashiko review has previously complained that leaving the disabled flag set "permanently" disables Tx timestamps if vernier calibration never completes. This is true, but its important to realize that timestamps would still fail regardless of whether the flag is set. Until vernier calibration completes the device will not report valid timestamps regardless. Thus, keeping the calibrating flag set simply prevents new timestamp requests from software while it is known that the hardware will not complete them.

---
 drivers/net/ethernet/intel/ice/ice_ptp.c | 37 +++++++++++++++++-------
 drivers/net/ethernet/intel/ice/ice_ptp.h |  6 ++--
 2 files changed, 29 insertions(+), 14 deletions(-)
drivers/net/ethernet/intel/ice/ice_ptp.c +26 -11
index 9587b807e6648..1d0e8d5fccb6b 100644
@@ -532,7 +532,7 @@ ice_ptp_is_tx_tracker_up(struct ice_ptp_tx *tx)
 {
 	lockdep_assert_held(&tx->lock);
 
-	return tx->init && !tx->calibrating;
+	return tx->init && !tx->disabled;
 }
 
 /**
@@ -1334,6 +1334,7 @@ static int ice_ptp_check_tx_fifo(struct ice_ptp_port *port)
 static void ice_ptp_wait_for_offsets(struct kthread_work *work)
 {
 	struct ice_ptp_port *port;
+	unsigned long flags;
 	struct ice_pf *pf;
 	struct ice_hw *hw;
 	int tx_err;
@@ -1354,9 +1355,26 @@ static void ice_ptp_wait_for_offsets(struct kthread_work *work)
 	tx_err = ice_ptp_check_tx_fifo(port);
 	if (!tx_err)
 		tx_err = ice_phy_cfg_tx_offset_e82x(hw, port->port_num);
+	if (!tx_err) {
+		/* Tx offset has been configured, re-enable Tx timestamps */
+		spin_lock_irqsave(&port->tx.lock, flags);
+		if (port->tx.disabled) {
+			port->tx.disabled = false;
+			dev_dbg(ice_pf_to_dev(pf), "PTP Tx offset valid for port %u, Tx timestamps enabled\n",
+				port->port_num);
+		}
+		spin_unlock_irqrestore(&port->tx.lock, flags);
+	}
+
 	rx_err = ice_phy_cfg_rx_offset_e82x(hw, port->port_num);
 	if (tx_err || rx_err) {
-		/* Tx and/or Rx offset not yet configured, try again later */
+		/* Tx and/or Rx offset not yet configured, try again later.
+		 * This is expected during normal link-up: the vernier offset
+		 * calibration cannot complete until at least one packet has
+		 * been transmitted, so the first retries routinely land here.
+		 */
+		dev_dbg(ice_pf_to_dev(pf), "PTP offset not yet valid for port %u (tx_err=%d rx_err=%d)\n",
+			port->port_num, tx_err, rx_err);
 		kthread_queue_delayed_work(pf->ptp.kworker,
 					   &port->ov_work,
 					   msecs_to_jiffies(100));
@@ -1435,11 +1453,9 @@ ice_ptp_port_phy_restart(struct ice_ptp_port *ptp_port)
 		/* Start the PHY timer in Vernier mode */
 		kthread_cancel_delayed_work_sync(&ptp_port->ov_work);
 
-		/* temporarily disable Tx timestamps while calibrating
-		 * PHY offset
-		 */
+		/* Disable Tx timestamps until PHY calibration completes */
 		spin_lock_irqsave(&ptp_port->tx.lock, flags);
-		ptp_port->tx.calibrating = true;
+		ptp_port->tx.disabled = true;
 		spin_unlock_irqrestore(&ptp_port->tx.lock, flags);
 		ptp_port->tx_fifo_busy_cnt = 0;
 
@@ -1448,11 +1464,10 @@ ice_ptp_port_phy_restart(struct ice_ptp_port *ptp_port)
 		if (err)
 			break;
 
-		/* Enable Tx timestamps right away */
-		spin_lock_irqsave(&ptp_port->tx.lock, flags);
-		ptp_port->tx.calibrating = false;
-		spin_unlock_irqrestore(&ptp_port->tx.lock, flags);
-
+		/* Do not clear disabled flag here. Tx timestamp requests
+		 * remain disabled until ice_ptp_wait_for_offsets() has
+		 * verified that the Tx offset calibration has completed.
+		 */
 		kthread_queue_delayed_work(pf->ptp.kworker, &ptp_port->ov_work,
 					   0);
 		break;
drivers/net/ethernet/intel/ice/ice_ptp.h +3 -3
index ccc1eeb16f0e8..5842fdadf0942 100644
@@ -135,8 +135,8 @@ enum ice_tx_tstamp_work {
  * @offset: offset into timestamp block to get the real index
  * @len: length of the tstamps and in_use fields.
  * @init: if true, the tracker is initialized;
- * @calibrating: if true, the PHY is calibrating the Tx offset. During this
- *               window, timestamps are temporarily disabled.
+ * @disabled: set to true when new Tx timestamp requests are disabled, such as
+ *            while the PHY Tx offset configuration has not yet completed.
  * @has_ready_bitmap: if true, the hardware has a valid Tx timestamp ready
  *                    bitmap register. If false, fall back to verifying new
  *                    timestamp values against previously cached copy.
@@ -151,7 +151,7 @@ struct ice_ptp_tx {
 	u8 offset;
 	u8 len;
 	u8 init : 1;
-	u8 calibrating : 1;
+	u8 disabled : 1;
 	u8 has_ready_bitmap : 1;
 	s8 last_ll_ts_idx_read;
 };
Signature · 1 line
2.53.0
author maintainer
#1685 lore raw

PATCH 1655/1756 bridge: No DEV_PATH_BR_VLAN_UNTAG_HW for dsa foreign

In reply to Greg Kroah-Hartman

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

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

From: Eric Woudstra <[email protected]>

[ Upstream commit 96450df197bda7de927b51372c13f1002d0e76e3 ]

In network setup as below:

fastpath bypass
.----------------------------------------.
/ \

|                        IP - forwarding    |
|                       /                \  v
|                      /                  wan ...
|                     /
|                     |
|                     |
|                   brlan.1
|                     |
|    +-------------------------------+
|    |           vlan 1              |
|    |                               |
|    |     brlan (vlan-filtering)    |
|    |               +---------------+
|    |               |  DSA-SWITCH   |
|    |    vlan 1     |               |
|    |      to       |               |
|    |   untagged    1     vlan 1    |
|    +---------------+---------------+
.         /                   \
 ----->wlan1                 lan0
       .                       .
       .                       ^
       ^                     vlan 1 tagged packets

untagged packets

br_vlan_fill_forward_path_mode() sets DEV_PATH_BR_VLAN_UNTAG_HW when filling in from brlan.1 towards wlan1. But it should be set to DEV_PATH_BR_VLAN_UNTAG in this case. Using BR_VLFLAG_ADDED_BY_SWITCHDEV is not correct. The dsa switchdev adds it as a foreign port.

The same problem for all foreignly added dsa vlans on the bridge.

First add the vlan, trying only native devices.
If this fails, we know this may be a vlan from a foreign device.

Use BR_VLFLAG_TAGGING_BY_SWITCHDEV to make sure DEV_PATH_BR_VLAN_UNTAG_HW is set only when there if no foreign device involved.

Stable-dep-of: fcc00b15cb21 ("net: bridge: netlink: do not clear the vlan info dump error")

---
 include/net/switchdev.h   |  1 +
 net/bridge/br_private.h   | 10 ++++++++++
 net/bridge/br_switchdev.c | 15 +++++++++++++++
 net/bridge/br_vlan.c      |  7 ++++++-
 net/switchdev/switchdev.c |  2 +-
 5 files changed, 33 insertions(+), 2 deletions(-)
include/net/switchdev.h +1 -0
index 8346b0d29542c..ee500706496b0 100644
@@ -15,6 +15,7 @@
 #define SWITCHDEV_F_NO_RECURSE		BIT(0)
 #define SWITCHDEV_F_SKIP_EOPNOTSUPP	BIT(1)
 #define SWITCHDEV_F_DEFER		BIT(2)
+#define SWITCHDEV_F_NO_FOREIGN		BIT(3)
 
 enum switchdev_attr_id {
 	SWITCHDEV_ATTR_ID_UNDEFINED,
net/bridge/br_private.h +10 -0
index d8e991df20643..22bd82aaca73f 100644
@@ -182,6 +182,7 @@ enum {
 	BR_VLFLAG_MCAST_ENABLED = BIT(2),
 	BR_VLFLAG_GLOBAL_MCAST_ENABLED = BIT(3),
 	BR_VLFLAG_NEIGH_SUPPRESS_ENABLED = BIT(4),
+	BR_VLFLAG_TAGGING_BY_SWITCHDEV = BIT(5),
 };
 
 /**
@@ -2199,6 +2200,8 @@ void br_switchdev_mdb_notify(struct net_device *dev,
 			     int type);
 int br_switchdev_port_vlan_add(struct net_device *dev, u16 vid, u16 flags,
 			       bool changed, struct netlink_ext_ack *extack);
+int br_switchdev_port_vlan_no_foreign_add(struct net_device *dev, u16 vid, u16 flags,
+					  bool changed, struct netlink_ext_ack *extack);
 int br_switchdev_port_vlan_del(struct net_device *dev, u16 vid);
 void br_switchdev_init(struct net_bridge *br);
 
@@ -2282,6 +2285,13 @@ static inline int br_switchdev_port_vlan_add(struct net_device *dev, u16 vid,
 	return -EOPNOTSUPP;
 }
 
+static inline int br_switchdev_port_vlan_no_foreign_add(struct net_device *dev, u16 vid,
+							u16 flags, bool changed,
+							struct netlink_ext_ack *extack)
+{
+	return -EOPNOTSUPP;
+}
+
 static inline int br_switchdev_port_vlan_del(struct net_device *dev, u16 vid)
 {
 	return -EOPNOTSUPP;
net/bridge/br_switchdev.c +15 -0
index f10bd6a233dcf..40bb8e6989137 100644
@@ -190,6 +190,21 @@ int br_switchdev_port_vlan_add(struct net_device *dev, u16 vid, u16 flags,
 	return switchdev_port_obj_add(dev, &v.obj, extack);
 }
 
+int br_switchdev_port_vlan_no_foreign_add(struct net_device *dev, u16 vid, u16 flags,
+					  bool changed, struct netlink_ext_ack *extack)
+{
+	struct switchdev_obj_port_vlan v = {
+		.obj.orig_dev = dev,
+		.obj.id = SWITCHDEV_OBJ_ID_PORT_VLAN,
+		.obj.flags = SWITCHDEV_F_NO_FOREIGN,
+		.flags = flags,
+		.vid = vid,
+		.changed = changed,
+	};
+
+	return switchdev_port_obj_add(dev, &v.obj, extack);
+}
+
 int br_switchdev_port_vlan_del(struct net_device *dev, u16 vid)
 {
 	struct switchdev_obj_port_vlan v = {
net/bridge/br_vlan.c +6 -1
index a61211a09e1e8..234d36ced4bc0 100644
@@ -109,6 +109,11 @@ static int __vlan_vid_add(struct net_device *dev, struct net_bridge *br,
 	/* Try switchdev op first. In case it is not supported, fallback to
 	 * 8021q add.
 	 */
+	err = br_switchdev_port_vlan_no_foreign_add(dev, v->vid, flags, false, extack);
+	if (err != -EOPNOTSUPP) {
+		v->priv_flags |= BR_VLFLAG_ADDED_BY_SWITCHDEV | BR_VLFLAG_TAGGING_BY_SWITCHDEV;
+		return err;
+	}
 	err = br_switchdev_port_vlan_add(dev, v->vid, flags, false, extack);
 	if (err == -EOPNOTSUPP)
 		return vlan_vid_add(dev, br->vlan_proto, v->vid);
@@ -1489,7 +1494,7 @@ int br_vlan_fill_forward_path_mode(struct net_bridge *br,
 
 	if (path->bridge.vlan_mode == DEV_PATH_BR_VLAN_TAG)
 		path->bridge.vlan_mode = DEV_PATH_BR_VLAN_KEEP;
-	else if (v->priv_flags & BR_VLFLAG_ADDED_BY_SWITCHDEV)
+	else if (v->priv_flags & BR_VLFLAG_TAGGING_BY_SWITCHDEV)
 		path->bridge.vlan_mode = DEV_PATH_BR_VLAN_UNTAG_HW;
 	else
 		path->bridge.vlan_mode = DEV_PATH_BR_VLAN_UNTAG;
net/switchdev/switchdev.c +1 -1
index 4d5fbacef496f..bf252d116ed38 100644
@@ -760,7 +760,7 @@ static int __switchdev_handle_port_obj_add(struct net_device *dev,
 	/* Event is neither on a bridge nor a LAG. Check whether it is on an
 	 * interface that is in a bridge with us.
 	 */
-	if (!foreign_dev_check_cb)
+	if (!foreign_dev_check_cb || port_obj_info->obj->flags & SWITCHDEV_F_NO_FOREIGN)
 		return err;
 
 	br = netdev_master_upper_dev_get(dev);
Signature · 1 line
2.53.0
author maintainer
#1686 lore raw

PATCH 1656/1756 bridge: Add internal flags for neigh_forward_grat

In reply to Greg Kroah-Hartman

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

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

From: Danielle Ratson <[email protected]>

[ Upstream commit 3a28ccb9dd47d1b6f64c64a94c958a968299aa1d ]

Add internal flags for the neigh_forward_grat feature:

- BR_NEIGH_FORWARD_GRAT: Port-level flag
- BR_VLFLAG_NEIGH_FORWARD_GRAT_ENABLED: Per-VLAN flag

These will be used to control whether gratuitous ARP and unsolicited NA packets are forwarded when neighbor suppression is enabled.

Stable-dep-of: fcc00b15cb21 ("net: bridge: netlink: do not clear the vlan info dump error")

---
 include/linux/if_bridge.h | 1 +
 net/bridge/br_private.h   | 1 +
 2 files changed, 2 insertions(+)
include/linux/if_bridge.h +1 -0
index c5fe3b2a53e82..ec9ffea1e46ed 100644
@@ -61,6 +61,7 @@ struct br_ip_list {
 #define BR_PORT_LOCKED		BIT(21)
 #define BR_PORT_MAB		BIT(22)
 #define BR_NEIGH_VLAN_SUPPRESS	BIT(23)
+#define BR_NEIGH_FORWARD_GRAT	BIT(24)
 
 #define BR_DEFAULT_AGEING_TIME	(300 * HZ)
 
net/bridge/br_private.h +1 -0
index 22bd82aaca73f..4a7353de27981 100644
@@ -183,6 +183,7 @@ enum {
 	BR_VLFLAG_GLOBAL_MCAST_ENABLED = BIT(3),
 	BR_VLFLAG_NEIGH_SUPPRESS_ENABLED = BIT(4),
 	BR_VLFLAG_TAGGING_BY_SWITCHDEV = BIT(5),
+	BR_VLFLAG_NEIGH_FORWARD_GRAT_ENABLED = BIT(6),
 };
 
 /**
Signature · 1 line
2.53.0
author maintainer
#1687 lore raw

PATCH 1657/1756 bridge: add bridge_flags_bit enum

In reply to Greg Kroah-Hartman

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

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

From: Eric Dumazet <[email protected]>

[ Upstream commit 87020def2529ec26fc9077e889fa1c34f53f1f83 ]

We want to use atomic operations for lockless p->flags changes and reads.

Add definitions for bits in addition of masks so that we can use test_bit(), clear_bit() and set_bit() in subsequent patches.

Stable-dep-of: fcc00b15cb21 ("net: bridge: netlink: do not clear the vlan info dump error")

---
 include/linux/if_bridge.h | 78 ++++++++++++++++++++++++++-------------
 1 file changed, 53 insertions(+), 25 deletions(-)
include/linux/if_bridge.h +53 -25
index ec9ffea1e46ed..75673b8bffcb8 100644
@@ -36,32 +36,60 @@ struct br_ip_list {
 	struct br_ip addr;
 };
 
-#define BR_HAIRPIN_MODE		BIT(0)
-#define BR_BPDU_GUARD		BIT(1)
-#define BR_ROOT_BLOCK		BIT(2)
-#define BR_MULTICAST_FAST_LEAVE	BIT(3)
-#define BR_ADMIN_COST		BIT(4)
-#define BR_LEARNING		BIT(5)
-#define BR_FLOOD		BIT(6)
+enum bridge_flags_bit {
+	BR_HAIRPIN_MODE_BIT,
+	BR_BPDU_GUARD_BIT,
+	BR_ROOT_BLOCK_BIT,
+	BR_MULTICAST_FAST_LEAVE_BIT,
+	BR_ADMIN_COST_BIT,
+	BR_LEARNING_BIT,
+	BR_FLOOD_BIT,
+	BR_PROMISC_BIT,
+	BR_PROXYARP_BIT,
+	BR_LEARNING_SYNC_BIT,
+	BR_PROXYARP_WIFI_BIT,
+	BR_MCAST_FLOOD_BIT,
+	BR_MULTICAST_TO_UNICAST_BIT,
+	BR_VLAN_TUNNEL_BIT,
+	BR_BCAST_FLOOD_BIT,
+	BR_NEIGH_SUPPRESS_BIT,
+	BR_ISOLATED_BIT,
+	BR_MRP_AWARE_BIT,
+	BR_MRP_LOST_CONT_BIT,
+	BR_MRP_LOST_IN_CONT_BIT,
+	BR_TX_FWD_OFFLOAD_BIT,
+	BR_PORT_LOCKED_BIT,
+	BR_PORT_MAB_BIT,
+	BR_NEIGH_VLAN_SUPPRESS_BIT,
+	BR_NEIGH_FORWARD_GRAT_BIT,
+};
+
+#define BR_HAIRPIN_MODE		BIT(BR_HAIRPIN_MODE_BIT)
+#define BR_BPDU_GUARD		BIT(BR_BPDU_GUARD_BIT)
+#define BR_ROOT_BLOCK		BIT(BR_ROOT_BLOCK_BIT)
+#define BR_MULTICAST_FAST_LEAVE	BIT(BR_MULTICAST_FAST_LEAVE_BIT)
+#define BR_ADMIN_COST		BIT(BR_ADMIN_COST_BIT)
+#define BR_LEARNING		BIT(BR_LEARNING_BIT)
+#define BR_FLOOD		BIT(BR_FLOOD_BIT)
 #define BR_AUTO_MASK		(BR_FLOOD | BR_LEARNING)
-#define BR_PROMISC		BIT(7)
-#define BR_PROXYARP		BIT(8)
-#define BR_LEARNING_SYNC	BIT(9)
-#define BR_PROXYARP_WIFI	BIT(10)
-#define BR_MCAST_FLOOD		BIT(11)
-#define BR_MULTICAST_TO_UNICAST	BIT(12)
-#define BR_VLAN_TUNNEL		BIT(13)
-#define BR_BCAST_FLOOD		BIT(14)
-#define BR_NEIGH_SUPPRESS	BIT(15)
-#define BR_ISOLATED		BIT(16)
-#define BR_MRP_AWARE		BIT(17)
-#define BR_MRP_LOST_CONT	BIT(18)
-#define BR_MRP_LOST_IN_CONT	BIT(19)
-#define BR_TX_FWD_OFFLOAD	BIT(20)
-#define BR_PORT_LOCKED		BIT(21)
-#define BR_PORT_MAB		BIT(22)
-#define BR_NEIGH_VLAN_SUPPRESS	BIT(23)
-#define BR_NEIGH_FORWARD_GRAT	BIT(24)
+#define BR_PROMISC		BIT(BR_PROMISC_BIT)
+#define BR_PROXYARP		BIT(BR_PROXYARP_BIT)
+#define BR_LEARNING_SYNC	BIT(BR_LEARNING_SYNC_BIT)
+#define BR_PROXYARP_WIFI	BIT(BR_PROXYARP_WIFI_BIT)
+#define BR_MCAST_FLOOD		BIT(BR_MCAST_FLOOD_BIT)
+#define BR_MULTICAST_TO_UNICAST	BIT(BR_MULTICAST_TO_UNICAST_BIT)
+#define BR_VLAN_TUNNEL		BIT(BR_VLAN_TUNNEL_BIT)
+#define BR_BCAST_FLOOD		BIT(BR_BCAST_FLOOD_BIT)
+#define BR_NEIGH_SUPPRESS	BIT(BR_NEIGH_SUPPRESS_BIT)
+#define BR_ISOLATED		BIT(BR_ISOLATED_BIT)
+#define BR_MRP_AWARE		BIT(BR_MRP_AWARE_BIT)
+#define BR_MRP_LOST_CONT	BIT(BR_MRP_LOST_CONT_BIT)
+#define BR_MRP_LOST_IN_CONT	BIT(BR_MRP_LOST_IN_CONT_BIT)
+#define BR_TX_FWD_OFFLOAD	BIT(BR_TX_FWD_OFFLOAD_BIT)
+#define BR_PORT_LOCKED		BIT(BR_PORT_LOCKED_BIT)
+#define BR_PORT_MAB		BIT(BR_PORT_MAB_BIT)
+#define BR_NEIGH_VLAN_SUPPRESS	BIT(BR_NEIGH_VLAN_SUPPRESS_BIT)
+#define BR_NEIGH_FORWARD_GRAT	BIT(BR_NEIGH_FORWARD_GRAT_BIT)
 
 #define BR_DEFAULT_AGEING_TIME	(300 * HZ)
 
Signature · 1 line
2.53.0
author maintainer
#1688 lore raw

PATCH 1658/1756 net: bridge: use atomic ops to read/change p->flags (III)

In reply to Greg Kroah-Hartman

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

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

From: Eric Dumazet <[email protected]>

[ Upstream commit f76ae12b6ba3530590e151a18dca51d90c5d81d4 ]

Use test_bit(), clear_bit(), set_bit() in:

net/bridge/br_multicast.c
net/bridge/br_netlink.c
net/bridge/br_stp.c
net/bridge/br_stp_bpdu.c
net/bridge/br_switchdev.c
net/bridge/br_vlan_options.c

Stable-dep-of: fcc00b15cb21 ("net: bridge: netlink: do not clear the vlan info dump error")

---
 net/bridge/br_multicast.c    | 5 +++--
 net/bridge/br_netlink.c      | 2 +-
 net/bridge/br_stp.c          | 4 ++--
 net/bridge/br_stp_bpdu.c     | 2 +-
 net/bridge/br_switchdev.c    | 8 ++++----
 net/bridge/br_vlan_options.c | 2 +-
 6 files changed, 12 insertions(+), 11 deletions(-)
net/bridge/br_multicast.c +3 -2
index 7d1b64df94c92..5dfe4732bbeb0 100644
@@ -285,7 +285,7 @@ static bool br_port_group_equal(struct net_bridge_port_group *p,
 	if (p->key.port != port)
 		return false;
 
-	if (!(port->flags & BR_MULTICAST_TO_UNICAST))
+	if (!test_bit(BR_MULTICAST_TO_UNICAST_BIT, &port->flags))
 		return true;
 
 	return ether_addr_equal(src, p->eth_addr);
@@ -3705,7 +3705,8 @@ br_multicast_leave_group(struct net_bridge_mcast *brmctx,
 	if (!mp)
 		goto out;
 
-	if (pmctx && (pmctx->port->flags & BR_MULTICAST_FAST_LEAVE)) {
+	if (pmctx &&
+	    test_bit(BR_MULTICAST_FAST_LEAVE_BIT, &pmctx->port->flags)) {
 		struct net_bridge_port_group __rcu **pp;
 
 		for (pp = &mp->ports;
net/bridge/br_netlink.c +1 -1
index 6b97ae47f8552..deba331537fbe 100644
@@ -534,7 +534,7 @@ static int br_fill_ifinfo(struct sk_buff *skb,
 		else
 			err = br_fill_ifvlaninfo(skb, vg);
 
-		if (port && (port->flags & BR_VLAN_TUNNEL))
+		if (port && test_bit(BR_VLAN_TUNNEL_BIT, &port->flags))
 			err = br_fill_vlan_tunnel_info(skb, vg);
 		rcu_read_unlock();
 		if (err)
net/bridge/br_stp.c +2 -2
index 4cfebf5fcdf54..95484b05b6c38 100644
@@ -39,7 +39,7 @@ void br_set_state(struct net_bridge_port *p, unsigned int state)
 	/* Don't change the state of the ports if they are driven by a different
 	 * protocol.
 	 */
-	if (p->flags & BR_MRP_AWARE)
+	if (test_bit(BR_MRP_AWARE_BIT, &p->flags))
 		return;
 
 	p->state = state;
@@ -173,7 +173,7 @@ static void br_root_selection(struct net_bridge *br)
 		if (!br_should_become_root_port(p, root_port))
 			continue;
 
-		if (p->flags & BR_ROOT_BLOCK)
+		if (test_bit(BR_ROOT_BLOCK_BIT, &p->flags))
 			br_root_port_block(br, p);
 		else
 			root_port = p->port_no;
net/bridge/br_stp_bpdu.c +1 -1
index e44e448b1157b..21d092f5acbb8 100644
@@ -181,7 +181,7 @@ void br_stp_rcv(const struct stp_proto *proto, struct sk_buff *skb,
 	if (!ether_addr_equal(eth_hdr(skb)->h_dest, br->group_addr))
 		goto out;
 
-	if (p->flags & BR_BPDU_GUARD) {
+	if (test_bit(BR_BPDU_GUARD_BIT, &p->flags)) {
 		br_notice(br, "BPDU received on blocked port %u(%s)\n",
 			  (unsigned int) p->port_no, p->dev->name);
 		br_stp_disable_port(p);
net/bridge/br_switchdev.c +4 -4
index 40bb8e6989137..58ac99b08f2ec 100644
@@ -20,7 +20,7 @@ static bool nbp_switchdev_can_offload_tx_fwd(const struct net_bridge_port *p,
 	if (br_multicast_igmp_type(skb))
 		return false;
 
-	return (p->flags & BR_TX_FWD_OFFLOAD) &&
+	return test_bit(BR_TX_FWD_OFFLOAD_BIT, &p->flags) &&
 	       (p->hwdom != BR_INPUT_SKB_CB(skb)->src_hwdom);
 }
 
@@ -288,7 +288,7 @@ static int nbp_switchdev_add(struct net_bridge_port *p,
 		return err;
 
 	if (tx_fwd_offload) {
-		p->flags |= BR_TX_FWD_OFFLOAD;
+		set_bit(BR_TX_FWD_OFFLOAD_BIT, &p->flags);
 		static_branch_inc(&br_switchdev_tx_fwd_offload);
 	}
 
@@ -308,8 +308,8 @@ static void nbp_switchdev_del(struct net_bridge_port *p)
 	if (p->hwdom)
 		nbp_switchdev_hwdom_put(p);
 
-	if (p->flags & BR_TX_FWD_OFFLOAD) {
-		p->flags &= ~BR_TX_FWD_OFFLOAD;
+	if (test_bit(BR_TX_FWD_OFFLOAD_BIT, &p->flags)) {
+		clear_bit(BR_TX_FWD_OFFLOAD_BIT, &p->flags);
 		static_branch_dec(&br_switchdev_tx_fwd_offload);
 	}
 }
net/bridge/br_vlan_options.c +1 -1
index 4a736e005bad7..8025d421b457a 100644
@@ -148,7 +148,7 @@ static int br_vlan_modify_tunnel(const struct net_bridge_port *p,
 		NL_SET_ERR_MSG_MOD(extack, "Can't modify tunnel mapping of non-port vlans");
 		return -EINVAL;
 	}
-	if (!(p->flags & BR_VLAN_TUNNEL)) {
+	if (!test_bit(BR_VLAN_TUNNEL_BIT, &p->flags)) {
 		NL_SET_ERR_MSG_MOD(extack, "Port doesn't have tunnel flag set");
 		return -EINVAL;
 	}
Signature · 1 line
2.53.0
author maintainer
#1689 lore raw

PATCH 1659/1756 net: bridge: netlink: do not clear the vlan info dump error

In reply to Greg Kroah-Hartman

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

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

From: Linkui Xiao <[email protected]>

[ Upstream commit fcc00b15cb21a6de76826e5012b2c758505f5e65 ]

br_fill_ifinfo() assigns the result of br_fill_vlan_tunnel_info() over the result of br_fill_ifvlaninfo() or br_fill_ifvlaninfo_compressed() instead of only running the second helper when the first one succeeded.

When the vlan information no longer fits in the skb but the port has no vlan mapped to a tunnel dst, br_fill_vlan_tunnel_info() walks the vlan list and returns 0 without touching the skb. The -EMSGSIZE is lost, br_fill_ifinfo() completes a message whose IFLA_AF_SPEC is truncated, and the dump carries on to the next interface instead of stopping, so userspace silently sees an incomplete vlan list.

Only fill the tunnel information when the vlan information was filled successfully.

This was flagged as a pre-existing issue in the Sashiko review of the net-next series, which noted that the VLAN fill result is overwritten before it is tested (see the Link tag below). Not triggered or tested.

---
 net/bridge/br_netlink.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/bridge/br_netlink.c +1 -1
index deba331537fbe..b8fcad8e64f30 100644
@@ -534,7 +534,7 @@ static int br_fill_ifinfo(struct sk_buff *skb,
 		else
 			err = br_fill_ifvlaninfo(skb, vg);
 
-		if (port && test_bit(BR_VLAN_TUNNEL_BIT, &port->flags))
+		if (!err && port && test_bit(BR_VLAN_TUNNEL_BIT, &port->flags))
 			err = br_fill_vlan_tunnel_info(skb, vg);
 		rcu_read_unlock();
 		if (err)
Signature · 1 line
2.53.0
author maintainer
#1690 lore raw

PATCH 1660/1756 net: mctp: free reassembly head skb when key_add fails on SOM

In reply to Greg Kroah-Hartman

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

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

From: Joas Antonio dos Santos <[email protected]>

[ Upstream commit d2bfe74a8fe219a86b86c1f126e1d722a5001790 ]

When a start-of-message fragment creates a new reassembly key on the broadcast/bind path, mctp_frag_queue() stores the skb as key->reasm_head before the key is made observable with mctp_key_add().

If mctp_key_add() fails (a race with another SOM packet for the same source/dest/tag, or the receiving socket going away), the error path only drops the key reference via mctp_key_unref(). The final key destructor frees the key itself but not key->reasm_head, and since the key was never added to any list, neither the expiry worker nor socket teardown can reach it to release the queued fragment. The skb is leaked.

Free key->reasm_head on the key_add failure path before releasing the key. Other teardown paths (__mctp_key_done_in(), EOM delivery) already clear reasm_head before the final unref, so this only affects the failure path.

---
 net/mctp/route.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
net/mctp/route.c +9 -1
index eb7c1166d11b6..10a5e53057548 100644
@@ -496,8 +496,16 @@ static int mctp_route_input(struct mctp_route *route, struct sk_buff *skb)
 			 * can do is drop.
 			 */
 			rc = mctp_key_add(key, msk);
-			if (!rc)
+			if (!rc) {
 				trace_mctp_key_acquire(key);
+			} else {
+				/* key_add failed: the key is not observable by
+				 * any cleanup path, so free the fragment we
+				 * just queued on it to avoid leaking the skb.
+				 */
+				kfree_skb(key->reasm_head);
+				key->reasm_head = NULL;
+			}
 
 			/* we don't need to release key->lock on exit, so
 			 * clean up here and suppress the unlock via
Signature · 1 line
2.53.0
author maintainer
#1691 lore raw

PATCH 1661/1756 rtc: s35390a: Add missing newline to dev_err

In reply to Greg Kroah-Hartman

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

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

From: Markus Probst <[email protected]>

[ Upstream commit a27b25bb9b422c8468cb6965b2d72b7b64187fd2 ]

Fixes 3bd32722c827d ("rtc: s35390a: improve irq handling")
---
 drivers/rtc/rtc-s35390a.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/rtc/rtc-s35390a.c +1 -1
index e3dc18882f414..a680d2c354261 100644
@@ -467,7 +467,7 @@ static int s35390a_probe(struct i2c_client *client)
 		buf = 0;
 		err = s35390a_set_reg(s35390a, S35390A_CMD_STATUS2, &buf, 1);
 		if (err < 0) {
-			dev_err(dev, "error disabling alarm");
+			dev_err(dev, "error disabling alarm\n");
 			return err;
 		}
 	} else {
Signature · 1 line
2.53.0
author maintainer
#1692 lore raw

PATCH 1662/1756 rtc: s35390a: Fix alarm not disabling

In reply to Greg Kroah-Hartman

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

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

From: Markus Probst <[email protected]>

[ Upstream commit d93f29e41089bbb14637289fe77bdd72b71e9ac5 ]

Implement alarm_irq_enable callback.

Fixes 542dd33a4925 ("drivers/rtc/rtc-s35390a.c: add wakealarm support for rtc-s35390A rtc chip")
---
 drivers/rtc/rtc-s35390a.c | 29 ++++++++++++++++++++++++-----
 1 file changed, 24 insertions(+), 5 deletions(-)
drivers/rtc/rtc-s35390a.c +24 -5
index a680d2c354261..d7e6c4ada3628 100644
@@ -270,6 +270,24 @@ static int s35390a_rtc_read_time(struct device *dev, struct rtc_time *tm)
 	return 0;
 }
 
+static int s35390a_rtc_alarm_irq_enable(struct device *dev, unsigned int enabled)
+{
+	struct s35390a *s35390a = dev_get_drvdata(dev);
+	u8 sts;
+	int err;
+
+	if (enabled)
+		sts = S35390A_INT2_MODE_ALARM;
+	else
+		sts = S35390A_INT2_MODE_NOINTR;
+
+	err = s35390a_set_reg(s35390a, S35390A_CMD_STATUS2, &sts, sizeof(sts));
+	if (err < 0)
+		return err;
+
+	return 0;
+}
+
 static int s35390a_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alm)
 {
 	struct i2c_client *client = to_i2c_client(dev);
@@ -410,11 +428,12 @@ static int s35390a_rtc_ioctl(struct device *dev, unsigned int cmd,
 }
 
 static const struct rtc_class_ops s35390a_rtc_ops = {
-	.read_time	= s35390a_rtc_read_time,
-	.set_time	= s35390a_rtc_set_time,
-	.set_alarm	= s35390a_rtc_set_alarm,
-	.read_alarm	= s35390a_rtc_read_alarm,
-	.ioctl          = s35390a_rtc_ioctl,
+	.read_time		= s35390a_rtc_read_time,
+	.set_time		= s35390a_rtc_set_time,
+	.set_alarm		= s35390a_rtc_set_alarm,
+	.read_alarm		= s35390a_rtc_read_alarm,
+	.alarm_irq_enable	= s35390a_rtc_alarm_irq_enable,
+	.ioctl			= s35390a_rtc_ioctl,
 };
 
 static int s35390a_probe(struct i2c_client *client)
Signature · 1 line
2.53.0
author maintainer
#1693 lore raw

PATCH 1663/1756 rtc: s35390a: drop needless struct s35390a::rtc member

In reply to Greg Kroah-Hartman

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

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

From: André Draszik <[email protected]>

[ Upstream commit cd2a7052482e8a34348e30e6a6525ecb23f0d383 ]

The memory pointed to by the ::rtc member is managed via devres, and no code in this driver uses it past _probe().

We can drop it from the structure and just use a local temporary variable, reducing runtime memory consumption by a few bytes.

Stable-dep-of: 6199051016cd ("rtc: s35390a: Read 24-hour mode on access")

---
 drivers/rtc/rtc-s35390a.c | 22 +++++++++++-----------
 1 file changed, 11 insertions(+), 11 deletions(-)
drivers/rtc/rtc-s35390a.c +11 -11
index d7e6c4ada3628..c8fafdc64c508 100644
@@ -63,7 +63,6 @@ MODULE_DEVICE_TABLE(of, s35390a_of_match);
 
 struct s35390a {
 	struct i2c_client *client[8];
-	struct rtc_device *rtc;
 	int twentyfourhour;
 };
 
@@ -441,6 +440,7 @@ static int s35390a_probe(struct i2c_client *client)
 	int err, err_read;
 	unsigned int i;
 	struct s35390a *s35390a;
+	struct rtc_device *rtc;
 	char buf, status1;
 	struct device *dev = &client->dev;
 
@@ -466,9 +466,9 @@ static int s35390a_probe(struct i2c_client *client)
 		}
 	}
 
-	s35390a->rtc = devm_rtc_allocate_device(dev);
-	if (IS_ERR(s35390a->rtc))
-		return PTR_ERR(s35390a->rtc);
+	rtc = devm_rtc_allocate_device(dev);
+	if (IS_ERR(rtc))
+		return PTR_ERR(rtc);
 
 	err_read = s35390a_read_status(s35390a, &status1);
 	if (err_read < 0) {
@@ -499,17 +499,17 @@ static int s35390a_probe(struct i2c_client *client)
 
 	device_set_wakeup_capable(dev, 1);
 
-	s35390a->rtc->ops = &s35390a_rtc_ops;
-	s35390a->rtc->range_min = RTC_TIMESTAMP_BEGIN_2000;
-	s35390a->rtc->range_max = RTC_TIMESTAMP_END_2099;
+	rtc->ops = &s35390a_rtc_ops;
+	rtc->range_min = RTC_TIMESTAMP_BEGIN_2000;
+	rtc->range_max = RTC_TIMESTAMP_END_2099;
 
-	set_bit(RTC_FEATURE_ALARM_RES_MINUTE, s35390a->rtc->features);
-	clear_bit(RTC_FEATURE_UPDATE_INTERRUPT, s35390a->rtc->features );
+	set_bit(RTC_FEATURE_ALARM_RES_MINUTE, rtc->features);
+	clear_bit(RTC_FEATURE_UPDATE_INTERRUPT, rtc->features);
 
 	if (status1 & S35390A_FLAG_INT2)
-		rtc_update_irq(s35390a->rtc, 1, RTC_AF);
+		rtc_update_irq(rtc, 1, RTC_AF);
 
-	return devm_rtc_register_device(s35390a->rtc);
+	return devm_rtc_register_device(rtc);
 }
 
 static struct i2c_driver s35390a_driver = {
Signature · 1 line
2.53.0
author maintainer
#1694 lore raw

PATCH 1664/1756 rtc: s35390a: use u8 instead of char for register buffer

In reply to Greg Kroah-Hartman

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

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

From: Nick Huang <[email protected]>

[ Upstream commit 73c4638a2864e69ff2251080ce874d360fd13056 ]

The register buffer in s35390a_get_reg() was previously defined as char *buf. This is not ideal since register data represents raw binary values rather than textual data.

Switch the type to u8 *buf to better reflect its intended usage and to avoid potential issues with sign extension when handling register values on platforms where char is signed by default.

This change improves type safety and makes the code consistent with other RTC drivers that operate on raw register data.

Stable-dep-of: 6199051016cd ("rtc: s35390a: Read 24-hour mode on access")

---
 drivers/rtc/rtc-s35390a.c | 18 +++++++++---------
 1 file changed, 9 insertions(+), 9 deletions(-)
drivers/rtc/rtc-s35390a.c +9 -9
index c8fafdc64c508..0713a5afadfa6 100644
@@ -66,7 +66,7 @@ struct s35390a {
 	int twentyfourhour;
 };
 
-static int s35390a_set_reg(struct s35390a *s35390a, int reg, char *buf, int len)
+static int s35390a_set_reg(struct s35390a *s35390a, int reg, u8  *buf, int len)
 {
 	struct i2c_client *client = s35390a->client[reg];
 	struct i2c_msg msg[] = {
@@ -83,7 +83,7 @@ static int s35390a_set_reg(struct s35390a *s35390a, int reg, char *buf, int len)
 	return 0;
 }
 
-static int s35390a_get_reg(struct s35390a *s35390a, int reg, char *buf, int len)
+static int s35390a_get_reg(struct s35390a *s35390a, int reg, u8 *buf, int len)
 {
 	struct i2c_client *client = s35390a->client[reg];
 	struct i2c_msg msg[] = {
@@ -168,7 +168,7 @@ static int s35390a_read_status(struct s35390a *s35390a, char *status1)
 
 static int s35390a_disable_test_mode(struct s35390a *s35390a)
 {
-	char buf[1];
+	u8 buf[1];
 
 	if (s35390a_get_reg(s35390a, S35390A_CMD_STATUS2, buf, sizeof(buf)) < 0)
 		return -EIO;
@@ -210,7 +210,7 @@ static int s35390a_rtc_set_time(struct device *dev, struct rtc_time *tm)
 	struct i2c_client *client = to_i2c_client(dev);
 	struct s35390a	*s35390a = i2c_get_clientdata(client);
 	int i;
-	char buf[7], status;
+	u8 buf[7], status;
 
 	dev_dbg(&client->dev, "%s: tm is secs=%d, mins=%d, hours=%d mday=%d, "
 		"mon=%d, year=%d, wday=%d\n", __func__, tm->tm_sec,
@@ -239,7 +239,7 @@ static int s35390a_rtc_read_time(struct device *dev, struct rtc_time *tm)
 {
 	struct i2c_client *client = to_i2c_client(dev);
 	struct s35390a *s35390a = i2c_get_clientdata(client);
-	char buf[7], status;
+	u8 buf[7], status;
 	int i, err;
 
 	if (s35390a_read_status(s35390a, &status) == 1)
@@ -291,7 +291,7 @@ static int s35390a_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alm)
 {
 	struct i2c_client *client = to_i2c_client(dev);
 	struct s35390a *s35390a = i2c_get_clientdata(client);
-	char buf[3], sts = 0;
+	u8 buf[3], sts = 0;
 	int err, i;
 
 	dev_dbg(&client->dev, "%s: alm is secs=%d, mins=%d, hours=%d mday=%d, "\
@@ -344,7 +344,7 @@ static int s35390a_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alm)
 {
 	struct i2c_client *client = to_i2c_client(dev);
 	struct s35390a *s35390a = i2c_get_clientdata(client);
-	char buf[3], sts;
+	u8 buf[3], sts;
 	int i, err;
 
 	err = s35390a_get_reg(s35390a, S35390A_CMD_STATUS2, &sts, sizeof(sts));
@@ -401,7 +401,7 @@ static int s35390a_rtc_ioctl(struct device *dev, unsigned int cmd,
 {
 	struct i2c_client *client = to_i2c_client(dev);
 	struct s35390a *s35390a = i2c_get_clientdata(client);
-	char sts;
+	u8 sts;
 	int err;
 
 	switch (cmd) {
@@ -441,7 +441,7 @@ static int s35390a_probe(struct i2c_client *client)
 	unsigned int i;
 	struct s35390a *s35390a;
 	struct rtc_device *rtc;
-	char buf, status1;
+	u8 buf, status1;
 	struct device *dev = &client->dev;
 
 	if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C))
Signature · 1 line
2.53.0
author maintainer
#1695 lore raw

PATCH 1665/1756 rtc: s35390a: fix typo in comment

In reply to Greg Kroah-Hartman

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

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

From: Alexandre Belloni <[email protected]>

[ Upstream commit 50ccdc31010ed623e68e496aebd4b1d3d8430664 ]

Fix trivial typo

Stable-dep-of: 6199051016cd ("rtc: s35390a: Read 24-hour mode on access")

---
 drivers/rtc/rtc-s35390a.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/rtc/rtc-s35390a.c +1 -1
index 0713a5afadfa6..94c75cdf0c8a7 100644
@@ -314,7 +314,7 @@ static int s35390a_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alm)
 	else
 		sts = S35390A_INT2_MODE_NOINTR;
 
-	/* set interupt mode*/
+	/* set interrupt mode*/
 	err = s35390a_set_reg(s35390a, S35390A_CMD_STATUS2, &sts, sizeof(sts));
 	if (err < 0)
 		return err;
Signature · 1 line
2.53.0
author maintainer
#1696 lore raw

PATCH 1666/1756 rtc: s35390a: Read 24-hour mode on access

In reply to Greg Kroah-Hartman

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

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

From: Markus Probst <[email protected]>

[ Upstream commit 6199051016cddba920b6023a44199c5221352c44 ]

Instead of reading if the 24-hour mode is used on probe once, read it on access. This makes it impossible for the mode to be out of sync and fixes time corruption if resetting the chip while in 12-hour mode, as s35390a_init did not update the cached value.

Fixes 16486d0c1c65 ("rtc: s35390a: handle invalid RTC time")
---
 drivers/rtc/rtc-s35390a.c | 78 +++++++++++++++++++++------------------
 1 file changed, 42 insertions(+), 36 deletions(-)
drivers/rtc/rtc-s35390a.c +42 -36
index 94c75cdf0c8a7..0f4599ea558c0 100644
@@ -63,7 +63,6 @@ MODULE_DEVICE_TABLE(of, s35390a_of_match);
 
 struct s35390a {
 	struct i2c_client *client[8];
-	int twentyfourhour;
 };
 
 static int s35390a_set_reg(struct s35390a *s35390a, int reg, u8  *buf, int len)
@@ -101,9 +100,8 @@ static int s35390a_get_reg(struct s35390a *s35390a, int reg, u8 *buf, int len)
 	return 0;
 }
 
-static int s35390a_init(struct s35390a *s35390a)
+static int s35390a_init(struct s35390a *s35390a, u8 *sts)
 {
-	u8 buf;
 	int ret;
 	unsigned initcount = 0;
 
@@ -116,17 +114,17 @@ static int s35390a_init(struct s35390a *s35390a)
 	 * The 24H bit is kept over reset, so set it already here.
 	 */
 initialize:
-	buf = S35390A_FLAG_RESET | S35390A_FLAG_24H;
-	ret = s35390a_set_reg(s35390a, S35390A_CMD_STATUS1, &buf, 1);
+	*sts = S35390A_FLAG_RESET | S35390A_FLAG_24H;
+	ret = s35390a_set_reg(s35390a, S35390A_CMD_STATUS1, sts, 1);
 
 	if (ret < 0)
 		return ret;
 
-	ret = s35390a_get_reg(s35390a, S35390A_CMD_STATUS1, &buf, 1);
+	ret = s35390a_get_reg(s35390a, S35390A_CMD_STATUS1, sts, 1);
 	if (ret < 0)
 		return ret;
 
-	if (buf & (S35390A_FLAG_POC | S35390A_FLAG_BLD)) {
+	if (*sts & (S35390A_FLAG_POC | S35390A_FLAG_BLD)) {
 		/* Try up to five times to reset the chip */
 		if (initcount < 5) {
 			++initcount;
@@ -180,9 +178,9 @@ static int s35390a_disable_test_mode(struct s35390a *s35390a)
 	return s35390a_set_reg(s35390a, S35390A_CMD_STATUS2, buf, sizeof(buf));
 }
 
-static char s35390a_hr2reg(struct s35390a *s35390a, int hour)
+static char s35390a_hr2reg(int hour, bool twentyfourhour)
 {
-	if (s35390a->twentyfourhour)
+	if (twentyfourhour)
 		return bin2bcd(hour);
 
 	if (hour < 12)
@@ -191,11 +189,11 @@ static char s35390a_hr2reg(struct s35390a *s35390a, int hour)
 	return 0x40 | bin2bcd(hour - 12);
 }
 
-static int s35390a_reg2hr(struct s35390a *s35390a, char reg)
+static int s35390a_reg2hr(char reg, bool twentyfourhour)
 {
 	unsigned hour;
 
-	if (s35390a->twentyfourhour)
+	if (twentyfourhour)
 		return bcd2bin(reg & 0x3f);
 
 	hour = bcd2bin(reg & 0x3f);
@@ -209,7 +207,7 @@ static int s35390a_rtc_set_time(struct device *dev, struct rtc_time *tm)
 {
 	struct i2c_client *client = to_i2c_client(dev);
 	struct s35390a	*s35390a = i2c_get_clientdata(client);
-	int i;
+	int i, err;
 	u8 buf[7], status;
 
 	dev_dbg(&client->dev, "%s: tm is secs=%d, mins=%d, hours=%d mday=%d, "
@@ -217,14 +215,18 @@ static int s35390a_rtc_set_time(struct device *dev, struct rtc_time *tm)
 		tm->tm_min, tm->tm_hour, tm->tm_mday, tm->tm_mon, tm->tm_year,
 		tm->tm_wday);
 
-	if (s35390a_read_status(s35390a, &status) == 1)
-		s35390a_init(s35390a);
+	err = s35390a_read_status(s35390a, &status);
+	if (err == 1)
+		err = s35390a_init(s35390a, &status);
+
+	if (err < 0)
+		return err;
 
 	buf[S35390A_BYTE_YEAR] = bin2bcd(tm->tm_year - 100);
 	buf[S35390A_BYTE_MONTH] = bin2bcd(tm->tm_mon + 1);
 	buf[S35390A_BYTE_DAY] = bin2bcd(tm->tm_mday);
 	buf[S35390A_BYTE_WDAY] = bin2bcd(tm->tm_wday);
-	buf[S35390A_BYTE_HOURS] = s35390a_hr2reg(s35390a, tm->tm_hour);
+	buf[S35390A_BYTE_HOURS] = s35390a_hr2reg(tm->tm_hour, status & S35390A_FLAG_24H);
 	buf[S35390A_BYTE_MINS] = bin2bcd(tm->tm_min);
 	buf[S35390A_BYTE_SECS] = bin2bcd(tm->tm_sec);
 
@@ -242,8 +244,11 @@ static int s35390a_rtc_read_time(struct device *dev, struct rtc_time *tm)
 	u8 buf[7], status;
 	int i, err;
 
-	if (s35390a_read_status(s35390a, &status) == 1)
+	err = s35390a_read_status(s35390a, &status);
+	if (err == 1)
 		return -EINVAL;
+	if (err < 0)
+		return err;
 
 	err = s35390a_get_reg(s35390a, S35390A_CMD_TIME1, buf, sizeof(buf));
 	if (err < 0)
@@ -255,7 +260,7 @@ static int s35390a_rtc_read_time(struct device *dev, struct rtc_time *tm)
 
 	tm->tm_sec = bcd2bin(buf[S35390A_BYTE_SECS]);
 	tm->tm_min = bcd2bin(buf[S35390A_BYTE_MINS]);
-	tm->tm_hour = s35390a_reg2hr(s35390a, buf[S35390A_BYTE_HOURS]);
+	tm->tm_hour = s35390a_reg2hr(buf[S35390A_BYTE_HOURS], status & S35390A_FLAG_24H);
 	tm->tm_wday = bcd2bin(buf[S35390A_BYTE_WDAY]);
 	tm->tm_mday = bcd2bin(buf[S35390A_BYTE_DAY]);
 	tm->tm_mon = bcd2bin(buf[S35390A_BYTE_MONTH]) - 1;
@@ -291,7 +296,7 @@ static int s35390a_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alm)
 {
 	struct i2c_client *client = to_i2c_client(dev);
 	struct s35390a *s35390a = i2c_get_clientdata(client);
-	u8 buf[3], sts = 0;
+	u8 buf[3], status1, status2 = 0;
 	int err, i;
 
 	dev_dbg(&client->dev, "%s: alm is secs=%d, mins=%d, hours=%d mday=%d, "\
@@ -300,22 +305,22 @@ static int s35390a_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alm)
 		alm->time.tm_mon, alm->time.tm_year, alm->time.tm_wday);
 
 	/* disable interrupt (which deasserts the irq line) */
-	err = s35390a_set_reg(s35390a, S35390A_CMD_STATUS2, &sts, sizeof(sts));
+	err = s35390a_set_reg(s35390a, S35390A_CMD_STATUS2, &status2, sizeof(status2));
 	if (err < 0)
 		return err;
 
 	/* clear pending interrupt (in STATUS1 only), if any */
-	err = s35390a_get_reg(s35390a, S35390A_CMD_STATUS1, &sts, sizeof(sts));
+	err = s35390a_get_reg(s35390a, S35390A_CMD_STATUS1, &status1, sizeof(status1));
 	if (err < 0)
 		return err;
 
 	if (alm->enabled)
-		sts = S35390A_INT2_MODE_ALARM;
+		status2 = S35390A_INT2_MODE_ALARM;
 	else
-		sts = S35390A_INT2_MODE_NOINTR;
+		status2 = S35390A_INT2_MODE_NOINTR;
 
 	/* set interrupt mode*/
-	err = s35390a_set_reg(s35390a, S35390A_CMD_STATUS2, &sts, sizeof(sts));
+	err = s35390a_set_reg(s35390a, S35390A_CMD_STATUS2, &status2, sizeof(status2));
 	if (err < 0)
 		return err;
 
@@ -324,8 +329,8 @@ static int s35390a_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alm)
 	else
 		buf[S35390A_ALRM_BYTE_WDAY] = 0;
 
-	buf[S35390A_ALRM_BYTE_HOURS] = s35390a_hr2reg(s35390a,
-			alm->time.tm_hour) | 0x80;
+	buf[S35390A_ALRM_BYTE_HOURS] = s35390a_hr2reg(alm->time.tm_hour,
+						      status1 & S35390A_FLAG_24H) | 0x80;
 	buf[S35390A_ALRM_BYTE_MINS] = bin2bcd(alm->time.tm_min) | 0x80;
 
 	if (alm->time.tm_hour >= 12)
@@ -344,14 +349,20 @@ static int s35390a_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alm)
 {
 	struct i2c_client *client = to_i2c_client(dev);
 	struct s35390a *s35390a = i2c_get_clientdata(client);
-	u8 buf[3], sts;
+	u8 buf[3], status1, status2;
 	int i, err;
 
-	err = s35390a_get_reg(s35390a, S35390A_CMD_STATUS2, &sts, sizeof(sts));
+	err = s35390a_read_status(s35390a, &status1);
+	if (err == 1)
+		return -EINVAL;
+	if (err < 0)
+		return err;
+
+	err = s35390a_get_reg(s35390a, S35390A_CMD_STATUS2, &status2, sizeof(status2));
 	if (err < 0)
 		return err;
 
-	if ((sts & S35390A_INT2_MODE_MASK) != S35390A_INT2_MODE_ALARM) {
+	if ((status2 & S35390A_INT2_MODE_MASK) != S35390A_INT2_MODE_ALARM) {
 		/*
 		 * When the alarm isn't enabled, the register to configure
 		 * the alarm time isn't accessible.
@@ -380,8 +391,8 @@ static int s35390a_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alm)
 
 	if (buf[S35390A_ALRM_BYTE_HOURS] & 0x80)
 		alm->time.tm_hour =
-			s35390a_reg2hr(s35390a,
-				       buf[S35390A_ALRM_BYTE_HOURS] & ~0x80);
+			s35390a_reg2hr(buf[S35390A_ALRM_BYTE_HOURS] & ~0x80,
+				       status1 & S35390A_FLAG_24H);
 
 	if (buf[S35390A_ALRM_BYTE_MINS] & 0x80)
 		alm->time.tm_min = bcd2bin(buf[S35390A_ALRM_BYTE_MINS] & ~0x80);
@@ -415,7 +426,7 @@ static int s35390a_rtc_ioctl(struct device *dev, unsigned int cmd,
 		break;
 	case RTC_VL_CLR:
 		/* update flag and clear register */
-		err = s35390a_init(s35390a);
+		err = s35390a_init(s35390a, &sts);
 		if (err < 0)
 			return err;
 		break;
@@ -476,11 +487,6 @@ static int s35390a_probe(struct i2c_client *client)
 		return err_read;
 	}
 
-	if (status1 & S35390A_FLAG_24H)
-		s35390a->twentyfourhour = 1;
-	else
-		s35390a->twentyfourhour = 0;
-
 	if (status1 & S35390A_FLAG_INT2) {
 		/* disable alarm (and maybe test mode) */
 		buf = 0;
Signature · 1 line
2.53.0
author maintainer
#1697 lore raw

PATCH 1667/1756 fork: Let nobody keep a task that may not come to life

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 5cf0881344cfa0a3b558107741884d8f43269d7b ]

dup_task_struct() sets rcu_users to 2. From then on bpf_task_acquire() hands out references to the new task, which BPF programs see as a trusted pointer long before it is sure to live: in the task_alloc LSM hook and in ops.init_task() of sched_ext.

If copy_process() fails later on, it undoes what it has done and frees the task without a look at the count. A program that has stored its reference in a map is left with a pointer to freed memory:

  BUG: KASAN: slab-use-after-free in put_task_struct_rcu_user+0x22/0x90

The program is loaded by the administrator, but any user can make a fork fail, for example at the pids.max of a cgroup.

Honouring the count would not do: the task would stay behind with its mm, files and credentials freed. Leave rcu_users at zero until copy_process() cannot fail any more. bpf_task_acquire() returns NULL until then, which its callers have to be prepared for, and which they get for init_task, whose count has always been zero. The other users of rcu_users deal with tasks that have run.

Fixes 90660309b0c7 ("bpf: Add kfuncs for storing struct task_struct * as a kptr")
---
 kernel/fork.c | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)
kernel/fork.c +9 -3
index f3ba045debeda..1f1bb6e341f07 100644
@@ -1162,10 +1162,10 @@ static struct task_struct *dup_task_struct(struct task_struct *orig, int node)
 	dup_user_cpus_ptr(tsk, orig, node);
 
 	/*
-	 * One for the user space visible state that goes away when reaped.
-	 * One for the scheduler.
+	 * Nobody can keep the task while copy_process() may still fail, which
+	 * frees it no matter what.
 	 */
-	refcount_set(&tsk->rcu_users, 2);
+	refcount_set(&tsk->rcu_users, 0);
 	/* One for the rcu users */
 	refcount_set(&tsk->usage, 1);
 #ifdef CONFIG_BLK_DEV_IO_TRACE
@@ -2584,6 +2584,12 @@ __latent_entropy struct task_struct *copy_process(
 
 	/* No more failure paths after this point. */
 
+	/*
+	 * One for the user space visible state that goes away when reaped.
+	 * One for the scheduler.
+	 */
+	refcount_set(&p->rcu_users, 2);
+
 	/*
 	 * Copy seccomp details explicitly here, in case they were changed
 	 * before holding sighand lock.
Signature · 1 line
2.53.0
author maintainer
#1698 lore raw

PATCH 1668/1756 xattr: always invoke cap_convert_nscap() for security.capability writes

In reply to Greg Kroah-Hartman

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

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

From: Dominik Maier <[email protected]>

[ Upstream commit 0f4a9e682f7fa5becc3af7204606d9bf4780e425 ]

Commit 8db6c34f1dbc ("Introduce v3 namespaced file capabilities") changed cap_inode_setxattr() to return 0 unconditionally for XATTR_NAME_CAPS ("security.capability") and moved capability validation into cap_convert_nscap(), but placed the call inside the "if (size)" block in setxattr(). Commit 7c03e2cda4a5 ("vfs: move cap_convert_nscap() call into vfs_setxattr()") preserved that "size &&" condition in vfs_setxattr():

	if (size && strcmp(name, XATTR_NAME_CAPS) == 0) {
		error = cap_convert_nscap(idmap, dentry, &value, size);
		...
	}

For security.* extended attributes, xattr_permission() skips inode_permission(MAY_WRITE) and leaves permission checks to the security module, while cap_inode_setxattr() returns 0 for XATTR_NAME_CAPS assuming cap_convert_nscap() has already validated the write. Because __vfs_setxattr() treats size == 0 as an empty attribute write (setting value = "") rather than a removal, calling setxattr(2) on "security.capability" with size == 0 bypasses cap_convert_nscap() and allows an unprivileged caller without CAP_SETFCAP or write permission on the target inode to write a 0-byte security.capability xattr (or overwrite an existing one).

When that binary is subsequently executed, get_vfs_caps_from_disk() reads the 0-byte security.capability xattr and fails the
size < sizeof(magic_etc) check with -EINVAL, causing execve(2) to fail with -EINVAL.

Always invoke cap_convert_nscap() when strcmp(name, XATTR_NAME_CAPS) == 0 regardless of size, so that 0-byte writes hit the existing !*ivalue / !validheader() checks in cap_convert_nscap() and are rejected with -EINVAL.

Fixes 8db6c34f1dbc ("Introduce v3 namespaced file capabilities")
---
 fs/xattr.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/xattr.c +1 -1
index 23b9e4b1f3dd8..72a49e0a2ec1e 100644
@@ -309,7 +309,7 @@ vfs_setxattr(struct mnt_idmap *idmap, struct dentry *dentry,
 	const void  *orig_value = value;
 	int error;
 
-	if (size && strcmp(name, XATTR_NAME_CAPS) == 0) {
+	if (strcmp(name, XATTR_NAME_CAPS) == 0) {
 		error = cap_convert_nscap(idmap, dentry, &value, size);
 		if (error < 0)
 			return error;
Signature · 1 line
2.53.0
author maintainer
#1699 lore raw

PATCH 1669/1756 block: fix use-after-free of the disk in sync_bdevs()

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit cebb1c2331c2af1b7f1c822ac672a7f77b54bd90 ]

sync_bdevs() holds a reference to the bdev inode while it takes bd_disk->open_mutex. For a partition the inode doesn't keep the gendisk alive, the device reference does: part_release() drops the disk as soon as the last reference to the partition device is gone. A sync(2) racing with the last close of a partition of an already deleted disk locks a freed open_mutex.

Take a device reference before touching the disk, like blkdev_get_no_open() does, and skip the bdev if it's on its way out.

---
 block/bdev.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
block/bdev.c +10 -0
index 57aa344dc04a5..dc66a9bec5e33 100644
@@ -1274,6 +1274,15 @@ void sync_bdevs(bool wait)
 		old_inode = inode;
 		bdev = I_BDEV(inode);
 
+		/*
+		 * The inode does not keep the gendisk of a partition alive, the
+		 * device does.
+		 */
+		if (!kobject_get_unless_zero(&bdev->bd_device.kobj)) {
+			spin_lock(&blockdev_superblock->s_inode_list_lock);
+			continue;
+		}
+
 		mutex_lock(&bdev->bd_disk->open_mutex);
 		if (!atomic_read(&bdev->bd_openers)) {
 			; /* skip */
@@ -1289,6 +1298,7 @@ void sync_bdevs(bool wait)
 			filemap_fdatawrite(inode->i_mapping);
 		}
 		mutex_unlock(&bdev->bd_disk->open_mutex);
+		put_device(&bdev->bd_device);
 
 		spin_lock(&blockdev_superblock->s_inode_list_lock);
 	}
Signature · 1 line
2.53.0
author maintainer
#1700 lore raw

PATCH 1670/1756 block: dont lose the status of a failed flush request

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 67c43ceaa29e9b904216651697adf20445b219fc ]

flush_end_io() stores the status in fq->rq_status for whoever drops the last reference to finish the flush sequence. blk_mq_put_rq_ref() calls it with BLK_STS_OK from tag iterators and the timeout handler and overwrites an error the real completion stored. With two extra references, reading /sys/block/<disk>/inflight is enough for that, a failed flush completes everything waiting on it with success and fsync() lies to the application.

Only store a status that is an error.

Fixes 2e315dc07df0 ("blk-mq: grab rq->refcount before calling ->fn in blk_mq_tagset_busy_iter")
---
 block/blk-flush.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
block/blk-flush.c +7 -1
index a72e2a83d075f..86d064c0958fc 100644
@@ -211,7 +211,13 @@ static enum rq_end_io_ret flush_end_io(struct request *flush_rq,
 	spin_lock_irqsave(&fq->mq_flush_lock, flags);
 
 	if (!req_ref_put_and_test(flush_rq)) {
-		fq->rq_status = error;
+		/*
+		 * Remember the status of the flush for whoever drops the last
+		 * reference. blk_mq_put_rq_ref() gets here with BLK_STS_OK and
+		 * must not wipe it out.
+		 */
+		if (error != BLK_STS_OK)
+			fq->rq_status = error;
 		spin_unlock_irqrestore(&fq->mq_flush_lock, flags);
 		return RQ_END_IO_NONE;
 	}
Signature · 1 line
2.53.0
author maintainer
#1701 lore raw

PATCH 1671/1756 blk-mq: keep sharing tags fairly after a queue update

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 620cfc7a664278a55d068ed88fff1242fddc4ef2 ]

A hctx only gets BLK_MQ_F_TAG_QUEUE_SHARED from blk_mq_add_queue_tag_set(). The hctxs blk_mq_update_nr_hw_queues() allocates for queues that joined long ago never get it, so they aren't counted in active_queues and hctx_may_queue() lets them take all the tags. One NVMe namespace can starve the others after the first update.

Set the flag on the new hctxs.

---
 block/blk-mq.c | 3 +++
 1 file changed, 3 insertions(+)
block/blk-mq.c +3 -0
index c5be2e8578a7b..2ef0a69b6dd42 100644
@@ -5058,6 +5058,9 @@ static void __blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set,
 			goto fallback;
 		}
 		blk_mq_map_swqueue(q);
+		/* The new hctxs don't know yet that they share their tags */
+		if (set->flags & BLK_MQ_F_TAG_QUEUE_SHARED)
+			queue_set_hctx_shared(q, true);
 	}
 
 reregister:
Signature · 1 line
2.53.0
author maintainer
#1702 lore raw

PATCH 1672/1756 blk-mq: dont bring back flags of a completed request

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 9531230ee1fcb8eca2c9cbb9bf02651cbf798842 ]

The timeout handler sets and clears RQF_TIMED_OUT in a request it only holds a reference to, with a plain read-modify-write, while the completion clears flags in rq_flags the same way. If the two interleave, blk_mq_finish_request() runs twice with the flags back: the zone write plug reference is dropped twice and the scheduler's ->finish_request() is called again.

Change RQF_TIMED_OUT with cmpxchg, so the handler never writes back a flag that changed under it.

Fixes e5c0ca13659e ("blk-mq: release scheduler resource when request completes")
---
 block/blk-mq.c      |  2 +-
 block/blk-timeout.c |  3 ++-
 block/blk.h         | 14 ++++++++++++++
 3 files changed, 17 insertions(+), 2 deletions(-)
block/blk-mq.c +1 -1
index 2ef0a69b6dd42..c3c5a5c0772fd 100644
@@ -1618,7 +1618,7 @@ EXPORT_SYMBOL_GPL(blk_mq_queue_inflight);
 
 static void blk_mq_rq_timed_out(struct request *req)
 {
-	req->rq_flags |= RQF_TIMED_OUT;
+	blk_rq_change_timed_out(req, true);
 	if (req->q->mq_ops->timeout) {
 		enum blk_eh_timer_return ret;
 
block/blk-timeout.c +2 -1
index 1b8de0417fc1a..0590720e38c7f 100644
@@ -137,7 +137,8 @@ void blk_add_timer(struct request *req)
 	if (!req->timeout)
 		req->timeout = q->rq_timeout;
 
-	req->rq_flags &= ~RQF_TIMED_OUT;
+	if (req->rq_flags & RQF_TIMED_OUT)
+		blk_rq_change_timed_out(req, false);
 
 	expiry = jiffies + req->timeout;
 	WRITE_ONCE(req->deadline, expiry);
block/blk.h +14 -0
index 4500ba33dc7af..8458676fb1012 100644
@@ -316,6 +316,20 @@ static inline void bio_integrity_free(struct bio *bio)
 unsigned long blk_rq_timeout(unsigned long timeout);
 void blk_add_timer(struct request *req);
 
+/*
+ * The timeout handler changes RQF_TIMED_OUT in a request which it does not
+ * own: whoever completes it changes rq_flags at the same time, with plain
+ * loads and stores. Never write back a flag that has changed under us.
+ */
+static inline void blk_rq_change_timed_out(struct request *rq, bool set)
+{
+	req_flags_t old = READ_ONCE(rq->rq_flags), new;
+
+	do {
+		new = set ? old | RQF_TIMED_OUT : old & ~RQF_TIMED_OUT;
+	} while (!try_cmpxchg(&rq->rq_flags, &old, new));
+}
+
 enum bio_merge_status {
 	BIO_MERGE_OK,
 	BIO_MERGE_NONE,
Signature · 1 line
2.53.0
author maintainer
#1703 lore raw

PATCH 1673/1756 blk-mq: dont forget a timer the driver has restarted

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 0db9f8968a8941d4fc9fddf220d4983d9b68deaf ]

If ->timeout() returns BLK_EH_RESET_TIMER, blk_add_timer() gives the request a new deadline that blk_mq_timeout_work() doesn't know about when it picks the next expiry. A 2s nbd read next to a 60s one expires once and then not again for a minute. Let the new deadline take part.

Fixes 320ae51feed5 ("blk-mq: new multi-queue block IO queueing mechanism")
---
 block/blk-mq.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
block/blk-mq.c +4 -1
index c3c5a5c0772fd..7c5415ca2450d 100644
@@ -1689,8 +1689,11 @@ static bool blk_mq_handle_expired(struct request *rq, void *priv)
 {
 	struct blk_expired_data *expired = priv;
 
-	if (blk_mq_req_expired(rq, expired))
+	if (blk_mq_req_expired(rq, expired)) {
 		blk_mq_rq_timed_out(rq);
+		/* If its timer has been started again, count the new deadline */
+		blk_mq_req_expired(rq, expired);
+	}
 	return true;
 }
 
Signature · 1 line
2.53.0
author maintainer
#1704 lore raw

PATCH 1674/1756 blk-mq: quiesce a queue that joins a quiesced tag set

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 71ec3c7d6db80737b781d2739d1325b7e39758e1 ]

blk_mq_quiesce_tagset() only quiesces the queues on the list at that moment. A queue added before blk_mq_unquiesce_tagset() runs unquiesced, and then gets unquiesced without ever having been quiesced, which trips the warning in blk_mq_unquiesce_queue(). NVMe gets there when a controller fails while its namespaces are being scanned.

Count the quiesce calls in the tag set and quiesce a joining queue that many times, under a spinlock that also serializes the two functions. It can't be tag_list_lock, see commit 59e25ef2b413.

---
 block/blk-mq.c         | 22 ++++++++++++++++++++++
 include/linux/blk-mq.h |  6 ++++++
 2 files changed, 28 insertions(+)
block/blk-mq.c +22 -0
index 7c5415ca2450d..5f261097425ad 100644
@@ -364,12 +364,15 @@ void blk_mq_quiesce_tagset(struct blk_mq_tag_set *set)
 {
 	struct request_queue *q;
 
+	spin_lock(&set->quiesce_lock);
+	set->quiesce_depth++;
 	rcu_read_lock();
 	list_for_each_entry_rcu(q, &set->tag_list, tag_set_list) {
 		if (!blk_queue_skip_tagset_quiesce(q))
 			blk_mq_quiesce_queue_nowait(q);
 	}
 	rcu_read_unlock();
+	spin_unlock(&set->quiesce_lock);
 
 	blk_mq_wait_quiesce_done(set);
 }
@@ -379,12 +382,16 @@ void blk_mq_unquiesce_tagset(struct blk_mq_tag_set *set)
 {
 	struct request_queue *q;
 
+	spin_lock(&set->quiesce_lock);
+	if (set->quiesce_depth)
+		set->quiesce_depth--;
 	rcu_read_lock();
 	list_for_each_entry_rcu(q, &set->tag_list, tag_set_list) {
 		if (!blk_queue_skip_tagset_quiesce(q))
 			blk_mq_unquiesce_queue(q);
 	}
 	rcu_read_unlock();
+	spin_unlock(&set->quiesce_lock);
 }
 EXPORT_SYMBOL_GPL(blk_mq_unquiesce_tagset);
 
@@ -4274,6 +4281,8 @@ static void blk_mq_del_queue_tag_set(struct request_queue *q)
 static void blk_mq_add_queue_tag_set(struct blk_mq_tag_set *set,
 				     struct request_queue *q)
 {
+	unsigned int i;
+
 	mutex_lock(&set->tag_list_lock);
 
 	/*
@@ -4287,7 +4296,18 @@ static void blk_mq_add_queue_tag_set(struct blk_mq_tag_set *set,
 	}
 	if (set->flags & BLK_MQ_F_TAG_QUEUE_SHARED)
 		queue_set_hctx_shared(q, true);
+
+	/*
+	 * A queue that joins a quiesced tag set is quiesced like the others,
+	 * and blk_mq_unquiesce_tagset() finds what it is going to undo.
+	 */
+	spin_lock(&set->quiesce_lock);
 	list_add_tail_rcu(&q->tag_set_list, &set->tag_list);
+	if (!blk_queue_skip_tagset_quiesce(q)) {
+		for (i = 0; i < set->quiesce_depth; i++)
+			blk_mq_quiesce_queue_nowait(q);
+	}
+	spin_unlock(&set->quiesce_lock);
 
 	mutex_unlock(&set->tag_list_lock);
 }
@@ -4815,6 +4835,8 @@ int blk_mq_alloc_tag_set(struct blk_mq_tag_set *set)
 
 	mutex_init(&set->tag_list_lock);
 	INIT_LIST_HEAD(&set->tag_list);
+	spin_lock_init(&set->quiesce_lock);
+	set->quiesce_depth = 0;
 
 	return 0;
 
include/linux/blk-mq.h +6 -0
index 0c997069cf218..77db585fbedfa 100644
@@ -511,6 +511,10 @@ enum hctx_type {
  * @tag_list_lock: Serializes tag_list accesses.
  * @tag_list:	   List of the request queues that use this tag set. See also
  *		   request_queue.tag_set_list.
+ * @quiesce_lock:  Serializes blk_mq_[un]quiesce_tagset() against each other
+ *		   and against a request queue being added to @tag_list.
+ * @quiesce_depth: How often blk_mq_quiesce_tagset() has been called without
+ *		   blk_mq_unquiesce_tagset().
  * @srcu:	   Use as lock when type of the request queue is blocking
  *		   (BLK_MQ_F_BLOCKING).
  */
@@ -533,6 +537,8 @@ struct blk_mq_tag_set {
 
 	struct mutex		tag_list_lock;
 	struct list_head	tag_list;
+	spinlock_t		quiesce_lock;
+	unsigned int		quiesce_depth;
 	struct srcu_struct	*srcu;
 };
 
Signature · 1 line
2.53.0
author maintainer
#1705 lore raw

PATCH 1675/1756 blk-mq: exit the hctxs of a queue under tag_list_lock

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 89a2381482d8ff8e4fe0b7d32797bb4f77503b89 ]

blk_mq_update_nr_hw_queues() exits and replaces the hctxs of every queue on set->tag_list under tag_list_lock. blk_mq_exit_queue() exits its hctxs without the lock and only then takes the queue off the list, so an update running at the same time exits them again and sets up new ones that nobody exits. del_gendisk() is kept away by update_nr_hwq_lock, disk_release() of a never added disk and blk_mq_destroy_queue() are not, and nvme_alloc_ns() drops such a disk when it finds the queues frozen by a reset.

Hold tag_list_lock for both steps.

Fixes 630ef623ed26 ("blk-mq: Swap two calls in blk_mq_exit_queue()")
---
 block/blk-mq.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
block/blk-mq.c +8 -2
index 5f261097425ad..65a08aec007d2 100644
@@ -4267,7 +4267,8 @@ static void blk_mq_del_queue_tag_set(struct request_queue *q)
 {
 	struct blk_mq_tag_set *set = q->tag_set;
 
-	mutex_lock(&set->tag_list_lock);
+	lockdep_assert_held(&set->tag_list_lock);
+
 	list_del_rcu(&q->tag_set_list);
 	if (list_is_singular(&set->tag_list)) {
 		/* just transitioned to unshared */
@@ -4275,7 +4276,6 @@ static void blk_mq_del_queue_tag_set(struct request_queue *q)
 		/* update existing queue */
 		blk_mq_update_tag_set_shared(set, false);
 	}
-	mutex_unlock(&set->tag_list_lock);
 }
 
 static void blk_mq_add_queue_tag_set(struct blk_mq_tag_set *set,
@@ -4607,10 +4607,16 @@ void blk_mq_exit_queue(struct request_queue *q)
 {
 	struct blk_mq_tag_set *set = q->tag_set;
 
+	/*
+	 * As long as the queue is on set->tag_list, its hctxs belong to
+	 * blk_mq_update_nr_hw_queues() as well, which exits and replaces them.
+	 */
+	mutex_lock(&set->tag_list_lock);
 	/* Checks hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED. */
 	blk_mq_exit_hw_queues(q, set, set->nr_hw_queues);
 	/* May clear BLK_MQ_F_TAG_QUEUE_SHARED in hctx->flags. */
 	blk_mq_del_queue_tag_set(q);
+	mutex_unlock(&set->tag_list_lock);
 }
 
 static int __blk_mq_alloc_rq_maps(struct blk_mq_tag_set *set)
Signature · 1 line
2.53.0
author maintainer
#1706 lore raw

PATCH 1676/1756 block: partitions/mac: compute the sectors in 64 bits

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 6c55f94317249bc195e197f6a8730c843e72ea8c ]

start_block and block_count are converted to 512 byte sectors in 32-bit arithmetic, although put_partition() takes a sector_t. With a block size above 512 bytes anything beyond 2TiB wraps and the partition lands on top of another one.

---
 block/partitions/mac.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
block/partitions/mac.c +2 -2
index b02530d986297..f3bd95ee104f1 100644
@@ -97,8 +97,8 @@ int mac_partition(struct parsed_partitions *state)
 		if (be16_to_cpu(part->signature) != MAC_PARTITION_MAGIC)
 			break;
 		put_partition(state, slot,
-			be32_to_cpu(part->start_block) * (secsize/512),
-			be32_to_cpu(part->block_count) * (secsize/512));
+			(sector_t)be32_to_cpu(part->start_block) * (secsize/512),
+			(sector_t)be32_to_cpu(part->block_count) * (secsize/512));
 
 		if (!strncasecmp(part->type, "Linux_RAID", 10))
 			state->parts[slot].flags = ADDPART_FLAG_RAID;
Signature · 1 line
2.53.0
author maintainer
#1707 lore raw

PATCH 1677/1756 drbd: stop the start_resync timer of a dying device

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit a439d3fe3ec2bfe0b4ccb77973ae97949bcf46ec ]

start_resync_timer gets armed for up to a second and nothing ever deletes it, so drbd_destroy_device() can free the device with the timer pending. Shut it down where request_timer is shut down.

Fixes 370a43e7982d ("drbd: Work on the Ahead -> SyncSource transition")
Cc Philipp Reisner <[email protected]>
Cc Lars Ellenberg <[email protected]>
Cc "Christoph Böhmwalder" <[email protected]>
---
 drivers/block/drbd/drbd_main.c | 1 +
 1 file changed, 1 insertion(+)
drivers/block/drbd/drbd_main.c +1 -0
index 8c5a7bcfa82b2..23b771c0260c6 100644
@@ -2183,6 +2183,7 @@ void drbd_destroy_device(struct kref *kref)
 	struct drbd_peer_device *peer_device, *tmp_peer_device;
 
 	timer_shutdown_sync(&device->request_timer);
+	timer_shutdown_sync(&device->start_resync_timer);
 
 	/* paranoia asserts */
 	D_ASSERT(device, device->open_cnt == 0);
Signature · 1 line
2.53.0
author maintainer
#1708 lore raw

PATCH 1678/1756 drbd: take req_lock to skip the initial sync as peer

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit bf7fff620c890a7ee0b444f1c7e9f0d1263a30ac ]

_drbd_set_state() must be called with req_lock held. drbd_adm_new_c_uuid() does, receive_uuids() on the peer doesn't, so a concurrent state change gets lost: the device is Secondary again, or its failed disk UpToDate, while the work for the lost change is already queued.

Fixes b411b3637fa7 ("The DRBD driver")
Cc Philipp Reisner <[email protected]>
Cc Lars Ellenberg <[email protected]>
Cc "Christoph Böhmwalder" <[email protected]>
---
 drivers/block/drbd/drbd_receiver.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/block/drbd/drbd_receiver.c +2 -0
index f85ebdc3cff6b..1f3760bbf15d1 100644
@@ -4284,8 +4284,10 @@ static int receive_uuids(struct drbd_connection *connection, struct packet_info
 					BM_LOCKED_TEST_ALLOWED, NULL);
 			_drbd_uuid_set(device, UI_CURRENT, p_uuid[UI_CURRENT]);
 			_drbd_uuid_set(device, UI_BITMAP, 0);
+			spin_lock_irq(&device->resource->req_lock);
 			_drbd_set_state(_NS2(device, disk, D_UP_TO_DATE, pdsk, D_UP_TO_DATE),
 					CS_VERBOSE, NULL);
+			spin_unlock_irq(&device->resource->req_lock);
 			drbd_md_sync(device);
 			updated_uuids = 1;
 		}
Signature · 1 line
2.53.0
author maintainer
#1709 lore raw

PATCH 1679/1756 block/rnbd-srv: dont free the device on a sysfs error

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit d9667ade40f986c565769a900ced6ee95edd33c6 ]

rnbd_srv_create_dev_sysfs() drops the only kobject reference on its error paths, and the release function frees the rnbd_srv_dev. process_msg_open() keeps using it and ends in destroy_device() with a list_del() and a second kfree(). This doesn't need memory pressure: a client opening a device while its last mapping goes away gets -EEXIST from kobject_add() against the old directory.

Only undo kobject_add() on failure and leave the reference to destroy_device(). Initialise the kobject once, the next open retries.

Fixes 8cee532f469b ("block/rnbd: server: sysfs interface functions")
Fixes d3a95ccaaf4d ("block/rnbd: call kobject_put in the failure path")
Cc "Md. Haris Iqbal" <[email protected]>
Cc Jack Wang <[email protected]>
---
 drivers/block/rnbd/rnbd-srv-sysfs.c | 16 ++++++++++------
 drivers/block/rnbd/rnbd-srv.c       |  3 +++
 2 files changed, 13 insertions(+), 6 deletions(-)
drivers/block/rnbd/rnbd-srv-sysfs.c +10 -6
index 64780094442ce..33d5d1738be5a 100644
@@ -44,12 +44,17 @@ int rnbd_srv_create_dev_sysfs(struct rnbd_srv_dev *dev,
 	struct kobject *bdev_kobj;
 	int ret;
 
-	ret = kobject_init_and_add(&dev->dev_kobj, &dev_ktype,
-				   rnbd_devs_kobj, "%pg", bdev);
-	if (ret) {
-		kobject_put(&dev->dev_kobj);
+	/*
+	 * The release function frees the device, which the caller goes on
+	 * using and which others may share: never drop the reference of the
+	 * kobject here. That is for destroy_device().
+	 */
+	if (!dev->dev_kobj.state_initialized)
+		kobject_init(&dev->dev_kobj, &dev_ktype);
+
+	ret = kobject_add(&dev->dev_kobj, rnbd_devs_kobj, "%pg", bdev);
+	if (ret)
 		return ret;
-	}
 
 	dev->dev_sessions_kobj = kobject_create_and_add("sessions",
 							&dev->dev_kobj);
@@ -69,7 +74,6 @@ int rnbd_srv_create_dev_sysfs(struct rnbd_srv_dev *dev,
 	kobject_put(dev->dev_sessions_kobj);
 free_dev_kobj:
 	kobject_del(&dev->dev_kobj);
-	kobject_put(&dev->dev_kobj);
 	return ret;
 }
 
drivers/block/rnbd/rnbd-srv.c +3 -0
index 0c7d40ed8d199..441a6512616a6 100644
@@ -207,6 +207,9 @@ static void destroy_device(struct kref *kref)
 		 * Destroy kobj only if it was really created.
 		 */
 		rnbd_srv_destroy_dev_sysfs(dev);
+	else if (dev->dev_kobj.state_initialized)
+		/* The files could not be created. Frees the name, too. */
+		kobject_put(&dev->dev_kobj);
 	else
 		kfree(dev);
 }
Signature · 1 line
2.53.0
author maintainer
#1710 lore raw

PATCH 1680/1756 block/rnbd-srv: drop the sess_dev kobject unlocked

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 81941915d53ef3384ab4e4b68e92673e66cf66d7 ]

rnbd_srv_create_dev_session_sysfs() drops the kobject reference when it fails. The release function is rnbd_destroy_sess_dev(), which takes srv_dev->lock, and the caller holds that lock: the worker deadlocks on itself. A client opening one device as "ram0" and "./ram0" gets there through -EEXIST from kobject_add().

Have process_msg_open() drop the reference after releasing the lock, and leave the rest of the cleanup to the release function.

Fixes 8cee532f469b ("block/rnbd: server: sysfs interface functions")
Fixes d3a95ccaaf4d ("block/rnbd: call kobject_put in the failure path")
Cc "Md. Haris Iqbal" <[email protected]>
Cc Jack Wang <[email protected]>
---
 drivers/block/rnbd/rnbd-srv-sysfs.c | 12 ++++++------
 drivers/block/rnbd/rnbd-srv.c       |  8 +++++++-
 2 files changed, 13 insertions(+), 7 deletions(-)
drivers/block/rnbd/rnbd-srv-sysfs.c +6 -6
index 33d5d1738be5a..9d00c42f2624c 100644
@@ -193,6 +193,10 @@ static const struct kobj_type rnbd_srv_sess_dev_ktype = {
 	.release	= rnbd_srv_sess_dev_release,
 };
 
+/*
+ * On failure the caller has to drop the reference of the kobject. The release
+ * function takes the lock of the device, which the caller holds here.
+ */
 int rnbd_srv_create_dev_session_sysfs(struct rnbd_srv_sess_dev *sess_dev)
 {
 	int ret;
@@ -200,17 +204,13 @@ int rnbd_srv_create_dev_session_sysfs(struct rnbd_srv_sess_dev *sess_dev)
 	ret = kobject_init_and_add(&sess_dev->kobj, &rnbd_srv_sess_dev_ktype,
 				   sess_dev->dev->dev_sessions_kobj, "%s",
 				   sess_dev->sess->sessname);
-	if (ret) {
-		kobject_put(&sess_dev->kobj);
+	if (ret)
 		return ret;
-	}
 
 	ret = sysfs_create_group(&sess_dev->kobj,
 				 &rnbd_srv_default_dev_session_attr_group);
-	if (ret) {
+	if (ret)
 		kobject_del(&sess_dev->kobj);
-		kobject_put(&sess_dev->kobj);
-	}
 
 	return ret;
 }
drivers/block/rnbd/rnbd-srv.c +7 -1
index 441a6512616a6..8895862f55839 100644
@@ -589,6 +589,7 @@ rnbd_srv_create_set_sess_dev(struct rnbd_srv_session *srv_sess,
 		return sdev;
 
 	kref_init(&sdev->kref);
+	INIT_LIST_HEAD(&sdev->dev_list);
 
 	strscpy(sdev->pathname, open_msg->dev_name, sizeof(sdev->pathname));
 
@@ -787,7 +788,12 @@ static int process_msg_open(struct rnbd_srv_session *srv_sess,
 		rnbd_srv_err(srv_sess_dev,
 			      "Opening device failed, failed to create dev client sysfs files, err: %d\n",
 			      ret);
-		goto free_srv_sess_dev;
+		/*
+		 * rnbd_destroy_sess_dev() undoes everything down to the open
+		 * of the block device.
+		 */
+		kobject_put(&srv_sess_dev->kobj);
+		goto free_path;
 	}
 
 	list_add(&srv_sess_dev->dev_list, &srv_dev->sess_dev_list);
Signature · 1 line
2.53.0
author maintainer
#1711 lore raw

PATCH 1681/1756 rnbd-srv: fix use-after-free on two CLOSE messages

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

[ Upstream commit 4912dab88baa5f7034dc9e38807804d470ae5438 ]

process_msg_close() looks the sess_dev up with a kref, drops it right away, and only then takes the session mutex for the teardown. A session has several connections handled by different workers, so two CLOSE messages for the same ID both finish the lookup before either one tears the sess_dev down, and the second one works on freed memory. Any host that can open a device on the server can do that.

Take the mutex first and look the ID up with xa_load() under it. The second CLOSE then finds nothing.

Fixes 2de6c8de192b ("block/rnbd: server: main functionality")
Cc "Md. Haris Iqbal" <[email protected]>
Cc Jack Wang <[email protected]>
---
 drivers/block/rnbd/rnbd-srv.c | 15 ++++++++-------
 1 file changed, 8 insertions(+), 7 deletions(-)
drivers/block/rnbd/rnbd-srv.c +8 -7
index 8895862f55839..dc944a194cc3d 100644
@@ -359,14 +359,15 @@ static void process_msg_close(struct rnbd_srv_session *srv_sess,
 
 	trace_process_msg_close(srv_sess, close_msg);
 
-	sess_dev = rnbd_get_sess_dev(le32_to_cpu(close_msg->device_id),
-				      srv_sess);
-	if (IS_ERR(sess_dev))
-		return;
-
-	rnbd_put_sess_dev(sess_dev);
+	/*
+	 * Each teardown of a sess_dev runs under srv_sess->lock and erases the
+	 * ID, so an entry that is found under the lock is alive.
+	 */
 	mutex_lock(&srv_sess->lock);
-	rnbd_srv_destroy_dev_session_sysfs(sess_dev);
+	sess_dev = xa_load(&srv_sess->index_idr,
+			   le32_to_cpu(close_msg->device_id));
+	if (sess_dev)
+		rnbd_srv_destroy_dev_session_sysfs(sess_dev);
 	mutex_unlock(&srv_sess->lock);
 }
 
Signature · 1 line
2.53.0
author maintainer
#1712 lore raw

PATCH 1682/1756 rnbd-srv: publish the sess_dev at the end of OPEN

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

[ Upstream commit 08ebf69c78a02afb39b7728f3358c09bc4cf067d ]

rnbd_sess_dev_alloc() stores the empty sess_dev in the XArray as its first step. An IO message with the new ID from another connection can find it before bdev_file is set, or hold a reference while a failing OPEN frees it after a mere RCU grace period. Both are reachable from any host that can open a device.

Reserve the ID with a NULL entry and store the sess_dev once nothing can fail anymore. The error path still erases the ID, and no longer needs synchronize_rcu().

Fixes 2de6c8de192b ("block/rnbd: server: main functionality")
Cc "Md. Haris Iqbal" <[email protected]>
Cc Jack Wang <[email protected]>
---
 drivers/block/rnbd/rnbd-srv.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
drivers/block/rnbd/rnbd-srv.c +8 -2
index dc944a194cc3d..ced4e435f963f 100644
@@ -430,7 +430,7 @@ static struct rnbd_srv_sess_dev
 	if (!sess_dev)
 		return ERR_PTR(-ENOMEM);
 
-	error = xa_alloc(&srv_sess->index_idr, &sess_dev->device_id, sess_dev,
+	error = xa_alloc(&srv_sess->index_idr, &sess_dev->device_id, NULL,
 			 xa_limit_32b, GFP_NOWAIT);
 	if (error < 0) {
 		pr_warn("Allocating idr failed, err: %d\n", error);
@@ -800,6 +800,13 @@ static int process_msg_open(struct rnbd_srv_session *srv_sess,
 	list_add(&srv_sess_dev->dev_list, &srv_dev->sess_dev_list);
 	mutex_unlock(&srv_dev->lock);
 
+	/*
+	 * Nothing fails from here on, so let I/O messages find the sess_dev.
+	 * The ID is reserved, so this store allocates nothing.
+	 */
+	xa_store(&srv_sess->index_idr, srv_sess_dev->device_id, srv_sess_dev,
+		 GFP_KERNEL);
+
 	rnbd_srv_info(srv_sess_dev, "Opened device '%s'\n", srv_dev->name);
 
 	kfree(full_path);
@@ -811,7 +818,6 @@ static int process_msg_open(struct rnbd_srv_session *srv_sess,
 
 free_srv_sess_dev:
 	xa_erase(&srv_sess->index_idr, srv_sess_dev->device_id);
-	synchronize_rcu();
 	kfree(srv_sess_dev);
 srv_dev_put:
 	if (open_msg->access_mode != RNBD_ACCESS_RO) {
Signature · 1 line
2.53.0
author maintainer
#1713 lore raw

PATCH 1683/1756 block: remove redundant explicit memory barrier from rq_qos waiter and waker

In reply to Greg Kroah-Hartman

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

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

From: Muchun Song <[email protected]>

[ Upstream commit 904ebd2527c507752f5ddb358f887d2e0dab96a0 ]

The memory barriers in list_del_init_careful() and list_empty_careful() in pairs already handle the proper ordering between data.got_token and data.wq.entry. So remove the redundant explicit barriers. And also change a "break" statement to "return" to avoid redundant calling of finish_wait().

Stable-dep-of: 0150554a3f38 ("blk-iocost: publish hweights as one atomic value")

---
 block/blk-rq-qos.c | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)
block/blk-rq-qos.c +1 -3
index 058f92c4f9d57..eb9618cd68adf 100644
@@ -218,7 +218,6 @@ static int rq_qos_wake_function(struct wait_queue_entry *curr,
 		return -1;
 
 	data->got_token = true;
-	smp_wmb();
 	wake_up_process(data->task);
 	list_del_init_careful(&curr->entry);
 	return 1;
@@ -274,10 +273,9 @@ void rq_qos_wait(struct rq_wait *rqw, void *private_data,
 			 * which means we now have two. Put our local token
 			 * and wake anyone else potentially waiting for one.
 			 */
-			smp_rmb();
 			if (data.got_token)
 				cleanup_cb(rqw, private_data);
-			break;
+			return;
 		}
 		io_schedule();
 		has_sleeper = true;
Signature · 1 line
2.53.0