Skip to contentSkip to conversation

7.3.6-rc1 review

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

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

PATCH 1890/2651 Bluetooth: HCI: Fix tracking of instances sharing handle 0x00

In reply to Greg Kroah-Hartman

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

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

From: Luiz Augusto von Dentz <[email protected]>

[ Upstream commit 1bfecdbd031711e5205ae78f3b8c296e5a53bc55 ]

When the controller supports a single advertising set, instance 1 uses handle 0x00 which is the same handle used by instance 0 (Global Advertising), but hci_cc_le_set_ext_adv_enable would lookup the instance using the handle as instance identifier, marking instance 0 as enabled/disabled instead of instance 1, leaving its state out of sync.

Fix this by matching instances by handle and, for handle 0x00, using hdev->cur_adv_instance, now set when enabling an instance, to determine which instance owns the set. Also disable the instance sharing the advertising set of instance 0 before overriding it.

Fixes e77f43d531af ("Bluetooth: hci_core: Fix not handling hdev->le_num_of_adv_sets=1")
Assisted-by OpenCode:claude-opus-5.5
---
 net/bluetooth/hci_event.c | 47 ++++++++++++++++++++++++++++++---------
 net/bluetooth/hci_sync.c  | 35 ++++++++++++++++++++++++++++-
 2 files changed, 70 insertions(+), 12 deletions(-)
net/bluetooth/hci_event.c +36 -11
index 7309159a8930a..c9cf7f27d21b9 100644
@@ -1617,6 +1617,39 @@ static u8 hci_cc_le_set_adv_enable(struct hci_dev *hdev, void *data,
 	return rp->status;
 }
 
+/* Update the enabled state of the instance(s) using the advertising set
+ * identified by handle.
+ *
+ * Instances may share handle 0x00 with instance 0 (Global Advertising), e.g.
+ * when the controller supports a single advertising set, in which case the
+ * set is owned by the instance last enabled (hdev->cur_adv_instance) and any
+ * other instance sharing it shall be considered disabled.
+ */
+static void hci_le_ext_adv_set_enabled(struct hci_dev *hdev, u8 handle,
+				       bool enable)
+{
+	struct adv_info *adv;
+	bool owned = false;
+
+	list_for_each_entry(adv, &hdev->adv_instances, list) {
+		if (adv->handle != handle)
+			continue;
+
+		adv->enabled = enable &&
+			       (handle ||
+				adv->instance == hdev->cur_adv_instance);
+		owned |= adv->enabled;
+	}
+
+	if (handle)
+		return;
+
+	if (enable && !owned)
+		hci_dev_set_flag(hdev, HCI_LE_ADV_0);
+	else
+		hci_dev_clear_flag(hdev, HCI_LE_ADV_0);
+}
+
 static u8 hci_cc_le_set_ext_adv_enable(struct hci_dev *hdev, void *data,
 				       struct sk_buff *skb)
 {
@@ -1638,18 +1671,13 @@ static u8 hci_cc_le_set_ext_adv_enable(struct hci_dev *hdev, void *data,
 
 	hci_dev_lock(hdev);
 
-	if (cp->num_of_sets)
-		adv = hci_find_adv_instance(hdev, set->handle);
-
 	if (cp->enable) {
 		struct hci_conn *conn;
 
 		hci_dev_set_flag(hdev, HCI_LE_ADV);
 
-		if (adv)
-			adv->enabled = true;
-		else if (!set->handle)
-			hci_dev_set_flag(hdev, HCI_LE_ADV_0);
+		if (cp->num_of_sets)
+			hci_le_ext_adv_set_enabled(hdev, set->handle, true);
 
 		conn = hci_lookup_le_connect(hdev);
 		if (conn)
@@ -1658,10 +1686,7 @@ static u8 hci_cc_le_set_ext_adv_enable(struct hci_dev *hdev, void *data,
 					   conn->conn_timeout);
 	} else {
 		if (cp->num_of_sets) {
-			if (adv)
-				adv->enabled = false;
-			else if (!set->handle)
-				hci_dev_clear_flag(hdev, HCI_LE_ADV_0);
+			hci_le_ext_adv_set_enabled(hdev, set->handle, false);
 
 			/* If just one instance was disabled check if there are
 			 * any other instance enabled, including instance 0,
net/bluetooth/hci_sync.c +34 -1
index 7219742531124..1e7ff1414e215 100644
@@ -1158,6 +1158,30 @@ int hci_update_random_address_sync(struct hci_dev *hdev, bool require_privacy,
 	return 0;
 }
 
+/* Check if the advertising set with handle 0x00 is in use, either by instance
+ * 0 or by an instance sharing its advertising set.
+ */
+static bool hci_ext_adv_handle_0_enabled(struct hci_dev *hdev)
+{
+	struct adv_info *adv;
+	bool enabled;
+
+	hci_dev_lock(hdev);
+
+	enabled = hci_dev_test_flag(hdev, HCI_LE_ADV_0);
+
+	list_for_each_entry(adv, &hdev->adv_instances, list) {
+		if (!adv->handle && adv->enabled) {
+			enabled = true;
+			break;
+		}
+	}
+
+	hci_dev_unlock(hdev);
+
+	return enabled;
+}
+
 int hci_disable_ext_adv_legacy_instance_sync(struct hci_dev *hdev)
 {
 	struct hci_cp_le_set_ext_adv_enable *cp;
@@ -1165,7 +1189,7 @@ int hci_disable_ext_adv_legacy_instance_sync(struct hci_dev *hdev)
 	u8 data[sizeof(*cp) + sizeof(*set) * 1];
 	u8 size;
 
-	if (!hci_dev_test_flag(hdev, HCI_LE_ADV_0))
+	if (!hci_ext_adv_handle_0_enabled(hdev))
 		return 0;
 
 	memset(data, 0, sizeof(data));
@@ -1411,6 +1435,9 @@ int hci_setup_ext_adv_instance_sync(struct hci_dev *hdev, u8 instance)
 			return -EINVAL;
 		}
 	} else {
+		/* Disable the advertising set with handle 0x00, including any
+		 * instance sharing it, since it is going to be overridden.
+		 */
 		err = hci_disable_ext_adv_legacy_instance_sync(hdev);
 		if (err)
 			return err;
@@ -1679,6 +1706,12 @@ int hci_enable_ext_advertising_sync(struct hci_dev *hdev, u8 instance)
 		set->duration = cpu_to_le16(duration / 10);
 	}
 
+	/* Track which instance owns the advertising set since the handle
+	 * alone is ambiguous when instances share handle 0x00, see
+	 * hci_cc_le_set_ext_adv_enable.
+	 */
+	hdev->cur_adv_instance = instance;
+
 	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_EXT_ADV_ENABLE,
 				     sizeof(*cp) +
 				     sizeof(*set) * cp->num_of_sets,
Signature · 1 line
2.53.0
author maintainer
#1908 lore raw

PATCH 1891/2651 Bluetooth: MGMT: Fix pending state of instances added without HCI traffic

In reply to Greg Kroah-Hartman

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

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

From: Luiz Augusto von Dentz <[email protected]>

[ Upstream commit 5548fb51aa3cc24545029a286882d261a8e77d8a ]

When Add Advertising completes without HCI communication, e.g. when the device is not powered or the instance is overridden by Global Advertising, the instance is left marked as pending, so a subsequent failure in add_adv_complete would remove it despite it having been successfully added.

Fix this by clearing the pending state before completing the command.

Fixes fffd38bca51c ("Bluetooth: mgmt/hci_core: multi-adv for add_advertising*()")
Assisted-by OpenCode:claude-opus-5.5
---
 net/bluetooth/mgmt.c | 6 ++++++
 1 file changed, 6 insertions(+)
net/bluetooth/mgmt.c +6 -0
index c669c80d74bfb..492b86f39bdf9 100644
@@ -9160,6 +9160,12 @@ static int add_advertising(struct sock *sk, struct hci_dev *hdev,
 	if (!hdev_is_powered(hdev) ||
 	    adv_overridden_by_global(hdev, adv) ||
 	    !schedule_instance) {
+		/* Instance has been accepted so it shall no longer be
+		 * considered pending, otherwise a later failure in
+		 * add_adv_complete would remove it.
+		 */
+		adv->pending = false;
+
 		rp.instance = cp->instance;
 		err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_ADD_ADVERTISING,
 					MGMT_STATUS_SUCCESS, &rp, sizeof(rp));
Signature · 1 line
2.53.0
author maintainer
#1909 lore raw

PATCH 1892/2651 Bluetooth: MGMT: Fix leaking instance on Add Extended Advertising Parameters

In reply to Greg Kroah-Hartman

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

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

From: Luiz Augusto von Dentz <[email protected]>

[ Upstream commit f7f0d0a9eb6e4616c0b3a2a95498b5204c5543c9 ]

If queueing the command fails the instance is never removed, despite it having already been added or modified by hci_add_adv_instance, so remove it as it is done by add_ext_adv_params_complete on failure, signaling it has been removed if it was previously added.

Fixes cba6b758711c ("Bluetooth: hci_sync: Make use of hci_cmd_sync_queue set 2")
Assisted-by OpenCode:claude-opus-5.5
---
 net/bluetooth/mgmt.c | 19 ++++++++++++++++---
 1 file changed, 16 insertions(+), 3 deletions(-)
net/bluetooth/mgmt.c +16 -3
index 492b86f39bdf9..09fa3202f28ab 100644
@@ -9348,14 +9348,15 @@ static int add_ext_adv_params(struct sock *sk, struct hci_dev *hdev,
 				       data, data_len);
 		if (!cmd) {
 			err = -ENOMEM;
-			hci_remove_adv_instance(hdev, cp->instance);
-			goto unlock;
+			goto remove;
 		}
 
 		err = hci_cmd_sync_queue(hdev, add_ext_adv_params_sync, cmd,
 					 add_ext_adv_params_complete);
-		if (err < 0)
+		if (err < 0) {
 			mgmt_pending_free(cmd);
+			goto remove;
+		}
 	} else {
 		rp.instance = cp->instance;
 		rp.tx_power = HCI_ADV_TX_POWER_NO_PREFERENCE;
@@ -9366,6 +9367,18 @@ static int add_ext_adv_params(struct sock *sk, struct hci_dev *hdev,
 					MGMT_STATUS_SUCCESS, &rp, sizeof(rp));
 	}
 
+	goto unlock;
+
+remove:
+	/* The instance may have been modified already so remove it, like it
+	 * is done in add_ext_adv_params_complete, signaling it has been
+	 * removed if it was previously added.
+	 */
+	if (!adv->pending)
+		mgmt_advertising_removed(sk, hdev, cp->instance);
+
+	hci_remove_adv_instance(hdev, cp->instance);
+
 unlock:
 	hci_dev_unlock(hdev);
 
Signature · 1 line
2.53.0
author maintainer
#1910 lore raw

PATCH 1893/2651 Bluetooth: 6LoWPAN: Use RCU-safe device list removal

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit 8c27d7d06e21ba9455ddae4e14f364c57f095cba ]

RCU readers of bt_6lowpan_devices must be able to follow an adapter's forward link until their read-side critical section ends. The entries are published with list_add_rcu(), but device_event() removes an entry on NETDEV_UNREGISTER with list_del(), poisoning that link.

When an adapter is being unregistered and 6LoWPAN is enabled, a 6lowpan_control debugfs write with an existing LE L2CAP connection can enter lookup_peer() after unregister's first synchronize_net(). If the connection has no peer on that adapter, the reader must advance to the next list entry. Neither RTNL nor devices_lock excludes this RCU reader.

The last peer's chan_close_cb() schedules delete_netdev(), which reaches unregister_netdevice_many_notify() through unregister_dev() and lowpan_unregister_netdev(). The following ordering is possible:

Unregister worker Control writer
----------------- --------------
synchronize_net() returns
lowpan_control_write() lookup_peer(): rcu_read_lock() reach adapter; no matching peer
device_event(): devices_lock
list_del(&entry->list)
spin_unlock(&devices_lock)
follow poisoned next link read invalid adapter address
post-notifier synchronize_net()
waits for the reader

This invalid pointer access can fault in lookup_peer(). The first grace period drains existing readers but permits new ones to start, and the later grace period cannot prevent the intervening poisoned-link access.

Use list_del_rcu() under the existing devices_lock to preserve the forward link for readers that already reached the adapter. The existing post-notifier synchronize_net() waits for those readers before netdevice teardown frees the private storage containing lowpan_btle_dev.

KASAN report as below:

    [...]
    [   45.867526] Oops: general protection fault, probably for non-canonical address 0xfbd59c0000000023: 0000 [#1] SMP KASAN NOPTI
    [   45.869489] KASAN: maybe wild-memory-access in range [0xdead000000000118-0xdead00000000011f]
    [   45.870981] CPU: 1 UID: 0 PID: 646 Comm: sh Not tainted 7.2.0-rc6-pmb-bt-functional-v1+ #4 PREEMPT(lazy)
    [   45.872609] Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
    [   45.874380] RIP: 0010:lookup_peer+0x1ba/0x320
    [   45.875067] Code: 48 89 d9 ba 04 00 00 00 4c 89 fe bf a0 06 00 00 e8 2b e8 ad fb e9 56 ff ff ff e8 01 1e c3 fb 49 8d 7f 18 48 89 f8 48 c1 e8 03 <80> 3c 28 00 0f 85 4a 01 00 00 4d 8b 47 18 4c 89 f1 ba 04 00 00 00
    [   45.878206] RSP: 0018:ffff888114d67b90 EFLAGS: 00010212
    [   45.879106] RAX: 1bd5a00000000023 RBX: 0000000000000000 RCX: ffffffff85c1d19f
    [   45.880334] RDX: ffff88810dc35700 RSI: 0000000000000000 RDI: dead000000000118
    [   45.881455] RBP: dffffc0000000000 R08: 0000000000000001 R09: 0000000000000001
    [   45.882546] R10: ffffffff893d3057 R11: ffff88810dc35700 R12: ffff88810a690000
    [   45.883839] R13: ffff888115451038 R14: ffff88810a690000 R15: dead000000000100
    [   45.885186] FS:  00007fa889bac780(0000) GS:ffff8881fd852000(0000) knlGS:0000000000000000
    [   45.886539] CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
    [   45.887527] CR2: 00007ffe304f2f80 CR3: 0000000104f64005 CR4: 0000000000770ef0
    [   45.888687] PKRU: 55555554
    [   45.889183] Call Trace:
    [   45.889666]  <TASK>
    [   45.890061]  lowpan_control_write+0x445/0x9e0
    [   45.890854]  ? __pfx_lowpan_control_write+0x10/0x10
    [   45.891738]  ? srso_alias_return_thunk+0x5/0xfbef5
    [   45.892603]  ? srso_alias_return_thunk+0x5/0xfbef5
    [   45.893383]  ? __debugfs_file_get+0x1bd/0x7f0
    [   45.894057]  ? srso_alias_return_thunk+0x5/0xfbef5
    [   45.894902]  ? lock_acquire+0x17b/0x2f0
    [   45.895593]  ? ksys_write+0x111/0x200
    [   45.896290]  full_proxy_write+0x11f/0x180
    [   45.896991]  vfs_write+0x25a/0x1010
    [   45.897642]  ? __pfx_full_proxy_write+0x10/0x10
    [   45.898440]  ? __pfx_vfs_write+0x10/0x10
    [   45.899178]  ? lock_release+0x11f/0x280
    [   45.899855]  ksys_write+0x111/0x200
    [   45.900435]  ? __pfx_ksys_write+0x10/0x10
    [   45.901074]  ? irqentry_exit+0xbe/0x820
    [   45.901722]  ? srso_alias_return_thunk+0x5/0xfbef5
    [   45.902489]  do_syscall_64+0x115/0x6a0
    [   45.903064]  entry_SYSCALL_64_after_hwframe+0x77/0x7f
    [   45.903813] RIP: 0033:0x7fa889c3e687
    [   45.904359] Code: 48 89 fa 4c 89 df e8 58 b3 00 00 8b 93 08 03 00 00 59 5e 48 83 f8 fc 74 1a 5b c3 0f 1f 84 00 00 00 00 00 48 8b 44 24 10 0f 05 <5b> c3 0f 1f 80 00 00 00 00 83 e2 39 83 fa 08 75 de e8 23 ff ff ff
    [   45.906981] RSP: 002b:00007ffd7651b960 EFLAGS: 00000202 ORIG_RAX: 0000000000000001
    [   45.908070] RAX: ffffffffffffffda RBX: 00007fa889bac780 RCX: 00007fa889c3e687
    [   45.909102] RDX: 000000000000001c RSI: 00005570f25e8d10 RDI: 0000000000000001
    [   45.910133] RBP: 00005570f25e8d10 R08: 0000000000000000 R09: 0000000000000000
    [   45.911162] R10: 0000000000000000 R11: 0000000000000202 R12: 0000000000000001
    [   45.912190] R13: 000000000000001c R14: 0000000000000000 R15: 00005570f25e8a78
    [   45.913208]  </TASK>
    [   45.913530] Modules linked in:
    [   45.914022] ---[ end trace 0000000000000000 ]---
    [   45.914709] RIP: 0010:lookup_peer+0x1ba/0x320
    [   45.915436] Code: 48 89 d9 ba 04 00 00 00 4c 89 fe bf a0 06 00 00 e8 2b e8 ad fb e9 56 ff ff ff e8 01 1e c3 fb 49 8d 7f 18 48 89 f8 48 c1 e8 03 <80> 3c 28 00 0f 85 4a 01 00 00 4d 8b 47 18 4c 89 f1 ba 04 00 00 00
    [   45.919191] RSP: 0018:ffff888114d67b90 EFLAGS: 00010212
    [   45.920046] RAX: 1bd5a00000000023 RBX: 0000000000000000 RCX: ffffffff85c1d19f
    [   45.921129] RDX: ffff88810dc35700 RSI: 0000000000000000 RDI: dead000000000118
    [   45.922553] RBP: dffffc0000000000 R08: 0000000000000001 R09: 0000000000000001
    [   45.923653] R10: ffffffff893d3057 R11: ffff88810dc35700 R12: ffff88810a690000
    [   45.925119] R13: ffff888115451038 R14: ffff88810a690000 R15: dead000000000100
    [   45.926180] FS:  00007fa889bac780(0000) GS:ffff8881fd852000(0000) knlGS:0000000000000000
    [   45.927817] CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
    [   45.928726] CR2: 00007ffe304f2f80 CR3: 0000000104f64005 CR4: 0000000000770ef0
    [   45.930069] PKRU: 55555554
    [   45.930456] Kernel panic - not syncing: Fatal exception
    [   45.931542] Kernel Offset: disabled
    [   45.932040] Rebooting in 1 seconds..
Fixes 90305829635d ("Bluetooth: 6lowpan: Converting rwlocks to use RCU")
Assisted-by LLM
---
 net/bluetooth/6lowpan.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/bluetooth/6lowpan.c +1 -1
index 500211793528f..9a3e3ced9fd6c 100644
@@ -1273,7 +1273,7 @@ static int device_event(struct notifier_block *unused,
 			if (entry->netdev == netdev) {
 				BT_DBG("Unregistered netdev %s %p",
 				       netdev->name, netdev);
-				list_del(&entry->list);
+				list_del_rcu(&entry->list);
 				break;
 			}
 		}
Signature · 1 line
2.53.0
author maintainer
#1911 lore raw

PATCH 1894/2651 Bluetooth: Add missing newline to bt_dev_{err,warn}_ratelimited()

In reply to Greg Kroah-Hartman

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

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

From: Hitalo Souza <[email protected]>

[ Upstream commit f51ee3bb5fbe9c2019c31befe330bddd3aee39c2 ]

bt_dev_err_ratelimited() and bt_dev_warn_ratelimited() pass the format string to bt_err_ratelimited()/bt_warn_ratelimited() without appending a newline, unlike bt_dev_err() and bt_dev_warn(), which go through BT_ERR()/BT_WARN() and add one. Only 2 of the 22 in-tree callers (both in virtio_bt) put the newline in their own format string.

A printk record without a trailing newline is stored with prb_commit() instead of prb_final_commit(), and readers of the log buffer (/dev/kmsg, syslog) do not see it until it is finalized, which only happens when the next record is reserved. These messages therefore stay invisible until some unrelated message is printed, and journald, which timestamps a record when it reads it, logs them with the time of that later message.

This was observed with a MediaTek MT7921 controller (USB 04ca:3802):
when an eSCO link is closed, the host still receives a few SCO packets for the handle after Disconnection Complete, so hci_scodata_packet() logs "SCO packet for unknown connection handle". Comparing the record's kernel timestamp (_SOURCE_MONOTONIC_TIMESTAMP) with the time journald received it, over one capture:

  emitted       logged        delay
  15:36:52.896  15:37:00.214    7.3 s
  15:37:03.410  15:39:05.574  122.2 s
  15:39:05.574  15:39:12.506    6.9 s
  15:39:19.791  15:40:54.109   94.3 s
  15:41:22.021  15:41:24.647    2.6 s

Each message showed up together with the next kernel message; the 94 s one looked as if it had been logged in the middle of a later, healthy eSCO connection.

bt_dev_err_ratelimited() lost its newline in commit 657cc646475b ("Bluetooth: Remove usage of BT_ERR_RATELIMITED macro"), which replaced BT_ERR_RATELIMITED(), the variant that appended "\n", with a direct call to bt_err_ratelimited(). bt_dev_warn_ratelimited() never had one.

Append the newline in both macros, as BT_ERR() and BT_WARN() do, and drop it from the two virtio_bt format strings so that their messages do not gain an empty line.

Fixes 36278a5d4d35 ("Bluetooth: Adding a bt_dev_warn_ratelimited macro.")
Fixes 657cc646475b ("Bluetooth: Remove usage of BT_ERR_RATELIMITED macro")
Assisted-by Claude:claude-opus-5-5
---
 drivers/bluetooth/virtio_bt.c     | 4 ++--
 include/net/bluetooth/bluetooth.h | 4 ++--
 2 files changed, 4 insertions(+), 4 deletions(-)
drivers/bluetooth/virtio_bt.c +2 -2
index c20d54088c8c4..c67f329b67529 100644
@@ -228,7 +228,7 @@ static void virtbt_rx_handle(struct virtio_bluetooth *vbt, struct sk_buff *skb)
 
 	if (skb->len < min_hdr) {
 		bt_dev_err_ratelimited(vbt->hdev,
-				       "rx pkt_type 0x%02x payload %u < hdr %zu\n",
+				       "rx pkt_type 0x%02x payload %u < hdr %zu",
 				       pkt_type, skb->len, min_hdr);
 		kfree_skb(skb);
 		return;
@@ -251,7 +251,7 @@ static void virtbt_rx_work(struct work_struct *work)
 
 	if (!len || len > VIRTBT_RX_BUF_SIZE) {
 		bt_dev_err_ratelimited(vbt->hdev,
-				       "rx reply len %u outside [1, %u]\n",
+				       "rx reply len %u outside [1, %u]",
 				       len, VIRTBT_RX_BUF_SIZE);
 		kfree_skb(skb);
 	} else {
include/net/bluetooth/bluetooth.h +2 -2
index b624da5026f50..cd91892445666 100644
@@ -296,9 +296,9 @@ void bt_err_ratelimited(const char *fmt, ...);
 	BT_DBG("%s: " fmt, bt_dev_name(hdev), ##__VA_ARGS__)
 
 #define bt_dev_warn_ratelimited(hdev, fmt, ...)			\
-	bt_warn_ratelimited("%s: " fmt, bt_dev_name(hdev), ##__VA_ARGS__)
+	bt_warn_ratelimited("%s: " fmt "\n", bt_dev_name(hdev), ##__VA_ARGS__)
 #define bt_dev_err_ratelimited(hdev, fmt, ...)			\
-	bt_err_ratelimited("%s: " fmt, bt_dev_name(hdev), ##__VA_ARGS__)
+	bt_err_ratelimited("%s: " fmt "\n", bt_dev_name(hdev), ##__VA_ARGS__)
 
 /* Connection and socket states */
 enum bt_sock_state {
Signature · 1 line
2.53.0
author maintainer
#1912 lore raw

PATCH 1895/2651 Bluetooth: hci_core: Keep RCU protection through LTK filtering

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit 817cbcab91fe870e5b69c835cbd708242c9f8c8e ]

The LTK selected by hci_find_ltk() must remain allocated while its value is checked against the blocked-key list. The finder releases RCU before passing k->val to hci_is_blocked_key(). The helper's own RCU section protects the blocked-key list, but the selected LTK may already have been reclaimed before that section starts.

An LE ATT socket security request can reach smp_ltk_encrypt() without holding hdev->lock. With a matching stored LTK and an LTK-type blocked-key entry present, a concurrent MGMT_OP_LOAD_LONG_TERM_KEYS can remove the selected LTK in the following order:

Socket security Management / RCU reclamation
hci_find_ltk()

    rcu_read_lock()
    select k
    rcu_read_unlock()
                                  load_long_term_keys()
                                    hci_dev_lock(hdev)
                                    hci_smp_ltks_clear(hdev)
                                      list_del_rcu(&k->list)
                                      kfree_rcu(k, rcu)
                                  grace period ends; k is freed
    hci_is_blocked_key(..., k->val)
      memcmp(b->val, val, ...)

The final comparison reads freed LTK bytes. Entering a new RCU section in hci_is_blocked_key() cannot protect a pointer obtained before the completed grace period.

Keep the finder's RCU read-side section active through the blocked-key comparison and the warning that reads k->bdaddr. Release it before returning on either matched-key path. This delays reclamation until the finder has finished using the selected record, following the existing IRK lookup pattern.

KFENCE report as below:

    ==================================================================
    BUG: KFENCE: use-after-free read in hci_is_blocked_key+0xdf/0x240

    Use-after-free read at 0x00000000b9ee38e4 (in kfence-#249):
     hci_is_blocked_key+0xdf/0x240
     blocked_key_wrapper+0xc5/0x140 [pmbd_ltk_probe]
     hci_find_ltk+0x1aa/0x3e0
     smp_ltk_encrypt.isra.0+0xad/0x340
     smp_conn_security+0x3b8/0x8c0
     l2cap_sock_setsockopt+0x1c4b/0x2270
     do_sock_setsockopt+0x1fb/0x430
     __sys_setsockopt+0x106/0x180
     __x64_sys_setsockopt+0xc2/0x160
     do_syscall_64+0x115/0x6a0
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    kfence-#249: 0x00000000121f2ad9-0x000000005b5bfb3d, size=72, cache=kmalloc-96

    allocated by task 495 on cpu 0 at 36.722380s (2.603973s ago):
     hci_add_ltk+0x1f5/0x3a0
     load_long_term_keys+0x6d0/0x860
     hci_sock_sendmsg+0x128b/0x22e0
     __sys_sendto+0x425/0x470
     __x64_sys_sendto+0xe5/0x1c0
     do_syscall_64+0x115/0x6a0
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    freed by task 533 on cpu 0 at 36.993097s (2.339769s ago):
     __rcu_free_sheaf_prepare+0x261/0x2a0
     rcu_free_sheaf+0x1f/0xe0
     rcu_core+0x661/0x1d10
     handle_softirqs+0x201/0x930
     __irq_exit_rcu+0x110/0x1e0
     irq_exit_rcu+0xe/0x20
     sysvec_apic_timer_interrupt+0x6c/0x80
     asm_sysvec_apic_timer_interrupt+0x1a/0x20
     srso_alias_return_thunk+0x0/0xfbef5
     __asan_memcpy+0x23/0x60
     create_monitor_ctrl_event+0x1a2/0x460
     mgmt_cmd_complete+0x2da/0x580
     load_long_term_keys+0x741/0x860
     hci_sock_sendmsg+0x128b/0x22e0
     __sys_sendto+0x425/0x470
     __x64_sys_sendto+0xe5/0x1c0
     do_syscall_64+0x115/0x6a0
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    CPU: 1 UID: 0 PID: 495 Comm: python3 Tainted: G           O        7.2.0-rc6-pmb-bt-functional-v1+ #1 PREEMPT(lazy)
    Tainted: [O]=OOT_MODULE
    Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
    ==================================================================
Fixes 600a87490ff9 ("Bluetooth: Implementation of MGMT_OP_SET_BLOCKED_KEYS.")
Assisted-by LLM
---
 net/bluetooth/hci_core.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
net/bluetooth/hci_core.c +2 -2
index 74d9865e08c22..becac4a223dfd 100644
@@ -1153,16 +1153,16 @@ struct smp_ltk *hci_find_ltk(struct hci_dev *hdev, bdaddr_t *bdaddr,
 			continue;
 
 		if (smp_ltk_is_sc(k) || ltk_role(k->type) == role) {
-			rcu_read_unlock();
-
 			if (hci_is_blocked_key(hdev, HCI_BLOCKED_KEY_TYPE_LTK,
 					       k->val)) {
 				bt_dev_warn_ratelimited(hdev,
 							"LTK blocked for %pMR",
 							&k->bdaddr);
+				rcu_read_unlock();
 				return NULL;
 			}
 
+			rcu_read_unlock();
 			return k;
 		}
 	}
Signature · 1 line
2.53.0
author maintainer
#1913 lore raw

PATCH 1896/2651 Bluetooth: hci_sync: Serialize devcoredump reset during device open

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit 6d91353f6dbcc5c4fbb47bbd0c7f885453cfc939 ]

An ACTIVE devcoredump's buffer cursors must remain valid from the packet handler's state check through its copy. hci_devcd_rx() holds hdev->lock across that interval, and hci_devcd_reset() requires the same lock. However, hci_dev_open_sync() invokes reset without taking it.

A registered VHCI controller can collect a dump through its debugfs interface while the controller is down. If a successful open overlaps with handling a nonempty dump packet, reset can run after the receiver's ACTIVE check and before its copy:

hci_devcd_rx() hci_dev_open_sync()
dequeue nonempty skb
hci_dev_lock(hdev)
handler observes ACTIVE
hdev->open(hdev) succeeds hci_devcd_reset(hdev)
dump.tail = NULL dump.state = IDLE
hci_devcd_copy()
compare against old dump.end
memcpy(NULL, ..., skb->len)
hci_dev_unlock(hdev)

Reset leaves dump.end pointing at the old buffer and purges only queued packets, so it cannot discard the skb already dequeued by the receiver. The bounds check can pass with a NULL tail, leading to a nonempty copy to address zero. KASAN reported a 24-byte NULL write in hci_devcd_rx().

Take hdev->lock around the open-time reset. The receiver then finishes its state check and copy using valid cursors before reset, or observes IDLE after reset and skips the copy.

KASAN report as below:

    BUG: KASAN: null-ptr-deref in hci_devcd_rx+0x5d5/0x1a80
    Write of size 24 at addr 0000000000000000 by task kworker/u17:0/496

        CPU: 0 UID: 0 PID: 496 Comm: kworker/u17:0 Not tainted
    7.2.0-rc6-pmb-bt-functional-v1+ #1 PREEMPT(lazy)
        Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps
    fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
    Workqueue: hci0 hci_devcd_rx
    Call Trace:
     <TASK>
     dump_stack_lvl+0x93/0xd0
     kasan_report+0xe0/0x110
     ? hci_devcd_rx+0x5d5/0x1a80
     kasan_check_range+0x105/0x1b0
     __asan_memcpy+0x3c/0x60
     hci_devcd_rx+0x5d5/0x1a80
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx_hci_devcd_rx+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_release+0xc8/0x280
     ? srso_alias_return_thunk+0x5/0xfbef5
     process_one_work+0x908/0x19c0
     ? __pfx_process_one_work+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_is_held_type+0x8f/0x100
     ? srso_alias_return_thunk+0x5/0xfbef5
     worker_thread+0x65c/0xe40
     ? __pfx_worker_thread+0x10/0x10
     kthread+0x34f/0x460
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx_kthread+0x10/0x10
     ret_from_fork+0x659/0x940
     ? __pfx_ret_from_fork+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __switch_to+0x74f/0xf80
     ? __pfx_kthread+0x10/0x10
     ret_from_fork_asm+0x1a/0x30
     </TASK>
    ==================================================================
    Disabling lock debugging due to kernel taint
Fixes 9695ef876fd1 ("Bluetooth: Add support for hci devcoredump")
Assisted-by LLM
---
 net/bluetooth/hci_sync.c | 2 ++
 1 file changed, 2 insertions(+)
net/bluetooth/hci_sync.c +2 -0
index 1e7ff1414e215..2a34528da0752 100644
@@ -5479,7 +5479,9 @@ int hci_dev_open_sync(struct hci_dev *hdev)
 		goto done;
 	}
 
+	hci_dev_lock(hdev);
 	hci_devcd_reset(hdev);
+	hci_dev_unlock(hdev);
 
 	set_bit(HCI_RUNNING, &hdev->flags);
 	hci_sock_dev_event(hdev, HCI_DEV_OPEN);
Signature · 1 line
2.53.0
author maintainer
#1914 lore raw

PATCH 1897/2651 Bluetooth: ISO: Hold the listener during disconnect notification

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit b4a00dedc5cc6f6f98c07ec1b54d24a817d9fc88 ]

An ISO listener must remain alive until a queued child's disconnect notification completes. bt_accept_enqueue() retains only the child and stores a raw parent pointer; iso_conn_ready() drops its temporary listener reference after setup. iso_chan_del() saves that pointer, unlinks the child and then calls parent->sk_data_ready() without holding a listener reference.

With an incoming CIS child still queued, disconnect and listener release can proceed in this order:

HCI disconnect Listener release
iso_conn_del(): lock child
iso_chan_del(): save parent bt_accept_unlink(child)
iso_sock_cleanup_listen():
drain empty accept queue
iso_sock_release():
orphan and kill listener final sock_put(listener)
parent->sk_data_ready(parent)

After unlink, listener cleanup no longer has to take the child socket lock. The listener can therefore be freed before iso_chan_del() reads sk_data_ready, causing a use-after-free.

Take a temporary parent reference before bt_accept_unlink() and drop it after the notification. The child lock excludes accept dequeue while the child is still queued, so listener cleanup cannot complete before sock_hold(). The reference then keeps the listener alive across unlink and through the callback without changing lock order.

KASAN report as below:

    ==================================================================
    BUG: KASAN: slab-use-after-free in iso_chan_del+0x302/0x320
    Read of size 8 at addr ffff888105ca2188 by task kworker/2:1/50

        CPU: 2 UID: 0 PID: 50 Comm: kworker/2:1 Not tainted
    7.2.0-rc6-pmb-bt-functional-v1+ #1 PREEMPT(lazy)
        Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps
    fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
    Workqueue: events iso_fixture_disconnect_work
    Call Trace:
     <TASK>
     dump_stack_lvl+0x93/0xd0
     print_report+0xce/0x630
     ? iso_chan_del+0x302/0x320
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __virt_addr_valid+0x20d/0x410
     ? iso_chan_del+0x302/0x320
     kasan_report+0xe0/0x110
     ? iso_chan_del+0x302/0x320
     iso_chan_del+0x302/0x320
     iso_conn_del+0x19d/0x3c0
     ? __pfx_iso_disconn_cfm+0x10/0x10
     iso_disconn_cfm+0x78/0x120
     hci_disconn_complete_evt+0x319/0xa30
     ? find_held_lock+0x2b/0x80
     hci_test_iso_disconn_event+0x85/0xb0
     ? __pfx_hci_test_iso_disconn_event+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? _raw_read_unlock+0x23/0x40
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __hci_dev_get+0x15d/0x280
     iso_fixture_disconnect_work+0x67/0x290
     process_one_work+0x908/0x19c0
     ? __pfx_process_one_work+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_is_held_type+0x8f/0x100
     ? srso_alias_return_thunk+0x5/0xfbef5
     worker_thread+0x65c/0xe40
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __kthread_parkme+0x175/0x220
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx_worker_thread+0x10/0x10
     kthread+0x34f/0x460
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx_kthread+0x10/0x10
     ret_from_fork+0x659/0x940
     ? __pfx_ret_from_fork+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __switch_to+0x74f/0xf80
     ? __pfx_kthread+0x10/0x10
     ret_from_fork_asm+0x1a/0x30
     </TASK>

    Allocated by task 521:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     __kasan_kmalloc+0xaa/0xb0
     __kmalloc_noprof+0x2d7/0x770
     sk_prot_alloc+0x13e/0x260
     sk_alloc+0x37/0xb40
     bt_sock_alloc+0x40/0x3b0
     iso_sock_alloc.constprop.0+0x3a/0x360
     iso_sock_create+0xc7/0x160
     bt_sock_create+0x171/0x330
     __sock_create+0x2c4/0x730
     __sys_socket+0x141/0x210
     __x64_sys_socket+0x77/0xc0
     do_syscall_64+0x115/0x6a0
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    Freed by task 521:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     kasan_save_free_info+0x3b/0x60
     __kasan_slab_free+0x5f/0x80
     kfree+0x307/0x580
     __sk_destruct+0x64f/0x790
     sk_destruct+0xb3/0xd0
     __sk_free+0xdd/0x370
     sk_free+0x51/0x80
     iso_sock_release+0x46d/0x5b0
     __sock_release+0xb8/0x270
     sock_close+0x21/0x30
     __fput+0x39f/0xa60
     task_work_run+0x144/0x230
     do_exit+0x834/0x2830
     do_group_exit+0xc7/0x280
     get_signal+0x20a9/0x2400
     arch_do_signal_or_restart+0x94/0x6f0
     exit_to_user_mode_loop+0xcf/0x570
     do_syscall_64+0x4f0/0x6a0
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    The buggy address belongs to the object at ffff888105ca2000
                                                                which
                                belongs to the cache kmalloc-2k of size
                                2048
    The buggy address is located 392 bytes inside of
                                                                freed
                                2048-byte region [ffff888105ca2000,
                                ffff888105ca2800)

    The buggy address belongs to the physical page:
        page: refcount:0 mapcount:0 mapping:0000000000000000
    index:0xffff888105ca5000 pfn:0x105ca0
    head: order:3 mapcount:0 entire_mapcount:0 nr_pages_mapped:0 pincount:0
    flags: 0x200000000000240(workingset|head|node=0|zone=2)
    page_type: f5(slab)
        raw: 0200000000000240 ffff888100042f00 ffffea00042cd010
    ffffea00042c9210
        raw: ffff888105ca5000 0000000000080005 00000000f5000000
    0000000000000000
        head: 0200000000000240 ffff888100042f00 ffffea00042cd010
    ffffea00042c9210
        head: ffff888105ca5000 0000000000080005 00000000f5000000
    0000000000000000
        head: 0200000000000003 fffffffffffffe01 00000000ffffffff
    00000000ffffffff
        head: ffff888105ca1000 0000000000000000 00000000ffffffff
    0000000000000000
    page dumped because: kasan: bad access detected

    Memory state around the buggy address:
     ffff888105ca2080: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
     ffff888105ca2100: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
    >ffff888105ca2180: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
                          ^
     ffff888105ca2200: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
     ffff888105ca2280: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
    ==================================================================
Fixes f764a6c2c1e4 ("Bluetooth: ISO: Add broadcast support")
Assisted-by LLM
---
 net/bluetooth/iso.c | 3 +++
 1 file changed, 3 insertions(+)
net/bluetooth/iso.c +3 -0
index d6ac5b1f49bc1..8768d9c0cf512 100644
@@ -287,8 +287,11 @@ static void iso_chan_del(struct sock *sk, int err)
 
 	parent = bt_sk(sk)->parent;
 	if (parent) {
+		/* Unlinking the child allows the parent to be freed. */
+		sock_hold(parent);
 		bt_accept_unlink(sk);
 		parent->sk_data_ready(parent);
+		sock_put(parent);
 	} else {
 		sk->sk_state_change(sk);
 	}
Signature · 1 line
2.53.0
author maintainer
#1915 lore raw

PATCH 1898/2651 Bluetooth: MGMT: Reject quality report requests during unregister

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit 213e7a99bea19e2f29f394321b86c792eec73a24 ]

A quality report request must not call a driver callback after its module text has been released. hci_mgmt_cmd() holds an hci_dev reference through set_exp_feature(), but that reference only preserves the device allocation. set_quality_report_func() takes req_lock and invokes hdev->set_quality_report without checking HCI_UNREGISTER.

This is unsafe when a SET_EXP_FEATURE request for an Intel controller would change HCI_QUALITY_REPORT and is delayed before taking req_lock while the controller is removed. With btintel_pcie and btintel built as modules and no other btintel dependents, the following order is possible:

Management request Removal and module unload
------------------ -------------------------
hci_mgmt_cmd(): retain hdev
hci_unregister_dev():
set HCI_UNREGISTER remove hdev from lookup close under req_lock release req_lock
btintel_pcie_remove(): return unload btintel_pcie, then btintel
set_quality_report_func():

    take req_lock
    call hdev->set_quality_report

When the request resumes after btintel unload, the indirect call targets released module text and can cause an instruction-fetch page fault. The close operation serializes with a running callback but does not prevent a delayed management handler from invoking it afterwards.

Check HCI_UNREGISTER immediately after acquiring the existing req_lock and return MGMT_STATUS_INVALID_INDEX via the common unlock path. If unregister passed its close section first, the request now rejects the removed controller before accessing the callback. If the request passes the check first, hci_dev_do_close() must wait for req_lock until the callback has returned, so unregister cannot finish before the use.

Oops report as below:

    BUG: unable to handle page fault for address: ffffffffc0408e10
    #PF: supervisor instruction fetch in kernel mode
    #PF: error_code(0x0010) - not-present page
    PGD 80a9067 P4D 80a9067 PUD 80ab067 PMD 0
    Oops: Oops: 0010 [#1] SMP KASAN NOPTI
    CPU: 1 UID: 0 PID: 439 Comm: btmgmt Tainted: G           O        7.2.0-rc6-pmb-bt-functional-v1+ #1 PREEMPT(lazy)
    Tainted: [O]=OOT_MODULE
    Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
    RIP: 0010:0xffffffffc0408e10
    Code: Unable to access opcode bytes at 0xffffffffc0408de6.
    RSP: 0018:ffff888110927838 EFLAGS: 00010293
    RAX: 0000000000000000 RBX: 1ffff11022124f0c RCX: ffffffff85b1a1b6
    RDX: ffff888117511d00 RSI: 0000000000000001 RDI: ffff888117598000
    RBP: ffff888110927950 R08: 0000000000000001 R09: 0000000000000001
    R10: ffffffff893d3057 R11: ffff888117511d00 R12: ffff888117598000
    R13: 0000000000000001 R14: ffffffffc0408e10 R15: ffff888117599970
    FS:  00007f15453f2040(0000) GS:ffff8881fd852000(0000) knlGS:0000000000000000
    CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
    CR2: ffffffffc0408de6 CR3: 000000010b832005 CR4: 0000000000770ef0
    PKRU: 55555554
    Call Trace:
     <TASK>
     ? set_quality_report_func+0x232/0x660
     ? __pfx_set_quality_report_func+0x10/0x10
     ? pmbd_gate_maybe+0x47/0x60
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? pmbd_probe_hit_cookie+0xe7/0x1c0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? pmbd_probe_hit_cookie+0xee/0x1c0
     set_exp_feature+0xf7/0x260
     ? set_exp_feature+0xf7/0x260
     ? hci_sock_sendmsg+0x12b2/0x2400
     ? __pfx_hci_sock_sendmsg+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? selinux_socket_sendmsg+0x160/0x280
     ? sock_write_iter+0x4c0/0x550
     ? __pfx_hci_sock_sendmsg+0x10/0x10
     ? __pfx_sock_write_iter+0x10/0x10
     ? __file_has_perm+0x25e/0x420
     ? __pfx___file_has_perm+0x10/0x10
     ? do_iter_readv_writev+0x59c/0x860
     ? __pfx_do_iter_readv_writev+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? security_file_permission+0x26/0x80
     ? vfs_writev+0x30e/0xc10
     ? __pfx_vfs_writev+0x10/0x10
     ? __pfx_do_epoll_wait+0x10/0x10
     ? __pfx_do_epoll_ctl+0x10/0x10
     ? do_writev+0x241/0x2f0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? do_writev+0x241/0x2f0
     ? __pfx_do_writev+0x10/0x10
     ? irqentry_exit+0xbe/0x820
     ? do_syscall_64+0x115/0x6a0
     ? entry_SYSCALL_64_after_hwframe+0x77/0x7f
     </TASK>
    Modules linked in: [last unloaded: btintel(O)]
    CR2: ffffffffc0408e10
    ---[ end trace 0000000000000000 ]---
    RIP: 0010:0xffffffffc0408e10
    Code: Unable to access opcode bytes at 0xffffffffc0408de6.
    RSP: 0018:ffff888110927838 EFLAGS: 00010293
    RAX: 0000000000000000 RBX: 1ffff11022124f0c RCX: ffffffff85b1a1b6
    RDX: ffff888117511d00 RSI: 0000000000000001 RDI: ffff888117598000
    RBP: ffff888110927950 R08: 0000000000000001 R09: 0000000000000001
    R10: ffffffff893d3057 R11: ffff888117511d00 R12: ffff888117598000
    R13: 0000000000000001 R14: ffffffffc0408e10 R15: ffff888117599970
    FS:  00007f15453f2040(0000) GS:ffff8881fd852000(0000) knlGS:0000000000000000
    CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
    CR2: ffffffffc0408de6 CR3: 000000010b832005 CR4: 0000000000770ef0
    PKRU: 55555554
    Kernel panic - not syncing: Fatal exception
    Kernel Offset: disabled
    Rebooting in 1 seconds..
Fixes ae7d925b5c04 ("Bluetooth: Support the quality report events")
Assisted-by LLM
---
 net/bluetooth/mgmt.c | 7 +++++++
 1 file changed, 7 insertions(+)
net/bluetooth/mgmt.c +7 -0
index 09fa3202f28ab..23b65ceea8955 100644
@@ -4906,6 +4906,13 @@ static int set_quality_report_func(struct sock *sk, struct hci_dev *hdev,
 
 	hci_req_sync_lock(hdev);
 
+	if (hci_dev_test_flag(hdev, HCI_UNREGISTER)) {
+		err = mgmt_cmd_status(sk, hdev->id,
+				      MGMT_OP_SET_EXP_FEATURE,
+				      MGMT_STATUS_INVALID_INDEX);
+		goto unlock_quality_report;
+	}
+
 	val = !!cp->param[0];
 	changed = (val != hci_dev_test_flag(hdev, HCI_QUALITY_REPORT));
 
Signature · 1 line
2.53.0
author maintainer
#1916 lore raw

PATCH 1899/2651 Bluetooth: msft: Lock failed probe cleanup against feature readers

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit 21895f20fedc4504474bcb1022850b532ea4358e ]

The MSFT data must remain allocated while msft_get_features() reads its features. read_adv_mon_features() protects that access with hdev->lock, but msft_do_open() clears hdev->msft_data and frees the object without that lock when read_supported_features() fails.

After a successful probe, the data survives a normal close. A later open can fail the probe while a management feature request is running. hci_mgmt_cmd() permits requests during HCI_INIT, and the opener's hdev->req_lock does not serialize the management reader:

Management feature request HCI open

                                        hold hdev->req_lock
                                        msft_do_open()
  hold hdev->lock
  msft_get_features(): save msft
                                        read_supported_features() fails
                                        hdev->msft_data = NULL
                                        kfree(msft)

read msft->features
release hdev->lock release hdev->req_lock

The saved pointer then refers to freed memory, causing a use-after-free read. Advertisement reporting through mgmt_device_found() also reads the features with hdev->lock held.

Take hdev->lock around clearing and freeing msft_data in the failure branch. An existing feature reader finishes before the free, while a reader starting after cleanup sees NULL. Keep the synchronous probe outside this critical section, following the existing req_lock to hdev->lock ordering.

KASAN report as below:

    ==================================================================
    BUG: KASAN: slab-use-after-free in msft_monitor_supported+0xa9/0xb0
    Read of size 8 at addr ffff88811573ee00 by task mgmt-read-adv-m/532

        CPU: 2 UID: 0 PID: 532 Comm: mgmt-read-adv-m Not tainted
    7.2.0-rc6-pmb-bt-functional-v1+ #1 PREEMPT(lazy)
        Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps
    fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
    Call Trace:
     <TASK>
     dump_stack_lvl+0x93/0xd0
     print_report+0xce/0x630
     ? msft_monitor_supported+0xa9/0xb0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __virt_addr_valid+0x20d/0x410
     ? msft_monitor_supported+0xa9/0xb0
     kasan_report+0xe0/0x110
     ? msft_monitor_supported+0xa9/0xb0
     msft_monitor_supported+0xa9/0xb0
     read_adv_mon_features+0xdf/0x640
     ? trace_hardirqs_on+0x18/0x160
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx_read_adv_mon_features+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? do_raw_read_unlock+0x49/0xe0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? _raw_read_unlock+0x23/0x40
     hci_sock_sendmsg+0x12b5/0x2270
     ? __pfx_hci_sock_sendmsg+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? selinux_socket_sendmsg+0x160/0x280
     __sys_sendto+0x425/0x470
     ? __pfx_hci_sock_sendmsg+0x10/0x10
     ? __pfx___sys_sendto+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __sys_setsockopt+0x119/0x180
     __x64_sys_sendto+0xe5/0x1c0
     ? lockdep_hardirqs_on_prepare+0xea/0x1a0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? trace_hardirqs_on+0x18/0x160
     do_syscall_64+0x115/0x6a0
     entry_SYSCALL_64_after_hwframe+0x77/0x7f
    RIP: 0033:0x7f9ceb04a687
        Code: 48 89 fa 4c 89 df e8 58 b3 00 00 8b 93 08 03 00 00 59 5e 48
    83 f8 fc 74 1a 5b c3 0f 1f 84 00 00 00 00 00 48 8b 44 24 10 0f 05 <5b>
    c3 0f 1f 80 00 00 00 00 83 e2 39 83 fa 08 75 de e8 23 ff ff ff
    RSP: 002b:00007ffe6ab96a70 EFLAGS: 00000202 ORIG_RAX: 000000000000002c
    RAX: ffffffffffffffda RBX: 00007f9ceafb8780 RCX: 00007f9ceb04a687
    RDX: 0000000000000006 RSI: 00007ffe6ab96aea RDI: 0000000000000003
    RBP: 0000000000000002 R08: 0000000000000000 R09: 0000000000000000
    R10: 0000000000000000 R11: 0000000000000202 R12: 0000000000000003
    R13: 00007ffe6ab96d50 R14: 00007f9ceb1f6000 R15: 00005625e427dd68
     </TASK>

    Allocated by task 506:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     __kasan_kmalloc+0xaa/0xb0
     __kmalloc_cache_noprof+0x251/0x610
     msft_register+0x54/0x260
     hci_register_dev+0x6b7/0xc80
     __vhci_create_device+0x330/0x840
     vhci_write+0x287/0x440
     vfs_write+0x637/0x1010
     ksys_write+0x111/0x200
     do_syscall_64+0x115/0x6a0
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    Freed by task 529:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     kasan_save_free_info+0x3b/0x60
     __kasan_slab_free+0x5f/0x80
     kfree+0x307/0x580
     msft_do_open+0x604/0x9e0
     hci_dev_open_sync+0x94a/0x2110
     hci_dev_do_open+0x2f/0xb0
     hci_dev_open+0x17d/0x300
     hci_sock_ioctl+0x3c6/0x710
     sock_do_ioctl+0x120/0x2b0
     sock_ioctl+0x41b/0x670
     __x64_sys_ioctl+0x163/0x1d0
     do_syscall_64+0x115/0x6a0
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    The buggy address belongs to the object at ffff88811573ee00
     which belongs to the cache kmalloc-256 of size 256
    The buggy address is located 0 bytes inside of
     freed 256-byte region [ffff88811573ee00, ffff88811573ef00)

    The buggy address belongs to the physical page:
        page: refcount:0 mapcount:0 mapping:0000000000000000 index:0x0
    pfn:0x11573e
    head: order:1 mapcount:0 entire_mapcount:0 nr_pages_mapped:0 pincount:0
    flags: 0x200000000000040(head|node=0|zone=2)
    page_type: f5(slab)
        raw: 0200000000000040 ffff888100042b40 dead000000000100
    dead000000000122
        raw: 0000000000000000 0000000000100010 00000000f5000000
    0000000000000000
        head: 0200000000000040 ffff888100042b40 dead000000000100
    dead000000000122
        head: 0000000000000000 0000000000100010 00000000f5000000
    0000000000000000
        head: 0200000000000001 ffffffffffffff81 00000000ffffffff
    00000000ffffffff
        head: 0000000000000000 0000000000000000 00000000ffffffff
    0000000000000000
    page dumped because: kasan: bad access detected

    Memory state around the buggy address:
     ffff88811573ed00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
     ffff88811573ed80: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
    >ffff88811573ee00: fa fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
                       ^
     ffff88811573ee80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
     ffff88811573ef00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
    ==================================================================
Fixes 5031ffcc79b8 ("Bluetooth: Keep MSFT ext info throughout a hci_dev's life cycle")
Assisted-by LLM
---
 net/bluetooth/msft.c | 2 ++
 1 file changed, 2 insertions(+)
net/bluetooth/msft.c +2 -0
index d9dd722db3ebd..6f4b7c38a2474 100644
@@ -654,8 +654,10 @@ void msft_do_open(struct hci_dev *hdev)
 	msft->features = 0;
 
 	if (!read_supported_features(hdev, msft)) {
+		hci_dev_lock(hdev);
 		hdev->msft_data = NULL;
 		kfree(msft);
+		hci_dev_unlock(hdev);
 		return;
 	}
 
Signature · 1 line
2.53.0
author maintainer
#1917 lore raw

PATCH 1900/2651 Bluetooth: 6lowpan: Drain RCU readers on registration failure

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit ebba800d140b580540ad55f670d943e4a7edaffd ]

A lowpan_btle_dev is embedded in its net_device allocation and must remain alive until readers of bt_6lowpan_devices have left their RCU sections. setup_netdev() publishes it before registration, but its error path only unlinks it before calling free_netdev().

If a second controller's registration fails while multicast is sent on an existing 6LoWPAN interface, send_mcast_pkt() can already have selected the new entry. It reads entry->netdev before checking which interface owns it. An early failure, such as allocating the device's name node, leaves NETREG_UNINITIALIZED, so free_netdev() releases the storage immediately.

The following ordering frees the selected entry before the reader loads its netdev field:

Adapter creation (controller B) Multicast on controller A
setup_netdev()

    list_add_rcu()
                                       rcu_read_lock()
                                       select B's entry
    lowpan_register_netdev() fails
    list_del_rcu()
    free_netdev()
                                       read entry->netdev
                                       rcu_read_unlock()

Removing the list node does not wait for that reader, and devices_lock does not serialize the multicast reader. The subsequent field load is a use-after-free, reported by KASAN in bt_xmit().

Wait for an RCU grace period after dropping devices_lock and before free_netdev(). This keeps the failed adapter allocated until traversals that could have selected it complete. The callback is already sleepable, and the wait happens outside the list spinlock.

KASAN report as below:

    ==================================================================
    BUG: KASAN: slab-use-after-free in bt_xmit+0x1d06/0x21e0
    Read of size 8 at addr ffff88810ef45030 by task python3/556

    Call Trace:
     <TASK>
     dump_stack_lvl+0x93/0xd0
     print_report+0xce/0x630
     ? bt_xmit+0x1d06/0x21e0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __virt_addr_valid+0x20d/0x410
     ? bt_xmit+0x1d06/0x21e0
     kasan_report+0xe0/0x110
     ? bt_xmit+0x1d06/0x21e0
     bt_xmit+0x1d06/0x21e0
     ? __pfx_bt_xmit+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_acquire+0x17b/0x2f0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_is_held_type+0x8f/0x100
     ? dev_hard_start_xmit+0x187/0x660
     ? __pfx_bt_xmit+0x10/0x10
     dev_hard_start_xmit+0x187/0x660
     sch_direct_xmit+0x153/0x850
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx_sch_direct_xmit+0x10/0x10
     ? do_raw_spin_lock+0x130/0x270
     ? __pfx_do_raw_spin_lock+0x10/0x10
     ? lock_is_held_type+0x8f/0x100
     __dev_queue_xmit+0x3111/0x3aa0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? look_up_lock_class+0x59/0x130
     ? register_lock_class+0x41/0x790
     ? __pfx___dev_queue_xmit+0x10/0x10
     ? __lock_acquire+0x466/0x2260
     ? find_held_lock+0x2b/0x80
     ? ___neigh_create+0x1690/0x2540
     ? __local_bh_enable_ip+0xa6/0x120
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lockdep_hardirqs_on_prepare+0xea/0x1a0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_acquire+0x17b/0x2f0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? find_held_lock+0x2b/0x80
     ? ip6_finish_output2+0x8be/0x1840
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? neigh_connected_output+0x39f/0x4e0
     ? srso_alias_return_thunk+0x5/0xfbef5
     neigh_connected_output+0x33f/0x4e0
     ip6_finish_output2+0x8be/0x1840
     ip6_finish_output+0x424/0xd50
     ip6_output+0x210/0x640
     ? __pfx_ip6_mr_output+0x10/0x10
     ip6_local_out+0x193/0x1c0
     ip6_send_skb+0xfb/0x3e0
     udp_v6_send_skb+0x6e1/0x1180
     udpv6_sendmsg+0x1f9b/0x2a00
     ? get_random_u32+0xaf/0x640
     ? __pfx_udpv6_sendmsg+0x10/0x10
     ? lock_release+0xc8/0x280
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lockdep_hardirqs_on_prepare+0xea/0x1a0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? trace_hardirqs_on+0x18/0x160
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __local_bh_enable_ip+0xa6/0x120
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx_udpv6_sendmsg+0x10/0x10
     ? inet6_sendmsg+0xff/0x140
     inet6_sendmsg+0xff/0x140
     __sys_sendto+0x320/0x470
     ? __pfx___sys_sendto+0x10/0x10
     ? exc_page_fault+0x5c/0xc0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_release+0xc8/0x280
     ? handle_mm_fault+0x12e/0x580
     __x64_sys_sendto+0xe5/0x1c0
     ? lockdep_hardirqs_on_prepare+0xea/0x1a0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? trace_hardirqs_on+0x18/0x160
     do_syscall_64+0x115/0x6a0
     entry_SYSCALL_64_after_hwframe+0x77/0x7f
    Allocated by task 502:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     __kasan_kmalloc+0xaa/0xb0
     __kvmalloc_node_noprof+0x353/0x930
     alloc_netdev_mqs+0xa0/0x1250
     chan_ready_cb+0x198/0x1110
     l2cap_recv_frame+0x6dc0/0x8830
     l2cap_recv_acldata+0xe9f/0x10e0
     hci_rx_work+0x5a6/0xf00
     process_one_work+0x908/0x19c0
     worker_thread+0x65c/0xe40
     kthread+0x34f/0x460
     ret_from_fork+0x659/0x940
     ret_from_fork_asm+0x1a/0x30

    Freed by task 502:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     kasan_save_free_info+0x3b/0x60
     __kasan_slab_free+0x5f/0x80
     kfree+0x307/0x580
     free_netdev+0x6ca/0x8f0
     chan_ready_cb+0xd91/0x1110
     l2cap_recv_frame+0x6dc0/0x8830
     l2cap_recv_acldata+0xe9f/0x10e0
     hci_rx_work+0x5a6/0xf00
     process_one_work+0x908/0x19c0
     worker_thread+0x65c/0xe40
     kthread+0x34f/0x460
     ret_from_fork+0x659/0x940
     ret_from_fork_asm+0x1a/0x30

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

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

    Memory state around the buggy address:
     ffff88810ef44f00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
     ffff88810ef44f80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
    >ffff88810ef45000: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
                                         ^
     ffff88810ef45080: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
     ffff88810ef45100: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
    ==================================================================
    Disabling lock debugging due to kernel taint
Fixes 5857d1dbae7d ("Bluetooth: 6lowpan: Fix possible race")
Assisted-by LLM
---
 net/bluetooth/6lowpan.c | 1 +
 1 file changed, 1 insertion(+)
net/bluetooth/6lowpan.c +1 -0
index 9a3e3ced9fd6c..99fee6f4de88b 100644
@@ -706,6 +706,7 @@ static int setup_netdev(struct l2cap_chan *chan, struct lowpan_btle_dev **dev)
 		spin_lock(&devices_lock);
 		list_del_rcu(&(*dev)->list);
 		spin_unlock(&devices_lock);
+		synchronize_rcu();
 		free_netdev(netdev);
 		goto out;
 	}
Signature · 1 line
2.53.0
author maintainer
#1918 lore raw

PATCH 1901/2651 Bluetooth: btmtk: fix skb double free on ISO padding failure

In reply to Greg Kroah-Hartman

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

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

From: Eric Dumazet <[email protected]>

[ Upstream commit 491d2212ea0f0f6a3abbd67729df0c6a3ec9c58a ]

btmtk_isopkt_pad() uses skb_pad(), which frees the skb on failure.

The error is propagated by alloc_mtk_intr_urb() and btusb_send_frame_mtk() up to hci_send_frame(), which frees the skb a second time:

	err = hdev->send(hdev, skb);
	if (err < 0) {
		bt_dev_err(hdev, "sending frame failed (%d)", err);
		kfree_skb(skb);
		return err;
	}

Use __skb_put_padto(skb, MTK_ISO_THRESHOLD, false) so that the skb is left to the caller on error. This also replaces the open-coded skb_pad() + __skb_put() sequence.

Fixes ceac1cb0259d ("Bluetooth: btusb: mediatek: add ISO data transmission functions")
---
 drivers/bluetooth/btmtk.c | 8 ++------
 1 file changed, 2 insertions(+), 6 deletions(-)
drivers/bluetooth/btmtk.c +2 -6
index 54cfc83032fb4..56296d142187b 100644
@@ -1093,12 +1093,8 @@ static int btmtk_isopkt_pad(struct hci_dev *hdev, struct sk_buff *skb)
 	if (skb->len > MTK_ISO_THRESHOLD)
 		return -EINVAL;
 
-	if (skb_pad(skb, MTK_ISO_THRESHOLD - skb->len))
-		return -ENOMEM;
-
-	__skb_put(skb, MTK_ISO_THRESHOLD - skb->len);
-
-	return 0;
+	/* On error, the skb is freed by hci_send_frame(). */
+	return __skb_put_padto(skb, MTK_ISO_THRESHOLD, false);
 }
 
 static int __set_mtk_intr_interface(struct hci_dev *hdev)
Signature · 1 line
2.53.0
author maintainer
#1919 lore raw

PATCH 1902/2651 Bluetooth: hci_sync: Protect IRK identity reads with RCU

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit 4b76fa362110cf1b74a0263c14406b71de99894c ]

hci_le_set_privacy_mode_sync() needs the IRK returned by hci_find_irk_by_addr() to remain allocated until its identity address and type have been copied into the command. The finder drops its RCU read lock before returning this borrowed pointer, leaving the later field reads unprotected.

When a privacy-capable controller has a pending peer with address resolution and device privacy enabled, accept-list programming can reach this helper while management reloads the IRKs. The request worker holds hdev->req_lock, whereas load_irks() takes hdev->lock, allowing the following ordering:

Request worker Management / RCU reclaim
hci_le_set_privacy_mode_sync()

    hci_find_irk_by_addr()
      rcu_read_lock()
      find matching IRK
      rcu_read_unlock()
      return borrowed IRK
                                     load_irks()
                                       hci_dev_lock(hdev)
                                       hci_smp_irks_clear()
                                         list_del_rcu()
                                         kfree_rcu()
                                       hci_dev_unlock(hdev)
                                     RCU grace period and IRK free
    read irk->addr_type
    copy irk->bdaddr

The request then accesses a freed IRK. KASAN reports a one-byte use-after-free read of addr_type on this path.

Keep an outer RCU read-side critical section across the lookup and both identity-field copies. The finder's nested unlock then leaves the IRK protected until the caller finishes copying it. Release RCU on a lookup miss and after copying the fields, before the synchronous HCI command can sleep.

KASAN report as below:

    ==================================================================
        BUG: KASAN: slab-use-after-free in
    hci_le_add_accept_list_sync+0x90f/0x940
    Read of size 1 at addr ffff88810aa6072c by task kworker/u17:0/493

    Workqueue: hci0 hci_cmd_sync_work
    Call Trace:
     <TASK>
     dump_stack_lvl+0x93/0xd0
     print_report+0xce/0x630
     ? hci_le_add_accept_list_sync+0x90f/0x940
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __virt_addr_valid+0x20d/0x410
     ? hci_le_add_accept_list_sync+0x90f/0x940
     kasan_report+0xe0/0x110
     ? hci_le_add_accept_list_sync+0x90f/0x940
     hci_le_add_accept_list_sync+0x90f/0x940
     ? __pfx_hci_le_add_accept_list_sync+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? conn_params_copy+0x3a0/0x650
     hci_passive_scan_sync+0x8c9/0x1e80
     ? __pfx_hci_passive_scan_sync+0x10/0x10
     ? find_held_lock+0x2b/0x80
     ? hci_lookup_le_connect+0x181/0x3c0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? find_held_lock+0x2b/0x80
     ? hci_update_passive_scan_sync+0x437/0x950
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_release+0xc8/0x280
     hci_update_passive_scan_sync+0x461/0x950
     hci_cmd_sync_work+0x1b3/0x450
     ? srso_alias_return_thunk+0x5/0xfbef5
     process_one_work+0x908/0x19c0
     ? __pfx_process_one_work+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_is_held_type+0x8f/0x100
     ? srso_alias_return_thunk+0x5/0xfbef5
     worker_thread+0x65c/0xe40
     ? __pfx_worker_thread+0x10/0x10
     kthread+0x34f/0x460
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx_kthread+0x10/0x10
     ret_from_fork+0x659/0x940
     ? __pfx_ret_from_fork+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __switch_to+0x74f/0xf80
     ? __pfx_kthread+0x10/0x10
     ret_from_fork_asm+0x1a/0x30
     </TASK>

    Allocated by task 507:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     __kasan_kmalloc+0xaa/0xb0
     __kmalloc_cache_noprof+0x251/0x610
     hci_add_irk+0xb6/0x220
     load_irks+0x5ef/0x7e0
     hci_sock_sendmsg+0x128b/0x22e0
     __sys_sendto+0x425/0x470
     __x64_sys_sendto+0xe5/0x1c0
     do_syscall_64+0x115/0x6a0
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    Freed by task 0:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     kasan_save_free_info+0x3b/0x60
     __kasan_slab_free+0x5f/0x80
     __rcu_free_sheaf_prepare+0x65/0x2a0
     rcu_free_sheaf+0x1f/0xe0
     rcu_core+0x661/0x1d10
     handle_softirqs+0x201/0x930
     __irq_exit_rcu+0x110/0x1e0
     irq_exit_rcu+0xe/0x20
     sysvec_apic_timer_interrupt+0x6c/0x80
     asm_sysvec_apic_timer_interrupt+0x1a/0x20

    The buggy address belongs to the object at ffff88810aa60700
     which belongs to the cache kmalloc-64 of size 64
    The buggy address is located 44 bytes inside of
     freed 64-byte region [ffff88810aa60700, ffff88810aa60740)

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

    Memory state around the buggy address:
     ffff88810aa60600: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
     ffff88810aa60680: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
    >ffff88810aa60700: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
                                      ^
     ffff88810aa60780: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
     ffff88810aa60800: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
    ==================================================================
    Disabling lock debugging due to kernel taint
Fixes adae20cb2d20 ("Bluetooth: Convert IRK list to RCU")
Assisted-by LLM
---
 net/bluetooth/hci_sync.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
net/bluetooth/hci_sync.c +7 -1
index 2a34528da0752..789939fbaf1cf 100644
@@ -2591,13 +2591,19 @@ static int hci_le_set_privacy_mode_sync(struct hci_dev *hdev,
 	if (!(params->flags & HCI_CONN_FLAG_DEVICE_PRIVACY))
 		return 0;
 
+	rcu_read_lock();
+
 	irk = hci_find_irk_by_addr(hdev, &params->addr, params->addr_type);
-	if (!irk)
+	if (!irk) {
+		rcu_read_unlock();
 		return 0;
+	}
 
 	memset(&cp, 0, sizeof(cp));
 	cp.bdaddr_type = irk->addr_type;
 	bacpy(&cp.bdaddr, &irk->bdaddr);
+	rcu_read_unlock();
+
 	cp.mode = HCI_DEVICE_PRIVACY;
 
 	/* Note: params->privacy_mode is not updated since it is a copy */
Signature · 1 line
2.53.0
author maintainer
#1920 lore raw

PATCH 1903/2651 Bluetooth: btintel: Zero version data before parsing TLVs

In reply to Greg Kroah-Hartman

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

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

From: Kiran K <[email protected]>

[ Upstream commit cf87709d7ff83b4de5d42b61e4a9806fe374cb9d ]

Firmware may omit optional TLVs, leaving their corresponding fields unset in the caller-supplied struct intel_version_tlv. Since the structure is typically stack-allocated and not cleared beforehand, fields for which no TLV is received retain uninitialized stack memory. This stale data can be logged via btintel_version_info_tlv() and copied back to the caller, leaking kernel stack contents.

Clear the structure in btintel_read_version_tlv() before parsing so that fields with no corresponding TLV are deterministically zero instead of containing garbage.

Fixes 57375beef71a ("Bluetooth: btintel: Add infrastructure to read controller information")
---
 drivers/bluetooth/btintel.c | 1 +
 1 file changed, 1 insertion(+)
drivers/bluetooth/btintel.c +1 -0
index cf109d79569a2..4871a552d3aa0 100644
@@ -751,6 +751,7 @@ static int btintel_read_version_tlv(struct hci_dev *hdev,
 		return -EIO;
 	}
 
+	memset(version, 0, sizeof(*version));
 	err = btintel_parse_version_tlv(hdev, version, skb);
 
 	kfree_skb(skb);
Signature · 1 line
2.53.0
author maintainer
#1921 lore raw

PATCH 1904/2651 Bluetooth: MGMT: Allow connection rate request as peripheral

In reply to Greg Kroah-Hartman

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

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

From: Luiz Augusto von Dentz <[email protected]>

[ Upstream commit 47493e62e8a8522a250537ed2ce026dd7d9163b1 ]

Load Connection Subrate only issues the LE Connection Rate Request when connected as central, but either role can initiate the Connection Rate Update procedure, e.g. a HID device, which is the peripheral, does it once the HID host requests a HID SCI mode with the HID Control Point.

Issue it regardless of the role.

Fixes 19129d7037be ("Bluetooth: Add MGMT Load Connection Subrate command")
Assisted-by OpenCode:claude-opus-5.5
---
 net/bluetooth/mgmt.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
net/bluetooth/mgmt.c +4 -3
index 23b65ceea8955..11f01b8d53f80 100644
@@ -8334,8 +8334,10 @@ static int load_conn_subrate(struct sock *sk, struct hci_dev *hdev, void *data,
 		hci_param->cont_num = cont_num;
 		hci_param->rate_supv_timeout = supv_timeout;
 
-		/* If the device is connected as central check if the
-		 * connection rate parameters need to be updated.
+		/* If the device is connected check if the connection rate
+		 * parameters need to be updated, either role can initiate the
+		 * Connection Rate Update procedure, e.g. a HID device acting
+		 * as peripheral once the HID host requests a HID SCI mode.
 		 */
 		if (!i && param_count == 1) {
 			struct hci_conn *conn;
@@ -8344,7 +8346,6 @@ static int load_conn_subrate(struct sock *sk, struct hci_dev *hdev, void *data,
 						       &hci_param->addr,
 						       addr_type);
 			if (conn && conn->state == BT_CONNECTED &&
-			    conn->role == HCI_ROLE_MASTER &&
 			    (conn->le_rate_interval < min ||
 			     conn->le_rate_interval > max ||
 			     conn->le_subrate < subrate_min ||
Signature · 1 line
2.53.0
author maintainer
#1922 lore raw

PATCH 1905/2651 Bluetooth: MSFT: Serialize handle map cleanup with event processing

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit 56e20c3d8ad340bbfc90221c4aae1c870485fb57 ]

MSFT monitor handle mappings must remain valid while vendor events look up and use them under hdev->lock. msft_do_close() removes and frees the mappings without that lock.

hci_dev_close_sync() clears HCI_UP and drains the RX workqueue before MSFT cleanup. However, a transport callback that already passed hci_recv_frame()'s state check can queue a vendor event after the drain returns, if no earlier shutdown callback has quiesced reception. The driver close callback runs after MSFT cleanup, so event processing can overlap the unlocked removal. msft_monitor_device_evt() can then traverse freed list entries or read handle_data->mgmt_handle after it is freed.

Take hdev->lock while resetting monitor states and removing handle mappings in msft_do_close(), as normal monitor cancellation already does. An active event reader then finishes before its mapping is freed, and later lookups see an empty handle map.

An instrumented kernel produced this KASAN report (timestamps removed and unrelated frames omitted):

    BUG: KASAN: slab-use-after-free in msft_vendor_evt+0x1906/0x1990
    Read of size 2 at addr ffff888104df3602 by task kworker/u17:2/502

    Workqueue: hci0 hci_rx_work
    Call Trace:
      [...]
      msft_vendor_evt+0x1906/0x1990
      hci_vendor_evt+0x6f/0x90
      hci_event_packet+0x894/0xc70
      [...]
      hci_rx_work+0x3f8/0xfa0
      [...]

    Allocated by task 499:
      [...]
      msft_add_monitor_sync+0x6a8/0x10a0
      msft_add_monitor_pattern+0x7f/0xb0
      hci_add_adv_monitor+0x1fa/0x2e0
      [...]

    Freed by task 499:
      [...]
      kfree+0x307/0x580
      msft_do_close+0x238/0x750
      hci_dev_close_sync+0x546/0x1380
      [...]

    The buggy address belongs to the object at ffff888104df3600
      which belongs to the cache kmalloc-32 of size 32
    The buggy address is located 2 bytes inside of
      freed 32-byte region [ffff888104df3600, ffff888104df3620)
    [...]
Fixes 145373cb1b1f ("Bluetooth: Add framework for Microsoft vendor extension")
Assisted-by LLM
---
 net/bluetooth/msft.c | 4 ++++
 1 file changed, 4 insertions(+)
net/bluetooth/msft.c +4 -0
index 6f4b7c38a2474..2559c5b1bef02 100644
@@ -683,6 +683,8 @@ void msft_do_close(struct hci_dev *hdev)
 
 	bt_dev_dbg(hdev, "Cleanup of MSFT extension");
 
+	hci_dev_lock(hdev);
+
 	/* The controller will silently remove all monitors on power off.
 	 * Therefore, remove handle_data mapping and reset monitor state.
 	 */
@@ -697,6 +699,8 @@ void msft_do_close(struct hci_dev *hdev)
 		kfree(handle_data);
 	}
 
+	hci_dev_unlock(hdev);
+
 	mutex_lock(&msft->filter_lock);
 	list_for_each_entry_safe(address_filter, n, &msft->address_filters,
 				 list) {
Signature · 1 line
2.53.0
author maintainer
#1923 lore raw

PATCH 1906/2651 Bluetooth: hci_event: Fix LE link drop on remote features command status

In reply to Greg Kroah-Hartman

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

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

From: Kevin Dewald <[email protected]>

[ Upstream commit 91638f53ff2b8234195ff27ec913e068269a28e9 ]

When the local controller supports peripheral-initiated features exchange, the LE Read Remote Features procedure also runs for incoming connections, and it fails with Unsupported Remote Feature (0x1a) if the central does not support that feature. hci_le_remote_feat_complete_evt() and hci_le_read_all_remote_features_evt() handle this and let the connection transition into connected state.

A controller can also return that error in the Command Status event instead. An Intel controller does so for a central that does not support peripheral-initiated features exchange, presumably because it already has the features of the central. hci_cs_le_read_remote_features() and hci_cs_le_read_all_remote_features() then confirm the connection as failed while it is still in BT_CONFIG, and the hci_conn_drop() in le_read_features_complete() disconnects it right away:

Quoted 1 line

HCI Event: LE Meta Event (0x3e) plen 31

      LE Enhanced Connection Complete (0x0a)
        Status: Success (0x00)
        Role: Peripheral (0x01)

< HCI Command: LE Read Remote Used Features (0x08|0x0016) plen 2

Quoted 1 line

HCI Event: Command Status (0x0f) plen 4

      LE Read Remote Used Features (0x08|0x0016) ncmd 1
        Status: Unsupported Remote Feature / Unsupported LMP Feature (0x1a)
  < HCI Command: Disconnect (0x01|0x0006) plen 3
        Reason: Remote User Terminated Connection (0x13)

Data the central sends afterwards is reported as:

Bluetooth: hci0: ACL packet for unknown connection handle 3585

Handle Unsupported Remote Feature in the command status the same way as in the complete events.

Fixes 0fe29fd1cd77 ("Bluetooth: Read LE remote features during connection establishment")
Fixes a106e50be74b ("Bluetooth: HCI: Add support for LL Extended Feature Set")
Assisted-by Claude:claude-opus-5.5
---
 net/bluetooth/hci_event.c | 30 ++++++++++++++++++++++++++++--
 1 file changed, 28 insertions(+), 2 deletions(-)
net/bluetooth/hci_event.c +28 -2
index c9cf7f27d21b9..3ea6c06adaaf0 100644
@@ -2989,8 +2989,25 @@ static void hci_cs_le_read_remote_features(struct hci_dev *hdev, u8 status)
 	hci_dev_lock(hdev);
 
 	conn = hci_conn_hash_lookup_handle(hdev, __le16_to_cpu(cp->handle));
-	if (conn && conn->state == BT_CONFIG)
+	if (conn && conn->state == BT_CONFIG) {
+		/* If the local controller supports peripheral-initiated
+		 * features exchange, but the remote controller does not,
+		 * then the controller may already return the error code
+		 * 0x1a for unsupported remote feature in the command
+		 * status.
+		 *
+		 * Handle it as hci_le_remote_feat_complete_evt() does and
+		 * allow the connection to transition into connected state.
+		 */
+		if (!conn->out &&
+		    status == HCI_ERROR_UNSUPPORTED_REMOTE_FEATURE &&
+		    (hdev->le_features[0] & HCI_LE_PERIPHERAL_FEATURES)) {
+			conn->state = BT_CONNECTED;
+			status = 0x00;
+		}
+
 		hci_connect_cfm(conn, status);
+	}
 
 	hci_dev_unlock(hdev);
 }
@@ -4039,8 +4056,17 @@ static void hci_cs_le_read_all_remote_features(struct hci_dev *hdev, u8 status)
 	hci_dev_lock(hdev);
 
 	conn = hci_conn_hash_lookup_handle(hdev, __le16_to_cpu(cp->handle));
-	if (conn && conn->state == BT_CONFIG)
+	if (conn && conn->state == BT_CONFIG) {
+		/* See hci_cs_le_read_remote_features() */
+		if (!conn->out &&
+		    status == HCI_ERROR_UNSUPPORTED_REMOTE_FEATURE &&
+		    (hdev->le_features[0] & HCI_LE_PERIPHERAL_FEATURES)) {
+			conn->state = BT_CONNECTED;
+			status = 0x00;
+		}
+
 		hci_connect_cfm(conn, status);
+	}
 
 	hci_dev_unlock(hdev);
 }
Signature · 1 line
2.53.0
author maintainer
#1924 lore raw

PATCH 1907/2651 Bluetooth: Fix the LE Read Connection Interval response layout

In reply to Greg Kroah-Hartman

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

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

From: Luiz Augusto von Dentz <[email protected]>

[ Upstream commit 5874f8d03268d34189c6c12c56586b64d26a8bcc ]

The response to HCI_OP_LE_READ_CONN_INTERVAL carries a Minimum_Supported_Connection_Interval octet between the status and Num_Groups, which was missing from the structure. Without it the minimum interval was read as the number of groups, and every group after it from one octet off.

Take the minimum interval used to clamp the default rate parameters from that field rather than the smallest group minimum, as the number of groups can be zero, which left it unset.

Fixes 2f8784cfe8a9 ("Bluetooth: Add support for Shorter Connection Interval (SCI) feature")
Assisted-by OpenCode:claude-opus-5.5
---
 include/net/bluetooth/hci.h |  1 +
 net/bluetooth/hci_event.c   | 16 ++++------------
 2 files changed, 5 insertions(+), 12 deletions(-)
include/net/bluetooth/hci.h +1 -0
index 1641d879dbda9..9dc714d9145ee 100644
@@ -2527,6 +2527,7 @@ struct hci_le_conn_interval_group {
 
 struct hci_rp_le_read_conn_interval {
 	__u8	status;
+	__u8	min;
 	__u8	num_grps;
 	struct hci_le_conn_interval_group grps[];
 } __packed;
net/bluetooth/hci_event.c +4 -12
index 3ea6c06adaaf0..3288f92fe41bf 100644
@@ -1247,8 +1247,6 @@ static u8 hci_cc_le_read_conn_interval(struct hci_dev *hdev, void *data,
 				       struct sk_buff *skb)
 {
 	struct hci_rp_le_read_conn_interval *rp = data;
-	u16 min_interval = 0;
-	int i;
 
 	bt_dev_dbg(hdev, "status 0x%2.2x", rp->status);
 
@@ -1261,17 +1259,11 @@ static u8 hci_cc_le_read_conn_interval(struct hci_dev *hdev, void *data,
 		return HCI_ERROR_UNSPECIFIED;
 	}
 
-	/* Store the smallest minimum supported connection interval reported by
-	 * the controller so the default rate parameters can be clamped to it.
+	/* Store the minimum supported connection interval so the default rate
+	 * parameters can be clamped to it. It is reported on its own rather
+	 * than derived from the groups, as there may be none.
 	 */
-	for (i = 0; i < rp->num_grps; i++) {
-		u16 min = le16_to_cpu(rp->grps[i].min);
-
-		if (!min_interval || min < min_interval)
-			min_interval = min;
-	}
-
-	hdev->le_min_rate_interval = min_interval;
+	hdev->le_min_rate_interval = rp->min;
 
 	return rp->status;
 }
Signature · 1 line
2.53.0
author maintainer
#1925 lore raw

PATCH 1908/2651 Bluetooth: hci_sync: scan unfiltered for host-resolved RPAs

In reply to Greg Kroah-Hartman

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

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

From: Kyle Pepper <[email protected]>

[ Upstream commit 397464709a204da9b8dc3b01d6ea42539d951cd2 ]

Restore unfiltered scanning for pending IRK peers when the controller cannot resolve private addresses. Keep accept-list filtering while suspended and when forced by periodic advertising synchronization.

Fixes e209e5ccc5ac ("Bluetooth: MGMT: Mark LL Privacy as stable")
Assisted-by OpenCode:gpt-6.1-sol
---
 net/bluetooth/hci_sync.c | 13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)
net/bluetooth/hci_sync.c +9 -4
index 789939fbaf1cf..4e5c47872c30b 100644
@@ -2618,7 +2618,7 @@ static int hci_le_set_privacy_mode_sync(struct hci_dev *hdev,
  */
 static int hci_le_add_accept_list_sync(struct hci_dev *hdev,
 				       struct conn_params *params,
-				       u8 *num_entries)
+				       u8 *num_entries, bool force_filter)
 {
 	struct hci_cp_le_add_to_accept_list cp;
 	int err;
@@ -2631,6 +2631,11 @@ static int hci_le_add_accept_list_sync(struct hci_dev *hdev,
 		return 0;
 	}
 
+	/* Host-resolved peers need unfiltered scanning while awake. */
+	if (!force_filter && !hdev->suspended && !ll_privacy_capable(hdev) &&
+	    hci_find_irk_by_addr(hdev, &params->addr, params->addr_type))
+		return -EINVAL;
+
 	/* Select filter policy to accept all advertising */
 	if (*num_entries >= hdev->le_accept_list_size)
 		return -ENOSPC;
@@ -2962,7 +2967,7 @@ static u8 hci_update_accept_list_sync(struct hci_dev *hdev)
 
 			num_entries = 1;
 			err = hci_le_add_accept_list_sync(hdev, &pa,
-							  &num_entries);
+							  &num_entries, true);
 			goto done;
 		} else {
 			rcu_read_unlock();
@@ -3026,7 +3031,7 @@ static u8 hci_update_accept_list_sync(struct hci_dev *hdev)
 
 	for (i = 0; i < n; ++i) {
 		err = hci_le_add_accept_list_sync(hdev, &params[i],
-						  &num_entries);
+								&num_entries, false);
 		if (err) {
 			kvfree(params);
 			goto done;
@@ -3048,7 +3053,7 @@ static u8 hci_update_accept_list_sync(struct hci_dev *hdev)
 
 	for (i = 0; i < n; ++i) {
 		err = hci_le_add_accept_list_sync(hdev, &params[i],
-						  &num_entries);
+								&num_entries, false);
 		if (err) {
 			kvfree(params);
 			goto done;
Signature · 1 line
2.53.0
author maintainer
#1926 lore raw

PATCH 1909/2651 clocksource/drivers/timer-ti-dm: Handle runtime resume failure

In reply to Greg Kroah-Hartman

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

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

From: Jiale Yao <[email protected]>

[ Upstream commit c40b76c8cf580466d9e56223f7f74beecc165480 ]

omap_dm_timer_write_counter() accesses timer registers and updates the saved counter value after requesting a runtime PM reference. If runtime resume fails, the timer remains inaccessible and no reference is acquired, but the function still writes the register, drops a reference, updates the cached value, and reports success.

Check the return value and propagate an error before touching the timer state.

Fixes 0494fc345b37 ("clocksource/drivers/timer-ti-dm : Capture functionality for OMAP DM timer")
---
 drivers/clocksource/timer-ti-dm.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/clocksource/timer-ti-dm.c +5 -1
index ae8777d032154..8012d3f3e1a3f 100644
@@ -1095,6 +1095,7 @@ static int omap_dm_timer_write_counter(struct omap_dm_timer *cookie, unsigned in
 {
 	struct dmtimer *timer;
 	struct device *dev;
+	int ret;
 
 	timer = to_dmtimer(cookie);
 	if (unlikely(!timer)) {
@@ -1104,7 +1105,10 @@ static int omap_dm_timer_write_counter(struct omap_dm_timer *cookie, unsigned in
 
 	dev = &timer->pdev->dev;
 
-	pm_runtime_resume_and_get(dev);
+	ret = pm_runtime_resume_and_get(dev);
+	if (ret < 0)
+		return ret;
+
 	dmtimer_write(timer, OMAP_TIMER_COUNTER_REG, value);
 	pm_runtime_put_sync(dev);
 
Signature · 1 line
2.53.0
author maintainer
#1927 lore raw

PATCH 1910/2651 net: selftests: use skb_share_check() in the loopback receive hook

In reply to Greg Kroah-Hartman

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

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

From: Nicolai Buchwitz <[email protected]>

[ Upstream commit fbd3a301b1378423a5cfc23a42e3c0b04e26192c ]

The loopback hook gets a shared skb when another ETH_P_IP handler is bound to the device. skb_unshare() does not unshare it, so skb_linearize() on a non-linear frame hits BUG_ON(skb_shared()).

Use skb_share_check() instead.

---
 net/core/selftests.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/core/selftests.c +1 -1
index 36b949ae520b3..80029a67b2d2b 100644
@@ -170,7 +170,7 @@ static int net_test_loopback_validate(struct sk_buff *skb,
 	struct tcphdr *thdr;
 	struct iphdr *ihdr;
 
-	skb = skb_unshare(skb, GFP_ATOMIC);
+	skb = skb_share_check(skb, GFP_ATOMIC);
 	if (!skb)
 		goto out;
 
Signature · 1 line
2.53.0
author maintainer
#1928 lore raw

PATCH 1911/2651 net: stmmac: selftests: use skb_share_check() in the loopback receive hook

In reply to Greg Kroah-Hartman

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

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

From: Nicolai Buchwitz <[email protected]>

[ Upstream commit a7a89019bac0e8810bde7f1419f4adf9adc23d41 ]

The loopback hook gets a shared skb when another ETH_P_IP handler is bound to the device. skb_unshare() does not unshare it, so skb_linearize() on a non-linear frame hits BUG_ON(skb_shared()).

Use skb_share_check() instead.

---
 drivers/net/ethernet/stmicro/stmmac/stmmac_selftests.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/ethernet/stmicro/stmmac/stmmac_selftests.c +1 -1
index c485217ba880c..6c01fdb6667e6 100644
@@ -262,7 +262,7 @@ static int stmmac_test_loopback_validate(struct sk_buff *skb,
 	struct tcphdr *thdr;
 	struct iphdr *ihdr;
 
-	skb = skb_unshare(skb, GFP_ATOMIC);
+	skb = skb_share_check(skb, GFP_ATOMIC);
 	if (!skb)
 		goto out;
 
Signature · 1 line
2.53.0
author maintainer
#1929 lore raw

PATCH 1912/2651 net/mlx5e: use skb_share_check() in the loopback selftest hook

In reply to Greg Kroah-Hartman

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

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

From: Nicolai Buchwitz <[email protected]>

[ Upstream commit 16fb7aa6955a0af9f67ca42a61d9be58dfc9382a ]

The loopback hook gets a shared skb when another ETH_P_IP handler is bound to the device. skb_linearize() on a non-linear frame then hits BUG_ON(skb_shared()).

Call skb_share_check() before linearizing the skb.

---
 drivers/net/ethernet/mellanox/mlx5/core/en_selftest.c | 4 ++++
 1 file changed, 4 insertions(+)
drivers/net/ethernet/mellanox/mlx5/core/en_selftest.c +4 -0
index 1dcdb86690bb7..8eb9a9469549d 100644
@@ -166,6 +166,10 @@ mlx5e_test_loopback_validate(struct sk_buff *skb,
 	struct udphdr *udph;
 	struct iphdr *iph;
 
+	skb = skb_share_check(skb, GFP_ATOMIC);
+	if (!skb)
+		goto out;
+
 	if (skb_linearize(skb))
 		goto out;
 
Signature · 1 line
2.53.0
author maintainer
#1930 lore raw

PATCH 1913/2651 PCI: iproc: Use the EROM outbound window on BCMA

In reply to Greg Kroah-Hartman

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

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

From: Semih Baskan <[email protected]>

[ Upstream commit 9850907ee1dd4376c09c4129e0adbe3b39d191b7 ]

The PCIe outbound window base on Northstar depends on the PCIe Gen2 core revision. Revision 0x01 uses 0x08000000, 0x40000000 and 0x48000000 for controllers 0 to 2, while revision 0x07 (NS-B0) uses 0x08000000, 0x20000000 and 0x28000000. Broadcom's own driver branches on the core revision for exactly this reason.

bcm-ns.dtsi is shared by every Northstar SoC, so it cannot carry a value that is correct on both. Commit 767012397976 ("ARM: dts: BCM5301X:
Describe PCIe controllers fully") gave the controllers a ranges property. The commit shipped in v7.1.

With that property present, two things go wrong with this driver:

1) devm_pci_alloc_host_bridge() parses those ranges and requests them, then this driver adds its own window and requests the whole list a second time, so every controller fails to probe with -EBUSY.

2) The DT window itself is only correct on core revision 0x07. On revision 0x01 it points at an address the hardware does not decode, and the first MMIO access to a BAR takes an imprecise external abort.

The enumeration ROM reports the correct base for the revision actually present, and bcma already provides it as addr_s[0].

To solve 1), use pci_alloc_host_bridge() directly to avoid the request of all the DT resources done in pci_parse_request_of_pci_ranges(). Instead, request the memory window from the EROM.

To solve 2), parse the memory resources from DT and emit a warning if it describes a window that doesn't match the window from the EROM. The mismatch means the devicetree describes a window the hardware does not decode, and that should be fixed in the dts rather than ignored silently.

The driver is correct whether or not the DT describes a window.

The same commit also added compatible = "brcm,iproc-pcie", so these nodes now match pcie-iproc-platform. With CONFIG_PCIE_IPROC_PLATFORM enabled, which is the default on ARCH_BCM_IPROC, that driver binds them first and this driver's probe fails inside devm_pci_alloc_host_bridge(). This commit fixes the configurations where the BCMA driver is the one in use; OpenWrt builds that way, with PCIE_IPROC_PLATFORM disabled. The platform path takes the DT window as-is and has the same wrong address on core revision 0x01, so that side needs a devicetree fix either way.

Based on:
https://patch.msgid.link/[email protected]
https://patch.msgid.link/[email protected]

---
 drivers/pci/controller/pcie-iproc-bcma.c | 40 ++++++++++++++++++++++--
 1 file changed, 37 insertions(+), 3 deletions(-)
drivers/pci/controller/pcie-iproc-bcma.c +37 -3
index 593418c2bc3aa..1e258cd8fed4f 100644
@@ -11,7 +11,9 @@
 #include <linux/phy/phy.h>
 #include <linux/bcma/bcma.h>
 #include <linux/ioport.h>
+#include <linux/of_address.h>
 
+#include "../pci.h"
 #include "pcie-iproc.h"
 
 
@@ -31,6 +33,29 @@ static int iproc_bcma_pcie_map_irq(const struct pci_dev *dev, u8 slot, u8 pin)
 	return bcma_core_irq(bdev, 5);
 }
 
+static void iproc_bcma_pcie_check_dt_window(struct iproc_pcie *pcie)
+{
+	struct device_node *np = pcie->dev->of_node;
+	struct of_pci_range_parser parser;
+	struct of_pci_range range;
+	struct resource res;
+
+	if (!np || of_pci_range_parser_init(&parser, np))
+		return;
+
+	for_each_of_pci_range(&parser, &range) {
+		if ((range.flags & IORESOURCE_TYPE_BITS) != IORESOURCE_MEM)
+			continue;
+
+		if (of_pci_range_to_resource(&range, np, &res))
+			continue;
+
+		if (res.start != pcie->mem.start || res.end != pcie->mem.end)
+			dev_warn(pcie->dev, "DT window %pR does not match EROM window %pR, using EROM\n",
+				 &res, &pcie->mem);
+	}
+}
+
 static int iproc_bcma_pcie_probe(struct bcma_device *bdev)
 {
 	struct device *dev = &bdev->dev;
@@ -38,10 +63,20 @@ static int iproc_bcma_pcie_probe(struct bcma_device *bdev)
 	struct pci_host_bridge *bridge;
 	int ret;
 
-	bridge = devm_pci_alloc_host_bridge(dev, sizeof(*pcie));
+	bridge = pci_alloc_host_bridge(sizeof(*pcie));
 	if (!bridge)
 		return -ENOMEM;
 
+	bridge->dev.parent = dev;
+
+	ret = devm_add_action_or_reset(dev, devm_pci_alloc_host_bridge_release,
+				       bridge);
+	if (ret)
+		return -ENOMEM;
+
+	bridge->swizzle_irq = pci_common_swizzle;
+	bridge->map_irq = iproc_bcma_pcie_map_irq;
+
 	pcie = pci_host_bridge_priv(bridge);
 
 	pcie->dev = dev;
@@ -59,13 +94,12 @@ static int iproc_bcma_pcie_probe(struct bcma_device *bdev)
 	pcie->mem.end = bdev->addr_s[0] + SZ_128M - 1;
 	pcie->mem.name = "PCIe MEM space";
 	pcie->mem.flags = IORESOURCE_MEM;
+	iproc_bcma_pcie_check_dt_window(pcie);
 	pci_add_resource(&bridge->windows, &pcie->mem);
 	ret = devm_request_pci_bus_resources(dev, &bridge->windows);
 	if (ret)
 		return ret;
 
-	bridge->map_irq = iproc_bcma_pcie_map_irq;
-
 	bcma_set_drvdata(bdev, pcie);
 
 	return iproc_pcie_setup(pcie, &bridge->windows);
Signature · 1 line
2.53.0
#1931 lore raw

Re: [PATCH 7.3 1913/2651] PCI: iproc: Use the EROM outbound window on BCMA

Quoted 7 lines · Greg Kroah-Hartman

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

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

From: Semih Baskan <[email protected]>

[ Upstream commit 9850907ee1dd4376c09c4129e0adbe3b39d191b7 ]

...

Quoted 8 lines
---
  drivers/pci/controller/pcie-iproc-bcma.c | 40 ++++++++++++++++++++++--
  1 file changed, 37 insertions(+), 3 deletions(-)
drivers/pci/controller/pcie-iproc-bcma.c +0 -0
index 593418c2bc3aa..1e258cd8fed4f 100644

...

drivers/pci/controller/pcie-iproc-bcma.c static int iproc_bcma_pcie_probe(struct bcma_device *bdev) · line 73

Quoted 13 lines
drivers/pci/controller/pcie-iproc-bcma.c +5 -1
@@ -38,10 +63,20 @@ static int iproc_bcma_pcie_probe(struct bcma_device *bdev)
  	struct pci_host_bridge *bridge;
  	int ret;
 
-	bridge = devm_pci_alloc_host_bridge(dev, sizeof(*pcie));
+	bridge = pci_alloc_host_bridge(sizeof(*pcie));
  	if (!bridge)
  		return -ENOMEM;
 
+	bridge->dev.parent = dev;
+
+	ret = devm_add_action_or_reset(dev, devm_pci_alloc_host_bridge_release,
+				       bridge);

This does not build on armv7hl:
drivers/pci/controller/pcie-iproc-bcma.c:72:45: error: 'devm_pci_alloc_host_bridge_release' undeclared (first use in this function); did you mean 'devm_pci_alloc_host_bridge'?

Signature · 2 lines
js
suse labs
#1932 lore raw

Re: [PATCH 7.3 1913/2651] PCI: iproc: Use the EROM outbound window on BCMA

Quoted 1 line · Jiri Slaby

On 18. 11. 26, 15:52, Greg Kroah-Hartman wrote:

[...]

Quoted 7 lines

drivers/pci/controller/pcie-iproc-bcma.c static int iproc_bcma_pcie_probe(struct bcma_device *bdev) · line 73

Quoted 2 lines
drivers/pci/controller/pcie-iproc-bcma.c +2 -0
+    ret = devm_add_action_or_reset(dev, devm_pci_alloc_host_bridge_release,
+                       bridge);

This does not build on armv7hl:
drivers/pci/controller/pcie-iproc-bcma.c:72:45: error:
'devm_pci_alloc_host_bridge_release' undeclared (first use in this function); did you mean 'devm_pci_alloc_host_bridge'?

This needs commit 39d1c645bb99 ("PCI: Expose devm_pci_alloc_host_bridge_release()") from the same series. The two apply cleanly on 7.3.5 in that order.

Best regards,
Semih

maintainer Applied
#1933 lore raw

Re: [PATCH 7.3 1913/2651] PCI: iproc: Use the EROM outbound window on BCMA

Quoted 3 lines
Quoted 3 lines

This does not build on armv7hl:
drivers/pci/controller/pcie-iproc-bcma.c:72:45: error:
'devm_pci_alloc_host_bridge_release' undeclared (first use in this

Queued the missing prerequisite for 7.3, thanks.

Signature · 2 lines
Thanks,
Sasha
author maintainer
#1934 lore raw

PATCH 1914/2651 selftests/nolibc: use the configured kernel header directory

In reply to Greg Kroah-Hartman

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

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

[ Upstream commit f9532b372e415e8198287ce010efa22f337857b5 ]

The freestanding build hardcodes the source tree's usr/include even when selftests exports KHDR_INCLUDES for an output-directory build. Use the exported header location while preserving -nostdlib, -nostdinc and static linkage. GCC 14 and Clang 21 builds then find the generated UAPI headers.

Fixes eb1353110831 ("selftests/nolibc: integrate with kselftests")
---
 tools/testing/selftests/nolibc/Makefile | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/testing/selftests/nolibc/Makefile +1 -1
index 6bace04227a74..6981c220eed76 100644
@@ -10,7 +10,7 @@ cc-option = $(call __cc-option, $(CC),,$(1),$(2))
 include Makefile.include
 
 $(OUTPUT)/nolibc-test: CFLAGS = -nostdlib -nostdinc -static \
-	 -isystem $(top_srcdir)/tools/include/nolibc -isystem $(top_srcdir)/usr/include \
+	 -isystem $(top_srcdir)/tools/include/nolibc $(KHDR_INCLUDES) \
 	 $(CFLAGS_NOLIBC_TEST)
 $(OUTPUT)/nolibc-test: LDLIBS = $(if $(LLVM),,-lgcc)
 $(OUTPUT)/nolibc-test: $(NOLIBC_TEST_SOURCES) | headers
Signature · 1 line
2.53.0
author maintainer
#1935 lore raw

PATCH 1915/2651 resolve_btfids: Fix the --fatal_warnings exit status

In reply to Greg Kroah-Hartman

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

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

From: Petr Pavlu <[email protected]>

[ Upstream commit 201a454df948021916e051b0a84a674f4f0f9671 ]

The resolve_btfids --fatal_warnings option is intended to make the tool exit with a non-zero status if any warnings are reported. main() initializes err to -1 and uses 'goto out' to return this status when a sub-operation fails. If no error occurs,
'if (!(fatal_warnings && warnings)) err = 0;' modifies the final status depending on whether any warnings have been reported.

Commit 522397d05e7d ("resolve_btfids: Change in-place update with raw binary output") broke this logic by assigning the return values of newly added sub-operations to err. As a result, successful sub-operations overwrite the initial err value of -1 with 0, causing the tool to exit successfully even when --fatal_warnings is enabled and warnings have been reported.

Fix the issue by setting the final value of err unconditionally, so the code doesn't depend on its previous value.

Fixes 522397d05e7d ("resolve_btfids: Change in-place update with raw binary output")
---
 tools/bpf/resolve_btfids/main.c | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
tools/bpf/resolve_btfids/main.c +1 -2
index 37d7e7224207d..2a93517ca9ec1 100644
@@ -1842,8 +1842,7 @@ int main(int argc, const char **argv)
 			goto out;
 	}
 
-	if (!(fatal_warnings && warnings))
-		err = 0;
+	err = fatal_warnings && warnings ? -1 : 0;
 out:
 	btf__free(obj.base_btf);
 	btf__free(obj.btf);
Signature · 1 line
2.53.0
author maintainer
#1936 lore raw

PATCH 1916/2651 iommufd: Keep reserved IOVA ranges when a replace within one IOAS fails

In reply to Greg Kroah-Hartman

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

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

From: Donggeun Yoo <[email protected]>

[ Upstream commit 1e67cca28490f897788c128c650a6f2cbb565403 ]

iommufd_device_do_replace() installs the group's reserved IOVA ranges in the new hwpt's IOAS only when it differs from the old hwpt's IOAS. If the replace fails in iommufd_device_do_replace() or iommufd_group_do_replace_reserved_iova(), the error paths remove the ranges from the new hwpt's IOAS whether or not the IOAS is shared between the old and new hwpt, which removes the ranges that the old hwpt still needs.

For example, on x86 with intel-iommu, after a replace within a shared IOAS fails with -ENODEV, IOMMU_IOAS_IOVA_RANGES goes from

0x0-0xfedfffff
0xfef00000-0xffffffffffff

to

0x0-0xffffffffffff

and IOMMU_IOAS_MAP at 0xfee00000 succeeds.

Remove the ranges on failure only when the replace installed them, and look up the old hwpt_paging before the replace so that the error path can compare the IOAS.

Fixes e88d4ec154a8 ("iommufd: Add iommufd_device_replace()")
Assisted-by LLM
---
 drivers/iommu/iommufd/device.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
drivers/iommu/iommufd/device.c +5 -3
index a664c70a6fe73..1b0bdf57ac8ab 100644
@@ -849,7 +849,8 @@ iommufd_group_do_replace_reserved_iova(struct iommufd_group *igroup,
 	return 0;
 
 err_unresv:
-	iommufd_group_remove_reserved_iova(igroup, hwpt_paging);
+	if (!old_hwpt_paging || hwpt_paging->ioas != old_hwpt_paging->ioas)
+		iommufd_group_remove_reserved_iova(igroup, hwpt_paging);
 	return rc;
 }
 
@@ -889,6 +890,7 @@ iommufd_device_do_replace(struct iommufd_device *idev, ioasid_t pasid,
 		return NULL;
 	}
 
+	old_hwpt_paging = find_hwpt_paging(old_hwpt);
 	if (attach_resv) {
 		rc = iommufd_group_do_replace_reserved_iova(igroup, hwpt_paging);
 		if (rc)
@@ -899,7 +901,6 @@ iommufd_device_do_replace(struct iommufd_device *idev, ioasid_t pasid,
 	if (rc)
 		goto err_unresv;
 
-	old_hwpt_paging = find_hwpt_paging(old_hwpt);
 	if (old_hwpt_paging && pasid == IOMMU_NO_PASID &&
 	    (!hwpt_paging || hwpt_paging->ioas != old_hwpt_paging->ioas))
 		iommufd_group_remove_reserved_iova(igroup, old_hwpt_paging);
@@ -920,7 +921,8 @@ iommufd_device_do_replace(struct iommufd_device *idev, ioasid_t pasid,
 	/* Caller must destroy old_hwpt */
 	return old_hwpt;
 err_unresv:
-	if (attach_resv)
+	if (attach_resv &&
+	    (!old_hwpt_paging || hwpt_paging->ioas != old_hwpt_paging->ioas))
 		iommufd_group_remove_reserved_iova(igroup, hwpt_paging);
 err_unlock:
 	mutex_unlock(&igroup->lock);
Signature · 1 line
2.53.0
author maintainer
#1937 lore raw

PATCH 1917/2651 scsi: libsas: Fix out-of-bounds memcpy() in sas_ssp_task_response()

In reply to Greg Kroah-Hartman

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

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

From: Xingui Yang <[email protected]>

[ Upstream commit 4d7f9c3fdce773f6c69d17c1d4a05bd5e17f4b99 ]

The min_t(int, ...) clamp of the device-provided sense_data_len turns negative for values >= 0x80000000 and is then used as the memcpy() length, reading and writing out of bounds. Compare as u32 instead. Well-formed responses are unaffected.

Fixes 366ca51f30de ("[SCSI] libsas: abstract STP task status into a function")
---
 drivers/scsi/libsas/sas_task.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/scsi/libsas/sas_task.c +1 -1
index e9d291007817b..2080e5836179b 100644
@@ -25,7 +25,7 @@ void sas_ssp_task_response(struct device *dev, struct sas_task *task,
 	case SAS_DATAPRES_SENSE_DATA:
 		tstat->stat = SAS_SAM_STAT_CHECK_CONDITION;
 		tstat->buf_valid_size =
-			min_t(int, SAS_STATUS_BUF_SIZE,
+			min_t(u32, SAS_STATUS_BUF_SIZE,
 			      be32_to_cpu(iu->sense_data_len));
 		memcpy(tstat->buf, iu->sense_data, tstat->buf_valid_size);
 
Signature · 1 line
2.53.0
author maintainer
#1938 lore raw

PATCH 1918/2651 scsi: hisi_sas: Fix incorrect delay values from magic-number cleanup

In reply to Greg Kroah-Hartman

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

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

From: Xingui Yang <[email protected]>

[ Upstream commit 7307109c92f702434669bfcd29fb8058ccc07b45 ]

Commit 4ca7fe99fc84 ("scsi: hisi_sas: Use macro instead of magic number") replaced several delay constants with a single macro of value
100. However, three sites originally used different values:

- reset_hw_v3_hw: udelay(50) -> udelay(100) [doubled]
- disable_phy_v3_hw: mdelay(50) -> mdelay(100) [doubled]
- disable_host_v3_hw: mdelay(10) -> mdelay(100) [10x longer]

The overly long delays on the PHY disable and host shutdown paths increase boot and shutdown time for all local PHYs.

Add separate macros for each delay to restore the original values while still avoiding magic numbers.

Fixes 4ca7fe99fc84 ("scsi: hisi_sas: Use macro instead of magic number")
---
 drivers/scsi/hisi_sas/hisi_sas_v3_hw.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
drivers/scsi/hisi_sas/hisi_sas_v3_hw.c +6 -3
index 8a2500993e19d..9c363e2373538 100644
@@ -547,6 +547,9 @@ struct hisi_sas_err_record_v3 {
 #define IRQ_AXI_INDEX 11
 
 #define DELAY_FOR_RESET_HW 100
+#define STOP_PHY_DELAY_US 50
+#define DISABLE_PHY_DELAY_MS 50
+#define DISABLE_HOST_PHY_DELAY_MS 10
 #define HDR_SG_MOD 0x2
 #define LUN_SIZE 8
 #define ATTR_PRIO_REGION 9
@@ -983,7 +986,7 @@ static int reset_hw_v3_hw(struct hisi_hba *hisi_hba)
 
 	/* Disable all of the PHYs */
 	hisi_sas_stop_phys(hisi_hba);
-	udelay(HISI_SAS_DELAY_FOR_PHY_DISABLE);
+	udelay(STOP_PHY_DELAY_US);
 
 	/* Ensure axi bus idle */
 	ret = hisi_sas_read32_poll_timeout(AXI_CFG, val, !val,
@@ -1072,7 +1075,7 @@ static void disable_phy_v3_hw(struct hisi_hba *hisi_hba, int phy_no)
 	cfg &= ~PHY_CFG_ENA_MSK;
 	hisi_sas_phy_write32(hisi_hba, phy_no, PHY_CFG, cfg);
 
-	mdelay(HISI_SAS_DELAY_FOR_PHY_DISABLE);
+	mdelay(DISABLE_PHY_DELAY_MS);
 
 	state = hisi_sas_read32(hisi_hba, PHY_STATE);
 	if (state & BIT(phy_no)) {
@@ -2755,7 +2758,7 @@ static int disable_host_v3_hw(struct hisi_hba *hisi_hba)
 
 	hisi_sas_stop_phys(hisi_hba);
 
-	mdelay(HISI_SAS_DELAY_FOR_PHY_DISABLE);
+	mdelay(DISABLE_HOST_PHY_DELAY_MS);
 
 	reg_val = hisi_sas_read32(hisi_hba, AXI_MASTER_CFG_BASE +
 				  AM_CTRL_GLOBAL);
Signature · 1 line
2.53.0
author maintainer
#1939 lore raw

PATCH 1919/2651 scsi: hisi_sas: Fix spinup failure for SAS SSP devices in Active_Wait state

In reply to Greg Kroah-Hartman

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

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

From: Xingui Yang <[email protected]>

[ Upstream commit 92821c2358c78345909889793918af8763808bd4 ]

SAS HDDs powered up with RNOT=1 wait in Active_Wait state for a NOTIFY(ENABLE SPINUP) primitive and keep returning NOT_READY with ASC/ASCQ 0x04/0x11, causing endless mid-layer retries and spinup failure.

Parse the sense data in the slot completion path and, when LU_NOT_READY_NOTIFY_REQUIRED is returned by a directly-attached SSP device, queue work that sends the primitive from process context (sl_notify_ssp() contains msleep()). The work takes a runtime PM reference with pm_runtime_get_if_active(), pairing with pm_runtime_put_sync() in the work, so the controller stays resumed until the primitive is sent.

Fixes 60b4a5ee9034 ("scsi: hisi_sas: add v3 cq interrupt handler")
---
 drivers/scsi/hisi_sas/hisi_sas.h       |  3 ++
 drivers/scsi/hisi_sas/hisi_sas_main.c  | 43 ++++++++++++++++++++++++++
 drivers/scsi/hisi_sas/hisi_sas_v1_hw.c |  4 +++
 drivers/scsi/hisi_sas/hisi_sas_v2_hw.c |  4 +++
 drivers/scsi/hisi_sas/hisi_sas_v3_hw.c |  4 +++
 5 files changed, 58 insertions(+)
drivers/scsi/hisi_sas/hisi_sas.h +3 -0
index 1323ed8aa7171..d48ba3747b81b 100644
@@ -163,6 +163,7 @@ enum hisi_sas_phy_event {
 	HISI_PHYE_PHY_UP   = 0U,
 	HISI_PHYE_LINK_RESET,
 	HISI_PHYE_PHY_UP_PM,
+	HISI_PHYE_SPINUP_NOTIFY,
 	HISI_PHYES_NUM,
 };
 
@@ -689,4 +690,6 @@ extern void hisi_sas_sync_cqs(struct hisi_hba *hisi_hba);
 extern void hisi_sas_sync_poll_cqs(struct hisi_hba *hisi_hba);
 extern void hisi_sas_controller_reset_prepare(struct hisi_hba *hisi_hba);
 extern void hisi_sas_controller_reset_done(struct hisi_hba *hisi_hba);
+extern void hisi_sas_spinup_notify(struct hisi_hba *hisi_hba,
+				   struct sas_task *task);
 #endif
drivers/scsi/hisi_sas/hisi_sas_main.c +43 -0

59 lines not on this page · raw message

drivers/scsi/hisi_sas/hisi_sas_v1_hw.c +4 -0
index fa94d7110714f..5fcb8d5002f52 100644
@@ -1272,6 +1272,10 @@ static void slot_complete_v1_hw(struct hisi_hba *hisi_hba,
 				&status_buffer->iu[0];
 
 		sas_ssp_task_response(dev, task, iu);
+		if (unlikely(ts->stat == SAS_SAM_STAT_CHECK_CONDITION &&
+			     !dev_parent_is_expander(device)))
+			hisi_sas_spinup_notify(hisi_hba, task);
+
 		break;
 	}
 	case SAS_PROTOCOL_SMP:
drivers/scsi/hisi_sas/hisi_sas_v2_hw.c +4 -0
index f3516a0611dde..f16896e962fdd 100644
@@ -2427,6 +2427,10 @@ static void slot_complete_v2_hw(struct hisi_hba *hisi_hba,
 				&status_buffer->iu[0];
 
 		sas_ssp_task_response(dev, task, iu);
+		if (unlikely(ts->stat == SAS_SAM_STAT_CHECK_CONDITION &&
+			     !dev_parent_is_expander(device)))
+			hisi_sas_spinup_notify(hisi_hba, task);
+
 		break;
 	}
 	case SAS_PROTOCOL_SMP:
drivers/scsi/hisi_sas/hisi_sas_v3_hw.c +4 -0
index 9c363e2373538..e74ab20fdbda0 100644
@@ -2435,6 +2435,10 @@ static void slot_complete_v3_hw(struct hisi_hba *hisi_hba,
 			sizeof(struct hisi_sas_err_record);
 
 		sas_ssp_task_response(dev, task, iu);
+		if (unlikely(ts->stat == SAS_SAM_STAT_CHECK_CONDITION &&
+			     !dev_parent_is_expander(device)))
+			hisi_sas_spinup_notify(hisi_hba, task);
+
 		break;
 	}
 	case SAS_PROTOCOL_SMP: {
Signature · 1 line
2.53.0
author maintainer
#1940 lore raw

PATCH 1920/2651 spmi: pmic-arb: return 0 in spmi_pmic_arb_register_buses() on success

In reply to Greg Kroah-Hartman

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

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

From: Fenglin Wu <[email protected]>

[ Upstream commit 82f4c1948a4f951d7d501757a31c6a10eccd37ae ]

The "ret" could be returned with an uninitialized value. Fix it.

Fixes 979987371739 ("spmi: pmic-arb: Add multi bus support")
---
 drivers/spmi/spmi-pmic-arb.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/spmi/spmi-pmic-arb.c +1 -1
index 2e2cb47741038..402ffeaff8e2b 100644
@@ -2060,7 +2060,7 @@ static int spmi_pmic_arb_register_buses(struct spmi_pmic_arb *pmic_arb,
 		}
 	}
 
-	return ret;
+	return 0;
 }
 
 static void spmi_pmic_arb_deregister_buses(struct spmi_pmic_arb *pmic_arb)
Signature · 1 line
2.53.0
author maintainer
#1941 lore raw

PATCH 1921/2651 spmi: mtk-pmif: Add workaround for FSM lockup/error in read operation

In reply to Greg Kroah-Hartman

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

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

From: AngeloGioacchino Del Regno <[email protected]>

[ Upstream commit 84c72fc05f73df3473b3bfac89c0a7eae765513a ]

The SPMI PMIF in some SoCs like MT8196 is affected by a hardware issue that makes the first read operation on each SID to fail as the FSM locks up after sending the read command, and this happens at least in the following conditions:
- At boot, after bootloader handoff; and
- At every suspend->resume cycle.

This critical bug may produce unwanted issues in regulator drivers which may fail to set voltages, making the platform to end up in a undervoltage or, a bit more critically, an overvoltage condition, producing instability or ... worse.

In order to work around this issue, add a retry mechanism into the pmif_spmi_read_cmd() callback which will resend the read command up to 3 times in the following conditions:
- Software Interface returns an error; or
- Software Interface never gets in WFVLDCLR state.

As to avoid uselessly blocking for too much time, only during the read-retry loop, the maximum SWINF polling time for each trial is reduced to PMIF_TIMEOUT_US / 2: this was tested on multiple SoCs and seems to always be enough, as when any read succeeds it will always take less than 40ms.
In any case, this is still allowing 1.5 times the previous maximum polling time, reaching a total maximum (for 3 retries) of 150ms.

Worst case testing that I performed saw a third retry only 3 times out of ~100 reboots.

Fixes 1f5be2d7f743 ("spmi: mtk-pmif: Add support for MT8196 SPMI Controller")
---
 drivers/spmi/spmi-mtk-pmif.c | 38 +++++++++++++++++++++++++++---------
 1 file changed, 29 insertions(+), 9 deletions(-)
drivers/spmi/spmi-mtk-pmif.c +29 -9
index 1048420b5afb6..61c916edaec4c 100644
@@ -21,6 +21,7 @@
 #define SWINF_WFVLDCLR	0x06
 
 #define GET_SWINF(x)	(((x) >> 1) & 0x7)
+#define GET_SWINFERR(x) (((x) >> 18) & 0x1)
 
 #define PMIF_CMD_REG_0		0
 #define PMIF_CMD_REG		1
@@ -349,6 +350,7 @@ static int pmif_spmi_read_cmd(struct spmi_controller *ctrl, u8 opc, u8 sid,
 	struct pmif *arb = to_mtk_pmif(ctrl);
 	struct ch_reg *inf_reg;
 	int ret;
+	u8 retry = 0;
 	u32 data, cmd;
 	unsigned long flags;
 
@@ -385,17 +387,35 @@ static int pmif_spmi_read_cmd(struct spmi_controller *ctrl, u8 opc, u8 sid,
 		return ret;
 	}
 
-	/* Send the command. */
 	cmd = (opc << 30) | (sid << 24) | ((len - 1) << 16) | addr;
-	pmif_writel(arb, pbus, cmd, inf_reg->ch_send);
+	do {
+		/* Send the command. */
+		pmif_writel(arb, pbus, cmd, inf_reg->ch_send);
+
+		/*
+		 * Wait for Software Interface FSM state to be WFVLDCLR or to
+		 * return an error.
+		 *
+		 * If this is WFVLDCLR, read the data and clear the valid flag;
+		 * If error or timeout, retry for a maximum of 3 times as a
+		 * workaround for an hardware issue.
+		 */
+		ret = readl_poll_timeout_atomic(pbus->base + arb->data->regs[inf_reg->ch_sta],
+						data,
+						GET_SWINF(data) == SWINF_WFVLDCLR ||
+						GET_SWINFERR(data),
+						PMIF_DELAY_US, PMIF_TIMEOUT_US / 2);
+		if (ret < 0)
+			continue;
+
+		if (GET_SWINFERR(data)) {
+			ret = -EIO;
+			continue;
+		}
+
+		break;
+	} while (++retry < 3);
 
-	/*
-	 * Wait for Software Interface FSM state to be WFVLDCLR,
-	 * read the data and clear the valid flag.
-	 */
-	ret = readl_poll_timeout_atomic(pbus->base + arb->data->regs[inf_reg->ch_sta],
-					data, GET_SWINF(data) == SWINF_WFVLDCLR,
-					PMIF_DELAY_US, PMIF_TIMEOUT_US);
 	if (ret < 0) {
 		raw_spin_unlock_irqrestore(&pbus->lock, flags);
 		dev_err(&ctrl->dev, "failed to wait for SWINF_WFVLDCLR\n");
Signature · 1 line
2.53.0
author maintainer
#1942 lore raw

PATCH 1922/2651 spmi: mtk-pmif: Fix clock reference leak in mtk_spmi_bus_probe()

In reply to Greg Kroah-Hartman

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

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

From: Wentao Liang <[email protected]>

[ Upstream commit 636c4c026f47f0a7a009b1e39e310afca640a047 ]

of_clk_get_by_name() returns a reference that must be released with clk_put(). If the lookup of a later clock fails, the function returns without releasing the clocks that were already obtained. Put those clocks before returning.

Fixes 078117963b2c ("spmi: mtk-pmif: Add multi-bus support for SPMI 2.0")
---
 drivers/spmi/spmi-mtk-pmif.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/spmi/spmi-mtk-pmif.c +3 -1
index 61c916edaec4c..833c2b30d09f0 100644
@@ -746,9 +746,11 @@ static int mtk_spmi_bus_probe(struct platform_device *pdev,
 	for (i = 0; i < pbus->nclks; i++) {
 		pbus->clks[i].id = pmif_clock_names[i];
 		pbus->clks[i].clk = of_clk_get_by_name(node, pbus->clks[i].id);
-		if (IS_ERR(pbus->clks[i].clk))
+		if (IS_ERR(pbus->clks[i].clk)) {
+			clk_bulk_put(i, pbus->clks);
 			return dev_err_probe(&pdev->dev, PTR_ERR(pbus->clks[i].clk),
 					     "Failed to get clocks\n");
+		}
 	}
 
 	err = clk_bulk_prepare_enable(pbus->nclks, pbus->clks);
Signature · 1 line
2.53.0
author maintainer
#1943 lore raw

PATCH 1923/2651 dt-bindings: vendor-prefixes: add Ambarella

In reply to Greg Kroah-Hartman

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

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

From: Long Zhao <[email protected]>

[ Upstream commit 5ef299ffb56531b3a4f2b311000da76beed403ee ]

Document the Ambarella, Inc. vendor prefix so Ambarella DT bindings can be applied without waiting for the SoC series.

---
 Documentation/devicetree/bindings/vendor-prefixes.yaml | 2 ++
 1 file changed, 2 insertions(+)
Documentation/devicetree/bindings/vendor-prefixes.yaml +2 -0
index 2d93308624cea..fdc459eaa1211 100644
@@ -114,6 +114,8 @@ patternProperties:
     description: Amarula Solutions
   "^amazon,.*":
     description: Amazon.com, Inc.
+  "^ambarella,.*":
+    description: Ambarella, Inc.
   "^amcc,.*":
     description: Applied Micro Circuits Corporation (APM, formally AMCC)
   "^amd,.*":
Signature · 1 line
2.53.0
author maintainer
#1944 lore raw

PATCH 1924/2651 selftests/exec: report the skipped binfmt_misc_bpf test on stderr

In reply to Greg Kroah-Hartman

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

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

[ Upstream commit b36b990c50b1f581b9a7f35ae256f5542415fa69 ]

The exec Makefile announces that binfmt_misc_bpf is skipped with $(info), which writes to standard output whenever the Makefile is parsed. The selftests install target appends the standard output of "make -s emit_tests" to kselftest-list.txt, so on systems without the BPF toolchain the runlist gains a line that is not a test entry:

exec selftests: skipping binfmt_misc_bpf, needs clang, bpftool, ...

run_kselftest.sh and CI systems that parse the runlist then treat it as a malformed test entry.

Use $(warning) so that the notice still appears in build logs but goes to standard error.

Fixes 277d787feb2e ("selftests/exec: add binfmt_misc bpf-backed handler test")
---
 tools/testing/selftests/exec/Makefile | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/testing/selftests/exec/Makefile +1 -1
index b640af8f02b51..bb10d9523e7fc 100644
@@ -63,7 +63,7 @@ TEST_GEN_FILES += bpf_interp.bpf.o nix_origin.bpf.o transparent.bpf.o
 TEST_GEN_FILES += loader.bpf.o interp_bind.bpf.o
 TEST_GEN_FILES += binfmt_bpf_interp binfmt_bpf_app binfmt_bind_interp
 else
-$(info exec selftests: skipping binfmt_misc_bpf, needs clang, bpftool, vmlinux BTF and libbpf)
+$(warning exec selftests: skipping binfmt_misc_bpf, needs clang, bpftool, vmlinux BTF and libbpf)
 endif
 
 EXTRA_CLEAN := $(OUTPUT)/subdir.moved $(OUTPUT)/execveat.moved $(OUTPUT)/xxxxx*	\
Signature · 1 line
2.53.0
author maintainer
#1945 lore raw

PATCH 1925/2651 rust: zerocopy: fix link to upstream `README.md`

In reply to Greg Kroah-Hartman

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

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

From: Miguel Ojeda <[email protected]>

[ Upstream commit d61be5c960e4b89b2e6fa8cedc1d9aa64401ae13 ]

Upstream moved the zerocopy crate into a zerocopy/ subdirectory of their repository in v0.8.51 [1]. However, in our v0.8.52 update, the link was not updated.

Fix it by adding the subdirectory.

---
 rust/zerocopy-derive/README.md | 2 +-
 rust/zerocopy/README.md        | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
rust/zerocopy-derive/README.md +1 -1
index d62c798043424..49de31b8e0827 100644
@@ -8,7 +8,7 @@ non-ASCII identifiers.
 
 For copyright details, please see:
 
-    https://github.com/google/zerocopy/blob/v0.8.54/README.md?plain=1
+    https://github.com/google/zerocopy/blob/v0.8.54/zerocopy/README.md?plain=1
     https://github.com/google/zerocopy/blob/v0.8.54/LICENSE-BSD
     https://github.com/google/zerocopy/blob/v0.8.54/LICENSE-APACHE
     https://github.com/google/zerocopy/blob/v0.8.54/LICENSE-MIT
rust/zerocopy/README.md +1 -1
index 3d11a6502cf0c..8443f61660089 100644
@@ -7,7 +7,7 @@ modified to tweak the SPDX license identifiers.
 
 For copyright details, please see:
 
-    https://github.com/google/zerocopy/blob/v0.8.54/README.md?plain=1
+    https://github.com/google/zerocopy/blob/v0.8.54/zerocopy/README.md?plain=1
     https://github.com/google/zerocopy/blob/v0.8.54/LICENSE-BSD
     https://github.com/google/zerocopy/blob/v0.8.54/LICENSE-APACHE
     https://github.com/google/zerocopy/blob/v0.8.54/LICENSE-MIT
Signature · 1 line
2.53.0
author maintainer
#1946 lore raw

PATCH 1926/2651 ata: libahci: re-enable FBS after error handling on a port multiplier

In reply to Greg Kroah-Hartman

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

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

From: Kyrylo Biryuk <[email protected]>

[ Upstream commit 23eab9e877497397a0e2394ee9174d576816209e ]

ahci_do_softreset() disables FBS before resetting a device behind a port multiplier, as required by AHCI 1.2 section 9.3.9, and re-enables it only when that softreset succeeds. If it fails, for example because a hot-plugged drive is still spinning up ("softreset failed (device not ready)"), EH escalates to a hardreset of the PMP link, and nothing turns FBS back on: only ahci_pmp_attach() does, which runs at the next boot. The port keeps working with command-based switching until then.

Seen on a Marvell 88SE9235 (1b4b:9235) with Marvell 88SM9705 port multipliers (1b4b:9705, in a Synology DX1222 expansion unit): after hot-plugging a drive, the kernel logged "FBS is disabled" followed by "softreset failed (device not ready)" and a PMP hardreset, and never "FBS is enabled" again (twice, on two different ports).

At the end of ahci_error_handler(), re-enable FBS if a PMP is still attached and FBS is supported but disabled.

Fixes 89dafa20f3da ("ahci: disabled FBS prior to issuing software reset")
Assisted-by LLM
---
 drivers/ata/libahci.c | 15 +++++++++++++++
 1 file changed, 15 insertions(+)
drivers/ata/libahci.c +15 -0
index f3fd56f153340..222af8d9fc013 100644
@@ -2233,6 +2233,21 @@ void ahci_error_handler(struct ata_port *ap)
 
 	sata_pmp_error_handler(ap);
 
+	/*
+	 * ahci_do_softreset() turns FBS off before resetting a fan-out link
+	 * and turns it back on only if that reset succeeds. When it fails
+	 * (e.g. a hot-plugged drive is still spinning up), EH escalates to a
+	 * PMP hardreset, which never re-enables FBS, so the port would keep
+	 * command-based switching until the PMP is attached again (reboot).
+	 * Restore FBS once recovery is done and the PMP is still attached.
+	 */
+	if (sata_pmp_attached(ap) && ata_dev_enabled(ap->link.device)) {
+		struct ahci_port_priv *pp = ap->private_data;
+
+		if (pp->fbs_supported && !pp->fbs_enabled)
+			ahci_enable_fbs(ap);
+	}
+
 	if (!ata_dev_enabled(ap->link.device))
 		hpriv->stop_engine(ap);
 }
Signature · 1 line
2.53.0
author maintainer
#1947 lore raw

PATCH 1927/2651 net: axienet: free outstanding TX buffers in axienet_dma_bd_release()

In reply to Greg Kroah-Hartman

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

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

From: Sagi Maimon <[email protected]>

[ Upstream commit 0c20cb4cfb40cf270d6c4c2c2ff5e5d72322644a ]

axienet_dma_bd_release() walks the RX ring to unmap and free every receive buffer before releasing it, but frees the TX descriptor ring with dma_free_coherent() alone. Any descriptor that axienet_free_tx_chain() had not yet reclaimed still holds its skb and its streaming DMA mapping, and both are lost.

axienet_stop() disables TX NAPI and stops the DMA engine before calling it, so nothing reclaims those descriptors afterwards. Bringing the interface down while frames are in flight therefore leaks up to lp->tx_bd_num skbs and mappings each time.

axienet_dma_err_handler() already walks the TX ring this way before it restarts the DMA engine: it unmaps every descriptor whose cntrl is still set - axienet_free_tx_chain() clears it on reclaim - frees any skb still attached, and clears the descriptor. Move that loop into a helper, axienet_free_tx_bufs(), and call it from axienet_dma_bd_release() too. This relies on axienet_stop() having stopped the DMA engine first, as the RX walk in the same function already does. The helper frees the skbs with dev_kfree_skb_any(), as drops: in the error handler, which runs from a workqueue, that frees them directly rather than deferring them to softirq as dev_kfree_skb_irq() did.

The walk must not run on a ring that is not there. axienet_open() does not check the result of the reset that runs axienet_dma_bd_init(), so when that reset fails tx_bd_v is either still NULL or, after an earlier close, points at the ring that close freed. Clear tx_bd_v and rx_bd_v once their rings are freed, and skip the walk when tx_bd_v is NULL. That also ends the second dma_free_coherent() of a stale ring which the same path already did. On the axienet_dma_bd_init() error path the TX ring has just been allocated zeroed, so the walk does nothing.

This was reported by the Sashiko AI review bot.

Tested on the AXI Ethernet MAC of an ADVA TimeCard X2 (PCIe card, with the built-in AXI DMA): traffic passes, and after each of ten down/up cycles and five module reloads, all made with traffic running and each running axienet_dma_bd_release(), traffic resumes and nothing is logged. The leak itself was not measured, and neither the failed-reset paths nor axienet_dma_err_handler() were exercised.

Fixes 8a3b7a252dca ("drivers/net/ethernet/xilinx: added Xilinx AXI Ethernet driver")
Assisted-by LLM sparse
---
 .../net/ethernet/xilinx/xilinx_axienet_main.c | 74 +++++++++++++------
 1 file changed, 50 insertions(+), 24 deletions(-)
drivers/net/ethernet/xilinx/xilinx_axienet_main.c +50 -24
index 09443623a3e2a..318ff03b04e69 100644
@@ -173,6 +173,46 @@ static dma_addr_t desc_get_phys_addr(struct axienet_local *lp,
 	return ret;
 }
 
+/**
+ * axienet_free_tx_bufs - Release the buffers still held by the TX ring
+ * @lp:		Pointer to the axienet_local structure
+ *
+ * Unmap every descriptor whose mapping is still live, free any skb still
+ * attached, and clear the descriptor for reuse.  axienet_free_tx_chain()
+ * clears cntrl when it reclaims a descriptor, so a non-zero value means
+ * the mapping is live.  The DMA engine must be stopped.
+ */
+static void axienet_free_tx_bufs(struct axienet_local *lp)
+{
+	struct axidma_bd *cur_p;
+	u32 i;
+
+	for (i = 0; i < lp->tx_bd_num; i++) {
+		cur_p = &lp->tx_bd_v[i];
+		if (cur_p->cntrl) {
+			dma_addr_t addr = desc_get_phys_addr(lp, cur_p);
+
+			dma_unmap_single(lp->dev, addr,
+					 (cur_p->cntrl &
+					  XAXIDMA_BD_CTRL_LENGTH_MASK),
+					 DMA_TO_DEVICE);
+		}
+		/* not reclaimed by axienet_free_tx_chain(), so a drop */
+		if (cur_p->skb)
+			dev_kfree_skb_any(cur_p->skb);
+		cur_p->phys = 0;
+		cur_p->phys_msb = 0;
+		cur_p->cntrl = 0;
+		cur_p->status = 0;
+		cur_p->app0 = 0;
+		cur_p->app1 = 0;
+		cur_p->app2 = 0;
+		cur_p->app3 = 0;
+		cur_p->app4 = 0;
+		cur_p->skb = NULL;
+	}
+}
+
 /**
  * axienet_dma_bd_release - Release buffer descriptor rings
  * @ndev:	Pointer to the net_device structure
@@ -186,11 +226,18 @@ static void axienet_dma_bd_release(struct net_device *ndev)
 	int i;
 	struct axienet_local *lp = netdev_priv(ndev);
 
-	/* If we end up here, tx_bd_v must have been DMA allocated. */
+	/* tx_bd_v is NULL if axienet_dma_bd_init() did not get as far as
+	 * allocating it, and is cleared below once the ring is freed;
+	 * dma_free_coherent() accepts NULL.
+	 */
+	if (lp->tx_bd_v)
+		axienet_free_tx_bufs(lp);
+
 	dma_free_coherent(lp->dev,
 			  sizeof(*lp->tx_bd_v) * lp->tx_bd_num,
 			  lp->tx_bd_v,
 			  lp->tx_bd_p);
+	lp->tx_bd_v = NULL;
 
 	if (!lp->rx_bd_v)
 		return;
@@ -221,6 +268,7 @@ static void axienet_dma_bd_release(struct net_device *ndev)
 			  sizeof(*lp->rx_bd_v) * lp->rx_bd_num,
 			  lp->rx_bd_v,
 			  lp->rx_bd_p);
+	lp->rx_bd_v = NULL;
 }
 
 static u64 axienet_dma_rate(struct axienet_local *lp)
@@ -2749,29 +2797,7 @@ static void axienet_dma_err_handler(struct work_struct *work)
 	axienet_dma_stop(lp);
 	netdev_reset_queue(ndev);
 
-	for (i = 0; i < lp->tx_bd_num; i++) {
-		cur_p = &lp->tx_bd_v[i];
-		if (cur_p->cntrl) {
-			dma_addr_t addr = desc_get_phys_addr(lp, cur_p);
-
-			dma_unmap_single(lp->dev, addr,
-					 (cur_p->cntrl &
-					  XAXIDMA_BD_CTRL_LENGTH_MASK),
-					 DMA_TO_DEVICE);
-		}
-		if (cur_p->skb)
-			dev_kfree_skb_irq(cur_p->skb);
-		cur_p->phys = 0;
-		cur_p->phys_msb = 0;
-		cur_p->cntrl = 0;
-		cur_p->status = 0;
-		cur_p->app0 = 0;
-		cur_p->app1 = 0;
-		cur_p->app2 = 0;
-		cur_p->app3 = 0;
-		cur_p->app4 = 0;
-		cur_p->skb = NULL;
-	}
+	axienet_free_tx_bufs(lp);
 
 	for (i = 0; i < lp->rx_bd_num; i++) {
 		cur_p = &lp->rx_bd_v[i];
Signature · 1 line
2.53.0
author maintainer
#1948 lore raw

PATCH 1928/2651 ata: libata-core: Fix NO_FUA quirks shadowed by earlier quirk entries

In reply to Greg Kroah-Hartman

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

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

From: Niklas Cassel <[email protected]>

[ Upstream commit 4153718a215eeb5bab3df50417bbd9602e84658c ]

ata_dev_quirks() uses the first entry in __ata_dev_quirks[] that matches the device and ignores all later entries. Commit 38d431229bfb ("ata: libata: exclude FUA support for known buggy drives") appended three ATA_QUIRK_NO_FUA entries to the end of the table, with model patterns meant to cover whole product lines. Earlier entries already match some or all of these drives, so NO_FUA is not always applied:

- "INTEL*SSDSC2CT*" never takes effect. Every model it matches also matches the earlier "INTEL*SSD*" entry, so these drives only get ATA_QUIRK_ZERO_AFTER_TRIM.

- "WDC*WD2500J*" does not take effect for "WDC WD2500JD-*" drives, which match the earlier ATA_QUIRK_WD_BROKEN_LPM entry.

- "OCZ-VERTEX*" does not take effect for "OCZ-VERTEX" drives with firmware "1.30", which match the earlier ATA_QUIRK_BROKEN_HPA entry.

Move the Intel entry in front of "INTEL*SSD*" and keep ATA_QUIRK_ZERO_AFTER_TRIM in it, so these drives stay on the ZERO_AFTER_TRIM whitelist. Add ATA_QUIRK_NO_FUA to the WD2500JD and OCZ Vertex 1.30 entries. The quirks of all other drives are unchanged.

libata only uses FUA when it is enabled with libata.fua=1, so systems using the default setting are not affected.

Fixes 38d431229bfb ("ata: libata: exclude FUA support for known buggy drives")
Assisted-by LLM
---
 drivers/ata/libata-core.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
drivers/ata/libata-core.c +6 -3
index f218773f187fc..1fe222008abd2 100644
@@ -4323,7 +4323,8 @@ static const struct ata_dev_quirks_entry __ata_dev_quirks[] = {
 	{ "MAXTOR 6L080L4",	"A93.0500",	ATA_QUIRK_BROKEN_HPA },
 
 	/* this one allows HPA unlocking but fails IOs on the area */
-	{ "OCZ-VERTEX",		    "1.30",	ATA_QUIRK_BROKEN_HPA },
+	{ "OCZ-VERTEX",		    "1.30",	ATA_QUIRK_BROKEN_HPA |
+						ATA_QUIRK_NO_FUA },
 
 	/* Devices which report 1 sector over size HPA */
 	{ "ST340823A",		NULL,		ATA_QUIRK_HPA_SIZE },
@@ -4459,6 +4460,8 @@ static const struct ata_dev_quirks_entry __ata_dev_quirks[] = {
 	{ "Crucial*",			NULL,	ATA_QUIRK_ZERO_AFTER_TRIM },
 	{ "INTEL SSDSC2KG480G8", "XCV10120",	ATA_QUIRK_ZERO_AFTER_TRIM |
 						ATA_QUIRK_MAX_SEC },
+	{ "INTEL*SSDSC2CT*",		NULL,	ATA_QUIRK_ZERO_AFTER_TRIM |
+						ATA_QUIRK_NO_FUA },
 	{ "INTEL*SSD*",			NULL,	ATA_QUIRK_ZERO_AFTER_TRIM },
 	{ "SSD*INTEL*",			NULL,	ATA_QUIRK_ZERO_AFTER_TRIM },
 	{ "Samsung*SSD*",		NULL,	ATA_QUIRK_ZERO_AFTER_TRIM },
@@ -4479,7 +4482,8 @@ static const struct ata_dev_quirks_entry __ata_dev_quirks[] = {
 	{ "WDC WD1200JD-*",		NULL,	ATA_QUIRK_WD_BROKEN_LPM },
 	{ "WDC WD1600JD-*",		NULL,	ATA_QUIRK_WD_BROKEN_LPM },
 	{ "WDC WD2000JD-*",		NULL,	ATA_QUIRK_WD_BROKEN_LPM },
-	{ "WDC WD2500JD-*",		NULL,	ATA_QUIRK_WD_BROKEN_LPM },
+	{ "WDC WD2500JD-*",		NULL,	ATA_QUIRK_WD_BROKEN_LPM |
+						ATA_QUIRK_NO_FUA },
 	{ "WDC WD3000JD-*",		NULL,	ATA_QUIRK_WD_BROKEN_LPM },
 	{ "WDC WD3200JD-*",		NULL,	ATA_QUIRK_WD_BROKEN_LPM },
 
@@ -4504,7 +4508,6 @@ static const struct ata_dev_quirks_entry __ata_dev_quirks[] = {
 	{ "Maxtor",		"BANC1G10",	ATA_QUIRK_NO_FUA },
 	{ "WDC*WD2500J*",	NULL,		ATA_QUIRK_NO_FUA },
 	{ "OCZ-VERTEX*",	NULL,		ATA_QUIRK_NO_FUA },
-	{ "INTEL*SSDSC2CT*",	NULL,		ATA_QUIRK_NO_FUA },
 
 	/* End Marker */
 	{ }
Signature · 1 line
2.53.0
author maintainer
#1949 lore raw

PATCH 1929/2651 selftests/bpf: Use its own netns in flow_dissector_skb_less_direct_attach

In reply to Greg Kroah-Hartman

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

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

From: Qiliang Yuan <[email protected]>

[ Upstream commit 76c1913f311f32971dc2c3e106e285bd63c1804d ]

test_flow_dissector_skb_less_direct_attach() and test_flow_dissector_skb_less_indirect_attach() each create a netns to run in, and test_progs may run the two at the same time.

Both name their netns flow_dissector_skb_less_indirect_attach_ns. When the two tests overlap, one of them fails to create or open the netns, or loses it to the cleanup of the other one.

Name the netns of the direct attach test after that test.

---
 tools/testing/selftests/bpf/prog_tests/flow_dissector.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/testing/selftests/bpf/prog_tests/flow_dissector.c +1 -1
index fb48926814647..f6fefb14cda3c 100644
@@ -706,7 +706,7 @@ void test_flow_dissector_skb_less_direct_attach(void)
 	struct bpf_flow *skel;
 	struct netns_obj *ns;
 
-	ns = netns_new("flow_dissector_skb_less_indirect_attach_ns", true);
+	ns = netns_new("flow_dissector_skb_less_direct_attach_ns", true);
 	if (!ASSERT_OK_PTR(ns, "create and open netns"))
 		return;
 
Signature · 1 line
2.53.0
author maintainer
#1950 lore raw

PATCH 1930/2651 selftests/bpf: Report a failure to register the session key in test_progs

In reply to Greg Kroah-Hartman

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

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

From: Qiliang Yuan <[email protected]>

[ Upstream commit 66fd5eb9da12ef4ed089ed1974160d07ff034a19 ]

test_progs adds the key that verifies signed programs to the session keyring before it runs any test, and exits when that fails.

It exits with 255 without printing anything. pam_keyinit revokes the session keyring on logout, so a test_progs started in the background from an ssh session that has been closed since leaves nothing but an empty log behind, with no hint of what went wrong.

Print the error before exiting.

---
 tools/testing/selftests/bpf/test_progs.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
tools/testing/selftests/bpf/test_progs.c +4 -1
index 46eb201b96a38..168d84cf4eb76 100644
@@ -2065,8 +2065,11 @@ int main(int argc, char **argv)
 	libbpf_set_print(libbpf_print_fn);
 	err = register_session_key((const char *)test_progs_verification_cert,
 				   test_progs_verification_cert_len);
-	if (err < 0)
+	if (err < 0) {
+		fprintf(stderr, "Failed to add libbpf_session_key to the session keyring: %s\n",
+			strerror(errno));
 		return err;
+	}
 
 	traffic_monitor_set_print(traffic_monitor_print_fn);
 
Signature · 1 line
2.53.0
author maintainer
#1951 lore raw

PATCH 1931/2651 selftests/bpf: Expect at least one tp_recursion miss in missed

In reply to Greg Kroah-Hartman

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

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

From: Qiliang Yuan <[email protected]>

[ Upstream commit a5e144985d6855c84b56ea5443fd6333490ce8ec ]

missed_tp_recursion attaches its tp programs to bpf_trace_printk and expects each of them to miss exactly one run, the one that its kprobe program on bpf_fentry_test1 triggers by calling bpf_printk().

The test is not serial, so tests running in parallel can add misses to the tp programs while they are attached:

- The kprobe on bpf_fentry_test1 is global. Any other test that does bpf_prog_test_run() on a fentry/fexit program calls bpf_fentry_test1() and thereby fires the kprobe program, which calls bpf_printk() from kprobe context and makes the tp programs fail the bpf_prog_active check once more.

- Any other program that runs under the bpf_prog_active check, such as a kprobe program or the perf event tracepoint program in legacy_printk, and calls bpf_printk() hits bpf_trace_printk the same way.

Either way, test2_recursion_misses comes out as 2 instead of 1.

Expect at least one miss, as missed_kprobe_recursion does since commit 08a7078feacf ("selftests/bpf: Improve missed_kprobe_recursion test robustness").

Fixes 85981e0f9e9f ("selftests/bpf: Add test for recursion counts of perf event link tracepoint")
---
 tools/testing/selftests/bpf/prog_tests/missed.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
tools/testing/selftests/bpf/prog_tests/missed.c +3 -3
index ed8857ae914a6..0b8f1aa5a3e74 100644
@@ -120,9 +120,9 @@ static void test_missed_tp_recursion(void)
 	ASSERT_EQ(topts.retval, 0, "test_run");
 
 	ASSERT_EQ(get_missed_count(bpf_program__fd(skel->progs.test1)), 0, "test1_recursion_misses");
-	ASSERT_EQ(get_missed_count(bpf_program__fd(skel->progs.test2)), 1, "test2_recursion_misses");
-	ASSERT_EQ(get_missed_count(bpf_program__fd(skel->progs.test3)), 1, "test3_recursion_misses");
-	ASSERT_EQ(get_missed_count(bpf_program__fd(skel->progs.test4)), 1, "test4_recursion_misses");
+	ASSERT_GE(get_missed_count(bpf_program__fd(skel->progs.test2)), 1, "test2_recursion_misses");
+	ASSERT_GE(get_missed_count(bpf_program__fd(skel->progs.test3)), 1, "test3_recursion_misses");
+	ASSERT_GE(get_missed_count(bpf_program__fd(skel->progs.test4)), 1, "test4_recursion_misses");
 
 cleanup:
 	missed_tp_recursion__destroy(skel);
Signature · 1 line
2.53.0
author maintainer
#1952 lore raw

PATCH 1932/2651 veth: clear rx queue hint in veth_xmit

In reply to Greg Kroah-Hartman

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

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

From: Jiayuan Chen <[email protected]>

[ Upstream commit 1b1c0e87cfe78d731bbab99c9c018655980b6790 ]

With more tx queues on one end of a veth pair than rx queues on the other, and RPS or generic XDP enabled on the receiving end, we get:

    veth1 received packet on queue 2, but number of RX queues is 2
    WARNING: net/core/dev.c:5212 at get_rps_cpu+0x560/0x1360
    Call Trace:
     <TASK>
     netif_rx_internal+0x1af/0x4c0
     __netif_rx+0x99/0x350
     veth_xmit+0x713/0xca0
     dev_hard_start_xmit+0x166/0x5f0
     __dev_queue_xmit+0x1797/0x42d0
     ip_finish_output2+0xa34/0x1f40
     __ip_finish_output+0x510/0x7e0
     ip_finish_output+0x2f/0x320
     ip_output+0x17a/0x3f0
     ip_send_skb+0x1bc/0x220
     ......

Easy to hit with "ethtool -L veth0 tx 4", "ethtool -L veth1 rx 2", rps_cpus set on veth1 and a few flows sent over the pair [1].

veth_xmit() uses skb->queue_mapping to pick the peer rq, but never clears it before veth_forward_skb(), so the rx side still sees the tx queue index. Everything on the rx side that goes through skb_get_rx_queue(), like get_rps_cpu() and netif_get_rxqueue() for generic XDP, takes it as a recorded rx queue and warns once it is out of range.

Clear it before handing the skb to the peer:

- It is the tx queue index of this device, it says nothing about the rx queue of the peer.

- The two sides don't even agree on the encoding. The tx side stores the index as is, the rx side stores index + 1 so that 0 can mean "not recorded". So tx queue k is read back as rx queue k - 1, and tx queue 0 as "not recorded".

- Commit 710ad98c363a ("veth: Do not record rx queue hint in veth_xmit") already decided that veth should not pass any queue hint to the peer. There is no tx->rx queue mapping to preserve, so nothing is lost by clearing it.

On NETDEV_TX_BUSY the skb goes back to the qdisc, which looks up the txq from skb->queue_mapping to decide when to retry, so restore it there, next to the existing __skb_push().

[1]: https://lore.kernel.org/netdev/[email protected]/

Fixes 76ff5cc91935 ("rtnl: allow to specify number of rx and tx queues on device creation")
---
 drivers/net/veth.c | 5 +++++
 1 file changed, 5 insertions(+)
drivers/net/veth.c +5 -0
index c1859ffcdaf1a..8e61f67dc37c1 100644
@@ -377,6 +377,9 @@ static netdev_tx_t veth_xmit(struct sk_buff *skb, struct net_device *dev)
 
 	skb_tx_timestamp(skb);
 
+	/* tx queue index of this device, meaningless as rx queue of the peer */
+	skb_set_queue_mapping(skb, 0);
+
 	ret = veth_forward_skb(rcv, skb, rq, use_napi);
 	switch (ret) {
 	case NET_RX_SUCCESS: /* same as NETDEV_TX_OK */
@@ -397,6 +400,8 @@ static netdev_tx_t veth_xmit(struct sk_buff *skb, struct net_device *dev)
 		}
 		/* Restore Eth hdr pulled by dev_forward_skb/eth_type_trans */
 		__skb_push(skb, ETH_HLEN);
+		/* qdisc requeues the skb on the txq it points to */
+		skb_set_queue_mapping(skb, rxq);
 		netif_tx_stop_queue(txq);
 		/* Makes sure NAPI peer consumer runs. Consumer is responsible
 		 * for starting txq again, until then ndo_start_xmit (this
Signature · 1 line
2.53.0
author maintainer
#1953 lore raw

PATCH 1933/2651 IB/IPoIB: Cancel normal flush work on device stop

In reply to Greg Kroah-Hartman

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

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

From: Carolina Jubran <[email protected]>

[ Upstream commit 66196a559be5963b1ced18418c876caf9bfb76e6 ]

ipoib_ib_dev_flush_normal() can race with ipoib_stop() because the normal flush work does not run under RTNL.

Before commit a77a57a1a22a ("IPoIB: Fix deadlock on RTNL in ipoib_stop()"), ipoib_stop() flushed ipoib_workqueue after clearing IPOIB_FLAG_ADMIN_UP and before calling ipoib_ib_dev_down(). This ensured that any in-flight flush work completed before ipoib_ib_dev_down() performed the final clear of IPOIB_FLAG_OPER_UP.

After that commit removed the workqueue flush to avoid a deadlock with workqueue tasks taking RTNL, a normal flush can continue running concurrently with ipoib_stop() after IPOIB_FLAG_ADMIN_UP has been cleared.

The flush may observe IPOIB_FLAG_ADMIN_UP set and continue running while ipoib_stop() clears IPOIB_FLAG_ADMIN_UP and brings the device down. The flush can then call ipoib_ib_dev_up() and set IPOIB_FLAG_OPER_UP again after the device has already been stopped:

flush_normal (ipoib_workqueue) ipoib_stop() (RTNL held)
------------------------------ ------------------------
test_bit(ADMIN_UP) == 1

                                    clear_bit(ADMIN_UP)
                                    ipoib_ib_dev_down()
                                      clear_bit(OPER_UP)

ipoib_ib_dev_up()
set_bit(OPER_UP)

This leaves the interface with ADMIN_UP clear and OPER_UP set. During device removal, ipoib_ndo_uninit() waits in destroy_workqueue() while holding RTNL, while ipoib_mcast_carrier_on_task() may keep retrying rtnl_trylock() as long as OPER_UP remains set, resulting in a deadlock.

Cancel the normal flush work from ipoib_stop() after clearing IPOIB_FLAG_ADMIN_UP and before bringing the device down. A pending normal flush is canceled, while an already running flush is allowed to finish before ipoib_ib_dev_down() performs the final transition to OPER_UP clear.

Only the normal flush needs this synchronization. The heavy flush is already serialized with ipoib_stop() by RTNL, while the light flush does not bring the device back up and therefore cannot recreate this race.

---
 drivers/infiniband/ulp/ipoib/ipoib_main.c | 7 +++++++
 1 file changed, 7 insertions(+)
drivers/infiniband/ulp/ipoib/ipoib_main.c +7 -0
index 6c14246befb1f..f0b72d65fdeb7 100644
@@ -230,6 +230,13 @@ static int ipoib_stop(struct net_device *dev)
 
 	clear_bit(IPOIB_FLAG_ADMIN_UP, &priv->flags);
 
+	/* Normal flush runs without RTNL and may bring the device back
+	 * up. Cancel it before the device down transition.
+	 * Heavy flush is already serialized by RTNL and must not be
+	 * waited on here while RTNL is held.
+	 */
+	cancel_work_sync(&priv->flush_normal);
+
 	netif_stop_queue(dev);
 
 	ipoib_ib_dev_down(dev);
Signature · 1 line
2.53.0
author maintainer
#1954 lore raw

PATCH 1934/2651 rxrpc: Revert "rxrpc: rxperf: Fix missing decoding of terminal magic cookie"

In reply to Greg Kroah-Hartman

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

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

From: David Howells <[email protected]>

[ Upstream commit 870143cfdac1cad166d1dc03fbef915fac0c229a ]

Revert commit c34d999ca3145d9fe858258cc3342ec493f47d2e:

The rxperf RPCs seem to have a magic cookie at the end of the request that was failing to be taken account of by the unmarshalling of the request. Fix the rxperf code to expect this.

Actually, this isn't true; it's just that other Rx implementations ignore the extra data in the request and so my test programs are sending too much data without noticeable consequence.

Fixes c34d999ca314 ("rxrpc: rxperf: Fix missing decoding of terminal magic cookie")
cc Marc Dionne <[email protected]>
cc Eric Dumazet <[email protected]>
cc "David S. Miller" <[email protected]>
cc Jakub Kicinski <[email protected]>
cc Paolo Abeni <[email protected]>
cc Simon Horman <[email protected]>
---
 net/rxrpc/rxperf.c | 12 ------------
 1 file changed, 12 deletions(-)
net/rxrpc/rxperf.c +0 -12
index 6a815a4bb314b..02f8ed2f74c05 100644
@@ -495,18 +495,6 @@ static int rxperf_deliver_request(struct rxperf_call *call)
 		call->unmarshal++;
 		fallthrough;
 	case 2:
-		ret = rxperf_extract_data(call, true);
-		if (ret < 0)
-			return ret;
-
-		/* Deal with the terminal magic cookie. */
-		call->iov_len = 4;
-		call->kvec[0].iov_len	= call->iov_len;
-		call->kvec[0].iov_base	= call->tmp;
-		iov_iter_kvec(&call->iter, READ, call->kvec, 1, call->iov_len);
-		call->unmarshal++;
-		fallthrough;
-	case 3:
 		ret = rxperf_extract_data(call, false);
 		if (ret < 0)
 			return ret;
Signature · 1 line
2.53.0
author maintainer
#1955 lore raw

PATCH 1935/2651 rxrpc: Fix rxperf test rxgk key kvno to be 0

In reply to Greg Kroah-Hartman

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

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

From: David Howells <[email protected]>

[ Upstream commit a7c8c3ab072375fc667ee294b58bcb9071d6e3ca ]

Fix the test rxgk keys in the rxperf test server to have kvno 0 to match other implementations.

Fixes aa2199088a39 ("rxrpc: rxperf: Add test RxGK server keys")
cc Marc Dionne <[email protected]>
cc Jeffrey Altman <[email protected]>
cc Eric Dumazet <[email protected]>
cc "David S. Miller" <[email protected]>
cc Jakub Kicinski <[email protected]>
cc Paolo Abeni <[email protected]>
cc Simon Horman <[email protected]>
---
 net/rxrpc/rxperf.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/rxrpc/rxperf.c +1 -1
index 02f8ed2f74c05..441beb077742e 100644
@@ -593,7 +593,7 @@ static int rxperf_add_yfs_rxgk_key(struct key *keyring, u32 enctype)
 	for (int i = 0; i < krb5->key_len; i++)
 		key[i] = i;
 
-	sprintf(name, "%u:6:1:%u", RX_PERF_SERVICE, enctype);
+	sprintf(name, "%u:6:0:%u", RX_PERF_SERVICE, enctype);
 
 	kref = key_create_or_update(make_key_ref(keyring, true),
 				    "rxrpc_s", name,
Signature · 1 line
2.53.0
author maintainer
#1956 lore raw

PATCH 1936/2651 rxrpc: Fix aborting in rxperf test server

In reply to Greg Kroah-Hartman

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

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

From: David Howells <[email protected]>

[ Upstream commit 7f15923909866e76608ea6474368570938e783fc ]

Fix rxperf_process_call() to always abort if it gets a send error rather than only aborting on ENOMEM.

Fixes 75bfdbf2fca3 ("rxrpc: Implement an in-kernel rxperf server for testing purposes")
cc Marc Dionne <[email protected]>
cc Eric Dumazet <[email protected]>
cc "David S. Miller" <[email protected]>
cc Jakub Kicinski <[email protected]>
cc Paolo Abeni <[email protected]>
cc Simon Horman <[email protected]>
---
 include/trace/events/rxrpc.h |  2 +-
 net/rxrpc/rxperf.c           | 11 ++++++-----
 2 files changed, 7 insertions(+), 6 deletions(-)
include/trace/events/rxrpc.h +1 -1
index 554dfb777b93e..56dc9b6140716 100644
@@ -28,8 +28,8 @@
 	EM(afs_abort_unsupported_sec_class,	"afs-unsup-sec-class")	\
 	/* rxperf errors */						\
 	EM(rxperf_abort_general_error,		"rxperf-error")		\
-	EM(rxperf_abort_oom,			"rxperf-oom")		\
 	EM(rxperf_abort_op_not_supported,	"rxperf-op-notsupp")	\
+	EM(rxperf_abort_send_error,		"rxperf-send-error")	\
 	EM(rxperf_abort_unmarshal_error,	"rxperf-unmarshal")	\
 	/* RxKAD security errors */					\
 	EM(rxkad_abort_1_short_check,		"rxkad1-short-check")	\
net/rxrpc/rxperf.c +6 -5
index 441beb077742e..0bc3de061b938 100644
@@ -527,7 +527,7 @@ static int rxperf_process_call(struct rxperf_call *call)
 		ret = rxrpc_kernel_send_data(rxperf_socket, call->rxcall, &msg,
 					     rxperf_notify_end_reply_tx);
 		if (ret < 0)
-			return ret;
+			goto send_error;
 		reply_len -= len;
 	}
 
@@ -538,10 +538,11 @@ static int rxperf_process_call(struct rxperf_call *call)
 	msg.msg_flags = 0;
 	ret = rxrpc_kernel_send_data(rxperf_socket, call->rxcall, &msg,
 				     rxperf_notify_end_reply_tx);
-	if (ret == -ENOMEM)
-		rxrpc_kernel_abort_call(rxperf_socket, call->rxcall,
-					RXGEN_SS_MARSHAL, -ENOMEM,
-					rxperf_abort_oom);
+	if (ret == 0)
+		return 0;
+send_error:
+	rxrpc_kernel_abort_call(rxperf_socket, call->rxcall, RXGEN_SS_MARSHAL,
+				ret, rxperf_abort_send_error);
 	return ret;
 }
 
Signature · 1 line
2.53.0
author maintainer
#1957 lore raw

PATCH 1937/2651 rxrpc: Fix sendmsg length

In reply to Greg Kroah-Hartman

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

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

From: David Howells <[email protected]>

[ Upstream commit ef369cacbd524931199078427ae152c63a826189 ]

rxrpc_send_data() is given two data lengths (len and msg->msg_iter.count) and is inconsistent about how it uses them. Fix this by using len in preference to msg->msg_iter.count. Also limit the amount copied to either len or msg->msg_iter.count, whichever is smaller.

Note that, currently, all the callers have len and msg->msg_iter.count the same and so the problem won't occur. This is a prerequisite for another patch that fixes the handling of encryption errors.

Fixes 382d7974de31 ("RxRPC: Use iov_iter_count() in rxrpc_send_data() instead of the len argument")
cc Marc Dionne <[email protected]>
cc Jeffrey Altman <[email protected]>
cc Eric Dumazet <[email protected]>
cc "David S. Miller" <[email protected]>
cc Jakub Kicinski <[email protected]>
cc Paolo Abeni <[email protected]>
cc Simon Horman <[email protected]>
---
 net/rxrpc/sendmsg.c | 17 +++++++++--------
 1 file changed, 9 insertions(+), 8 deletions(-)
net/rxrpc/sendmsg.c +9 -8
index 393a2dcfda07d..312be27ca75b5 100644
@@ -374,9 +374,9 @@ static int rxrpc_send_data(struct rxrpc_sock *rx,
 
 	ret = -EMSGSIZE;
 	if (call->tx_total_len != -1) {
-		if (len - copied > call->tx_total_len)
+		if (len > call->tx_total_len)
 			goto maybe_error;
-		if (!more && len - copied != call->tx_total_len)
+		if (!more && len != call->tx_total_len)
 			goto maybe_error;
 	}
 
@@ -402,7 +402,7 @@ static int rxrpc_send_data(struct rxrpc_sock *rx,
 			 * the security header is going to be in the padded
 			 * region (enc blocksize), but the trailer is not.
 			 */
-			remain = more ? INT_MAX : msg_data_left(msg);
+			remain = more ? INT_MAX : len;
 			txb = call->conn->security->alloc_txbuf(call, remain, sk->sk_allocation);
 			if (!txb) {
 				ret = -ENOMEM;
@@ -416,8 +416,8 @@ static int rxrpc_send_data(struct rxrpc_sock *rx,
 		_debug("append");
 
 		/* append next segment of data to the current buffer */
-		if (msg_data_left(msg) > 0) {
-			size_t copy = umin(txb->space, msg_data_left(msg));
+		if (len > 0) {
+			size_t copy = min3(txb->space, len, msg_data_left(msg));
 
 			_debug("add %zu", copy);
 			if (!copy_from_iter_full(txb->data + txb->offset,
@@ -428,6 +428,7 @@ static int rxrpc_send_data(struct rxrpc_sock *rx,
 			txb->len += copy;
 			txb->offset += copy;
 			copied += copy;
+			len -= copy;
 			if (call->tx_total_len != -1)
 				call->tx_total_len -= copy;
 		}
@@ -439,8 +440,8 @@ static int rxrpc_send_data(struct rxrpc_sock *rx,
 
 		/* add the packet to the send queue if it's now full */
 		if (!txb->space ||
-		    (msg_data_left(msg) == 0 && !more)) {
-			if (msg_data_left(msg) == 0 && !more)
+		    (len == 0 && !more)) {
+			if (len == 0 && !more)
 				txb->flags |= RXRPC_LAST_PACKET;
 
 			ret = call->security->secure_packet(call, txb);
@@ -449,7 +450,7 @@ static int rxrpc_send_data(struct rxrpc_sock *rx,
 			rxrpc_queue_packet(rx, call, txb, notify_end_tx);
 			call->tx_pending = NULL;
 		}
-	} while (msg_data_left(msg) > 0);
+	} while (len > 0 && msg_data_left(msg) > 0);
 
 success:
 	ret = copied;
Signature · 1 line
2.53.0
author maintainer
#1958 lore raw

PATCH 1938/2651 irqchip/gic-v3: Release the partition node in gic_irq_get_fwspec_info()

In reply to Greg Kroah-Hartman

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

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

From: Fuad Tabba <[email protected]>

[ Upstream commit 0773b76611e9c596c825076d422d372697da9940 ]

gic_irq_get_fwspec_info() never puts the node it takes from of_find_node_by_phandle(), so every lookup from a four-cell PPI or EPPI specifier naming a partition leaks one.

The node is only used for the comparison against gic_data.parts[], and the mask returned points into gic_data, so it can go out of scope with the lookup.

---
 drivers/irqchip/irq-gic-v3.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
drivers/irqchip/irq-gic-v3.c +4 -3
index 6e1fa5b247fc4..b0142b0a93fa4 100644
@@ -1728,8 +1728,6 @@ static int gic_irq_get_fwspec_info(struct irq_fwspec *fwspec, struct irq_fwspec_
 
 	/* If the specifier provides an affinity, use it */
 	if (fwspec->param_count == 4 && fwspec->param[3]) {
-		struct fwnode_handle *fw;
-
 		switch (fwspec->param[0]) {
 		case 1:			/* PPI */
 		case 3:			/* EPPI */
@@ -1738,7 +1736,10 @@ static int gic_irq_get_fwspec_info(struct irq_fwspec *fwspec, struct irq_fwspec_
 			return 0;
 		}
 
-		fw = of_fwnode_handle(of_find_node_by_phandle(fwspec->param[3]));
+		struct device_node *np __free(device_node) =
+			of_find_node_by_phandle(fwspec->param[3]);
+		struct fwnode_handle *fw = of_fwnode_handle(np);
+
 		if (!fw)
 			return -ENOENT;
 
Signature · 1 line
2.53.0
author maintainer
#1959 lore raw

PATCH 1939/2651 irqchip/gic-v3-its: Clear vpt_page after freeing the pending table

In reply to Greg Kroah-Hartman

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

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

From: Fuad Tabba <[email protected]>

[ Upstream commit 0d604b1e4617d18dbb5573290ba447d7369251d1 ]

its_vpe_teardown() frees vpt_page without clearing it, so its vpt_page == NULL guard only holds the first time it runs on a vPE. struct its_vpe outlives a failed KVM_DEV_ARM_VGIC_CTRL_INIT, so a retry that fails again frees the pending table and the vPE ID a second time.

---
 drivers/irqchip/irq-gic-v3-its.c | 1 +
 1 file changed, 1 insertion(+)
drivers/irqchip/irq-gic-v3-its.c +1 -0
index 1bef7ecd3090c..4083265750b6b 100644
@@ -4600,6 +4600,7 @@ static void its_vpe_teardown(struct its_vpe *vpe)
 	its_vpe_db_proxy_unmap(vpe);
 	its_vpe_id_free(vpe->vpe_id);
 	its_free_pending_table(vpe->vpt_page);
+	vpe->vpt_page = NULL;
 }
 
 static void its_vpe_irq_domain_free(struct irq_domain *domain,
Signature · 1 line
2.53.0
author maintainer
#1960 lore raw

PATCH 1940/2651 irqchip/qcom: Enable compile testing for QCOM_PDC and QCOM_MPM

In reply to Greg Kroah-Hartman

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

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

From: Krzysztof Kozlowski <[email protected]>

[ Upstream commit 1b852de05f74cfc96c58caad9df4cc1fa2dc7689 ]

QCOM_PDC and QCOM_MPM do not reference any architecture code, thus should be compile-testable.

Stable-dep-of: 8e6b8708f925 ("irqchip/qcom-pdc: Fix linking against QCOM_SCM firmware")

---
 drivers/irqchip/Kconfig | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/irqchip/Kconfig +2 -2
index 20b77fbc51ee0..5a881ddfa3abe 100644
@@ -522,7 +522,7 @@ config GOLDFISH_PIC
 
 config QCOM_PDC
 	tristate "Qualcomm PDC"
-	depends on ARCH_QCOM
+	depends on ARCH_QCOM || COMPILE_TEST
 	select IRQ_DOMAIN_HIERARCHY
 	help
 	  Power Domain Controller driver to manage and configure wakeup
@@ -530,7 +530,7 @@ config QCOM_PDC
 
 config QCOM_MPM
 	tristate "Qualcomm MPM"
-	depends on ARCH_QCOM
+	depends on ARCH_QCOM || COMPILE_TEST
 	depends on MAILBOX
 	select IRQ_DOMAIN_HIERARCHY
 	help
Signature · 1 line
2.53.0
author maintainer
#1961 lore raw

PATCH 1941/2651 irqchip/qcom-pdc: Fix linking against QCOM_SCM firmware

In reply to Greg Kroah-Hartman

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

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

From: Arnd Bergmann <[email protected]>

[ Upstream commit 8e6b8708f925b015e2af4d77757c2fbee7da6ec8 ]

Build testing with SCM disabled or in a loadable module fails with a link error:

s390-linux-ld: drivers/irqchip/qcom-pdc.o: in function `qcom_pdc_probe':
qcom-pdc.c:(.text+0x18b8): undefined reference to qcom_scm_is_available' qcom-pdc.c:(.text+0x18ce): undefined reference to qcom_scm_io_writel'

As QCOM_SCM can already be enabled for compile testing on non-qualcomm machines, but is always enabled on Qualcomm Arm kernels, use that as the Kconfig dependency and remove the ||COMPILE_TEST check.

Fixes 1b852de05f74 ("irqchip/qcom: Enable compile testing for QCOM_PDC and QCOM_MPM")
Fixes ad01c2b2f291 ("irqchip/qcom-pdc: Configure PDC to pass through mode")
---
 drivers/irqchip/Kconfig | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/irqchip/Kconfig +1 -1
index 5a881ddfa3abe..01f8415f62fc7 100644
@@ -522,7 +522,7 @@ config GOLDFISH_PIC
 
 config QCOM_PDC
 	tristate "Qualcomm PDC"
-	depends on ARCH_QCOM || COMPILE_TEST
+	depends on QCOM_SCM
 	select IRQ_DOMAIN_HIERARCHY
 	help
 	  Power Domain Controller driver to manage and configure wakeup
Signature · 1 line
2.53.0
author maintainer
#1962 lore raw

PATCH 1942/2651 irqchip/mst-intc: Validate the DT interrupt range

In reply to Greg Kroah-Hartman

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

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

From: Pengpeng Hou <[email protected]>

[ Upstream commit 16f25d326e5d3b9fd51bc5e3916ecbffbca63e7b ]

The driver takes an inclusive interrupt range from the device tree without checking its endpoints. A reversed range wraps the unsigned count calculation, and a range larger than MST_INTC_MAX_IRQS exceeds the controller capacity used by the driver.

Reject these ranges before calculating nr_irqs or creating the domain. Check the difference after ordering the endpoints so the validation itself cannot wrap.

The issue was found by our static-analysis tool.

Fixes ad4c938c92af ("irqchip/irq-mst: Add MStar interrupt controller support")
Assisted-by gpt 5
---
 drivers/irqchip/irq-mst-intc.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/irqchip/irq-mst-intc.c +3 -0
index b5335f6fd6d6e..1070de5de8cce 100644
@@ -263,6 +263,9 @@ static int __init mst_intc_of_init(struct device_node *dn,
 	    of_property_read_u32_index(dn, "mstar,irqs-map-range", 1, &irq_end))
 		return -EINVAL;
 
+	if (irq_end < irq_start || irq_end - irq_start >= MST_INTC_MAX_IRQS)
+		return -EINVAL;
+
 	cd = kzalloc_obj(*cd);
 	if (!cd)
 		return -ENOMEM;
Signature · 1 line
2.53.0
author maintainer
#1963 lore raw

PATCH 1943/2651 irqchip/sifive-plic: Avoid signed shift in interrupt enable mask

In reply to Greg Kroah-Hartman

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

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

From: Pengpeng Hou <[email protected]>

[ Upstream commit 0f214e5bbee59d5952d3c061fd65ed9a1e175981 ]

__plic_toggle() builds a 32-bit interrupt enable mask using a signed integer literal. A valid interrupt selecting bit 31 evaluates 1 << 31, which shifts a signed int into its sign bit.

Use BIT(), matching the equivalent mask construction in plic_irq_eoi(). The resulting mask remains representable in u32 on both RV32 and RV64.

The issue was found by our static-analysis tool.

Fixes 8237f8bc4f6e ("irqchip: add a SiFive PLIC driver")
Assisted-by gpt 5
---
 drivers/irqchip/irq-sifive-plic.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/irqchip/irq-sifive-plic.c +1 -1
index 5b0dac1048140..d3d4187b96ab9 100644
@@ -108,7 +108,7 @@ static int plic_irq_set_type(struct irq_data *d, unsigned int type);
 static void __plic_toggle(struct plic_handler *handler, int hwirq, int enable)
 {
 	u32 __iomem *base = handler->enable_base;
-	u32 hwirq_mask = 1 << (hwirq % 32);
+	u32 hwirq_mask = BIT(hwirq % 32);
 	int group = hwirq / 32;
 	u32 value;
 
Signature · 1 line
2.53.0
author maintainer
#1964 lore raw

PATCH 1944/2651 irqchip/riscv-imsic: Reject overlapping group index fields

In reply to Greg Kroah-Hartman

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

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

From: Pengpeng Hou <[email protected]>

[ Upstream commit 8caa8fcec8db5358437b9b7ca456bc3093d2a4d0 ]

The IMSIC address layout places the group index above the page offset, guest index and HART index. imsic_parse_fwnode() checks the individual field widths and the upper end of the group field, but does not check that its lower end is above the other fields.

Reject a nonzero group field whose shift overlaps the lower fields. Otherwise a firmware-supplied layout can assign the same address bit to different indices when MSI target addresses are constructed.

Keep the existing upper-bound check unchanged. The new lower-bound check applies only when group index bits are present.

The issue was found by our static-analysis tool.

Fixes 21a8f8a0eb35 ("irqchip: Add RISC-V incoming MSI controller early driver")
Assisted-by gpt 5
---
 drivers/irqchip/irq-riscv-imsic-state.c | 8 ++++++++
 1 file changed, 8 insertions(+)
drivers/irqchip/irq-riscv-imsic-state.c +8 -0
index 9505ddbd9eec9..960c71d6295ba 100644
@@ -740,6 +740,14 @@ static int __init imsic_parse_fwnode(struct fwnode_handle *fwnode,
 		return -EINVAL;
 	}
 
+	/* Group index bits must not overlap guest and HART index bits. */
+	i = IMSIC_MMIO_PAGE_SHIFT + global->guest_index_bits +
+	    global->hart_index_bits;
+	if (global->group_index_bits && global->group_index_shift < i) {
+		pr_err("%pfwP: group index shift too small\n", fwnode);
+		return -EINVAL;
+	}
+
 	/* Sanity check group index shift */
 	i = global->group_index_bits + global->group_index_shift - 1;
 	if (i >= BITS_PER_LONG) {
Signature · 1 line
2.53.0
author maintainer
#1965 lore raw

PATCH 1945/2651 irqchip/gic-v3-its: Dont free a vPE table shared with another ITS

In reply to Greg Kroah-Hartman

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

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

From: Fuad Tabba <[email protected]>

[ Upstream commit 32e056cc1d1582951f981113ca8b98914f29c32a ]

On GICv4.1, its_alloc_tables() copies a sibling's vPE table baser rather than allocating one, but its_free_tables() frees it like the rest. A probe failure on the copying ITS then frees pages the enabled sibling still points GITS_BASER2 at, and the kernel comes up running on that sibling.

Mark a shared table so its_free_tables() skips it.

Fixes 5e5168461c22c ("irqchip/gic-v4.1: VPE table (aka GICR_VPROPBASER) allocation")
---
 drivers/irqchip/irq-gic-v3-its.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/irqchip/irq-gic-v3-its.c +5 -1
index 4083265750b6b..73bce111d202f 100644
@@ -87,6 +87,8 @@ struct its_baser {
 	u64		val;
 	u32		order;
 	u32		psz;
+	/* Inherited from a sibling ITS, not freed here */
+	bool		shared;
 };
 
 struct its_device;
@@ -2605,7 +2607,8 @@ static void its_free_tables(struct its_node *its)
 
 	for (i = 0; i < GITS_BASER_NR_REGS; i++) {
 		if (its->tables[i].base) {
-			its_free_pages(its->tables[i].base, its->tables[i].order);
+			if (!its->tables[i].shared)
+				its_free_pages(its->tables[i].base, its->tables[i].order);
 			its->tables[i].base = NULL;
 		}
 	}
@@ -2704,6 +2707,7 @@ static int its_alloc_tables(struct its_node *its)
 				WARN_ON(i != 2);
 				if ((sibling = find_sibling_its(its))) {
 					*baser = sibling->tables[2];
+					baser->shared = true;
 					its_write_baser(its, baser, baser->val);
 					continue;
 				}
Signature · 1 line
2.53.0
author maintainer
#1966 lore raw

PATCH 1946/2651 irqchip/gic-v3-its: Dont free the tables of an enabled ITS

In reply to Greg Kroah-Hartman

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

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

From: Fuad Tabba <[email protected]>

[ Upstream commit d09b36d8e0e60f35bd1cd7d63aadc6dfad61700c ]

its_probe_one() enables the ITS before its_init_domain(), the last step that can fail, and the unwind from there frees the tables and the command queue without disabling it. The kernel comes up with an enabled ITS pointing at freed pages.

Enable the ITS last. Nothing reaches the new domain before then: this runs from init_IRQ(), and the ITS joins its_nodes only after the enable.

Fixes 4c21f3c26ecc2 ("irqchip: GICv3: ITS: DT probing and initialization")
---
 drivers/irqchip/irq-gic-v3-its.c | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)
drivers/irqchip/irq-gic-v3-its.c +6 -4
index 73bce111d202f..011415f59b34e 100644
@@ -5334,16 +5334,18 @@ static int __init its_probe_one(struct its_node *its)
 	}
 
 	gits_write_cwriter(0, its->base + GITS_CWRITER);
+
+	err = its_init_domain(its);
+	if (err)
+		goto out_free_collection;
+
+	/* Enable last: the unwind frees memory an enabled ITS may access */
 	ctlr = readl_relaxed(its->base + GITS_CTLR);
 	ctlr |= GITS_CTLR_ENABLE;
 	if (is_v4(its))
 		ctlr |= GITS_CTLR_ImDe;
 	writel_relaxed(ctlr, its->base + GITS_CTLR);
 
-	err = its_init_domain(its);
-	if (err)
-		goto out_free_collection;
-
 	raw_spin_lock(&its_lock);
 	list_add(&its->entry, &its_nodes);
 	raw_spin_unlock(&its_lock);
Signature · 1 line
2.53.0
author maintainer
#1967 lore raw

PATCH 1947/2651 irqchip/gic-v3: Dont register a redistributor that was never counted

In reply to Greg Kroah-Hartman

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

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

From: Fuad Tabba <[email protected]>

[ Upstream commit 6a21693b97ee5cb0a21d04bfd051a05dde5aa783 ]

gic_acpi_match_gicc() counts only the enabled GICCs with a non-zero gicr_base_address, and that count sizes redist_regs[], but gic_acpi_parse_madt_gicc() registers every enabled one. On a MADT with no GICR entries, an enabled GICC with a zero GICR base therefore makes gic_acpi_register_redist() write a struct redist_region past the end of the array.

Commit fa2dabe57220e ("irqchip/gic-v3: Don't return errors from gic_acpi_match_gicc()") removed the check that kept the two consistent. Its message says such entries are still caught by gic_populate_rdist(), but that runs from gic_cpu_init(), after the write.

Skip the entry instead, and mark the CPU's redistributor broken as the online-capable path does, so that gic_check_rdist() rejects the CPU. gic_starting_cpu() runs past cpuhp's last failure point, so without the mark the CPU would come online with its redistributor and CPU interface unconfigured. With an ITS, its_cpu_init() would then dereference a NULL rd_base.

Fixes fa2dabe57220e ("irqchip/gic-v3: Don't return errors from gic_acpi_match_gicc()")
---
 drivers/irqchip/irq-gic-v3.c | 11 +++++++++++
 1 file changed, 11 insertions(+)
drivers/irqchip/irq-gic-v3.c +11 -0
index b0142b0a93fa4..93d7364352317 100644
@@ -2345,6 +2345,17 @@ gic_acpi_parse_madt_gicc(union acpi_subtable_headers *header,
 		return 0;
 	}
 
+	/* Not counted by gic_acpi_match_gicc(), so there is no slot for it */
+	if (!gicc->gicr_base_address) {
+		int cpu = get_cpu_for_acpi_id(gicc->uid);
+
+		pr_warn(FW_BUG "GICC entry with ACPI UID %u has no GICR base address, CPU kept offline\n",
+			gicc->uid);
+		if (cpu >= 0)
+			cpumask_set_cpu(cpu, &broken_rdists);
+		return 0;
+	}
+
 	redist_base = ioremap(gicc->gicr_base_address, size);
 	if (!redist_base)
 		return -ENOMEM;
Signature · 1 line
2.53.0
author maintainer
#1968 lore raw

PATCH 1948/2651 irqchip/gic: Fix UBSAN shift-out-of-bounds in GIC helpers

In reply to Greg Kroah-Hartman

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

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

From: Zhu Ling <[email protected]>

[ Upstream commit 13ce14ca41a35f5ee90b77ffa57da91ce6048a2d ]

When running with UBSAN enabled, enabling a GPIO controller that uses a GIC interrupt as its parent triggers several shift-out-of-bounds warnings:

shift-out-of-bounds in drivers/irqchip/irq-gic-common.c:50:21 left shift of 2 by 30 places cannot be represented in type 'int'

Similar reports are emitted from gic_poke_irq() and gic_peek_irq() in drivers/irqchip/irq-gic-v3.c. The corresponding GICv2 helpers use the same signed-shift pattern. These masks are generated by shifting signed integer constants, which invokes undefined behavior when bit 31 is selected.

Use BIT() to generate the masks with an unsigned type and make their intent explicit.

---
 drivers/irqchip/irq-gic-common.c | 2 +-
 drivers/irqchip/irq-gic-v3.c     | 4 ++--
 drivers/irqchip/irq-gic.c        | 4 ++--
 3 files changed, 5 insertions(+), 5 deletions(-)
drivers/irqchip/irq-gic-common.c +1 -1
index c776f9142610e..8bd1eaa54295e 100644
@@ -48,7 +48,7 @@ void gic_enable_quirks(u32 iidr, const struct gic_quirk *quirks,
 int gic_configure_irq(unsigned int irq, unsigned int type,
 		       void __iomem *base)
 {
-	u32 confmask = 0x2 << ((irq % 16) * 2);
+	u32 confmask = BIT(((irq % 16) * 2) + 1);
 	u32 confoff = (irq / 16) * 4;
 	u32 val, oldval;
 	int ret = 0;
drivers/irqchip/irq-gic-v3.c +2 -2
index 93d7364352317..187bd149f68c0 100644
@@ -457,7 +457,7 @@ static int gic_peek_irq(struct irq_data *d, u32 offset)
 	u32 index, mask;
 
 	offset = convert_offset_index(d, offset, &index);
-	mask = 1 << (index % 32);
+	mask = BIT(index % 32);
 
 	if (gic_irq_in_rdist(d))
 		base = gic_data_rdist_sgi_base();
@@ -473,7 +473,7 @@ static void gic_poke_irq(struct irq_data *d, u32 offset)
 	u32 index, mask;
 
 	offset = convert_offset_index(d, offset, &index);
-	mask = 1 << (index % 32);
+	mask = BIT(index % 32);
 
 	if (gic_irq_in_rdist(d))
 		base = gic_data_rdist_sgi_base();
drivers/irqchip/irq-gic.c +2 -2
index f6bc29f515fb7..fb7a55f5b394b 100644
@@ -178,14 +178,14 @@ static inline bool cascading_gic_irq(struct irq_data *d)
  */
 static void gic_poke_irq(struct irq_data *d, u32 offset)
 {
-	u32 mask = 1 << (irqd_to_hwirq(d) % 32);
+	u32 mask = BIT(irqd_to_hwirq(d) % 32);
 
 	writel_relaxed(mask, gic_dist_base(d) + offset + (irqd_to_hwirq(d) / 32) * 4);
 }
 
 static int gic_peek_irq(struct irq_data *d, u32 offset)
 {
-	u32 mask = 1 << (irqd_to_hwirq(d) % 32);
+	u32 mask = BIT(irqd_to_hwirq(d) % 32);
 
 	return !!(readl_relaxed(gic_dist_base(d) + offset + (irqd_to_hwirq(d) / 32) * 4) & mask);
 }
Signature · 1 line
2.53.0
author maintainer
#1969 lore raw

PATCH 1949/2651 irqchip/mips-gic: Fix unbalanced cm_core_lock in for_each_online_cpu_gic()

In reply to Greg Kroah-Hartman

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

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

From: Benoît Monin <[email protected]>

[ Upstream commit 03c4d26933d54556a89379db5923ae9e474569e8 ]

Commit d9e2ed610a60 ("irqchip/mips-gic: Support multi-cluster in for_each_online_cpu_gic()") added a gic_unlock_cluster() call to the macro's loop increment, which unconditionally invokes mips_cm_unlock_other() on multi-cluster systems. However nothing in the loop ever acquires the corresponding mips_cm_lock_other(), so on multi-cluster hardware every invocation of for_each_online_cpu_gic() releases an unheld per-CPU cm_core_lock.

With CONFIG_PROVE_LOCKING this triggers a "bad unlock balance detected" warning at boot, e.g. from gic_irq_domain_map() while mapping local interrupts. Only the first occurrence is reported, since the first warning permanently disables lockdep (debug_locks = 0); the unbalanced release itself silently persists.

Fix this by moving both the acquire and release into __gic_with_next_online_cpu() so they stay balanced. When advancing to a CPU in a remote cluster, lock the CM redirect block for that cluster via mips_cm_lock_other(); when leaving a remote cluster (or finishing the iteration) release it with mips_cm_unlock_other(). Local-cluster CPUs require no locking, so single-cluster systems are unaffected. This also makes the redirect region behave correctly when accessing local register blocks of CPUs in other clusters.

Drop the now-unused gic_unlock_cluster() helper and its call from the for_each_online_cpu_gic() increment.

Fixes d9e2ed610a60 ("irqchip/mips-gic: Support multi-cluster in for_each_online_cpu_gic()")
---
 drivers/irqchip/irq-mips-gic.c | 20 ++++++--------------
 1 file changed, 6 insertions(+), 14 deletions(-)
drivers/irqchip/irq-mips-gic.c +6 -14
index 19a57c5e2b2ea..3b31cbcbed6f3 100644
@@ -70,6 +70,10 @@ static int __gic_with_next_online_cpu(int prev)
 {
 	unsigned int cpu;
 
+	/* Release the redirect/other region lock to the previous CPU, if any. */
+	if (prev >= 0)
+		mips_cm_unlock_other();
+
 	/* Discover the next online CPU */
 	cpu = cpumask_next(prev, cpu_online_mask);
 
@@ -77,23 +81,12 @@ static int __gic_with_next_online_cpu(int prev)
 	if (cpu >= nr_cpu_ids)
 		return cpu;
 
-	/*
-	 * Move the access lock to the next CPU's GIC local register block.
-	 *
-	 * Set GIC_VL_OTHER. Since the caller holds gic_lock nothing can
-	 * clobber the written value.
-	 */
-	write_gic_vl_other(mips_cm_vp_id(cpu));
+	/* Lock access to redirect/other region to the next CPU */
+	mips_cm_lock_other_cpu(cpu, CM_GCR_Cx_OTHER_BLOCK_LOCAL);
 
 	return cpu;
 }
 
-static inline void gic_unlock_cluster(void)
-{
-	if (mips_cps_multicluster_cpus())
-		mips_cm_unlock_other();
-}
-
 /**
  * for_each_online_cpu_gic() - Iterate over online CPUs, access local registers
  * @cpu: An integer variable to hold the current CPU number
@@ -108,7 +101,6 @@ static inline void gic_unlock_cluster(void)
 	guard(raw_spinlock_irqsave)(gic_lock);		\
 	for ((cpu) = __gic_with_next_online_cpu(-1);	\
 	     (cpu) < nr_cpu_ids;			\
-	     gic_unlock_cluster(),			\
 	     (cpu) = __gic_with_next_online_cpu(cpu))
 
 /**
Signature · 1 line
2.53.0
author maintainer
#1970 lore raw

PATCH 1950/2651 irqchip/mips-gic: Fix recursive acquisition of gic_lock in gic_set_affinity()

In reply to Greg Kroah-Hartman

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

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

From: Benoît Monin <[email protected]>

[ Upstream commit 1bae25dcc6beb8b874f23601d2efa142ac4f9f36 ]

Commit 322a90638768 ("irqchip/mips-gic: Multi-cluster support") made gic_set_affinity() call gic_set_type() when an interrupt's affinity is moved between clusters. gic_set_type() takes gic_lock with raw_spin_lock_irqsave(), but gic_set_affinity() holds gic_lock at that point, so the same raw spinlock is acquired twice, triggering a deadlock.

Split gic_set_type() into a gic_set_type_locked() helper that assumes gic_lock is already held. gic_set_type() takes gic_lock and calls the helper, and gic_set_affinity() calls gic_set_type_locked() directly, since it already holds gic_lock.

---
 drivers/irqchip/irq-mips-gic.c | 15 ++++++++++-----
 1 file changed, 10 insertions(+), 5 deletions(-)
drivers/irqchip/irq-mips-gic.c +10 -5
index 3b31cbcbed6f3..f2ae60d39d66d 100644
@@ -297,14 +297,14 @@ static void gic_ack_irq(struct irq_data *d)
 	}
 }
 
-static int gic_set_type(struct irq_data *d, unsigned int type)
+static int gic_set_type_locked(struct irq_data *d, unsigned int type)
 {
 	unsigned int irq, pol, trig, dual;
-	unsigned long flags;
+
+	lockdep_assert_held(&gic_lock);
 
 	irq = GIC_HWIRQ_TO_SHARED(d->hwirq);
 
-	raw_spin_lock_irqsave(&gic_lock, flags);
 	switch (type & IRQ_TYPE_SENSE_MASK) {
 	case IRQ_TYPE_EDGE_FALLING:
 		pol = GIC_POL_FALLING_EDGE;
@@ -351,11 +351,16 @@ static int gic_set_type(struct irq_data *d, unsigned int type)
 	else
 		irq_set_chip_handler_name_locked(d, &gic_level_irq_controller,
 						 handle_level_irq, NULL);
-	raw_spin_unlock_irqrestore(&gic_lock, flags);
 
 	return 0;
 }
 
+static int gic_set_type(struct irq_data *d, unsigned int type)
+{
+	guard(raw_spinlock_irqsave)(&gic_lock);
+	return gic_set_type_locked(d, type);
+}
+
 #ifdef CONFIG_SMP
 static int gic_set_affinity(struct irq_data *d, const struct cpumask *cpumask,
 			    bool force)
@@ -407,7 +412,7 @@ static int gic_set_affinity(struct irq_data *d, const struct cpumask *cpumask,
 	 * trigger type in the new cluster.
 	 */
 	if (cl != old_cl)
-		gic_set_type(d, irqd_get_trigger_type(d));
+		gic_set_type_locked(d, irqd_get_trigger_type(d));
 
 	/* Route the interrupt to its new VP(E) */
 	if (gic_irq_lock_cluster(d)) {
Signature · 1 line
2.53.0
author maintainer
#1971 lore raw

PATCH 1951/2651 irqchip/mips-gic: Transfer interrupt mask state across clusters

In reply to Greg Kroah-Hartman

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

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

From: Benoît Monin <[email protected]>

[ Upstream commit a5f0dc656e89d0eb140547823a36212902cdf673 ]

When an interrupt's affinity is moved to a CPU in another cluster, gic_set_affinity() updates the routing (GIC_SH_MAP_VP) and trigger type in the destination cluster, but never touched the interrupt's mask state.

The interrupt mask is per-cluster. After such a move the interrupt may be left disabled in the destination cluster, so it never fires despite being correctly routed to its new VP.

Move the mask state along with the interrupt: disable it in the old cluster while clearing the route so it is no longer delivered, then configure the trigger type in the new cluster and re-enable it there if it was enabled in the old cluster.

---
 drivers/irqchip/irq-mips-gic.c | 24 ++++++++++++++++++++----
 1 file changed, 20 insertions(+), 4 deletions(-)
drivers/irqchip/irq-mips-gic.c +20 -4
index f2ae60d39d66d..be38989d8e73e 100644
@@ -368,6 +368,7 @@ static int gic_set_affinity(struct irq_data *d, const struct cpumask *cpumask,
 	unsigned int irq = GIC_HWIRQ_TO_SHARED(d->hwirq);
 	unsigned int cpu, cl, old_cpu, old_cl;
 	unsigned long flags;
+	bool enabled;
 
 	/*
 	 * The GIC specifies that we can only route an interrupt to one VP(E),
@@ -389,15 +390,20 @@ static int gic_set_affinity(struct irq_data *d, const struct cpumask *cpumask,
 	raw_spin_lock_irqsave(&gic_lock, flags);
 
 	/*
-	 * If we're moving affinity between clusters, stop routing the
-	 * interrupt to any VP(E) in the old cluster.
+	 * If we're moving affinity between clusters, save the interrupt's
+	 * mask state, stop routing it to any VP(E) in the old cluster and
+	 * disable it there so it is no longer delivered.
 	 */
 	if (cl != old_cl) {
 		if (gic_irq_lock_cluster(d)) {
+			enabled = read_gic_redir_mask(irq);
 			write_gic_redir_map_vp(irq, 0);
+			write_gic_redir_rmask(irq);
 			mips_cm_unlock_other();
 		} else {
+			enabled = read_gic_mask(irq);
 			write_gic_map_vp(irq, 0);
+			write_gic_rmask(irq);
 		}
 	}
 
@@ -409,10 +415,20 @@ static int gic_set_affinity(struct irq_data *d, const struct cpumask *cpumask,
 
 	/*
 	 * If we're moving affinity between clusters, configure the interrupt
-	 * trigger type in the new cluster.
+	 * trigger type and, if it was enabled in the old cluster, enable it
+	 * in the new one.
 	 */
-	if (cl != old_cl)
+	if (cl != old_cl) {
 		gic_set_type_locked(d, irqd_get_trigger_type(d));
+		if (enabled) {
+			if (gic_irq_lock_cluster(d)) {
+				write_gic_redir_smask(irq);
+				mips_cm_unlock_other();
+			} else {
+				write_gic_smask(irq);
+			}
+		}
+	}
 
 	/* Route the interrupt to its new VP(E) */
 	if (gic_irq_lock_cluster(d)) {
Signature · 1 line
2.53.0
author maintainer
#1972 lore raw

PATCH 1952/2651 ALSA: pcm: Add refcount for races between drain and unlink

In reply to Greg Kroah-Hartman

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

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

From: Takashi Iwai <[email protected]>

[ Upstream commit 91d0048a97e0fdc0a071caa0ba59e659bc6f84df ]

We added a workaround for the case where a linked substream gets unlinked during the drain operation by another substream of the same linked group in the commit 9b1dbd69ba6f ("ALSA: pcm: fix use-after-free on linked stream runtime in snd_pcm_drain()"). There, we just cached the parameters of the draining substream for avoiding UAF.

Then, we check the draining substream (to_check) again in the loop and remove it from the queue only when it's still present. It means, however, that the wait queue entry won't be removed if the substream went out of the link beforehand, hence a stale wq entry remains. Later on, this can be woken up, and this may hit a UAF, too. The problem surfaced more due to the recent change to call snd_pcm_unlink() earlier.

For properly handling both cases above, in this patch, we introduce a refcount to the snd_pcm_runtime that indicates the substream is being accessed / used, then at snd_pcm_release_substream(), it's synced before the actual resource release via snd_refcount_sync(). This guarantees that the accessors are finished, and safe to release memories. Along with the introduction of a refcount, the comments and the code changes by the former fix were partially reverted as they don't fit with the updated code flow any longer.

Last but not least, the setup of wait queue entry and prepare_to_wait() call are moved before the group unref. With this change, we can avoid the race between the enqueue and the wakeup, too.

Fixes 9b1dbd69ba6f ("ALSA: pcm: fix use-after-free on linked stream runtime in snd_pcm_drain()")
---
 include/sound/pcm.h     |  2 ++
 sound/core/pcm.c        |  1 +
 sound/core/pcm_native.c | 54 ++++++++++++++++-------------------------
 3 files changed, 24 insertions(+), 33 deletions(-)
include/sound/pcm.h +2 -0
index 02d8689354c4a..1cf511f8d880e 100644
@@ -8,6 +8,7 @@
  *                   Abramo Bagnara <[email protected]>
  */
 
+#include <sound/core.h>
 #include <sound/asound.h>
 #include <sound/memalloc.h>
 #include <sound/minors.h>
@@ -414,6 +415,7 @@ struct snd_pcm_runtime {
 	snd_pcm_uframes_t twake; 	/* do transfer (!poll) wakeup if non-zero */
 	wait_queue_head_t sleep;	/* poll sleep */
 	wait_queue_head_t tsleep;	/* transfer sleep */
+	struct snd_refcount refcnt;	/* refcount for draining, etc */
 	struct snd_fasync *fasync;
 	bool stop_operating;		/* sync_stop will be called */
 	struct mutex buffer_mutex;	/* protect for buffer changes */
sound/core/pcm.c +1 -0
index 6aad7a1fbf1a9..423a183e395eb 100644
@@ -959,6 +959,7 @@ int snd_pcm_attach_substream(struct snd_pcm *pcm, int stream,
 
 	init_waitqueue_head(&runtime->sleep);
 	init_waitqueue_head(&runtime->tsleep);
+	snd_refcount_init(&runtime->refcnt);
 
 	__snd_pcm_set_state(runtime, SNDRV_PCM_STATE_OPEN);
 	mutex_init(&runtime->buffer_mutex);
sound/core/pcm_native.c +21 -33

81 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#1973 lore raw

PATCH 1953/2651 ata: ahci: preserve preset port masks

In reply to Greg Kroah-Hartman

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

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

From: zhoumin <[email protected]>

[ Upstream commit 014c29a8e3bdcaad8c6fdfcf1af2fdbbab3fc323 ]

ahci_get_port_mask() returns zero for absent or unmatched parameters, overwriting the mask set by the Marvell PATA quirk.

Update the mask in place only when parsing a global value or a matching device entry. Leave the mask unchanged on parsing errors.

Fixes 70c1595c181c ("ata: ahci: Allow ignoring the external/hotplug capability of ports")
---
 drivers/ata/ahci.c | 31 +++++++++++--------------------
 1 file changed, 11 insertions(+), 20 deletions(-)
drivers/ata/ahci.c +11 -20
index 9b8c0935001cb..fdce365969b4f 100644
@@ -1642,34 +1642,27 @@ MODULE_PARM_DESC(mask_port_ext,
 		 "where <pci_dev> is the PCI ID of an AHCI controller in the "
 		 "form \"domain:bus:dev.func\"");
 
-static u32 ahci_port_mask(struct device *dev, char *mask_s)
+static void ahci_port_mask(struct device *dev, char *mask_s, u32 *mask)
 {
-	unsigned int mask;
-
-	if (kstrtouint(mask_s, 0, &mask)) {
+	if (kstrtou32(mask_s, 0, mask))
 		dev_err(dev, "Invalid port map mask\n");
-		return 0;
-	}
-
-	return mask;
 }
 
-static u32 ahci_get_port_mask(struct device *dev, char *mask_p)
+static void ahci_get_port_mask(struct device *dev, char *mask_p, u32 *mask)
 {
 	char *param, *end, *str, *mask_s;
 	char *name;
-	u32 mask = 0;
 
 	if (!mask_p || !strlen(mask_p))
-		return 0;
+		return;
 
 	str = kstrdup(mask_p, GFP_KERNEL);
 	if (!str)
-		return 0;
+		return;
 
 	/* Handle single mask case */
 	if (!strchr(str, '=')) {
-		mask = ahci_port_mask(dev, str);
+		ahci_port_mask(dev, str, mask);
 		goto free;
 	}
 
@@ -1704,13 +1697,11 @@ static u32 ahci_get_port_mask(struct device *dev, char *mask_p)
 			param++;
 		}
 
-		mask = ahci_port_mask(dev, mask_s);
+		ahci_port_mask(dev, mask_s, mask);
 	}
 
 free:
 	kfree(str);
-
-	return mask;
 }
 
 static void ahci_pci_save_initial_config(struct pci_dev *pdev,
@@ -1736,10 +1727,10 @@ static void ahci_pci_save_initial_config(struct pci_dev *pdev,
 	}
 
 	/* Handle port map masks passed as module parameter. */
-	hpriv->mask_port_map =
-		ahci_get_port_mask(&pdev->dev, ahci_mask_port_map);
-	hpriv->mask_port_ext =
-		ahci_get_port_mask(&pdev->dev, ahci_mask_port_ext);
+	ahci_get_port_mask(&pdev->dev, ahci_mask_port_map,
+			   &hpriv->mask_port_map);
+	ahci_get_port_mask(&pdev->dev, ahci_mask_port_ext,
+			   &hpriv->mask_port_ext);
 
 	ahci_save_initial_config(&pdev->dev, hpriv);
 }
Signature · 1 line
2.53.0
author maintainer
#1974 lore raw

PATCH 1954/2651 efi/runtime-wrappers: Dont park the worker after a recovered firmware fault

In reply to Greg Kroah-Hartman

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

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

From: Ard Biesheuvel <[email protected]>

[ Upstream commit b49be1e7478afdb4ec96aedeb17f906253326c48 ]

Commit 4b2c033b5bc9 ("efi/runtime-wrappers: retire the worker if a wedged call ever returns") parks the efi_rts_wq worker instead of completing the call if EFI runtime services have been disabled by the time the firmware returns. The assumption is that this only happens if __efi_queue_work() has given up waiting for the call.

However, arm64 also disables EFI runtime services when it recovers from a synchronous exception taken by the firmware: efi_runtime_fixup_exception() clears EFI_RUNTIME_SERVICES and unwinds the call so that it returns EFI_ABORTED to efi_call_rts(), while the caller is still waiting for the completion. The worker now parks without signalling it, so the caller is stuck for the full EFI_RTS_TIMEOUT of 120 seconds, after which it reports that the firmware is wedged, which is misleading.

x86 is not affected, as it signals the completion from its page fault handler before parking the worker.

So record explicitly that the caller has given up on the call, and only park the worker in that case.

Fixes 4b2c033b5bc9 ("efi/runtime-wrappers: retire the worker if a wedged call ever returns")
Cc Breno Leitao <[email protected]>
---
 drivers/firmware/efi/runtime-wrappers.c | 14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)
drivers/firmware/efi/runtime-wrappers.c +13 -1
index 2344b9d1e81f8..8f4de91727d0b 100644
@@ -126,6 +126,12 @@ struct efi_runtime_work efi_rts_work;
  */
 #define EFI_RTS_TIMEOUT		(120 * HZ)
 
+/*
+ * Set when __efi_queue_work() gives up waiting for a call that is wedged in
+ * firmware. EFI runtime services are disabled for good at that point.
+ */
+static bool efi_rts_abandoned;
+
 /*
  * efi_queue_work:	Queue EFI runtime service call and wait for completion
  * @_rts:		EFI runtime service function identifier
@@ -336,7 +342,12 @@ static void __nocfi efi_call_rts(struct work_struct *work)
 	efi_call_virt_check_flags(flags, efi_rts_work.caller);
 	arch_efi_call_virt_teardown();
 
-	if (!efi_enabled(EFI_RUNTIME_SERVICES))
+	/*
+	 * EFI runtime services may also have been disabled because the
+	 * firmware faulted, but the caller is still waiting for us in that
+	 * case. Only park the worker if the caller has given up on it.
+	 */
+	if (READ_ONCE(efi_rts_abandoned))
 		efi_rts_park_worker();
 
 	efi_rts_work.status = status;
@@ -373,6 +384,7 @@ static efi_status_t __efi_queue_work(enum efi_rts_ids id,
 					 EFI_RTS_TIMEOUT)) {
 		pr_err("EFI runtime service %d wedged in firmware; disabling EFI runtime services\n",
 		       id);
+		WRITE_ONCE(efi_rts_abandoned, true);
 		clear_bit(EFI_RUNTIME_SERVICES, &efi.flags);
 		return EFI_ABORTED;
 	}
Signature · 1 line
2.53.0
author maintainer
#1975 lore raw

PATCH 1955/2651 block: reject NOWAIT buffered write fallback

In reply to Greg Kroah-Hartman

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

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

From: Julian Sun <[email protected]>

[ Upstream commit a08bf4b9f87898628e70882430b8dd4260730dba ]

blkdev_write_iter() rejects NOWAIT buffered writes, but does not enforce this restriction when direct I/O falls back to buffered I/O. Successful fallback waits for writeback, violating NOWAIT semantics.

Reject NOWAIT requests in blkdev_buffered_write() with -EAGAIN.

Fixes c35fc7a5abae ("block_dev: support RFW_NOWAIT on block device nodes")
---
 block/fops.c | 4 ++++
 1 file changed, 4 insertions(+)
block/fops.c +4 -0
index 562cc52af5aa2..d2e38951bab81 100644
@@ -729,6 +729,10 @@ blkdev_direct_write(struct kiocb *iocb, struct iov_iter *from)
 
 static ssize_t blkdev_buffered_write(struct kiocb *iocb, struct iov_iter *from)
 {
+	/* Buffered fallback waits for writeback, which NOWAIT cannot allow. */
+	if (iocb->ki_flags & IOCB_NOWAIT)
+		return -EAGAIN;
+
 	return iomap_file_buffered_write(iocb, from, &blkdev_iomap_ops, NULL,
 			NULL);
 }
Signature · 1 line
2.53.0
author maintainer
#1976 lore raw

PATCH 1956/2651 block: take the inode lock for buffered write fallback

In reply to Greg Kroah-Hartman

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

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

From: Julian Sun <[email protected]>

[ Upstream commit 1b1be9ea4e34ccede1e7cf9ff2b6317328a5b6ad ]

Commit c0e473a0d226 ("block: fix race between set_blocksize and read paths") added shared inode locking around ordinary buffered writes, but missed the direct-I/O fallback path.

Move the lock into blkdev_buffered_write() so both paths serialize with set_blocksize().

Also correct the comment claiming that this path takes invalidate_lock; it only takes i_rwsem.

Fixes c0e473a0d226 ("block: fix race between set_blocksize and read paths")
---
 block/fops.c | 21 ++++++++++++---------
 1 file changed, 12 insertions(+), 9 deletions(-)
block/fops.c +12 -9
index d2e38951bab81..847db3841ff23 100644
@@ -729,12 +729,22 @@ blkdev_direct_write(struct kiocb *iocb, struct iov_iter *from)
 
 static ssize_t blkdev_buffered_write(struct kiocb *iocb, struct iov_iter *from)
 {
+	struct inode *inode = bdev_file_inode(iocb->ki_filp);
+	ssize_t ret;
+
 	/* Buffered fallback waits for writeback, which NOWAIT cannot allow. */
 	if (iocb->ki_flags & IOCB_NOWAIT)
 		return -EAGAIN;
 
-	return iomap_file_buffered_write(iocb, from, &blkdev_iomap_ops, NULL,
-			NULL);
+	/*
+	 * Take i_rwsem to avoid racing with set_blocksize() changing
+	 * i_blkbits/folio order and truncating the page cache.
+	 */
+	inode_lock_shared(inode);
+	ret = iomap_file_buffered_write(iocb, from, &blkdev_iomap_ops, NULL,
+					NULL);
+	inode_unlock_shared(inode);
+	return ret;
 }
 
 /*
@@ -823,14 +833,7 @@ static ssize_t blkdev_write_iter(struct kiocb *iocb, struct iov_iter *from)
 			need_sync = true;
 		}
 	} else {
-		/*
-		 * Take i_rwsem and invalidate_lock to avoid racing with
-		 * set_blocksize changing i_blkbits/folio order and punching
-		 * out the pagecache.
-		 */
-		inode_lock_shared(bd_inode);
 		ret = blkdev_buffered_write(iocb, from);
-		inode_unlock_shared(bd_inode);
 		need_sync = true;
 	}
 
Signature · 1 line
2.53.0
author maintainer
#1977 lore raw

PATCH 1957/2651 spi: omap2-mcspi: handle DMA setup failures

In reply to Greg Kroah-Hartman

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

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

From: Sahaj Chaudhari <[email protected]>

[ Upstream commit c126e07bde21c518f1356937ac240500d1bc81c0 ]

The DMA paths ignore failures from dmaengine_slave_config(), descriptor preparation and dmaengine_submit(), and carry FIXME comments about falling back to PIO. A failed setup can leave a half-started transfer or wait for a completion that never arrives.

Check each step and clean up with dmaengine_terminate_sync() on error. Prepare both descriptors before issuing either channel. Fall back to PIO only for host-mode transfers that have a TX buffer, when no DMA has been started and cleanup succeeded. RX-only and target-mode transfers return the error instead, since the bus may already be clocking.

The FIFO is enabled before the DMA attempt, but the PIO path polls per-word TXS/RXS and does not expect FIFO mode. Disable the FIFO, with the channel off while its bits change, before falling back.

Tested on an AM642 board with a TI 6.12.57 vendor kernel built with this patch and booted from RAM. On a McSPI bus using DMA, 200 iterations of 4096-byte TX and 1024-byte RX spidev transfers completed with no errors, timeouts or kernel warnings. With a temporary change that fails every DMA-sized TX setup, 60 spidev writes fell back to PIO with no errors or timeouts. That test used a bus with no device attached and did not show a difference with and without the FIFO disable, which is based on reading the code.

---
 drivers/spi/spi-omap2-mcspi.c | 236 ++++++++++++++++++++++++----------
 1 file changed, 167 insertions(+), 69 deletions(-)
drivers/spi/spi-omap2-mcspi.c +167 -69
index 82c8b91e504e7..7d54739206dda 100644
@@ -413,10 +413,11 @@ static void omap2_mcspi_tx_callback(void *data)
 	complete(&mcspi_dma->dma_tx_completion);
 }
 
-static void omap2_mcspi_tx_dma(struct spi_device *spi,
-				struct spi_transfer *xfer,
-				struct dma_slave_config cfg)
+static int omap2_mcspi_tx_dma(struct spi_device *spi,
+			      struct spi_transfer *xfer,
+			      struct dma_slave_config cfg)
 {
+	int ret;
 	struct omap2_mcspi	*mcspi;
 	struct omap2_mcspi_dma  *mcspi_dma;
 	struct dma_async_tx_descriptor *tx;
@@ -424,31 +425,31 @@ static void omap2_mcspi_tx_dma(struct spi_device *spi,
 	mcspi = spi_controller_get_devdata(spi->controller);
 	mcspi_dma = &mcspi->dma_channels[spi_get_chipselect(spi, 0)];
 
-	dmaengine_slave_config(mcspi_dma->dma_tx, &cfg);
+	ret = dmaengine_slave_config(mcspi_dma->dma_tx, &cfg);
+	if (ret)
+		return ret;
 
 	tx = dmaengine_prep_slave_sg(mcspi_dma->dma_tx, xfer->tx_sg.sgl,
 				     xfer->tx_sg.nents,
 				     DMA_MEM_TO_DEV,
 				     DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
-	if (tx) {
-		tx->callback = omap2_mcspi_tx_callback;
-		tx->callback_param = spi;
-		dmaengine_submit(tx);
-	} else {
-		/* FIXME: fall back to PIO? */
-	}
-	dma_async_issue_pending(mcspi_dma->dma_tx);
-	omap2_mcspi_set_dma_req(spi, 0, 1);
+	if (!tx)
+		return -EIO;
+
+	tx->callback = omap2_mcspi_tx_callback;
+	tx->callback_param = spi;
+
+	return dma_submit_error(dmaengine_submit(tx));
 }
 
-static unsigned
+static int
 omap2_mcspi_rx_dma(struct spi_device *spi, struct spi_transfer *xfer,
-				struct dma_slave_config cfg,
-				unsigned es)
+		   struct dma_slave_config cfg, unsigned int es,
+		   unsigned int *count, bool *rx_submitted, bool *dma_started)
 {
 	struct omap2_mcspi	*mcspi;
 	struct omap2_mcspi_dma  *mcspi_dma;
-	unsigned int		count, transfer_reduction = 0;
+	unsigned int		transfer_reduction = 0;
 	struct scatterlist	*sg_out[2];
 	int			nb_sizes = 0, out_mapped_nents[2], ret, x;
 	size_t			sizes[2];
@@ -461,7 +462,8 @@ omap2_mcspi_rx_dma(struct spi_device *spi, struct spi_transfer *xfer,
 
 	mcspi = spi_controller_get_devdata(spi->controller);
 	mcspi_dma = &mcspi->dma_channels[spi_get_chipselect(spi, 0)];
-	count = xfer->len;
+	*count = xfer->len;
+	*rx_submitted = false;
 
 	/*
 	 *  In the "End-of-Transfer Procedure" section for DMA RX in OMAP35x TRM
@@ -475,14 +477,16 @@ omap2_mcspi_rx_dma(struct spi_device *spi, struct spi_transfer *xfer,
 	l = mcspi_cached_chconf0(spi);
 
 	if (word_len <= 8)
-		element_count = count;
+		element_count = *count;
 	else if (word_len <= 16)
-		element_count = count >> 1;
+		element_count = *count >> 1;
 	else /* word_len <= 32 */
-		element_count = count >> 2;
+		element_count = *count >> 2;
 
 
-	dmaengine_slave_config(mcspi_dma->dma_rx, &cfg);
+	ret = dmaengine_slave_config(mcspi_dma->dma_rx, &cfg);
+	if (ret)
+		return ret;
 
 	/*
 	 *  Reduce DMA transfer length by one more if McSPI is
@@ -493,7 +497,7 @@ omap2_mcspi_rx_dma(struct spi_device *spi, struct spi_transfer *xfer,
 
 	if (transfer_reduction) {
 		/* Split sgl into two. The second sgl won't be used. */
-		sizes[0] = count - transfer_reduction;
+		sizes[0] = *count - transfer_reduction;
 		sizes[1] = transfer_reduction;
 		nb_sizes = 2;
 	} else {
@@ -501,44 +505,56 @@ omap2_mcspi_rx_dma(struct spi_device *spi, struct spi_transfer *xfer,
 		 * Don't bother splitting the sgl. This essentially
 		 * clones the original sgl.
 		 */
-		sizes[0] = count;
+		sizes[0] = *count;
 		nb_sizes = 1;
 	}
 
 	ret = sg_split(xfer->rx_sg.sgl, xfer->rx_sg.nents, 0, nb_sizes,
 		       sizes, sg_out, out_mapped_nents, GFP_KERNEL);
 
-	if (ret < 0) {
+	if (ret) {
 		dev_err(&spi->dev, "sg_split failed\n");
-		return 0;
+		return ret;
 	}
 
 	tx = dmaengine_prep_slave_sg(mcspi_dma->dma_rx, sg_out[0],
 				     out_mapped_nents[0], DMA_DEV_TO_MEM,
 				     DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
-	if (tx) {
-		tx->callback = omap2_mcspi_rx_callback;
-		tx->callback_param = spi;
-		dmaengine_submit(tx);
-	} else {
-		/* FIXME: fall back to PIO? */
+	if (!tx) {
+		ret = -EIO;
+		goto out_free_sg;
 	}
 
+	tx->callback = omap2_mcspi_rx_callback;
+	tx->callback_param = spi;
+	ret = dma_submit_error(dmaengine_submit(tx));
+	if (ret)
+		goto out_free_sg;
+
+	*rx_submitted = true;
+	if (mcspi->target_aborted) {
+		ret = -EINTR;
+		goto out_free_sg;
+	}
+	*dma_started = true;
+	if (xfer->tx_buf) {
+		if (spi_controller_is_target(mcspi->ctlr))
+			mcspi_write_reg(mcspi->ctlr, OMAP2_MCSPI_IRQENABLE,
+					OMAP2_MCSPI_IRQSTATUS_EOW);
+		dma_async_issue_pending(mcspi_dma->dma_tx);
+		omap2_mcspi_set_dma_req(spi, 0, 1);
+	}
 	dma_async_issue_pending(mcspi_dma->dma_rx);
 	omap2_mcspi_set_dma_req(spi, 1, 1);
-
 	ret = mcspi_wait_for_completion(mcspi, &mcspi_dma->dma_rx_completion);
-	if (ret || mcspi->target_aborted) {
-		dmaengine_terminate_sync(mcspi_dma->dma_rx);
-		omap2_mcspi_set_dma_req(spi, 1, 0);
-		return 0;
-	}
+	if (ret || mcspi->target_aborted)
+		goto out_free_sg;
 
 	for (x = 0; x < nb_sizes; x++)
 		kfree(sg_out[x]);
 
 	if (mcspi->fifo_depth > 0)
-		return count;
+		return 0;
 
 	/*
 	 *  Due to the DMA transfer length reduction the missing bytes must
@@ -565,9 +581,9 @@ omap2_mcspi_rx_dma(struct spi_device *spi, struct spi_transfer *xfer,
 		} else {
 			int bytes_per_word = mcspi_bytes_per_word(word_len);
 			dev_err(&spi->dev, "DMA RX penultimate word empty\n");
-			count -= (bytes_per_word << 1);
+			*count -= (bytes_per_word << 1);
 			omap2_mcspi_set_enable(spi, 1);
-			return count;
+			return 0;
 		}
 	}
 	if (!mcspi_wait_for_reg_bit(chstat_reg, OMAP2_MCSPI_CHSTAT_RXS)) {
@@ -582,19 +598,27 @@ omap2_mcspi_rx_dma(struct spi_device *spi, struct spi_transfer *xfer,
 			((u32 *)xfer->rx_buf)[elements] = w;
 	} else {
 		dev_err(&spi->dev, "DMA RX last word empty\n");
-		count -= mcspi_bytes_per_word(word_len);
+		*count -= mcspi_bytes_per_word(word_len);
 	}
 	omap2_mcspi_set_enable(spi, 1);
-	return count;
+	return 0;
+
+out_free_sg:
+	if (!ret)
+		ret = -EINTR;
+	for (x = 0; x < nb_sizes; x++)
+		kfree(sg_out[x]);
+	return ret;
 }
 
-static unsigned
-omap2_mcspi_txrx_dma(struct spi_device *spi, struct spi_transfer *xfer)
+static int omap2_mcspi_txrx_dma(struct spi_device *spi,
+				struct spi_transfer *xfer,
+				unsigned int *count,
+				bool *pio_fallback)
 {
 	struct omap2_mcspi	*mcspi;
 	struct omap2_mcspi_cs	*cs = spi->controller_state;
 	struct omap2_mcspi_dma  *mcspi_dma;
-	unsigned int		count;
 	u8			*rx;
 	const u8		*tx;
 	struct dma_slave_config	cfg;
@@ -602,10 +626,13 @@ omap2_mcspi_txrx_dma(struct spi_device *spi, struct spi_transfer *xfer)
 	unsigned es;
 	void __iomem		*chstat_reg;
 	void __iomem            *irqstat_reg;
-	int			wait_res;
+	bool			tx_submitted = false, rx_submitted = false;
+	bool			dma_started = false, terminate_failed = false;
+	int			ret, wait_res;
 
 	mcspi = spi_controller_get_devdata(spi->controller);
 	mcspi_dma = &mcspi->dma_channels[spi_get_chipselect(spi, 0)];
+	*pio_fallback = false;
 
 	if (cs->word_len <= 8) {
 		width = DMA_SLAVE_BUSWIDTH_1_BYTE;
@@ -618,7 +645,7 @@ omap2_mcspi_txrx_dma(struct spi_device *spi, struct spi_transfer *xfer)
 		es = 4;
 	}
 
-	count = xfer->len;
+	*count = xfer->len;
 
 	memset(&cfg, 0, sizeof(cfg));
 	cfg.src_addr = cs->phys + OMAP2_MCSPI_RX0;
@@ -636,31 +663,39 @@ omap2_mcspi_txrx_dma(struct spi_device *spi, struct spi_transfer *xfer)
 	reinit_completion(&mcspi_dma->dma_rx_completion);
 	reinit_completion(&mcspi->txdone);
 	if (tx) {
-		/* Enable EOW IRQ to know end of tx in target mode */
+		ret = omap2_mcspi_tx_dma(spi, xfer, cfg);
+		if (ret)
+			goto out;
+		tx_submitted = true;
+	}
+
+	if (rx) {
+		ret = omap2_mcspi_rx_dma(spi, xfer, cfg, es, count,
+					 &rx_submitted, &dma_started);
+		if (ret)
+			goto out;
+	} else if (tx) {
+		if (mcspi->target_aborted) {
+			ret = -EINTR;
+			goto out;
+		}
 		if (spi_controller_is_target(spi->controller))
-			mcspi_write_reg(spi->controller,
-					OMAP2_MCSPI_IRQENABLE,
+			mcspi_write_reg(spi->controller, OMAP2_MCSPI_IRQENABLE,
 					OMAP2_MCSPI_IRQSTATUS_EOW);
-		omap2_mcspi_tx_dma(spi, xfer, cfg);
+		dma_started = true;
+		dma_async_issue_pending(mcspi_dma->dma_tx);
+		omap2_mcspi_set_dma_req(spi, 0, 1);
 	}
 
-	if (rx != NULL)
-		count = omap2_mcspi_rx_dma(spi, xfer, cfg, es);
-
-	if (tx != NULL) {
-		int ret;
-
+	if (tx) {
 		ret = mcspi_wait_for_completion(mcspi, &mcspi_dma->dma_tx_completion);
-		if (ret || mcspi->target_aborted) {
-			dmaengine_terminate_sync(mcspi_dma->dma_tx);
-			omap2_mcspi_set_dma_req(spi, 0, 0);
-			return 0;
-		}
+		if (ret || mcspi->target_aborted)
+			goto out;
 
 		if (spi_controller_is_target(mcspi->ctlr)) {
 			ret = mcspi_wait_for_completion(mcspi, &mcspi->txdone);
 			if (ret || mcspi->target_aborted)
-				return 0;
+				goto out;
 		}
 
 		if (mcspi->fifo_depth > 0) {
@@ -694,7 +729,43 @@ omap2_mcspi_txrx_dma(struct spi_device *spi, struct spi_transfer *xfer)
 				dev_err(&spi->dev, "EOT timed out\n");
 		}
 	}
-	return count;
+	return 0;
+
+out:
+	if (!ret)
+		ret = -EINTR;
+	if (rx_submitted) {
+		wait_res = dmaengine_terminate_sync(mcspi_dma->dma_rx);
+		if (wait_res) {
+			dev_err(&spi->dev, "failed to terminate RX DMA: %d\n",
+				wait_res);
+			terminate_failed = true;
+			ret = wait_res;
+		}
+		omap2_mcspi_set_dma_req(spi, 1, 0);
+	}
+	if (tx_submitted) {
+		wait_res = dmaengine_terminate_sync(mcspi_dma->dma_tx);
+		if (wait_res) {
+			dev_err(&spi->dev, "failed to terminate TX DMA: %d\n",
+				wait_res);
+			terminate_failed = true;
+			ret = wait_res;
+		}
+		omap2_mcspi_set_dma_req(spi, 0, 0);
+	}
+	if (spi_controller_is_target(mcspi->ctlr))
+		mcspi_write_reg(mcspi->ctlr, OMAP2_MCSPI_IRQENABLE, 0);
+
+	*pio_fallback = !dma_started && !terminate_failed;
+	return ret;
+}
+
+static bool omap2_mcspi_can_pio_fallback(bool cleanup_ok,
+					 const struct spi_transfer *xfer,
+					 bool is_target)
+{
+	return cleanup_ok && xfer->tx_buf && !is_target;
 }
 
 static unsigned
@@ -1214,6 +1285,8 @@ static int omap2_mcspi_transfer_one(struct spi_controller *ctlr,
 
 	if (t->len) {
 		unsigned	count;
+		bool		pio_fallback;
+		int		ret;
 
 		if ((mcspi_dma->dma_rx && mcspi_dma->dma_tx) &&
 		    spi_xfer_is_dma_mapped(ctlr, spi, t))
@@ -1227,10 +1300,31 @@ static int omap2_mcspi_transfer_one(struct spi_controller *ctlr,
 					+ OMAP2_MCSPI_TX0);
 
 		if ((mcspi_dma->dma_rx && mcspi_dma->dma_tx) &&
-		    spi_xfer_is_dma_mapped(ctlr, spi, t))
-			count = omap2_mcspi_txrx_dma(spi, t);
-		else
+		    spi_xfer_is_dma_mapped(ctlr, spi, t)) {
+			ret = omap2_mcspi_txrx_dma(spi, t, &count,
+						   &pio_fallback);
+			if (ret) {
+				bool is_target = spi_controller_is_target(ctlr);
+				bool fallback;
+
+				fallback = omap2_mcspi_can_pio_fallback(pio_fallback, t,
+									is_target);
+				if (!fallback) {
+					status = ret;
+					goto out;
+				}
+
+				dev_warn(&spi->dev,
+					 "DMA setup failed, falling back to PIO\n");
+				/* PIO does not use the FIFO enabled for DMA */
+				omap2_mcspi_set_enable(spi, 0);
+				omap2_mcspi_set_fifo(spi, t, 0);
+				omap2_mcspi_set_enable(spi, 1);
+				count = omap2_mcspi_txrx_pio(spi, t);
+			}
+		} else {
 			count = omap2_mcspi_txrx_pio(spi, t);
+		}
 
 		if (count != t->len) {
 			status = -EIO;
@@ -1246,8 +1340,12 @@ static int omap2_mcspi_transfer_one(struct spi_controller *ctlr,
 out:
 	/* Restore defaults if they were overriden */
 	if (par_override) {
+		int restore_status;
+
 		par_override = 0;
-		status = omap2_mcspi_setup_transfer(spi, NULL);
+		restore_status = omap2_mcspi_setup_transfer(spi, NULL);
+		if (!status)
+			status = restore_status;
 	}
 
 	omap2_mcspi_set_enable(spi, 0);
Signature · 1 line
2.53.0
author maintainer
#1978 lore raw

PATCH 1958/2651 RDMA/rxe: refuse to destroy a QP with type 2 MWs still bound

In reply to Greg Kroah-Hartman

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

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

From: Youngsung Ahn <[email protected]>

[ Upstream commit 9e61a2ac6590e9c42d2eeef687749781334b300f ]

Binding a type 2 memory window takes a reference on the QP:
rxe_do_bind_mw() does rxe_get(qp) and stores it in mw->qp. That reference is released only when the window is invalidated (rxe_do_invalidate_mw() on IB_WR_LOCAL_INV) or the window itself is destroyed (rxe_mw_cleanup()).

rxe_qp_chk_destroy() does not account for those references -- it only refuses when qp->mcg_num is non-zero. So an unprivileged user can bind a type 2 MW to a QP and then destroy the QP while the binding is still live. __rxe_cleanup() cannot drop the QP refcount to zero (the MW still holds a reference), hits its -ETIMEDOUT path, and frees the QP anyway; mw->qp is left dangling. When the MW is later invalidated or deallocated, rxe_mw_cleanup()/rxe_do_invalidate_mw() do rxe_put(mw->qp) on the freed struct rxe_qp -- a use-after-free write (refcount_dec, and complete()/list work if it reaches zero) reachable from userspace. IB_WR_BIND_MW is a local operation, so no peer is required.

Track the number of type 2 MWs bound to a QP and refuse to destroy the QP while that count is non-zero, returning -EBUSY exactly as the existing multicast-attachment check does. The window must be invalidated or deallocated, which drops the reference and the count, before the QP can be destroyed.

---
 drivers/infiniband/sw/rxe/rxe_mw.c    |  3 +++
 drivers/infiniband/sw/rxe/rxe_qp.c    | 10 ++++++++++
 drivers/infiniband/sw/rxe/rxe_verbs.h |  1 +
 3 files changed, 14 insertions(+)
drivers/infiniband/sw/rxe/rxe_mw.c +3 -0
index bddb7a2578313..a2e3a6ce09463 100644
@@ -161,6 +161,7 @@ static void rxe_do_bind_mw(struct rxe_qp *qp, struct rxe_send_wqe *wqe,
 
 	if (mw->ibmw.type == IB_MW_TYPE_2) {
 		rxe_get(qp);
+		atomic_inc(&qp->mw_bind_num);
 		mw->qp = qp;
 	}
 }
@@ -245,6 +246,7 @@ static void rxe_do_invalidate_mw(struct rxe_mw *mw)
 	/* valid type 2 MW will always have a QP pointer */
 	qp = mw->qp;
 	mw->qp = NULL;
+	atomic_dec(&qp->mw_bind_num);
 	rxe_put(qp);
 
 	/* valid type 2 MW will always have an MR pointer */
@@ -332,6 +334,7 @@ void rxe_mw_cleanup(struct rxe_pool_elem *elem)
 		struct rxe_qp *qp = mw->qp;
 
 		mw->qp = NULL;
+		atomic_dec(&qp->mw_bind_num);
 		rxe_put(qp);
 	}
 
drivers/infiniband/sw/rxe/rxe_qp.c +10 -0
index 311f285d78a6b..fea55bc3b0cb9 100644
@@ -858,6 +858,16 @@ int rxe_qp_chk_destroy(struct rxe_qp *qp)
 		return -EBUSY;
 	}
 
+	/* An attempt to destroy a QP while it still holds references for
+	 * bound type 2 memory windows will fail immediately.  Otherwise the
+	 * QP is freed with those references outstanding and the windows are
+	 * left pointing at freed memory (use-after-free).
+	 */
+	if (atomic_read(&qp->mw_bind_num)) {
+		rxe_dbg_qp(qp, "Attempt to destroy while type 2 MWs are bound\n");
+		return -EBUSY;
+	}
+
 	return 0;
 }
 
drivers/infiniband/sw/rxe/rxe_verbs.h +1 -0
index 0f5ffd94643f9..80df376e61eea 100644
@@ -261,6 +261,7 @@ struct rxe_qp {
 	struct rxe_av		alt_av;
 
 	atomic_t		mcg_num;
+	atomic_t		mw_bind_num;
 
 	struct sk_buff_head	req_pkts;
 	struct sk_buff_head	resp_pkts;
Signature · 1 line
2.53.0
author maintainer
#1979 lore raw

PATCH 1959/2651 RDMA/rxe: reject IB_WR_REG_MR from user QPs in rxe_reg_fast_mr()

In reply to Greg Kroah-Hartman

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

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

From: Youngsung Ahn <[email protected]>

[ Upstream commit 33afe9909f213d8bb8e80f0b93382dde0f56e2c7 ]

IB_WR_REG_MR is documented as kernel-only ("can not be issued by userspace"), but nothing enforces it. rxe_wr_opcode_info[IB_WR_REG_MR] sets WR_LOCAL_OP_MASK for IB_QPT_RC, a QP type userspace can create, so a user QP that writes opcode = IB_WR_REG_MR into its mmap'd SQ ring reaches rxe_do_local_ops() -> rxe_reg_fast_mr(). That function then trusts the ring-supplied fields:

	struct rxe_mr *mr = to_rmr(wqe->wr.wr.reg.mr);
	...
	if (unlikely(mr->state != RXE_MR_STATE_FREE))    /* deref */
	...
	mr->access = access;                             /* write */

For a user QP wqe->wr.wr.reg.mr is a fully attacker-chosen pointer, so this is an arbitrary-kernel-address dereference (arbitrary read confirmed, oops). No existing check distinguishes a user QP on this path.

Reject IB_WR_REG_MR for user QPs before dereferencing the supplied pointer.

---
 drivers/infiniband/sw/rxe/rxe_mr.c | 4 ++++
 1 file changed, 4 insertions(+)
drivers/infiniband/sw/rxe/rxe_mr.c +4 -0
index 71d9ea4772890..3a914c2438294 100644
@@ -777,6 +777,10 @@ int rxe_reg_fast_mr(struct rxe_qp *qp, struct rxe_send_wqe *wqe)
 	u32 key = wqe->wr.wr.reg.key;
 	u32 access = wqe->wr.wr.reg.access;
 
+	/* IB_WR_REG_MR is a kernel-only op; a user QP must not reach here. */
+	if (qp->is_user)
+		return -EOPNOTSUPP;
+
 	/* user can only register MR in free state */
 	if (unlikely(mr->state != RXE_MR_STATE_FREE)) {
 		rxe_dbg_mr(mr, "mr->lkey = 0x%x not free\n", mr->lkey);
Signature · 1 line
2.53.0
author maintainer
#1980 lore raw

PATCH 1960/2651 RDMA/rxe: bound the ODP page index against the umem in rxe_check_pagefault()

In reply to Greg Kroah-Hartman

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

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

From: Youngsung Ahn <[email protected]>

[ Upstream commit 7797bbb0e86f0062fe58480a0116c86e4ec0d0d1 ]

An ODP MR has a page array, map.pfn_list[]. Its size is computed from the umem start address. But rxe_check_pagefault() builds the index into that array from an iova that is relative to the same start, while the access itself was range-checked against the MR's iova (ibmr.iova).

Those two bases do not have to match. reg_mr only requires that start and hca_va have the same page offset, so a user can register an MR with hca_va = start + N*PAGE. The difference then becomes an index skew of (hca_va - start) >> PAGE_SHIFT. Nothing compares the result with the size of pfn_list[], so the read goes past the end of the array.

An unprivileged local user can reach this with a single RDMA operation on a self-connected rxe QP. KASAN reports a slab-out-of-bounds read. If the out-of-bounds qword happens to look like a writable HMM pfn, rxe then copies the payload into a page the user never registered.

Reject an index that falls outside the umem and take the fault path instead. That path rejects the out-of-range access in ib_umem_odp_map_dma_and_lock(), which does check the umem range. The other users of pfn_list[], __rxe_odp_mr_copy() and the atomic helpers, run only after a successful map, so this single check covers them too.

Fixes 2fae67ab63db ("RDMA/rxe: Add support for Send/Recv/Write/Read with ODP")
---
 drivers/infiniband/sw/rxe/rxe_odp.c | 5 +++++
 1 file changed, 5 insertions(+)
drivers/infiniband/sw/rxe/rxe_odp.c +5 -0
index c375d3efd9992..9d27244f89bca 100644
@@ -136,6 +136,11 @@ static inline bool rxe_check_pagefault(struct ib_umem_odp *umem_odp, u64 iova,
 	while (addr < iova + length) {
 		idx = (addr - ib_umem_start(umem_odp)) >> umem_odp->page_shift;
 
+		if (idx >= ib_umem_odp_num_pages(umem_odp)) {
+			need_fault = true;
+			break;
+		}
+
 		if ((umem_odp->map.pfn_list[idx] & access) != access) {
 			need_fault = true;
 			break;
Signature · 1 line
2.53.0
author maintainer
#1981 lore raw

PATCH 1961/2651 RDMA/rxe: validate inline sge_offset in finish_packet() before indexing inline_data[]

In reply to Greg Kroah-Hartman

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

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

From: Youngsung Ahn <[email protected]>

[ Upstream commit 47a9c0338f2e0d4178d77b0d2f529fe1fde84642 ]

For a user QP, rxe_post_send() takes the qp->is_user branch and never runs init_send_wqe(), so dma.length/resid/num_sge/cur_sge/sge_offset all come straight from the mmap'd SQ ring. In the inline send path finish_packet() uses sge_offset directly as an index:

	u8 *tmp = &wqe->dma.inline_data[wqe->dma.sge_offset];
	memcpy(payload_addr(pkt), tmp, payload);

inline_data is a flex array whose capacity is qp->sq.max_inline, but sge_offset is a u32 from user space, so the source pointer is
displaced arbitrarily past the WQE and the memcpy reads out of
bounds.
commit 126c757e4cd4 ("RDMA/rxe: Validate num_sge/cur_sge before indexing wqe->dma.sge[]") added num_sge/cur_sge checks on the send path but not sge_offset, the
third attacker-controlled index in the same struct.

Read sge_offset once with READ_ONCE() and bound it (and the payload that follows it) by qp->sq.max_inline before indexing, so the value that is validated is the value that is used.

---
 drivers/infiniband/sw/rxe/rxe_req.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)
drivers/infiniband/sw/rxe/rxe_req.c +8 -1
index 24f5c044363f7..152f02eed0ff1 100644
@@ -510,7 +510,14 @@ static int finish_packet(struct rxe_qp *qp, struct rxe_av *av,
 
 	if (pkt->mask & RXE_WRITE_OR_SEND_MASK) {
 		if (wqe->wr.send_flags & IB_SEND_INLINE) {
-			u8 *tmp = &wqe->dma.inline_data[wqe->dma.sge_offset];
+			u32 sge_offset = READ_ONCE(wqe->dma.sge_offset);
+			u8 *tmp;
+
+			if (unlikely(sge_offset > (u32)qp->sq.max_inline ||
+				     payload > (u32)qp->sq.max_inline - sge_offset))
+				return -EINVAL;
+
+			tmp = &wqe->dma.inline_data[sge_offset];
 
 			memcpy(payload_addr(pkt), tmp, payload);
 
Signature · 1 line
2.53.0
author maintainer
#1982 lore raw

PATCH 1962/2651 RDMA/rxe: Hold netdev reference for transmit skbs

In reply to Greg Kroah-Hartman

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

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

From: xiongweimin <[email protected]>

[ Upstream commit 19881618ffa454c63e6b6bf34acd7cac28c695dc ]

rxe_init_packet() assigns skb->dev from an RCU-protected GID attribute without holding a netdev reference. If the netdev is unregistered before the skb is freed, subsequent accesses to skb->dev are unsafe.

Hold a reference with dev_hold() when the skb is initialized and release it from the transmit destructor or via rxe_put_skb() on error paths that run before the destructor is installed.

skb->dev can change on the TX path (VLAN/bond/tunnel, ip_finish_output2, etc.), so put must use the same netdev that was held. Stash that pointer in skb_shinfo()->destructor_arg: skb->cb is already used by rxe_pkt_info and is rewritten by IP control blocks.

To avoid blocking netdev unregistration on held skbs, flush all QPs to the error state on NETDEV_GOING_DOWN and NETDEV_UNREGISTER so pending TX work is drained and references can be dropped.

Stable-dep-of: 56a27df6cedd ("RDMA/rxe: Fix out-of-range unsigned-to-signed conversion for RDMA message in 2GiB size")

---
 drivers/infiniband/sw/rxe/rxe_loc.h  |  1 +
 drivers/infiniband/sw/rxe/rxe_net.c  | 68 ++++++++++++++++++++++++++--
 drivers/infiniband/sw/rxe/rxe_req.c  |  2 +-
 drivers/infiniband/sw/rxe/rxe_resp.c |  4 +-
 4 files changed, 68 insertions(+), 7 deletions(-)
drivers/infiniband/sw/rxe/rxe_loc.h +1 -0
index 64d636bf80fd2..7c3cc48e845c4 100644
@@ -92,6 +92,7 @@ void rxe_mw_cleanup(struct rxe_pool_elem *elem);
 /* rxe_net.c */
 struct sk_buff *rxe_init_packet(struct rxe_dev *rxe, struct rxe_av *av,
 				int paylen, struct rxe_pkt_info *pkt);
+void rxe_put_skb(struct sk_buff *skb);
 int rxe_prepare(struct rxe_av *av, struct rxe_pkt_info *pkt,
 		struct sk_buff *skb);
 int rxe_xmit_packet(struct rxe_qp *qp, struct rxe_pkt_info *pkt,
drivers/infiniband/sw/rxe/rxe_net.c +64 -4

111 lines not on this page · raw message

drivers/infiniband/sw/rxe/rxe_req.c +1 -1
index 152f02eed0ff1..4f353abd76f55 100644
@@ -818,7 +818,7 @@ int rxe_requester(struct rxe_qp *qp)
 			wqe->status = IB_WC_LOC_PROT_ERR;
 		else
 			wqe->status = IB_WC_LOC_QP_OP_ERR;
-		kfree_skb(skb);
+		rxe_put_skb(skb);
 		if (ah)
 			rxe_put(ah);
 		goto err;
drivers/infiniband/sw/rxe/rxe_resp.c +2 -2
index cd51042857d62..ba3b2d23b36b7 100644
@@ -868,7 +868,7 @@ static struct sk_buff *prepare_ack_packet(struct rxe_qp *qp,
 
 	err = rxe_prepare(&qp->pri_av, ack, skb);
 	if (err) {
-		kfree_skb(skb);
+		rxe_put_skb(skb);
 		return NULL;
 	}
 
@@ -996,7 +996,7 @@ static enum resp_states read_reply(struct rxe_qp *qp,
 	err = rxe_mr_copy(mr, res->read.va, payload_addr(&ack_pkt),
 			  payload, RXE_FROM_MR_OBJ);
 	if (err) {
-		kfree_skb(skb);
+		rxe_put_skb(skb);
 		state = RESPST_ERR_RKEY_VIOLATION;
 		goto err_out;
 	}
Signature · 1 line
2.53.0
author maintainer
#1983 lore raw

PATCH 1963/2651 RDMA/rxe: Fix out-of-range unsigned-to-signed conversion for RDMA message in 2GiB size

In reply to Greg Kroah-Hartman

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

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

From: Honggang LI <[email protected]>

[ Upstream commit 56a27df6cedd4f3918969d61c7b9d3cc177b2d1b ]

When RDMA READ request for 2GiB in single WR, res->read.resid is u32 0x80000000, which is INT_MIN (-2147483648).

    payload = min_t(int, res->read.resid, mtu);

The min_t function will return -2147483648 for payload. The wrong size is propagated through call chain, read_reply -> prepare_ack_packet -> rxe_init_packet -> alloc_skb . alloc_skb failed because of invalid size. The passive side failed to emit response packet for RDMA READ request.

After fixed it, the active side of RDMA READ failed with error code "IB_WC_LOC_PROT_ERR". When RDMA_READ_RESPONSE_FIRST packet recived by the active side, do_read call copy_data. dma->resid is u32 0x80000000.

   int resid	= dma->resid;

This conversion set resid to -2147483648. copy_data abort as length greater than resid.

RDMA SEND and WRITE 2GiB message works too, after fixed these two bugs.

---
 drivers/infiniband/sw/rxe/rxe_loc.h  |  4 ++--
 drivers/infiniband/sw/rxe/rxe_mr.c   |  8 ++++----
 drivers/infiniband/sw/rxe/rxe_net.c  |  2 +-
 drivers/infiniband/sw/rxe/rxe_resp.c | 17 +++++++++--------
 4 files changed, 16 insertions(+), 15 deletions(-)
drivers/infiniband/sw/rxe/rxe_loc.h +2 -2
index 7c3cc48e845c4..e57861a628236 100644
@@ -64,7 +64,7 @@ int rxe_flush_pmem_iova(struct rxe_mr *mr, u64 iova, unsigned int length);
 int rxe_mr_copy(struct rxe_mr *mr, u64 iova, void *addr,
 		unsigned int length, enum rxe_mr_copy_dir dir);
 int copy_data(struct rxe_pd *pd, int access, struct rxe_dma_info *dma,
-	      void *addr, int length, enum rxe_mr_copy_dir dir);
+	      void *addr, u32 length, enum rxe_mr_copy_dir dir);
 int rxe_map_mr_sg(struct ib_mr *ibmr, struct scatterlist *sg,
 		  int sg_nents, unsigned int *sg_offset);
 enum resp_states rxe_mr_do_atomic_op(struct rxe_mr *mr, u64 iova, int opcode,
@@ -91,7 +91,7 @@ void rxe_mw_cleanup(struct rxe_pool_elem *elem);
 
 /* rxe_net.c */
 struct sk_buff *rxe_init_packet(struct rxe_dev *rxe, struct rxe_av *av,
-				int paylen, struct rxe_pkt_info *pkt);
+				u32 paylen, struct rxe_pkt_info *pkt);
 void rxe_put_skb(struct sk_buff *skb);
 int rxe_prepare(struct rxe_av *av, struct rxe_pkt_info *pkt,
 		struct sk_buff *skb);
drivers/infiniband/sw/rxe/rxe_mr.c +4 -4
index 3a914c2438294..bc7e3cb5a11b2 100644
@@ -418,13 +418,13 @@ int copy_data(
 	int			access,
 	struct rxe_dma_info	*dma,
 	void			*addr,
-	int			length,
+	u32			length,
 	enum rxe_mr_copy_dir	dir)
 {
-	int			bytes;
+	u32			bytes;
 	struct rxe_sge		*sge	= &dma->sge[dma->cur_sge];
-	int			offset	= dma->sge_offset;
-	int			resid	= dma->resid;
+	u32			offset	= dma->sge_offset;
+	u32			resid	= dma->resid;
 	struct rxe_mr		*mr	= NULL;
 	u64			iova;
 	int			err;
drivers/infiniband/sw/rxe/rxe_net.c +1 -1
index 9f1c7f21d88d9..c572cda8fe18c 100644
@@ -571,7 +571,7 @@ int rxe_xmit_packet(struct rxe_qp *qp, struct rxe_pkt_info *pkt,
 }
 
 struct sk_buff *rxe_init_packet(struct rxe_dev *rxe, struct rxe_av *av,
-				int paylen, struct rxe_pkt_info *pkt)
+				u32 paylen, struct rxe_pkt_info *pkt)
 {
 	unsigned int hdr_len;
 	struct sk_buff *skb = NULL;
drivers/infiniband/sw/rxe/rxe_resp.c +9 -8
index ba3b2d23b36b7..1b7f317372259 100644
@@ -614,7 +614,7 @@ static enum resp_states check_rkey(struct rxe_qp *qp,
 }
 
 static enum resp_states send_data_in(struct rxe_qp *qp, void *data_addr,
-				     int data_len)
+				     u32 data_len)
 {
 	int err;
 
@@ -829,20 +829,21 @@ static enum resp_states atomic_write_reply(struct rxe_qp *qp,
 static struct sk_buff *prepare_ack_packet(struct rxe_qp *qp,
 					  struct rxe_pkt_info *ack,
 					  int opcode,
-					  int payload,
+					  u32 payload,
 					  u32 psn,
 					  u8 syndrome)
 {
 	struct rxe_dev *rxe = to_rdev(qp->ibqp.device);
 	struct sk_buff *skb;
-	int paylen;
-	int pad;
+	u32 paylen;
+	u32 pad = 0;
 	int err;
 
 	/*
 	 * allocate packet
 	 */
-	pad = (-payload) & 0x3;
+	if (payload % 4)
+		pad = 4 - payload % 4;
 	paylen = rxe_opcode[opcode].length + payload + pad + RXE_ICRC_SIZE;
 
 	skb = rxe_init_packet(rxe, &qp->pri_av, paylen, ack);
@@ -936,9 +937,9 @@ static enum resp_states read_reply(struct rxe_qp *qp,
 {
 	struct rxe_pkt_info ack_pkt;
 	struct sk_buff *skb;
-	int mtu = qp->mtu;
+	u32 mtu = qp->mtu;
 	enum resp_states state;
-	int payload;
+	u32 payload;
 	int opcode;
 	int err;
 	struct resp_res *res = qp->resp.res;
@@ -984,7 +985,7 @@ static enum resp_states read_reply(struct rxe_qp *qp,
 
 	res->state = rdatm_res_state_next;
 
-	payload = min_t(int, res->read.resid, mtu);
+	payload = min(res->read.resid, mtu);
 
 	skb = prepare_ack_packet(qp, &ack_pkt, opcode, payload,
 				 res->cur_psn, AETH_ACK_UNLIMITED);
Signature · 1 line
2.53.0
author maintainer
#1984 lore raw

PATCH 1964/2651 RDMA/rxe: bound the WQE opcode before indexing rxe_wr_opcode_info[]

In reply to Greg Kroah-Hartman

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

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

From: Youngsung Ahn <[email protected]>

[ Upstream commit c887e53e1c852b88bd5442d1bf4717ee3e7aadda ]

wr_opcode_mask() indexes the global rxe_wr_opcode_info[] array with a caller-supplied opcode and no bounds check. For a user QP the WQE comes from an mmap'd SQ ring, so wqe->wr.opcode is an attacker-controlled __u32 read back by the requester (req_next_wqe() -> rxe_requester()); rxe_post_send() takes the qp->is_user branch and never runs validate_send_wr(), whose only opcode check is itself !wr_opcode_mask() (it indexes before it checks). rxe_wr_opcode_info[] has entries only up to IB_WR_REG_MR, so an out-of-range opcode reads out of bounds and the result is used as a mask and dereferenced; observed as a KASAN global-out-of-bounds "Read of size 4" and a wild-pointer oops.

Return a zero mask for an out-of-range opcode, matching how validate_send_wr() already treats a zero mask (an invalid WR), so no path indexes the array out of bounds.

---
 drivers/infiniband/sw/rxe/rxe_loc.h | 3 +++
 1 file changed, 3 insertions(+)
drivers/infiniband/sw/rxe/rxe_loc.h +3 -0
index e57861a628236..9a8e96dfb792d 100644
@@ -185,6 +185,9 @@ void rxe_comp_queue_pkt(struct rxe_qp *qp, struct sk_buff *skb);
 
 static inline unsigned int wr_opcode_mask(int opcode, struct rxe_qp *qp)
 {
+	if (unlikely(opcode < 0 || opcode > IB_WR_REG_MR))
+		return 0;
+
 	return rxe_wr_opcode_info[opcode].mask[qp->ibqp.qp_type];
 }
 
Signature · 1 line
2.53.0
author maintainer
#1985 lore raw

PATCH 1965/2651 drm/panthor: Fix handling of NO_MMAP BOs

In reply to Greg Kroah-Hartman

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

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

From: Akash Goel <[email protected]>

[ Upstream commit 9a07b36a511fe998f46372331758ef355273bdfb ]

The BOs created with DRM_PANTHOR_BO_NO_MMAP flag are not supposed to be mmappable by the Userspace. But after the rework to support shrinker, it became possible to mmap NO_MMAP BOs. Userspace could second guess the file offset range, allocated unconditionally at the BO creation time, and create a CPU mapping. There may not be any adverse effect of such a CPU mapping though.
This commit adds a check in the mmap callback of Panthor driver to fail the mmap() attempts on BOs created with NO_MMAP flag. The check covers private BOs as well as the prime exported BOs that are mmapped using prime fd.

v2:
- Fix breakage of mmap() on exported BOs that didn't have BO_MMAP_OFFSET ioctl invoked for them.

---
 drivers/gpu/drm/panthor/panthor_gem.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/gpu/drm/panthor/panthor_gem.c +3 -0
index 72908be5e144f..75d462f20b6c8 100644
@@ -744,6 +744,9 @@ static int panthor_gem_mmap(struct drm_gem_object *obj, struct vm_area_struct *v
 	struct panthor_gem_object *bo = to_panthor_bo(obj);
 	int ret;
 
+	if (bo->flags & DRM_PANTHOR_BO_NO_MMAP)
+		return -EINVAL;
+
 	if (drm_gem_is_imported(obj)) {
 		/* Reset both vm_ops and vm_private_data, so we don't end up with
 		 * vm_ops pointing to our implementation if the dma-buf backend
Signature · 1 line
2.53.0
author maintainer
#1986 lore raw

PATCH 1966/2651 ext4: fix orig_mlen initialization in ext4_map_blocks()

In reply to Greg Kroah-Hartman

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

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

From: Zhang Yi <[email protected]>

[ Upstream commit 3ec0eefc07cb9e2bb1193f1fa3d8157302a737f5 ]

Save orig_mlen after clamping map->m_len to INT_MAX. Otherwise, the unclamped value may be passed below, bypassing its overflow protection.

Fixes 5bb12b1837c0 ("ext4: Add support for EXT4_GET_BLOCKS_QUERY_LEAF_BLOCKS")
---
 fs/ext4/inode.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
fs/ext4/inode.c +2 -1
index 6697c33d3aa33..bd1c14b983768 100644
@@ -703,7 +703,7 @@ int ext4_map_blocks(handle_t *handle, struct inode *inode,
 	struct extent_status es;
 	int retval;
 	int ret = 0;
-	unsigned int orig_mlen = map->m_len;
+	unsigned int orig_mlen;
 #ifdef ES_AGGRESSIVE_TEST
 	struct ext4_map_blocks orig_map;
 
@@ -719,6 +719,7 @@ int ext4_map_blocks(handle_t *handle, struct inode *inode,
 	 */
 	if (unlikely(map->m_len > INT_MAX))
 		map->m_len = INT_MAX;
+	orig_mlen = map->m_len;
 
 	/* We can handle the block number less than EXT_MAX_BLOCKS */
 	if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
Signature · 1 line
2.53.0
author maintainer
#1987 lore raw

PATCH 1967/2651 ASoC: rt5645: Shut down the button timer on removal

In reply to Greg Kroah-Hartman

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

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

From: Myeonghun Pak <[email protected]>

[ Upstream commit f0ecc305442f20a6df2575943e9897825d80cc5d ]

jack_detect_work can rearm btn_check_timer, and the timer callback can queue jack_detect_work. Deleting the timer before cancelling the work does not break this cycle: an already running worker can rearm the timer after timer_delete_sync() returns. The timer can then outlive removal.

Use timer_shutdown_sync() before cancelling the delayed work so that subsequent attempts to rearm the timer are ignored. The IRQ producer has already been removed at this point. Keep the restartable timer deletion in the suspend path.

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

---
 sound/soc/codecs/rt5645.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
sound/soc/codecs/rt5645.c +4 -3
index 7313ea71c9580..3c4354d885093 100644
@@ -19,6 +19,7 @@
 #include <linux/acpi.h>
 #include <linux/dmi.h>
 #include <linux/regulator/consumer.h>
+#include <linux/timer.h>
 #include <sound/core.h>
 #include <sound/pcm.h>
 #include <sound/pcm_params.h>
@@ -4292,10 +4293,10 @@ static void rt5645_i2c_remove(struct i2c_client *i2c)
 		free_irq(i2c->irq, rt5645);
 
 	/*
-	 * Since the rt5645_btn_check_callback() can queue jack_detect_work,
-	 * the timer need to be delted first
+	 * The timer and jack_detect_work can rearm each other. Shut down the
+	 * timer before cancelling the work.
 	 */
-	timer_delete_sync(&rt5645->btn_check_timer);
+	timer_shutdown_sync(&rt5645->btn_check_timer);
 
 	cancel_delayed_work_sync(&rt5645->jack_detect_work);
 	cancel_delayed_work_sync(&rt5645->rcclock_work);
Signature · 1 line
2.53.0
author maintainer
#1988 lore raw

PATCH 1968/2651 selftests/ftrace: Avoid unlink error on first run

In reply to Greg Kroah-Hartman

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

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

From: Jaewon Jung <[email protected]>

[ Upstream commit 0abfa9ad5c6917cb9a509276f32009d944b3c269 ]

On the first run, ftracetest tries to unlink a symlink that does not exist.
Use rm -f to avoid the "No such file or directory" error.

Fixes 7dc1e125f07a ("ftrace/selftests: Add softlink to latest log directory")
---
 tools/testing/selftests/ftrace/ftracetest | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/testing/selftests/ftrace/ftracetest +1 -1
index 246d7e1d015cf..95804610e079d 100755
@@ -243,7 +243,7 @@ else
   mkdir -p $LOG_DIR || errexit "Failed to make a log directory: $LOG_DIR"
   date > $LOG_FILE
   if [ "x-$LINK_PTR" != "x-" ]; then
-    unlink $LINK_PTR
+    rm -f $LINK_PTR
     ln -fs $LOG_DATE $LINK_PTR
   fi
 fi
Signature · 1 line
2.53.0
author maintainer
#1989 lore raw

PATCH 1969/2651 PCI: endpoint: pci-epf-vntb: Track link state from both sides

In reply to Greg Kroah-Hartman

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

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

From: Koichiro Den <[email protected]>

[ Upstream commit f9eabc48327fae33cf0a02a8f312c24505dc413b ]

The control-region link status is currently updated only by COMMAND_LINK_UP and COMMAND_LINK_DOWN from the HOST. The virtual NTB link callbacks are empty. Consequently, the HOST can see the link as up before the VHOST has enabled it, and ntb_link_disable() on the VHOST leaves LINK_STATUS_UP set without notifying either NTB client.

ntb_netdev can hide this device-level state bug because ntb_transport uses a separate per-QP LINK_DOWN_FLAG message. Use ntb_tool to observe the device link state directly:

After bringing both sides up, start one waiter on each side:

HOST# echo N > /sys/kernel/debug/ntb_tool/<H-device>/peer0/link_event VHOST# echo N > /sys/kernel/debug/ntb_tool/<V-device>/peer0/link_event

While both waiters are blocked, disable the link on the VHOST:

VHOST# echo N > /sys/kernel/debug/ntb_tool/<V-device>/link

Without this patch, the link-disable command succeeds, but peer0/link remains Y on both sides and neither waiter returns.

Track HOST and VHOST enablement separately and report the effective link as up only when both sides have enabled it, as pci-epf-ntb does for its two physical hosts. Both NTB clients observe this effective state, so notify both sides only when it changes, including the side whose request completes the transition. Serialize the two paths because HOST commands run from delayed work while the VHOST callbacks may run concurrently.

With this patch, peer0/link changes to N on both sides and both waiters return.

---
 drivers/pci/endpoint/functions/pci-epf-vntb.c | 98 +++++++++++++++----
 1 file changed, 78 insertions(+), 20 deletions(-)
drivers/pci/endpoint/functions/pci-epf-vntb.c +78 -20
index 07ba338732d4e..bebdd93a067c0 100644
@@ -41,6 +41,7 @@
 #include <linux/delay.h>
 #include <linux/io.h>
 #include <linux/module.h>
+#include <linux/mutex.h>
 #include <linux/slab.h>
 
 #include <linux/pci-ep-msi.h>
@@ -147,7 +148,10 @@ struct epf_ntb {
 	u16 vntb_pid;
 	u16 vntb_vid;
 
-	bool linkup;
+	/* Serialize HOST and VHOST link state changes. */
+	struct mutex link_lock;
+	bool host_link_enabled;
+	bool vhost_link_enabled;
 
 	/*
 	 * True when doorbells are interrupt-driven (MSI or embedded), false
@@ -183,24 +187,55 @@ static struct pci_epf_header epf_ntb_header = {
 	.interrupt_pin	= PCI_INTERRUPT_INTA,
 };
 
+static void epf_ntb_update_link(struct epf_ntb *ntb)
+{
+	u16 link_status = READ_ONCE(ntb->reg->link_status);
+
+	/* The link is usable only after both sides have enabled it. */
+	if (ntb->host_link_enabled && ntb->vhost_link_enabled)
+		link_status |= LINK_STATUS_UP;
+	else
+		link_status &= ~LINK_STATUS_UP;
+
+	WRITE_ONCE(ntb->reg->link_status, link_status);
+}
+
+static int epf_ntb_notify_link(struct ntb_dev *ndev)
+{
+	struct pci_epf *epf = ntb_ndev(ndev)->epf;
+	int ret;
+
+	ntb_link_event(ndev);
+
+	ret = pci_epc_raise_irq(epf->epc, epf->func_no, epf->vfunc_no,
+				PCI_IRQ_MSI, EPF_IRQ_LINK + 1);
+	if (ret)
+		dev_err(&epf->dev, "Failed to raise link event IRQ: %d\n", ret);
+
+	return ret;
+}
+
 /**
- * epf_ntb_link_up() - Raise link_up interrupt to Virtual Host (VHOST)
+ * epf_ntb_set_link_enabled() - Set HOST link enablement
  * @ntb: NTB device that facilitates communication between HOST and VHOST
- * @link_up: true or false indicating Link is UP or Down
- *
- * Once NTB function in HOST invoke ntb_link_enable(),
- * this NTB function driver will trigger a link event to VHOST.
+ * @enabled: true when the HOST has enabled the link
  *
  * Returns: Zero for success, or an error code in case of failure
  */
-static int epf_ntb_link_up(struct epf_ntb *ntb, bool link_up)
+static int epf_ntb_set_link_enabled(struct epf_ntb *ntb, bool enabled)
 {
-	if (link_up)
-		ntb->reg->link_status |= LINK_STATUS_UP;
-	else
-		ntb->reg->link_status &= ~LINK_STATUS_UP;
+	bool notify;
+
+	scoped_guard(mutex, &ntb->link_lock) {
+		notify = ntb->host_link_enabled != enabled &&
+			 ntb->vhost_link_enabled;
+		ntb->host_link_enabled = enabled;
+		epf_ntb_update_link(ntb);
+	}
+
+	if (notify)
+		return epf_ntb_notify_link(ntb->ntb);
 
-	ntb_link_event(ntb->ntb);
 	return 0;
 }
 
@@ -325,16 +360,14 @@ static void epf_ntb_cmd_handler(struct work_struct *work)
 		ctrl->command_status = COMMAND_STATUS_OK;
 		break;
 	case COMMAND_LINK_UP:
-		ntb->linkup = true;
-		ret = epf_ntb_link_up(ntb, true);
+		ret = epf_ntb_set_link_enabled(ntb, true);
 		if (ret < 0)
 			ctrl->command_status = COMMAND_STATUS_ERROR;
 		else
 			ctrl->command_status = COMMAND_STATUS_OK;
 		goto reset_handler;
 	case COMMAND_LINK_DOWN:
-		ntb->linkup = false;
-		ret = epf_ntb_link_up(ntb, false);
+		ret = epf_ntb_set_link_enabled(ntb, false);
 		if (ret < 0)
 			ctrl->command_status = COMMAND_STATUS_ERROR;
 		else
@@ -1472,11 +1505,29 @@ static int vntb_epf_peer_mw_get_addr(struct ntb_dev *ndev, int idx,
 	return 0;
 }
 
+static int vntb_epf_set_link_enabled(struct ntb_dev *ndev, bool enabled)
+{
+	struct epf_ntb *ntb = ntb_ndev(ndev);
+	bool notify;
+
+	scoped_guard(mutex, &ntb->link_lock) {
+		notify = ntb->vhost_link_enabled != enabled &&
+			 ntb->host_link_enabled;
+		ntb->vhost_link_enabled = enabled;
+		epf_ntb_update_link(ntb);
+	}
+
+	if (notify)
+		return epf_ntb_notify_link(ndev);
+
+	return 0;
+}
+
 static int vntb_epf_link_enable(struct ntb_dev *ntb,
 			enum ntb_speed max_speed,
 			enum ntb_width max_width)
 {
-	return 0;
+	return vntb_epf_set_link_enabled(ntb, true);
 }
 
 static u32 vntb_epf_spad_read(struct ntb_dev *ndev, int idx)
@@ -1636,7 +1687,7 @@ static u64 vntb_epf_link_is_up(struct ntb_dev *ndev,
 {
 	struct epf_ntb *ntb = ntb_ndev(ndev);
 
-	return ntb->reg->link_status;
+	return READ_ONCE(ntb->reg->link_status);
 }
 
 static int vntb_epf_db_clear_mask(struct ntb_dev *ndev, u64 db_bits)
@@ -1654,7 +1705,7 @@ static int vntb_epf_db_clear(struct ntb_dev *ndev, u64 db_bits)
 
 static int vntb_epf_link_disable(struct ntb_dev *ntb)
 {
-	return 0;
+	return vntb_epf_set_link_enabled(ntb, false);
 }
 
 static struct device *vntb_epf_get_dma_dev(struct ntb_dev *ndev)
@@ -1797,6 +1848,10 @@ static int epf_ntb_bind(struct pci_epf *epf)
 		goto err_bar_alloc;
 	}
 
+	ntb->host_link_enabled = false;
+	ntb->vhost_link_enabled = false;
+	ntb->reg->link_status = 0;
+
 	ret = epf_ntb_epc_init(ntb);
 	if (ret) {
 		dev_err(dev, "Failed to initialize EPC\n");
@@ -1882,7 +1937,7 @@ static int epf_ntb_probe(struct pci_epf *epf,
 {
 	struct epf_ntb *ntb;
 	struct device *dev;
-	int i;
+	int ret, i;
 
 	dev = &epf->dev;
 
@@ -1893,6 +1948,9 @@ static int epf_ntb_probe(struct pci_epf *epf,
 	epf->header = &epf_ntb_header;
 	ntb->epf = epf;
 	ntb->vbus_number = 0xff;
+	ret = devm_mutex_init(dev, &ntb->link_lock);
+	if (ret)
+		return ret;
 
 	INIT_WORK(&ntb->peer_db_work, vntb_epf_peer_db_work);
 	disable_work(&ntb->peer_db_work);
Signature · 1 line
2.53.0
author maintainer
#1990 lore raw

PATCH 1970/2651 vdso/math64: Add and use __iter_div64_u64_rem()

In reply to Greg Kroah-Hartman

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

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

From: Zhan Xusheng <[email protected]>

[ Upstream commit dcd65074e2c593a06bed36178bba6d49d6b6883c ]

The vDSO basetimes for CLOCK_MONOTONIC and CLOCK_BOOTTIME are stored in the scaled nanoseconds of tkr_mono, so normalising them requires a division by NSEC_PER_SEC << shift. That divisor does not fit the u32 parameter of __iter_div_u64_rem(), so update_vdso_time_data() open-codes the same iterative division twice.

Repeated subtraction is the appropriate form at these two sites because the quotient never exceeds one. accumulate_nsecs_to_secs() keeps xtime_nsec below one scaled second, and the offset added to it is a normalised timespec64 fraction, so the dividend stays below twice the divisor. That bound holds on every architecture, which matters more here than the cost of a division on any particular one.

Add __iter_div64_u64_rem(), the u64-divisor counterpart of __iter_div_u64_rem(), and use it at both sites. Return the quotient as a u32 for consistency with the u32-divisor variant; the bound above leaves no use for a wider type.

Store the remainder directly into the basetime, as the coarse clocks already do. The CLOCK_BOOTTIME copy of the CLOCK_MONOTONIC values then takes both fields from the same place.

Folding the two open-coded loops into one inlined helper removes 16 bytes of vsyscall.o text on x86-64 with gcc 13.

No functional change.

Stable-dep-of: 8d17190fae2c ("vdso/vsyscall: Keep the CLOCK_AUX base scaled")

---
 include/vdso/math64.h  | 20 ++++++++++++++++++++
 kernel/time/vsyscall.c | 16 +++++-----------
 2 files changed, 25 insertions(+), 11 deletions(-)
include/vdso/math64.h +20 -0
index 22ae212f8b28f..2ef4905585c59 100644
@@ -21,6 +21,26 @@ __iter_div_u64_rem(u64 dividend, u32 divisor, u64 *remainder)
 	return ret;
 }
 
+static __always_inline u32 __iter_div64_u64_rem(u64 dividend, u64 divisor, u64 *remainder)
+{
+	u32 ret = 0;
+
+	while (dividend >= divisor) {
+		/*
+		 * Prevent the compiler from optimising this loop into a
+		 * modulo operation.
+		 */
+		OPTIMIZER_HIDE_VAR(dividend);
+
+		dividend -= divisor;
+		ret++;
+	}
+
+	*remainder = dividend;
+
+	return ret;
+}
+
 #if defined(CONFIG_ARCH_SUPPORTS_INT128) && defined(__SIZEOF_INT128__)
 
 #ifndef mul_u64_u32_add_u64_shr
kernel/time/vsyscall.c +5 -11
index aa59919b8f2c2..f43dd3f4744b5 100644
@@ -41,14 +41,12 @@ static inline void update_vdso_time_data(struct vdso_time_data *vdata, struct ti
 
 	nsec = tk->tkr_mono.xtime_nsec;
 	nsec += ((u64)tk->wall_to_monotonic.tv_nsec << tk->tkr_mono.shift);
-	while (nsec >= (((u64)NSEC_PER_SEC) << tk->tkr_mono.shift)) {
-		nsec -= (((u64)NSEC_PER_SEC) << tk->tkr_mono.shift);
-		vdso_ts->sec++;
-	}
-	vdso_ts->nsec	= nsec;
+	vdso_ts->sec	+= __iter_div64_u64_rem(nsec, (u64)NSEC_PER_SEC << tk->tkr_mono.shift,
+						&vdso_ts->nsec);
 
 	/* Copy MONOTONIC time for BOOTTIME */
 	sec	= vdso_ts->sec;
+	nsec	= vdso_ts->nsec;
 	/* Add the boot offset */
 	sec	+= tk->monotonic_to_boot.tv_sec;
 	nsec	+= (u64)tk->monotonic_to_boot.tv_nsec << tk->tkr_mono.shift;
@@ -56,12 +54,8 @@ static inline void update_vdso_time_data(struct vdso_time_data *vdata, struct ti
 	/* CLOCK_BOOTTIME */
 	vdso_ts		= &vc[CS_HRES_COARSE].basetime[CLOCK_BOOTTIME];
 	vdso_ts->sec	= sec;
-
-	while (nsec >= (((u64)NSEC_PER_SEC) << tk->tkr_mono.shift)) {
-		nsec -= (((u64)NSEC_PER_SEC) << tk->tkr_mono.shift);
-		vdso_ts->sec++;
-	}
-	vdso_ts->nsec	= nsec;
+	vdso_ts->sec	+= __iter_div64_u64_rem(nsec, (u64)NSEC_PER_SEC << tk->tkr_mono.shift,
+						&vdso_ts->nsec);
 
 	/* CLOCK_MONOTONIC_RAW */
 	vdso_ts		= &vc[CS_RAW].basetime[CLOCK_MONOTONIC_RAW];
Signature · 1 line
2.53.0
author maintainer
#1991 lore raw

PATCH 1971/2651 vdso/vsyscall: Keep the CLOCK_AUX base scaled

In reply to Greg Kroah-Hartman

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

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

From: Zhan Xusheng <[email protected]>

[ Upstream commit 8d17190fae2caab89cd5df19257ed9dac0739e3b ]

The vDSO basetime of a clock is stored in the scaled nanoseconds of tkr_mono, so that the reader can floor the base and the cycle delta together in vdso_calc_ns().

vdso_time_update_aux() instead shifts the base down to nanoseconds, adds the offset, and shifts it back up, which zeroes the fractional nanoseconds of xtime_nsec. The reader then floors the base and the delta separately:

ktime_get_aux(): base + ((delta * mult + xtime_nsec) >> shift)
vdso: base + (xtime_nsec >> shift)
+ ((delta * mult) >> shift)

Since floor(a) + floor(b) <= floor(a + b), the vDSO reports 0 or 1 ns below the syscall for the same clock. It is not a monotonicity problem:
across an update the step is floor(a + d) - floor(a) - floor(d), which is 0 or 1, never negative.

Add the offset in scaled nanoseconds as the other high resolution clocks do, and normalise with __iter_div64_u64_rem() so that the stored base stays below one second and the userspace fast-path does not iterate more in __iter_div_u64_rem().

Only the sub-second field changes. (a + (b << shift)) >> shift is exactly (a >> shift) + b, so the seconds carried out of the normalisation are the same as before; what the old form dropped was the low shift bits of the remainder.

monotonic_to_aux.tv_nsec is a normalised timespec64 fraction, so it stays below NSEC_PER_SEC even for a negative offset, and the sum stays below 2 * (NSEC_PER_SEC << shift). The largest shift clocks_calc_mult_shift() can pick is 32, which makes that 8.6e18 against a u64 limit of 1.8e19.

Fixes 380b84e168e5 ("vdso/vsyscall: Update auxiliary clock data in the datapage")
---
 kernel/time/vsyscall.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
kernel/time/vsyscall.c +5 -5
index f43dd3f4744b5..0e4b499328c08 100644
@@ -155,11 +155,11 @@ void vdso_time_update_aux(struct timekeeper *tk)
 
 		vdso_ts->sec = tk->xtime_sec + tk->monotonic_to_aux.tv_sec;
 
-		nsec = tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift;
-		nsec += tk->monotonic_to_aux.tv_nsec;
-		vdso_ts->sec += __iter_div_u64_rem(nsec, NSEC_PER_SEC, &nsec);
-		nsec = nsec << tk->tkr_mono.shift;
-		vdso_ts->nsec = nsec;
+		nsec = tk->tkr_mono.xtime_nsec;
+		nsec += (u64)tk->monotonic_to_aux.tv_nsec << tk->tkr_mono.shift;
+		vdso_ts->sec += __iter_div64_u64_rem(nsec,
+						     (u64)NSEC_PER_SEC << tk->tkr_mono.shift,
+						     &vdso_ts->nsec);
 	}
 
 	__arch_update_vdso_clock(vc);
Signature · 1 line
2.53.0
author maintainer
#1992 lore raw

PATCH 1972/2651 IB/mlx4: Avoid requeueing executing CM timeout work

In reply to Greg Kroah-Hartman

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

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

From: Praveen Kumar Kannoju <[email protected]>

[ Upstream commit 9bcf45bfcaf83aed81b5fb12f0edf4c16e73e02e ]

id->scheduled_delete is set by schedule_delayed() itself. It is used in two cases after the RTU timeout support was added:

* A new id_map_entry is created, and a 60-second RTU timeout is scheduled.
* DREQ or REJ is received for an existing entry, and the normal 30-second teardown timeout is scheduled or adjusted.

The following race is possible when the RTU timeout expires while a DREQ or REJ is handled:

CPU 0: timeout work CPU 1: DREQ/REJ handler
-------------------- -----------------------
RTU timer expires
timeout callback starts
waits for id_map_lock takes id_map_lock

calls schedule_delayed() calls mod_delayed_work()

drops id_map_lock

takes id_map_lock
removes mapping
frees id_map_entry

requeued timeout runs accesses freed id_map_entry

mod_delayed_work() may requeue the work after the timeout callback has started. The original timeout callback then frees the id_map_entry, leaving the requeued work with a dangling delayed_work pointer.

When a timeout is already scheduled, first cancel its pending work. A successful cancellation means the callback has not started and the timeout can safely be scheduled again. If cancellation fails, the callback is executing and will free the entry after id_map_lock is released; do not requeue it.

cancel_delayed_work() is deliberately used instead of cancel_delayed_work_sync(), because the timeout callback may be waiting for id_map_lock, which is held by the caller.

Fixes fa09adf4231f ("IB/mlx4: Fix stale CM id_map entries when RTU is never received")
---
 drivers/infiniband/hw/mlx4/cm.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
drivers/infiniband/hw/mlx4/cm.c +10 -0
index 1e5e525fea733..810f95e55fda1 100644
@@ -301,10 +301,20 @@ static void schedule_delayed(struct ib_device *ibdev, struct id_map_entry *id,
 	spin_lock_irqsave(&sriov->going_down_lock, flags);
 	/*make sure that there is no schedule inside the scheduled work.*/
 	if (!sriov->is_going_down || id->scheduled_delete) {
+		/*
+		 * Do not requeue timeout work that is already executing. The
+		 * timeout handler may be waiting for id_map_lock and will free
+		 * this entry after the caller releases it.
+		 */
+		if (id->scheduled_delete &&
+		    !cancel_delayed_work(&id->timeout))
+			goto out;
+
 		id->scheduled_delete = 1;
 		id->rtu_timeout = rtu_timeout;
 		mod_delayed_work(cm_wq, &id->timeout, timeout);
 	}
+out:
 	spin_unlock_irqrestore(&sriov->going_down_lock, flags);
 }
 
Signature · 1 line
2.53.0
author maintainer
#1993 lore raw

PATCH 1973/2651 selftests/bpf: Create the vxlan devices of test_tunnel with their MAC

In reply to Greg Kroah-Hartman

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

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

From: Qiliang Yuan <[email protected]>

[ Upstream commit 33cbc5c2cadfe3b43f024e89880dd8fe2efb3a2e ]

The vxlan tests of test_tunnel create a tunnel device in the initial netns with "ip link add", and then give it the MAC address that the static neighbor entry at the other end points to with "ip link set".

systemd-udevd assigns new devices of the initial netns a MAC address of its own, following its MACAddressPolicy, when it handles their uevent. When it gets to that after the test set the address, the replies sent to the configured MAC are dropped as meant for another host, and the ping of vxlan_tunnel fails after 10 seconds.

Pass the address to "ip link add". udevd leaves alone the address of a device that was created with one.

---
 .../testing/selftests/bpf/prog_tests/test_tunnel.c  | 13 ++++++-------
 1 file changed, 6 insertions(+), 7 deletions(-)
tools/testing/selftests/bpf/prog_tests/test_tunnel.c +6 -7
index eb93099312720..7b35bf9498056 100644
@@ -161,9 +161,9 @@ static int add_vxlan_tunnel(void)
 	    IP4_ADDR2_VETH1, MAC_VETH1);
 
 	/* root namespace */
-	SYS(fail, "ip link add dev %s type vxlan external gbp dstport 4789",
-	    VXLAN_TUNL_DEV1);
-	SYS(fail, "ip link set dev %s address %s up", VXLAN_TUNL_DEV1, MAC_TUNL_DEV1);
+	SYS(fail, "ip link add dev %s address %s type vxlan external gbp dstport 4789",
+	    VXLAN_TUNL_DEV1, MAC_TUNL_DEV1);
+	SYS(fail, "ip link set dev %s up", VXLAN_TUNL_DEV1);
 	SYS(fail, "ip addr add dev %s %s/24", VXLAN_TUNL_DEV1, IP4_ADDR_TUNL_DEV1);
 	SYS(fail, "ip neigh add %s lladdr %s dev %s",
 	    IP4_ADDR_TUNL_DEV0, MAC_TUNL_DEV0, VXLAN_TUNL_DEV1);
@@ -198,11 +198,10 @@ static int add_ip6vxlan_tunnel(void)
 	    IP6VXLAN_TUNL_DEV0, MAC_TUNL_DEV0);
 
 	/* root namespace */
-	SYS(fail, "ip link add dev %s type vxlan external dstport 4789",
-	    IP6VXLAN_TUNL_DEV1);
-	SYS(fail, "ip addr add dev %s %s/24", IP6VXLAN_TUNL_DEV1, IP4_ADDR_TUNL_DEV1);
-	SYS(fail, "ip link set dev %s address %s up",
+	SYS(fail, "ip link add dev %s address %s type vxlan external dstport 4789",
 	    IP6VXLAN_TUNL_DEV1, MAC_TUNL_DEV1);
+	SYS(fail, "ip addr add dev %s %s/24", IP6VXLAN_TUNL_DEV1, IP4_ADDR_TUNL_DEV1);
+	SYS(fail, "ip link set dev %s up", IP6VXLAN_TUNL_DEV1);
 
 	return 0;
 fail:
Signature · 1 line
2.53.0
author maintainer
#1994 lore raw

PATCH 1974/2651 ALSA: core: Serialize snd_refcount put and sync

In reply to Greg Kroah-Hartman

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

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

From: Takashi Iwai <[email protected]>

[ Upstream commit 6904743ab77e0684dff319f3806ef982e5eea6cf ]

When a thread tries to sync-and-destroy the resource with snd_refcount_sync(), it might lead to a UAF in a very slight time window. Namely, snd_refount_put() calls wake_up() after atomic_dec_and_test(), but wait_event() in snd_refcount_sync() checks the condition via atomic_test() without serialization, hence the thread that called snd_refcount_sync() can continue immediately to release the resource before another thread calls wake_up().

For avoiding the race above, introduce the spinlock and take it at snd_refcount_put() and snd_refcount_sync() in order to serialize the operations.

---
 include/sound/core.h | 1 +
 sound/core/misc.c    | 5 ++++-
 2 files changed, 5 insertions(+), 1 deletion(-)
include/sound/core.h +1 -0
index 15be947a730ef..bea596f36f58e 100644
@@ -84,6 +84,7 @@ struct snd_device {
 struct snd_refcount {
 	atomic_t count;
 	wait_queue_head_t waiter;
+	spinlock_t lock;
 };
 
 void snd_refcount_init(struct snd_refcount *ref);
sound/core/misc.c +4 -1
index 066fb9ecdcdc3..6fe199e76e837 100644
@@ -183,11 +183,13 @@ void snd_refcount_init(struct snd_refcount *ref)
 {
 	atomic_set(&ref->count, 0);
 	init_waitqueue_head(&ref->waiter);
+	spin_lock_init(&ref->lock);
 }
 EXPORT_SYMBOL_GPL(snd_refcount_init);
 
 void snd_refcount_put(struct snd_refcount *ref)
 {
+	guard(spinlock_irqsave)(&ref->lock);
 	if (atomic_dec_and_test(&ref->count))
 		wake_up(&ref->waiter);
 }
@@ -195,6 +197,7 @@ EXPORT_SYMBOL_GPL(snd_refcount_put);
 
 void snd_refcount_sync(struct snd_refcount *ref)
 {
-	wait_event(ref->waiter, !atomic_read(&ref->count));
+	guard(spinlock_irq)(&ref->lock);
+	wait_event_lock_irq(ref->waiter, !atomic_read(&ref->count), ref->lock);
 }
 EXPORT_SYMBOL_GPL(snd_refcount_sync);
Signature · 1 line
2.53.0
author maintainer
#1995 lore raw

PATCH 1975/2651 selftests/bpf: Fix map fd leak in no-BTF wq test

In reply to Greg Kroah-Hartman

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

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

From: Yun Lu <[email protected]>

[ Upstream commit d3c9ecb8765d4befbc46ee325c8d76efd523eece ]

bpf_map__reuse_fd() duplicates the supplied file descriptor instead of taking ownership of it. test_failure_map_no_btf() closes the original map_fd only when reuse fails, leaking it when reuse succeeds, including when the test passes. Destroying the skeleton closes its own descriptor but leaves the original descriptor and its map reference alive.

Close map_fd immediately after bpf_map__reuse_fd(), before checking its return value, to release the original descriptor on both success and failure. The skeleton retains its own descriptor for the subsequent program load.

---
 tools/testing/selftests/bpf/prog_tests/wq.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
tools/testing/selftests/bpf/prog_tests/wq.c +2 -3
index 84831eecc935b..97926e35aaf26 100644
@@ -64,10 +64,9 @@ static void test_failure_map_no_btf(void)
 		goto out;
 
 	err = bpf_map__reuse_fd(skel->maps.array, map_fd);
-	if (!ASSERT_OK(err, "map reuse fd")) {
-		close(map_fd);
+	close(map_fd);
+	if (!ASSERT_OK(err, "map reuse fd"))
 		goto out;
-	}
 
 	insns = bpf_program__insns(skel->progs.test_map_no_btf);
 	if (!ASSERT_OK_PTR(insns, "insns ptr"))
Signature · 1 line
2.53.0
author maintainer
#1996 lore raw

PATCH 1976/2651 selftests/bpf: Accept unnamed dma-bufs in the dmabuf_iter default test

In reply to Greg Kroah-Hartman

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

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

From: Qiliang Yuan <[email protected]>

[ Upstream commit 653b8f14fdda385bd7c5b786f8dfdcc3e5599e27 ]

The dmabuf_collector iterator prints the inode, size, name and exporter of every dma-buf in the system on separate lines, with an empty name for the buffers that have none. The default_iter subtest parses that output and looks for the two buffers it created.

It requires a name for every buffer, and sscanf() finds none on the empty line of an unnamed one. On a system that has such a buffer, like one exported by udmabuf without a name, the subtest fails before it gets to its own buffers.

Take an empty name for a buffer without one.

---
 tools/testing/selftests/bpf/prog_tests/dmabuf_iter.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
tools/testing/selftests/bpf/prog_tests/dmabuf_iter.c +3 -2
index fb2cea710db3e..1a5dc1adae735 100644
@@ -188,8 +188,9 @@ static void subtest_dmabuf_iter_check_default_iter(struct dmabuf_iter *skel)
 			ASSERT_EQ(sscanf(line, "%ld", &bufinfo.size), 1,
 				  "read size");
 		} else if (f % FIELD_COUNT == NAME) {
-			ASSERT_EQ(sscanf(line, "%s", bufinfo.name), 1,
-				  "read name");
+			/* Keep an empty name for a buffer without one */
+			if (sscanf(line, "%s", bufinfo.name) != 1)
+				bufinfo.name[0] = '\0';
 		} else if (f % FIELD_COUNT == EXPORTER) {
 			ASSERT_EQ(sscanf(line, "%31s", bufinfo.exporter), 1,
 				  "read exporter");
Signature · 1 line
2.53.0
author maintainer
#1997 lore raw

PATCH 1977/2651 kselftest/arm64: signal: copy each test binary only once

In reply to Greg Kroah-Hartman

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

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

[ Upstream commit 7b3b147c4104f8211ad356a78cff9a2dcd966312 ]

The signal tests are built in testcases/ and then copied to the output directory. The copy rule lists every generated program as a target and copies all of them in each recipe:

  $(TEST_GEN_PROGS): $(PROGS)
          cp $(PROGS) $(OUTPUT)/

In a parallel build make runs that recipe once for each program, so several cp processes write the same destination files at the same time. cp then fails with "cannot create regular file ...: File exists", which fails the arm64 build even though every test compiled. A cross build of the arm64 signal tests at -j8 hit this in all of 8 runs.

Use a static pattern rule so that each output depends on, and copies, only its own binary.

Fixes f96bf4340316 ("kselftest: arm64: mangle_pstate_invalid_compat_toggle and common utils")
---
 tools/testing/selftests/arm64/signal/Makefile | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
tools/testing/selftests/arm64/signal/Makefile +2 -2
index 1381039fb36f9..c4df4be41636c 100644
@@ -17,8 +17,8 @@ TEST_GEN_PROGS := $(notdir $(PROGS))
 # the toplevel makefile
 include ../../lib.mk
 
-$(TEST_GEN_PROGS): $(PROGS)
-	cp $(PROGS) $(OUTPUT)/
+$(TEST_GEN_PROGS): $(OUTPUT)/%: testcases/%
+	cp $< $@
 
 # Common test-unit targets to build common-layout test-cases executables
 # Needs secondary expansion to properly include the testcase c-file in pre-reqs
Signature · 1 line
2.53.0
author maintainer
#1998 lore raw

PATCH 1978/2651 IB/rdmavt: Fix error unwind path for qp_priv_init() in rvt_create_qp()

In reply to Greg Kroah-Hartman

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

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

From: Serhat Kumral <[email protected]>

[ Upstream commit dd36137b218ad6f18ed15e6279412d7fc160980c ]

If driver_f.qp_priv_init() fails, execution jumps to bail_rq_wq, which bypasses bail_qpn. Because alloc_qpn() has already succeeded at this point, the allocated QP number is left unreleased.

Jump to bail_qpn instead to ensure the QPN is properly freed via rvt_free_qpn().

Fixes 5190f052a3654 ("IB/hfi1: Allow the driver to initialize QP priv struct")
---
 drivers/infiniband/sw/rdmavt/qp.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/infiniband/sw/rdmavt/qp.c +1 -1
index c40cce69e9457..ec64a595ce03e 100644
@@ -1173,7 +1173,7 @@ int rvt_create_qp(struct ib_qp *ibqp, struct ib_qp_init_attr *init_attr,
 		if (rdi->driver_f.qp_priv_init) {
 			ret = rdi->driver_f.qp_priv_init(rdi, qp, init_attr);
 			if (ret)
-				goto bail_rq_wq;
+				goto bail_qpn;
 		}
 		break;
 
Signature · 1 line
2.53.0
author maintainer
#1999 lore raw

PATCH 1979/2651 RDMA/irdma: Fix FRWR IRDMAQPSQ_PBLADDR field population

In reply to Greg Kroah-Hartman

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

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

From: Jacob Moroni <[email protected]>

[ Upstream commit 59df57262e6fa9e6f4aa76d6d324134777c702a0 ]

Previously, the IRDMAQPSQ_PBLADDR FRWR WQE field was being populated using a mask that was right-shifted, whereas it should have been the address being right-shifted.

This ended up working fine in many cases because the lowermost 12 bits are always zero (the addresses are page aligned) and the uppermost 12 bits are usually zero too, but it could break for DMA addresses that are wider than 52 bits.

Fix this by right-shifting the address instead of the mask, similar to how it was done in the original i40iw driver.

Tested with NFS over RDMA with some added debug logs to ensure it was hitting both the direct (single page) path as well as multi page (< 512).

Fixes 3f49d6842569 ("RDMA/irdma: Implement HW Admin Queue OPs")
---
 drivers/infiniband/hw/irdma/ctrl.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/infiniband/hw/irdma/ctrl.c +1 -1
index 7af1c68b2fb26..970b61aa3e24f 100644
@@ -1729,7 +1729,7 @@ int irdma_sc_mr_fast_register(struct irdma_sc_qp *qp,
 			 info->first_pm_pbl_index >> 16);
 	set_64bit_val(wqe, 8,
 		      FIELD_PREP(IRDMAQPSQ_FIRSTPMPBLIDXHI, temp) |
-		      FIELD_PREP(IRDMAQPSQ_PBLADDR >> IRDMA_HW_PAGE_SHIFT, info->reg_addr_pa));
+		      FIELD_PREP(IRDMAQPSQ_PBLADDR, info->reg_addr_pa >> IRDMA_HW_PAGE_SHIFT));
 	set_64bit_val(wqe, 16,
 		      info->total_len |
 		      FIELD_PREP(IRDMAQPSQ_FIRSTPMPBLIDXLO, info->first_pm_pbl_index));
Signature · 1 line
2.53.0
author maintainer
#2000 lore raw

PATCH 1980/2651 ASoC: Intel: avs: Unprepare a stream when recovery occurs

In reply to Greg Kroah-Hartman

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

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

From: Cezary Rojewski <[email protected]>

[ Upstream commit 85bc213f96ac03d74a3e531968c68861e5598281 ]

Recovery on alsa-lib side is handled with either:
1) snd_pcm_prepare(state=XRUN)
2) snd_pcm_drop/drain() -> snd_pcm_prepare(state=SETUP)

before starting the PCM anew. Relying solely on state=XRUN leaves 2) unaccounted for. sound/core/pcm_native.c ensures correctness of the state machine so plain state!=PREPARED check suffices.

This is the BE equivalent of job done previously for FE side only with commit cfca1637bc2b ("ASoC: Intel: avs: Unprepare a stream when XRUN occurs") and its follow up titled: ("ASoC: Intel: avs: Reset the stream unless it is already prepared").

---
 sound/soc/intel/avs/pcm.c | 2 ++
 1 file changed, 2 insertions(+)
sound/soc/intel/avs/pcm.c +2 -0
index 880cd7a9fb346..13a38ec8c917e 100644
@@ -461,6 +461,8 @@ static int avs_dai_hda_be_prepare(struct snd_pcm_substream *substream, struct sn
 	link_stream = data->link_stream;
 	p = &be->dpcm[substream->stream].hw_params;
 
+	if (substream->runtime->state != SNDRV_PCM_STATE_PREPARED)
+		link_stream->link_prepared = false;
 	if (link_stream->link_prepared)
 		return 0;
 
Signature · 1 line
2.53.0
author maintainer
#2001 lore raw

PATCH 1981/2651 ASoC: Intel: avs: Prevent module info underflow

In reply to Greg Kroah-Hartman

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

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

From: Cezary Rojewski <[email protected]>

[ Upstream commit 05c2975b4267246219e7aead0467626107e204e9 ]

Typically modules information is first initialized when loading the base AudioDSP base firmware and then expanded when loadable DSP modules are requested by platform-components, see avs_component_load_libraries().

While theoretically not possible in a production scenario, there is no reason to continue the IDAs preparation if an event caused the newly obtained module information to be smaller or equal than the existing information.

Fixes c1a427e8da93 ("ASoC: Intel: avs: Firmware resources management utilities")
---
 sound/soc/intel/avs/utils.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
sound/soc/intel/avs/utils.c +4 -2
index ea14ec1738552..f19a62e7e8b5a 100644
@@ -116,9 +116,11 @@ avs_module_ida_alloc(struct avs_dev *adev, struct avs_mods_info *newinfo, bool p
 	int i;
 
 	if (!purge && oldinfo) {
-		if (oldinfo->count >= newinfo->count)
-			dev_warn(adev->dev, "refreshing %d modules info with %d\n",
+		if (oldinfo->count >= newinfo->count) {
+			dev_warn(adev->dev, "modules info underflow, old: %d, new: %d\n",
 				 oldinfo->count, newinfo->count);
+			return -EPROTO;
+		}
 		tocopy_count = oldinfo->count;
 	}
 
Signature · 1 line
2.53.0
author maintainer
#2002 lore raw

PATCH 1982/2651 ASoC: qcom: sdm845: Disable the quaternary MI2S bit clock on shutdown

In reply to Greg Kroah-Hartman

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

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

From: Michael Auer <[email protected]>

[ Upstream commit cef5d087d6813d4c15847d0b71ecbd6c47c5f1d4 ]

sdm845_snd_startup() enables the quaternary MI2S bit clock in the ADSP, but sdm845_snd_shutdown() never disables it. After the first stream on this port the clock stays on.

On the OnePlus 6 the speaker amplifier is on this port. After the first playback the ADSP no longer power collapses: it slept under 9 s in 5 hours. With this change it sleeps again when audio is idle (about 40 s of 45 s).

Refcount the clock like the other MI2S and TDM ports and disable it when the last user is gone.

Fixes 5caf64c633a3 ("ASoC: qcom: sdm845: add support to DB845c and Lenovo Yoga")
Assisted-by LLM
---
 sound/soc/qcom/sdm845.c | 19 +++++++++++++++----
 1 file changed, 15 insertions(+), 4 deletions(-)
sound/soc/qcom/sdm845.c +15 -4
index 6843ab8ba017e..a777b3b83775b 100644
@@ -38,6 +38,7 @@ struct sdm845_snd_data {
 	bool stream_prepared[AFE_PORT_MAX];
 	uint32_t pri_mi2s_clk_count;
 	uint32_t sec_mi2s_clk_count;
+	uint32_t quat_mi2s_clk_count;
 	uint32_t quat_tdm_clk_count;
 };
 
@@ -365,9 +366,11 @@ static int sdm845_snd_startup(struct snd_pcm_substream *substream)
 		break;
 	case QUATERNARY_MI2S_RX:
 		codec_dai_fmt |= SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_I2S;
-		snd_soc_dai_set_sysclk(cpu_dai,
-			Q6AFE_LPASS_CLK_ID_QUAD_MI2S_IBIT,
-			MI2S_BCLK_RATE, SNDRV_PCM_STREAM_PLAYBACK);
+		if (++(data->quat_mi2s_clk_count) == 1) {
+			snd_soc_dai_set_sysclk(cpu_dai,
+				Q6AFE_LPASS_CLK_ID_QUAD_MI2S_IBIT,
+				MI2S_BCLK_RATE, SNDRV_PCM_STREAM_PLAYBACK);
+		}
 		snd_soc_dai_set_fmt(cpu_dai, fmt);
 		snd_soc_dai_set_fmt(codec_dai, codec_dai_fmt);
 		break;
@@ -454,8 +457,16 @@ static void  sdm845_snd_shutdown(struct snd_pcm_substream *substream)
 				0, SNDRV_PCM_STREAM_PLAYBACK);
 		}
 		break;
-	case SLIMBUS_0_RX...SLIMBUS_6_TX:
+
 	case QUATERNARY_MI2S_RX:
+		if (--(data->quat_mi2s_clk_count) == 0) {
+			snd_soc_dai_set_sysclk(cpu_dai,
+				Q6AFE_LPASS_CLK_ID_QUAD_MI2S_IBIT,
+				0, SNDRV_PCM_STREAM_PLAYBACK);
+		}
+		break;
+
+	case SLIMBUS_0_RX...SLIMBUS_6_TX:
 		break;
 
 	default:
Signature · 1 line
2.53.0
author maintainer
#2003 lore raw

PATCH 1983/2651 selftests: keep the build status from wrapping to success

In reply to Greg Kroah-Hartman

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

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

[ Upstream commit 907d138279ee3747efedc9f7403d8b0edb52aca2 ]

The top-level all and install rules return failure only when every selected target fails, which commit cad6f32665cb ("selftests: Deescalate error reporting") deliberately kept as the default. They implement this by multiplying the exit statuses of the targets:

  ret=$$((ret * $$?))

A failing recursive make exits with status 2, so eight failing targets produce 256, and "exit 256" reports success. Building eight or more targets that all fail therefore succeeds, and install goes on to package an empty installation.

Record a successful target instead of multiplying statuses. The rules still fail only when no target succeeds, and FORCE_TARGETS still stops at the first failure.

Fixes 5f70bde26a48 ("selftests: fix build behaviour on targets' failures")
---
 tools/testing/selftests/Makefile | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
tools/testing/selftests/Makefile +2 -2
index bc4fdb6f53375..45ab2d8eacffe 100644
@@ -232,7 +232,7 @@ all:
 		$(MAKE) OUTPUT=$$BUILD_TARGET -C $$TARGET	\
 				O=$(abs_objtree)		\
 				$(if $(FORCE_TARGETS),|| exit);	\
-		ret=$$((ret * $$?));				\
+		[ $$? -eq 0 ] && ret=0;				\
 	done; exit $$ret;
 
 run_tests: all
@@ -299,7 +299,7 @@ ifdef INSTALL_PATH
 				OBJ_PATH=$(INSTALL_PATH) \
 				O=$(abs_objtree)		\
 				$(if $(FORCE_TARGETS),|| exit);	\
-		ret=$$((ret * $$?));		\
+		[ $$? -eq 0 ] && ret=0;		\
 	done; exit $$ret;
 
 
Signature · 1 line
2.53.0
author maintainer
#2004 lore raw

PATCH 1984/2651 ublk: hold RCU read lock in ublk_try_buf_match()

In reply to Greg Kroah-Hartman

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

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

From: Paolo Bertinetti <[email protected]>

[ Upstream commit aaf49023041bc1f887a028a164d3bac714b65508 ]

syzbot reports a lockdep splat when I/O is dispatched to a ublk device with UBLK_F_SHMEM_ZC enabled:

WARNING: suspicious RCU usage
lib/maple_tree.c:720 suspicious rcu_dereference_check() usage!
...

  Call Trace:
   mas_root lib/maple_tree.c:720 [inline]
   mas_start+0x3cc/0x640 lib/maple_tree.c:1250
   mas_state_walk lib/maple_tree.c:3006 [inline]
   mas_walk+0x1db/0x490 lib/maple_tree.c:4458
   ublk_try_buf_match drivers/block/ublk_drv.c:5639 [inline]
   ublk_init_iod+0x5d2/0x1120 drivers/block/ublk_drv.c:521
   ublk_dispatch_req+0x97/0x9c0 drivers/block/ublk_drv.c:1776
   tctx_task_work_run+0x73d/0xa80 io_uring/tw.c:96

ublk_try_buf_match() calls mas_walk() on the buffer tree without holding the RCU read lock or the tree lock. Writers are already excluded because ublk_lock_buf_tree() freezes the queue, so there is no real race, but maple tree readers must still hold one of the two.

Take the RCU read lock around the walk.

---
 drivers/block/ublk_drv.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/block/ublk_drv.c +2 -0
index 959e6594013a8..ca4cb9d760353 100644
@@ -5738,6 +5738,8 @@ static bool ublk_try_buf_match(struct ublk_device *ub,
 	unsigned long expected_offset = 0;
 	bool first = true;
 
+	guard(rcu)();
+
 	rq_for_each_bvec(bv, rq, iter) {
 		unsigned long pfn = page_to_pfn(bv.bv_page);
 		unsigned long end_pfn = pfn +
Signature · 1 line
2.53.0
author maintainer
#2005 lore raw

PATCH 1985/2651 ASoC: rockchip: fix device node reference leak in rk3288_hdmi_analog

In reply to Greg Kroah-Hartman

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

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

From: Haotian Zhang <[email protected]>

[ Upstream commit f15b2df0b940cb2c01797f78791de3279d514086 ]

snd_rk_mc_probe() acquires references to the codec and CPU device nodes with of_parse_phandle() and stores them in the static rk_dailink, but the driver never calls of_node_put() on them. All error paths and the success path simply return, and the driver has no remove callback, so the references are leaked for the whole lifetime of the card and each failed or repeated probe leaks another pair. The same pattern was fixed for the sibling rockchip_rt5645.c driver.

Release the codec and CPU device nodes on every probe error path and in a new remove callback, and also drop the extra reference placed in args.np by of_parse_phandle_with_fixed_args().

Fixes eaae2ea73593 ("ASoC: rockchip: Add machine driver for RK3288 boards that use analog/HDMI")
Assisted-by DeepSeek-V4.1-Flash
---
 sound/soc/rockchip/rk3288_hdmi_analog.c | 42 +++++++++++++++++++------
 1 file changed, 33 insertions(+), 9 deletions(-)
sound/soc/rockchip/rk3288_hdmi_analog.c +33 -9
index 541163ed56fc3..9bb02d41d9013 100644
@@ -201,36 +201,59 @@ static int snd_rk_mc_probe(struct platform_device *pdev)
 	if (ret) {
 		dev_err(&pdev->dev,
 			"Unable to parse property 'rockchip,audio-codec'\n");
-		return ret;
+		goto put_codec_of_node;
 	}
 
 	ret = snd_soc_get_dai_name(&args, &rk_dailink.codecs[0].dai_name);
-	if (ret)
-		return dev_err_probe(&pdev->dev, ret,
-				     "Unable to get codec_dai_name\n");
+	of_node_put(args.np);
+	if (ret) {
+		dev_err_probe(&pdev->dev, ret,
+			      "Unable to get codec_dai_name\n");
+		goto put_codec_of_node;
+	}
 
 	rk_dailink.cpus->of_node = of_parse_phandle(np, "rockchip,i2s-controller",
 						  0);
 	if (!rk_dailink.cpus->of_node) {
 		dev_err(&pdev->dev,
 			"Property 'rockchip,i2s-controller' missing or invalid\n");
-		return -EINVAL;
+		ret = -EINVAL;
+		goto put_codec_of_node;
 	}
 
 	rk_dailink.platforms->of_node = rk_dailink.cpus->of_node;
 
 	ret = snd_soc_of_parse_audio_routing(card, "rockchip,routing");
 	if (ret)
-		return ret;
+		goto put_cpu_of_node;
 
 	snd_soc_card_set_drvdata(card, machine);
 
 	ret = devm_snd_soc_register_card(&pdev->dev, card);
-	if (ret)
-		return dev_err_probe(&pdev->dev, ret,
-				     "Soc register card failed\n");
+	if (ret) {
+		dev_err_probe(&pdev->dev, ret,
+			      "Soc register card failed\n");
+		goto put_cpu_of_node;
+	}
 
 	return 0;
+
+put_cpu_of_node:
+	of_node_put(rk_dailink.cpus->of_node);
+	rk_dailink.cpus->of_node = NULL;
+put_codec_of_node:
+	of_node_put(rk_dailink.codecs[0].of_node);
+	rk_dailink.codecs[0].of_node = NULL;
+
+	return ret;
+}
+
+static void snd_rk_mc_remove(struct platform_device *pdev)
+{
+	of_node_put(rk_dailink.cpus->of_node);
+	rk_dailink.cpus->of_node = NULL;
+	of_node_put(rk_dailink.codecs[0].of_node);
+	rk_dailink.codecs[0].of_node = NULL;
 }
 
 static const struct of_device_id rockchip_sound_of_match[] = {
@@ -242,6 +265,7 @@ MODULE_DEVICE_TABLE(of, rockchip_sound_of_match);
 
 static struct platform_driver rockchip_sound_driver = {
 	.probe = snd_rk_mc_probe,
+	.remove = snd_rk_mc_remove,
 	.driver = {
 		.name = DRV_NAME,
 		.pm = &snd_soc_pm_ops,
Signature · 1 line
2.53.0
author maintainer
#2006 lore raw

PATCH 1986/2651 spi: tegra114: initialize native chip selects inactive

In reply to Greg Kroah-Hartman

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

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

From: Abraham Zukor <[email protected]>

[ Upstream commit f8334fdfd858c27f090ce597806794e4a08c9f4f ]

tegra_spi_probe() initializes SPI_COMMAND1 with only SPI_M_S, leaving CS_POL_INACTIVE clear for every chip select. This drives every native active-low chip select low until tegra_spi_setup() runs for that device.

SPI children are registered and probed one at a time. A synchronous probe of an earlier child can therefore transfer while a later child's chip select is still asserted. On a Tegra234 system with active-low devices on CS0 and CS1, this caused both devices to be selected when the CS1 device probed first. Its initialization then intermittently failed. A logic analyzer showed CS0 remained low throughout the CS1 transfer and went high only after the CS1 probe failed.

Walk the controller's device tree children before SPI_COMMAND1 is written and set CS_POL_INACTIVE for each valid chip select without spi-cs-high. That way the line is already deasserted when the first child transfers and does not change level when setup runs.

Disabled children are walked too. The core only registers available children, so tegra_spi_setup() never runs for a disabled one and probe is the only chance to park its chip select at the level its hardware needs.

If an enabled child shares a chip select with disabled ones, its polarity takes priority. If only disabled children use a chip select and they disagree, warn and leave the line inactive high.

Fixes f333a331adfa ("spi/tegra114: add spi driver")
Assisted-by Claude:Opus-5
---
 drivers/spi/spi-tegra114.c | 49 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 49 insertions(+)
drivers/spi/spi-tegra114.c +49 -0
index 5f8d8da7a3fc1..f43f2df478b45 100644
@@ -1308,6 +1308,9 @@ static int tegra_spi_probe(struct platform_device *pdev)
 	struct resource		*r;
 	int ret, spi_irq;
 	int bus_num;
+	u32 conflicting_cs;
+	u32 enabled_child_cs_polarity = 0, disabled_child_cs_low = 0, disabled_child_cs_high = 0;
+	u32 enabled_cs_mask = 0;
 
 	host = devm_spi_alloc_host(&pdev->dev, sizeof(*tspi));
 	if (!host) {
@@ -1402,6 +1405,52 @@ static int tegra_spi_probe(struct platform_device *pdev)
 	udelay(2);
 	reset_control_deassert(tspi->rst);
 	tspi->def_command1_reg  = SPI_M_S;
+
+	/*
+	 * SPI_COMMAND1 is written before any child is registered, so a chip
+	 * select with CS_POL_INACTIVE clear stays asserted until
+	 * tegra_spi_setup() runs for that device. Program the level the
+	 * device tree asks for up front instead.
+	 *
+	 * Disabled children are included deliberately. The core never
+	 * registers them, so this is the only chance to park their chip
+	 * select at the level their hardware needs. An enabled child on the
+	 * same CS takes priority.
+	 */
+	for_each_child_of_node_scoped(pdev->dev.of_node, np) {
+		u32 cs;
+		u32 polarity_bitmask;
+		u32 cs_polarity = 0;
+
+		if (of_property_read_u32(np, "reg", &cs))
+			continue;
+
+		if (cs >= MAX_CHIP_SELECT)
+			continue;
+
+		polarity_bitmask = SPI_CS_POL_INACTIVE(cs);
+		if (!of_property_read_bool(np, "spi-cs-high"))
+			cs_polarity = polarity_bitmask;
+
+		if (of_device_is_available(np)) {
+			enabled_cs_mask |= polarity_bitmask;
+			enabled_child_cs_polarity |= cs_polarity;
+		} else {
+			if (cs_polarity)
+				disabled_child_cs_low |= polarity_bitmask;
+			else
+				disabled_child_cs_high |= polarity_bitmask;
+		}
+	}
+	conflicting_cs = disabled_child_cs_low & disabled_child_cs_high & ~enabled_cs_mask;
+	for (u32 cs = 0; cs < MAX_CHIP_SELECT; cs++) {
+		if (SPI_CS_POL_INACTIVE(cs) & conflicting_cs)
+			dev_warn(&pdev->dev,
+				 "Conflicting CS polarity on disabled nodes at cs %u\n", cs);
+	}
+
+	tspi->def_command1_reg |= enabled_child_cs_polarity |
+		(disabled_child_cs_low & ~enabled_cs_mask);
 	tegra_spi_writel(tspi, tspi->def_command1_reg, SPI_COMMAND1);
 	tspi->spi_cs_timing1 = tegra_spi_readl(tspi, SPI_CS_TIMING1);
 	tspi->spi_cs_timing2 = tegra_spi_readl(tspi, SPI_CS_TIMING2);
Signature · 1 line
2.53.0
author maintainer
#2007 lore raw

PATCH 1987/2651 ASoC: soc-link: Correct stream stop operations in snd_soc_link_trigger

In reply to Greg Kroah-Hartman

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

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

From: Amadeusz Sławiński <[email protected]>

[ Upstream commit 7ef99fcfbbac20ebec10d21a37aeaf8321de7829 ]

When snd_soc_link_trigger() is called to stop, pause push or suspend stream it should call soc_link_mark_pop() on proper target to reverse operation from trigger start, pause release or resume.

Fixes 6374f493d93b ("ASoC: soc-pcm: care trigger rollback")
---
 sound/soc/soc-link.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
sound/soc/soc-link.c +1 -1
index 02fd68f2e7028..50ff9ba3ac871 100644
@@ -161,7 +161,7 @@ int snd_soc_link_trigger(struct snd_pcm_substream *substream, int cmd,
 			break;
 
 		ret = soc_link_trigger(substream, cmd);
-		soc_link_mark_pop(rtd, startup);
+		soc_link_mark_pop(rtd, trigger);
 	}
 
 	return ret;
Signature · 1 line
2.53.0
author maintainer
#2008 lore raw

PATCH 1988/2651 ASoC: ops: Fix return value in snd_soc_limit_volume()

In reply to Greg Kroah-Hartman

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

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

From: Amadeusz Sławiński <[email protected]>

[ Upstream commit 223ec2a93bec6c5ee859094c826fec78516a0bb3 ]

As documented snd_soc_limit_volume() should return 0 on success, however at some point in time this promise was broken when snd_soc_clip_to_platform_max() was refactored, refactor it once again using __free() to automatically free struct snd_ctl_elem_value and return proper value.

Fixes 7e10d7242ea8 ("ASoC: ops: dynamically allocate struct snd_ctl_elem_value")
---
 sound/soc/soc-ops.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
sound/soc/soc-ops.c +5 -5
index c935571d43e9d..59ab521f99a84 100644
@@ -406,7 +406,7 @@ EXPORT_SYMBOL_GPL(snd_soc_put_volsw_sx);
 static int snd_soc_clip_to_platform_max(struct snd_kcontrol *kctl)
 {
 	struct soc_mixer_control *mc = (struct soc_mixer_control *)kctl->private_value;
-	struct snd_ctl_elem_value *uctl;
+	struct snd_ctl_elem_value *uctl __free(kfree) = NULL;
 	int ret;
 
 	if (!mc->platform_max)
@@ -418,7 +418,7 @@ static int snd_soc_clip_to_platform_max(struct snd_kcontrol *kctl)
 
 	ret = kctl->get(kctl, uctl);
 	if (ret < 0)
-		goto out;
+		return ret;
 
 	if (uctl->value.integer.value[0] > mc->platform_max)
 		uctl->value.integer.value[0] = mc->platform_max;
@@ -428,10 +428,10 @@ static int snd_soc_clip_to_platform_max(struct snd_kcontrol *kctl)
 		uctl->value.integer.value[1] = mc->platform_max;
 
 	ret = kctl->put(kctl, uctl);
+	if (ret < 0)
+		return ret;
 
-out:
-	kfree(uctl);
-	return ret;
+	return 0;
 }
 
 /**
Signature · 1 line
2.53.0
author maintainer
#2009 lore raw

PATCH 1989/2651 ASoC: soc-topology-test: Check return value of kunit_device_register()

In reply to Greg Kroah-Hartman

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

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

From: Amadeusz Sławiński <[email protected]>

[ Upstream commit 1641c1ba27abcd3ea3bba1232d9d817092f1b757 ]

Call to kunit_device_register() can fail. Check return result of register call. While at it introduce helper variable so that if it fails put_device is called on properly initialized variable.

Fixes e57cdff0ddc4 ("ASoC: topology: Replace fake root_device with kunit_device in tests")
---
 sound/soc/soc-topology-test.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
sound/soc/soc-topology-test.c +6 -2
index 346a52d3006a6..fb7e4d5690cd7 100644
@@ -24,8 +24,12 @@ static struct device *test_dev;
 
 static int snd_soc_tplg_test_init(struct kunit *test)
 {
-	test_dev = kunit_device_register(test, "sound-soc-topology-test");
-	test_dev = get_device(test_dev);
+	struct device *dev;
+
+	dev = kunit_device_register(test, "sound-soc-topology-test");
+	if (IS_ERR(dev))
+		return PTR_ERR(dev);
+	test_dev = get_device(dev);
 	if (!test_dev)
 		return -ENODEV;
 
Signature · 1 line
2.53.0
author maintainer
#2010 lore raw

PATCH 1990/2651 ASoC: soc-card-test: Check return value of kunit_device_register()

In reply to Greg Kroah-Hartman

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

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

From: Amadeusz Sławiński <[email protected]>

[ Upstream commit 77dfd98b1642b9bc6c2312bd8b805c321fb878b0 ]

Call to kunit_device_register() can fail. Check return result of register call. While at it introduce helper variable so that if it fails put_device is called on properly initialized variable.

Fixes ef7784e41db7 ("ASoC: soc-card: Add KUnit test case for snd_soc_card_get_kcontrol")
---
 sound/soc/soc-card-test.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
sound/soc/soc-card-test.c +5 -2
index 47dfd8b1babc2..610b8220786d1 100644
@@ -70,6 +70,7 @@ static void test_snd_soc_card_get_kcontrol(struct kunit *test)
 static int soc_card_test_case_init(struct kunit *test)
 {
 	struct soc_card_test_priv *priv;
+	struct device *dev;
 	int ret;
 
 	priv = kunit_kzalloc(test, sizeof(*priv), GFP_KERNEL);
@@ -82,8 +83,10 @@ static int soc_card_test_case_init(struct kunit *test)
 	if (!priv->card)
 		return -ENOMEM;
 
-	priv->card_dev = kunit_device_register(test, "sound-soc-card-test");
-	priv->card_dev = get_device(priv->card_dev);
+	dev = kunit_device_register(test, "sound-soc-card-test");
+	if (IS_ERR(dev))
+		return PTR_ERR(dev);
+	priv->card_dev = get_device(dev);
 	if (!priv->card_dev)
 		return -ENODEV;
 
Signature · 1 line
2.53.0
author maintainer
#2011 lore raw

PATCH 1991/2651 ASoC: soc-ac97: Fix error handling in snd_soc_new_ac97_component()

In reply to Greg Kroah-Hartman

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

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

From: Amadeusz Sławiński <[email protected]>

[ Upstream commit fc081cdfc6b370f6b6853cdeb4313f92561770d1 ]

If call to snd_soc_ac97_init_gpio() fails, proper removal procedure should mirror snd_soc_free_ac97_component() behaviour and call device_del() before put_device().

---
 sound/soc/soc-ac97.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
sound/soc/soc-ac97.c +3 -1
index 5f81e3606655b..5c573c8dc249b 100644
@@ -241,10 +241,12 @@ struct snd_ac97 *snd_soc_new_ac97_component(struct snd_soc_component *component,
 
 	ret = snd_soc_ac97_init_gpio(ac97, component);
 	if (ret)
-		goto err_put_device;
+		goto err_del_device;
 
 	return ac97;
 
+err_del_device:
+	device_del(&ac97->dev);
 err_put_device:
 	put_device(&ac97->dev);
 	return ERR_PTR(ret);
Signature · 1 line
2.53.0
author maintainer
#2012 lore raw

PATCH 1992/2651 ASoC: soc-component: Fix return type of snd_soc_pcm_component_pointer()

In reply to Greg Kroah-Hartman

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

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

From: Amadeusz Sławiński <[email protected]>

[ Upstream commit 9df30adce80dd6b0646e58c12a4cf7c6c88d0778 ]

Both caller and pointer callback expect the return value to be snd_pcm_uframes_t, however it was defined incorrectly leading to potential truncation of returned value.

Fixes 0035e2565b93 ("ASoC: soc-component: add snd_soc_pcm_component_pointer()")
---
 include/sound/soc-component.h | 2 +-
 sound/soc/soc-component.c     | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
include/sound/soc-component.h +1 -1
index c49b59630101f..bd64ebf2379b5 100644
@@ -423,7 +423,7 @@ int snd_soc_component_compr_set_metadata(struct snd_compr_stream *cstream,
 int snd_soc_component_compr_get_metadata(struct snd_compr_stream *cstream,
 					 struct snd_compr_metadata *metadata);
 
-int snd_soc_pcm_component_pointer(struct snd_pcm_substream *substream);
+snd_pcm_uframes_t snd_soc_pcm_component_pointer(struct snd_pcm_substream *substream);
 int snd_soc_pcm_component_ioctl(struct snd_pcm_substream *substream,
 				unsigned int cmd, void *arg);
 int snd_soc_pcm_component_sync_stop(struct snd_pcm_substream *substream);
sound/soc/soc-component.c +1 -1
index dc7d203cb76af..c4d9e80a9d851 100644
@@ -935,7 +935,7 @@ int snd_soc_component_test_bits(struct snd_soc_component *component,
 }
 EXPORT_SYMBOL_GPL(snd_soc_component_test_bits);
 
-int snd_soc_pcm_component_pointer(struct snd_pcm_substream *substream)
+snd_pcm_uframes_t snd_soc_pcm_component_pointer(struct snd_pcm_substream *substream)
 {
 	struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream);
 	struct snd_soc_component *component;
Signature · 1 line
2.53.0
author maintainer
#2013 lore raw

PATCH 1993/2651 ASoC: mediatek: mt8195: Fix tuner clock error handling

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit 8e5a2eabb0d7cbd6db0b94f7f30e1ca2c0a8994f ]

Check and propagate errors from mt8195_afe_enable_clk(). If enabling the tuner clock fails, disable the previously enabled APLL clock.

Fixes ff5a90173d98 ("ASoC: mediatek: mt8195: enable apll tuner")
---
 sound/soc/mediatek/mt8195/mt8195-afe-clk.c | 24 +++++++++++++++++-----
 1 file changed, 19 insertions(+), 5 deletions(-)
sound/soc/mediatek/mt8195/mt8195-afe-clk.c +19 -5
index 618d8400913a3..ec1ea5b988ffc 100644
@@ -241,21 +241,35 @@ static int mt8195_afe_enable_tuner_clk(struct mtk_base_afe *afe,
 				       unsigned int id)
 {
 	struct mt8195_afe_private *afe_priv = afe->platform_priv;
+	int ret;
 
 	switch (id) {
 	case MT8195_AUD_PLL1:
-		mt8195_afe_enable_clk(afe, afe_priv->clk[MT8195_CLK_AUD_APLL]);
-		mt8195_afe_enable_clk(afe, afe_priv->clk[MT8195_CLK_AUD_APLL1_TUNER]);
+		ret = mt8195_afe_enable_clk(afe, afe_priv->clk[MT8195_CLK_AUD_APLL]);
+		if (ret)
+			return ret;
+		ret = mt8195_afe_enable_clk(afe, afe_priv->clk[MT8195_CLK_AUD_APLL1_TUNER]);
+		if (ret) {
+			mt8195_afe_disable_clk(afe, afe_priv->clk[MT8195_CLK_AUD_APLL]);
+			return ret;
+		}
 		break;
 	case MT8195_AUD_PLL2:
-		mt8195_afe_enable_clk(afe, afe_priv->clk[MT8195_CLK_AUD_APLL2]);
-		mt8195_afe_enable_clk(afe, afe_priv->clk[MT8195_CLK_AUD_APLL2_TUNER]);
+		ret = mt8195_afe_enable_clk(afe, afe_priv->clk[MT8195_CLK_AUD_APLL2]);
+		if (ret)
+			return ret;
+		ret = mt8195_afe_enable_clk(afe, afe_priv->clk[MT8195_CLK_AUD_APLL2_TUNER]);
+		if (ret) {
+			mt8195_afe_disable_clk(afe, afe_priv->clk[MT8195_CLK_AUD_APLL2]);
+			return ret;
+		}
 		break;
 	default:
+		ret = 0;
 		break;
 	}
 
-	return 0;
+	return ret;
 }
 
 static int mt8195_afe_disable_tuner_clk(struct mtk_base_afe *afe,
Signature · 1 line
2.53.0
author maintainer
#2014 lore raw

PATCH 1994/2651 ASoC: mediatek: mt8195: Fix register access clock error handling

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit c23390ecf5c068976f25d9c8bfa8e298fa12ea3d ]

Check the return value of mt8195_afe_enable_clk() when enabling the register access clocks.

If enabling a clock fails, disable the clocks that were already enabled and propagate the error to the caller

Fixes 6746cc858259 ("ASoC: mediatek: mt8195: add platform driver")
---
 sound/soc/mediatek/mt8195/mt8195-afe-clk.c | 15 ++++++++++++---
 1 file changed, 12 insertions(+), 3 deletions(-)
sound/soc/mediatek/mt8195/mt8195-afe-clk.c +12 -3
index ec1ea5b988ffc..0b56a3335d501 100644
@@ -602,7 +602,7 @@ static int mt8195_afe_disable_top_cg(struct mtk_base_afe *afe, unsigned int cg_t
 int mt8195_afe_enable_reg_rw_clk(struct mtk_base_afe *afe)
 {
 	struct mt8195_afe_private *afe_priv = afe->platform_priv;
-	int i;
+	int i, ret;
 	static const unsigned int clk_array[] = {
 		MT8195_CLK_SCP_ADSP_AUDIODSP, /* bus clock for infra */
 		MT8195_CLK_TOP_AUDIO_H_SEL, /* clock for ADSP bus */
@@ -614,10 +614,19 @@ int mt8195_afe_enable_reg_rw_clk(struct mtk_base_afe *afe)
 		MT8195_CLK_AUD_A1SYS, /* AFE HW clock */
 	};
 
-	for (i = 0; i < ARRAY_SIZE(clk_array); i++)
-		mt8195_afe_enable_clk(afe, afe_priv->clk[clk_array[i]]);
+	for (i = 0; i < ARRAY_SIZE(clk_array); i++) {
+		ret = mt8195_afe_enable_clk(afe, afe_priv->clk[clk_array[i]]);
+		if (ret)
+			goto err_disable_clk;
+	}
 
 	return 0;
+
+err_disable_clk:
+	while (--i >= 0)
+		mt8195_afe_disable_clk(afe, afe_priv->clk[clk_array[i]]);
+
+	return ret;
 }
 
 int mt8195_afe_disable_reg_rw_clk(struct mtk_base_afe *afe)
Signature · 1 line
2.53.0
author maintainer
#2015 lore raw

PATCH 1995/2651 ASoC: mediatek: mt8195: Fix timing system clock error handling

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit f18c0a8e528eb8844ee362324220ab8df3664afe ]

Check the return value of mt8195_afe_enable_clk() when enabling the timing system clocks.

If enabling a clock fails, disable the clocks that were already enabled and propagate the error to the caller. In mt8195_afe_enable_main_clock(), return the error instead of continuing with AFE clock enable.

Fixes 6746cc858259 ("ASoC: mediatek: mt8195: add platform driver")
---
 sound/soc/mediatek/mt8195/mt8195-afe-clk.c | 15 ++++++++++++---
 1 file changed, 12 insertions(+), 3 deletions(-)
sound/soc/mediatek/mt8195/mt8195-afe-clk.c +12 -3
index 0b56a3335d501..dad7dddd9f521 100644
@@ -665,7 +665,7 @@ static int mt8195_afe_disable_afe_on(struct mtk_base_afe *afe)
 static int mt8195_afe_enable_timing_sys(struct mtk_base_afe *afe)
 {
 	struct mt8195_afe_private *afe_priv = afe->platform_priv;
-	int i;
+	int i, ret;
 	static const unsigned int clk_array[] = {
 		MT8195_CLK_AUD_A1SYS,
 		MT8195_CLK_AUD_A2SYS,
@@ -676,13 +676,22 @@ static int mt8195_afe_enable_timing_sys(struct mtk_base_afe *afe)
 		MT8195_TOP_CG_26M_TIMING,
 	};
 
-	for (i = 0; i < ARRAY_SIZE(clk_array); i++)
-		mt8195_afe_enable_clk(afe, afe_priv->clk[clk_array[i]]);
+	for (i = 0; i < ARRAY_SIZE(clk_array); i++) {
+		ret = mt8195_afe_enable_clk(afe, afe_priv->clk[clk_array[i]]);
+		if (ret)
+			goto err_disable_clk;
+	}
 
 	for (i = 0; i < ARRAY_SIZE(cg_array); i++)
 		mt8195_afe_enable_top_cg(afe, cg_array[i]);
 
 	return 0;
+
+err_disable_clk:
+	while (--i >= 0)
+		mt8195_afe_disable_clk(afe, afe_priv->clk[clk_array[i]]);
+
+	return ret;
 }
 
 static int mt8195_afe_disable_timing_sys(struct mtk_base_afe *afe)
Signature · 1 line
2.53.0
author maintainer
#2016 lore raw

PATCH 1996/2651 ASoC: mediatek: mt8195: Fix main clock error handling

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit 9f1b48c658ac38be81c04fbc29ed1522f89fb0c9 ]

Check the return values of clock enable functions and propagate errors to the caller.

Disable previously enabled clocks on failure to match the main clock disable sequence.

Fixes 6746cc858259 ("ASoC: mediatek: mt8195: add platform driver")
---
 sound/soc/mediatek/mt8195/mt8195-afe-clk.c | 23 +++++++++++++++++++---
 1 file changed, 20 insertions(+), 3 deletions(-)
sound/soc/mediatek/mt8195/mt8195-afe-clk.c +20 -3
index dad7dddd9f521..c6990a377af48 100644
@@ -719,14 +719,31 @@ static int mt8195_afe_disable_timing_sys(struct mtk_base_afe *afe)
 
 int mt8195_afe_enable_main_clock(struct mtk_base_afe *afe)
 {
-	mt8195_afe_enable_timing_sys(afe);
+	int ret;
+
+	ret = mt8195_afe_enable_timing_sys(afe);
+	if (ret)
+		return ret;
 
 	mt8195_afe_enable_afe_on(afe);
 
-	mt8195_afe_enable_apll_tuner(afe, MT8195_AUD_PLL1);
-	mt8195_afe_enable_apll_tuner(afe, MT8195_AUD_PLL2);
+	ret = mt8195_afe_enable_apll_tuner(afe, MT8195_AUD_PLL1);
+	if (ret)
+		goto err_disable_afe_on;
+
+	ret = mt8195_afe_enable_apll_tuner(afe, MT8195_AUD_PLL2);
+	if (ret)
+		goto err_disable_apll1_tuner;
 
 	return 0;
+
+err_disable_apll1_tuner:
+	mt8195_afe_disable_apll_tuner(afe, MT8195_AUD_PLL1);
+err_disable_afe_on:
+	mt8195_afe_disable_afe_on(afe);
+	mt8195_afe_disable_timing_sys(afe);
+
+	return ret;
 }
 
 int mt8195_afe_disable_main_clock(struct mtk_base_afe *afe)
Signature · 1 line
2.53.0
author maintainer
#2017 lore raw

PATCH 1997/2651 ASoC: mediatek: mt8195: Fix paired memif clock error handling

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit c0ec135cf3fd7c7c7cdefd234111e5d4f069a7e6 ]

Check and propagate errors when preparing and enabling the paired DL8/DL10 memif clocks.

If enabling the second clock fails, undo the clock that was already prepared or enabled to keep the clock state balanced.

Fixes 6746cc858259 ("ASoC: mediatek: mt8195: add platform driver")
---
 sound/soc/mediatek/mt8195/mt8195-afe-pcm.c | 24 ++++++++++++++++++----
 1 file changed, 20 insertions(+), 4 deletions(-)
sound/soc/mediatek/mt8195/mt8195-afe-pcm.c +20 -4
index bc0a63457cd75..889f2df71fd3b 100644
@@ -286,15 +286,23 @@ mt8195_afe_paired_memif_clk_prepare(struct snd_pcm_substream *substream,
 	struct mt8195_afe_private *afe_priv = afe->platform_priv;
 	int id = snd_soc_rtd_to_cpu(rtd, 0)->id;
 	int clk_id;
+	int ret;
 
 	if (id != MT8195_AFE_MEMIF_DL8 && id != MT8195_AFE_MEMIF_DL10)
 		return 0;
 
 	if (enable) {
 		clk_id = MT8195_CLK_AUD_MEMIF_DL10;
-		mt8195_afe_prepare_clk(afe, afe_priv->clk[clk_id]);
+		ret = mt8195_afe_prepare_clk(afe, afe_priv->clk[clk_id]);
+		if (ret)
+			return ret;
 		clk_id = MT8195_CLK_AUD_MEMIF_DL8;
-		mt8195_afe_prepare_clk(afe, afe_priv->clk[clk_id]);
+		ret = mt8195_afe_prepare_clk(afe, afe_priv->clk[clk_id]);
+		if (ret) {
+			clk_id = MT8195_CLK_AUD_MEMIF_DL10;
+			mt8195_afe_unprepare_clk(afe, afe_priv->clk[clk_id]);
+			return ret;
+		}
 	} else {
 		clk_id = MT8195_CLK_AUD_MEMIF_DL8;
 		mt8195_afe_unprepare_clk(afe, afe_priv->clk[clk_id]);
@@ -315,6 +323,7 @@ mt8195_afe_paired_memif_clk_enable(struct snd_pcm_substream *substream,
 	struct mt8195_afe_private *afe_priv = afe->platform_priv;
 	int id = snd_soc_rtd_to_cpu(rtd, 0)->id;
 	int clk_id;
+	int ret;
 
 	if (id != MT8195_AFE_MEMIF_DL8 && id != MT8195_AFE_MEMIF_DL10)
 		return 0;
@@ -322,11 +331,18 @@ mt8195_afe_paired_memif_clk_enable(struct snd_pcm_substream *substream,
 	if (enable) {
 		/* DL8_DL10_MEM */
 		clk_id = MT8195_CLK_AUD_MEMIF_DL10;
-		mt8195_afe_enable_clk_atomic(afe, afe_priv->clk[clk_id]);
+		ret = mt8195_afe_enable_clk_atomic(afe, afe_priv->clk[clk_id]);
+		if (ret)
+			return ret;
 		udelay(1);
 		/* DL8_DL10_AGENT */
 		clk_id = MT8195_CLK_AUD_MEMIF_DL8;
-		mt8195_afe_enable_clk_atomic(afe, afe_priv->clk[clk_id]);
+		ret = mt8195_afe_enable_clk_atomic(afe, afe_priv->clk[clk_id]);
+		if (ret) {
+			clk_id = MT8195_CLK_AUD_MEMIF_DL10;
+			mt8195_afe_disable_clk_atomic(afe, afe_priv->clk[clk_id]);
+			return ret;
+		}
 	} else {
 		/* DL8_DL10_AGENT */
 		clk_id = MT8195_CLK_AUD_MEMIF_DL8;
Signature · 1 line
2.53.0
author maintainer
#2018 lore raw

PATCH 1998/2651 ASoC: mediatek: mt8195: Fix FE startup error handling

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit b1db7408c8e0761d17b49b74f8f2d60c0c1929e8 ]

Check and propagate errors from paired memif clock preparation and PCM hardware constraints during FE startup.

Unprepare the paired memif clocks and shut down the FE when a later startup step fails to avoid leaving resources enabled on error.

Fixes 6746cc858259 ("ASoC: mediatek: mt8195: add platform driver")
---
 sound/soc/mediatek/mt8195/mt8195-afe-pcm.c | 40 +++++++++++++++-------
 1 file changed, 27 insertions(+), 13 deletions(-)
sound/soc/mediatek/mt8195/mt8195-afe-pcm.c +27 -13
index 889f2df71fd3b..b3e01d2839765 100644
@@ -364,24 +364,38 @@ static int mt8195_afe_fe_startup(struct snd_pcm_substream *substream,
 	int id = snd_soc_rtd_to_cpu(rtd, 0)->id;
 	int ret = 0;
 
-	mt8195_afe_paired_memif_clk_prepare(substream, dai, 1);
+	ret = mt8195_afe_paired_memif_clk_prepare(substream, dai, 1);
+	if (ret)
+		return ret;
 
 	ret = mtk_afe_fe_startup(substream, dai);
+	if (ret < 0)
+		goto err_clk_unprepare;
 
-	snd_pcm_hw_constraint_step(runtime, 0,
-				   SNDRV_PCM_HW_PARAM_BUFFER_BYTES,
-				   MT8195_MEMIF_BUFFER_BYTES_ALIGN);
+	ret = snd_pcm_hw_constraint_step(runtime, 0,
+					 SNDRV_PCM_HW_PARAM_BUFFER_BYTES,
+					 MT8195_MEMIF_BUFFER_BYTES_ALIGN);
+	if (ret)
+		goto err_fe_shutdow;
+
+	if (id == MT8195_AFE_MEMIF_DL7) {
+		ret = snd_pcm_hw_constraint_minmax(runtime,
+						   SNDRV_PCM_HW_PARAM_PERIOD_SIZE,
+						   1,
+						   MT8195_MEMIF_DL7_MAX_PERIOD_SIZE);
+		if (ret < 0) {
+			dev_dbg(afe->dev, "hw_constraint_minmax failed\n");
+			goto err_fe_shutdow;
+		}
+	}
 
-	if (id != MT8195_AFE_MEMIF_DL7)
-		goto out;
+	return 0;
+
+err_fe_shutdow:
+	mtk_afe_fe_shutdown(substream, dai);
+err_clk_unprepare:
+	mt8195_afe_paired_memif_clk_prepare(substream, dai, 0);
 
-	ret = snd_pcm_hw_constraint_minmax(runtime,
-					   SNDRV_PCM_HW_PARAM_PERIOD_SIZE,
-					   1,
-					   MT8195_MEMIF_DL7_MAX_PERIOD_SIZE);
-	if (ret < 0)
-		dev_dbg(afe->dev, "hw_constraint_minmax failed\n");
-out:
 	return ret;
 }
 
Signature · 1 line
2.53.0
author maintainer
#2019 lore raw

PATCH 1999/2651 ASoC: mediatek: mt8195: Check paired MEMIF clock enable in FE trigger

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit a2ae972c75a18ecbdcbf331ddaab21e1a08333fb ]

Check the return value of mt8195_afe_paired_memif_clk_enable() on START/RESUME. On failure, stop the MEMIF and disable the channel merge before returning the error.

Also skip enabling the paired clock if mtk_afe_fe_trigger() fails.

Fixes 6746cc858259 ("ASoC: mediatek: mt8195: add platform driver")
---
 sound/soc/mediatek/mt8195/mt8195-afe-pcm.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)
sound/soc/mediatek/mt8195/mt8195-afe-pcm.c +8 -1
index b3e01d2839765..9e6d1a2a9e7e0 100644
@@ -466,7 +466,14 @@ static int mt8195_afe_fe_trigger(struct snd_pcm_substream *substream, int cmd,
 	switch (cmd) {
 	case SNDRV_PCM_TRIGGER_START:
 	case SNDRV_PCM_TRIGGER_RESUME:
-		mt8195_afe_paired_memif_clk_enable(substream, dai, 1);
+		if (ret)
+			break;
+
+		ret = mt8195_afe_paired_memif_clk_enable(substream, dai, 1);
+		if (ret) {
+			mtk_afe_fe_trigger(substream, SNDRV_PCM_TRIGGER_STOP, dai);
+			mt8195_afe_enable_cm(afe, cm, false);
+		}
 		break;
 	case SNDRV_PCM_TRIGGER_STOP:
 	case SNDRV_PCM_TRIGGER_SUSPEND:
Signature · 1 line
2.53.0
author maintainer
#2020 lore raw

PATCH 2000/2651 ASoC: mediatek: mt8195: Fix runtime resume error handling

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit 933fbfb6648850e003a1fc47b7bcc08fe3687961 ]

Check and propagate errors when enabling the register access and main clocks during runtime resume.

If regcache_sync() or main clock enable fails, restore regmap cache-only mode and disable the register access clocks before returning the error.

Fixes 6746cc858259 ("ASoC: mediatek: mt8195: add platform driver")
---
 sound/soc/mediatek/mt8195/mt8195-afe-pcm.c | 23 +++++++++++++++++-----
 1 file changed, 18 insertions(+), 5 deletions(-)
sound/soc/mediatek/mt8195/mt8195-afe-pcm.c +18 -5
index 9e6d1a2a9e7e0..74999ea531bd2 100644
@@ -2965,18 +2965,31 @@ static int mt8195_afe_runtime_resume(struct device *dev)
 {
 	struct mtk_base_afe *afe = dev_get_drvdata(dev);
 	struct mt8195_afe_private *afe_priv = afe->platform_priv;
+	int ret;
 
-	mt8195_afe_enable_reg_rw_clk(afe);
+	ret = mt8195_afe_enable_reg_rw_clk(afe);
+	if (ret)
+		return ret;
 
 	if (!afe->regmap || afe_priv->pm_runtime_bypass_reg_ctl)
-		goto skip_regmap;
+		return 0;
 
 	regcache_cache_only(afe->regmap, false);
-	regcache_sync(afe->regmap);
+	ret = regcache_sync(afe->regmap);
+	if (ret)
+		goto err_restore_cache;
+
+	ret = mt8195_afe_enable_main_clock(afe);
+	if (ret)
+		goto err_restore_cache;
 
-	mt8195_afe_enable_main_clock(afe);
-skip_regmap:
 	return 0;
+
+err_restore_cache:
+	regcache_cache_only(afe->regmap, true);
+	mt8195_afe_disable_reg_rw_clk(afe);
+
+	return ret;
 }
 
 static int init_memif_priv_data(struct mtk_base_afe *afe)
Signature · 1 line
2.53.0
author maintainer
#2021 lore raw

PATCH 2001/2651 ASoC: mediatek: mt8195: Propagate IRQ lookup errors

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit 9d5dedb285fb61a40e04f337d9e06fc59c065857 ]

Propagate the error returned by platform_get_irq() instead of replacing it with -ENXIO.

This preserves errors such as -EPROBE_DEFER for proper handling by the caller.

Fixes 6746cc858259 ("ASoC: mediatek: mt8195: add platform driver")
---
 sound/soc/mediatek/mt8195/mt8195-afe-pcm.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
sound/soc/mediatek/mt8195/mt8195-afe-pcm.c +1 -1
index 74999ea531bd2..8e38c50a8bd44 100644
@@ -3132,7 +3132,7 @@ static int mt8195_afe_pcm_dev_probe(struct platform_device *pdev)
 	/* request irq */
 	irq_id = platform_get_irq(pdev, 0);
 	if (irq_id < 0)
-		return -ENXIO;
+		return irq_id;
 
 	ret = devm_request_irq(dev, irq_id, mt8195_afe_irq_handler,
 			       IRQF_TRIGGER_NONE, "asys-isr", (void *)afe);
Signature · 1 line
2.53.0
author maintainer
#2022 lore raw

PATCH 2002/2651 ASoC: mediatek: mt8195: Fix ETDM MCLK error handling

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit 91dce9c7eec25e95b5ca32e17e60e2c27333d411 ]

Propagate errors from mt8195_afe_enable_clk() when enabling the ETDM MCLK instead of always returning success.

This allows callers to properly handle failures when enabling the MCLK.

Fixes 1de9a54acafb ("ASoC: mediatek: mt8195: support etdm in platform driver")
---
 sound/soc/mediatek/mt8195/mt8195-dai-etdm.c | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)
sound/soc/mediatek/mt8195/mt8195-dai-etdm.c +1 -3
index 1a20adb2cbf53..fba51c552eecd 100644
@@ -1549,9 +1549,7 @@ static int mtk_dai_etdm_enable_mclk(struct mtk_base_afe *afe, int dai_id)
 	if (clkdiv_id < 0)
 		return -EINVAL;
 
-	mt8195_afe_enable_clk(afe, afe_priv->clk[clkdiv_id]);
-
-	return 0;
+	return mt8195_afe_enable_clk(afe, afe_priv->clk[clkdiv_id]);
 }
 
 static int mtk_dai_etdm_disable_mclk(struct mtk_base_afe *afe, int dai_id)
Signature · 1 line
2.53.0
author maintainer
#2023 lore raw

PATCH 2003/2651 ASoC: mediatek: mt8195: Fix ETDM startup error handling

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit 8e67c67f3fd2505b8b7a9dd38d8dabe47273490d ]

Check and propagate errors when enabling the ETDM MCLK and clock gates during startup.

If enabling a clock fails, disable the clocks that were already enabled to keep the clock state balanced.

Fixes 1de9a54acafb ("ASoC: mediatek: mt8195: support etdm in platform driver")
---
 sound/soc/mediatek/mt8195/mt8195-dai-etdm.c | 50 ++++++++++++++++-----
 1 file changed, 40 insertions(+), 10 deletions(-)
sound/soc/mediatek/mt8195/mt8195-dai-etdm.c +40 -10
index fba51c552eecd..1270fcac6b3f4 100644
@@ -1575,36 +1575,66 @@ static int mtk_dai_etdm_startup(struct snd_pcm_substream *substream,
 	int cg_id;
 	int mst_dai_id;
 	int slv_dai_id;
-	int i;
+	int i, ret;
 
 	if (is_cowork_mode(dai)) {
 		mst_dai_id = get_etdm_cowork_master_id(dai);
 		if (!mt8195_afe_etdm_is_valid(mst_dai_id))
 			return -EINVAL;
 
-		mtk_dai_etdm_enable_mclk(afe, mst_dai_id);
+		ret = mtk_dai_etdm_enable_mclk(afe, mst_dai_id);
+		if (ret)
+			return ret;
 		cg_id = mtk_dai_etdm_get_cg_id_by_dai_id(mst_dai_id);
-		if (cg_id >= 0)
-			mt8195_afe_enable_clk(afe, afe_priv->clk[cg_id]);
+		if (cg_id >= 0) {
+			ret = mt8195_afe_enable_clk(afe, afe_priv->clk[cg_id]);
+			if (ret)
+				goto err_disable_mclk;
+		}
 
 		mst_etdm_data = afe_priv->dai_priv[mst_dai_id];
 
 		for (i = 0; i < mst_etdm_data->cowork_slv_count; i++) {
 			slv_dai_id = mst_etdm_data->cowork_slv_id[i];
 			cg_id = mtk_dai_etdm_get_cg_id_by_dai_id(slv_dai_id);
-			if (cg_id >= 0)
-				mt8195_afe_enable_clk(afe,
-						      afe_priv->clk[cg_id]);
+			if (cg_id >= 0) {
+				ret = mt8195_afe_enable_clk(afe,
+							    afe_priv->clk[cg_id]);
+				if (ret)
+					goto err_disable_slv_clk;
+			}
 		}
 	} else {
-		mtk_dai_etdm_enable_mclk(afe, dai->id);
+		ret = mtk_dai_etdm_enable_mclk(afe, dai->id);
+		if (ret)
+			return ret;
 
 		cg_id = mtk_dai_etdm_get_cg_id_by_dai_id(dai->id);
-		if (cg_id >= 0)
-			mt8195_afe_enable_clk(afe, afe_priv->clk[cg_id]);
+		if (cg_id >= 0) {
+			ret = mt8195_afe_enable_clk(afe, afe_priv->clk[cg_id]);
+			if (ret)
+				goto err_disable_mclk;
+		}
 	}
 
 	return 0;
+
+err_disable_slv_clk:
+	while (--i >= 0) {
+		slv_dai_id = mst_etdm_data->cowork_slv_id[i];
+		cg_id = mtk_dai_etdm_get_cg_id_by_dai_id(slv_dai_id);
+		if (cg_id >= 0)
+			mt8195_afe_disable_clk(afe, afe_priv->clk[cg_id]);
+	}
+
+	cg_id = mtk_dai_etdm_get_cg_id_by_dai_id(mst_dai_id);
+	if (cg_id >= 0)
+		mt8195_afe_disable_clk(afe, afe_priv->clk[cg_id]);
+
+err_disable_mclk:
+	mtk_dai_etdm_disable_mclk(afe, is_cowork_mode(dai) ? mst_dai_id : dai->id);
+
+	return ret;
 }
 
 static void mtk_dai_etdm_shutdown(struct snd_pcm_substream *substream,
Signature · 1 line
2.53.0
author maintainer
#2024 lore raw

PATCH 2004/2651 ASoC: mediatek: mt8195: Fix HDMI TX startup error handling

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit 1d6f1785d90334b66809a57ebfc40a5b1cfa80ec ]

Check and propagate errors when enabling the clock gate and MCLK during HDMI TX/DP TX startup.

If MCLK enabling fails, disable the clock gate that was already enabled before returning the error.

Fixes 1de9a54acafb ("ASoC: mediatek: mt8195: support etdm in platform driver")
---
 sound/soc/mediatek/mt8195/mt8195-dai-etdm.c | 18 +++++++++++++++---
 1 file changed, 15 insertions(+), 3 deletions(-)
sound/soc/mediatek/mt8195/mt8195-dai-etdm.c +15 -3
index 1270fcac6b3f4..11317cdd14abc 100644
@@ -2321,13 +2321,25 @@ static int mtk_dai_hdmitx_dptx_startup(struct snd_pcm_substream *substream,
 	struct mtk_base_afe *afe = snd_soc_dai_get_drvdata(dai);
 	struct mt8195_afe_private *afe_priv = afe->platform_priv;
 	int cg_id = mtk_dai_etdm_get_cg_id_by_dai_id(dai->id);
+	int ret;
 
-	if (cg_id >= 0)
-		mt8195_afe_enable_clk(afe, afe_priv->clk[cg_id]);
+	if (cg_id >= 0) {
+		ret = mt8195_afe_enable_clk(afe, afe_priv->clk[cg_id]);
+		if (ret)
+			return ret;
+	}
 
-	mtk_dai_etdm_enable_mclk(afe, dai->id);
+	ret = mtk_dai_etdm_enable_mclk(afe, dai->id);
+	if (ret)
+		goto err_disable_cg_clk;
 
 	return 0;
+
+err_disable_cg_clk:
+	if (cg_id >= 0)
+		mt8195_afe_disable_clk(afe, afe_priv->clk[cg_id]);
+
+	return ret;
 }
 
 static void mtk_dai_hdmitx_dptx_shutdown(struct snd_pcm_substream *substream,
Signature · 1 line
2.53.0
author maintainer
#2025 lore raw

PATCH 2005/2651 ASoC: mediatek: mt8195: Fix ETDM probe error handling

In reply to Greg Kroah-Hartman

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

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

From: bui duc phuc <[email protected]>

[ Upstream commit ca3ac9a7eec1884bfff2d2dd92caf30f86a9eea7 ]

Use pm_runtime_resume_and_get() to properly handle runtime PM errors during ETDM probe.

Propagate errors from MCLK configuration and enabling instead of ignoring them.

Fixes 1de9a54acafb ("ASoC: mediatek: mt8195: support etdm in platform driver")
---
 sound/soc/mediatek/mt8195/mt8195-dai-etdm.c | 27 ++++++++++++++-------
 1 file changed, 18 insertions(+), 9 deletions(-)
sound/soc/mediatek/mt8195/mt8195-dai-etdm.c +18 -9
index 11317cdd14abc..8fa830a575029 100644
@@ -2503,6 +2503,7 @@ static int mtk_dai_etdm_probe(struct snd_soc_dai *dai)
 	struct mtk_base_afe *afe = snd_soc_dai_get_drvdata(dai);
 	struct mt8195_afe_private *afe_priv = afe->platform_priv;
 	struct mtk_dai_etdm_priv *etdm_data;
+	int ret;
 
 	dev_dbg(dai->dev, "%s id %d\n", __func__, dai->id);
 
@@ -2510,15 +2511,23 @@ static int mtk_dai_etdm_probe(struct snd_soc_dai *dai)
 		return -EINVAL;
 
 	etdm_data = afe_priv->dai_priv[dai->id];
-	if (etdm_data->mclk_freq) {
-		dev_dbg(afe->dev, "MCLK always on, rate %d\n",
-			etdm_data->mclk_freq);
-		pm_runtime_get_sync(afe->dev);
-		mtk_dai_etdm_mclk_configure(afe, dai->id);
-		mtk_dai_etdm_enable_mclk(afe, dai->id);
-		pm_runtime_put_sync(afe->dev);
-	}
-	return 0;
+	if (!etdm_data->mclk_freq)
+		return 0;
+
+	dev_dbg(afe->dev, "MCLK always on, rate %d\n",
+		etdm_data->mclk_freq);
+	ret = pm_runtime_resume_and_get(afe->dev);
+	if (ret)
+		return ret;
+	ret = mtk_dai_etdm_mclk_configure(afe, dai->id);
+	if (ret)
+		goto err_put_pm;
+	ret = mtk_dai_etdm_enable_mclk(afe, dai->id);
+
+err_put_pm:
+	pm_runtime_put_sync(afe->dev);
+
+	return ret;
 }
 
 static const struct snd_soc_dai_ops mtk_dai_hdmitx_dptx_ops = {
Signature · 1 line
2.53.0
author maintainer
#2026 lore raw

PATCH 2006/2651 tracing: Print the bucket size as unsigned

In reply to Greg Kroah-Hartman

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

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

From: Donggeun Yoo <[email protected]>

[ Upstream commit 387945e8d2f29fa8a28d219af5416e6d3bedc314 ]

A key's bucket size reads back negative once it exceeds LONG_MAX:

  # echo 'hist:keys=next_pid.buckets=18446744073709551615' > trigger
  # cat trigger
  hist:keys=next_pid.buckets=-1:vals=hitcount:...

parse_field() takes the size with kstrtoul() and rejects only zero, so the whole unsigned long range is accepted and stored, but hist_field_print() renders it with %ld.

Print it with %lu.

Fixes de9a48a360b7 ("tracing: Add linear buckets to histogram logic")
Assisted-by Claude:claude-fable-5
---
 kernel/trace/trace_events_hist.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/trace/trace_events_hist.c +1 -1
index 3915159b12360..1cd3d0552db83 100644
@@ -6208,7 +6208,7 @@ static void hist_field_print(struct seq_file *m, struct hist_field *hist_field)
 		}
 	}
 	if (hist_field->buckets)
-		seq_printf(m, "=%ld", hist_field->buckets);
+		seq_printf(m, "=%lu", hist_field->buckets);
 }
 
 static int event_hist_trigger_print(struct seq_file *m,
Signature · 1 line
2.53.0
author maintainer
#2027 lore raw

PATCH 2007/2651 tracing: Only report the stacktrace modifier on a real field

In reply to Greg Kroah-Hartman

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

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

From: Donggeun Yoo <[email protected]>

[ Upstream commit 18bb005845b78e0c0eb44b7f231c29d138552438 ]

get_hist_field_flags() returns "stacktrace" for any field carrying HIST_FIELD_FL_STACKTRACE, including the common_stacktrace pseudo-field, which has no ftrace_event_field behind it. parse_field() no longer takes the modifier there:

	if (stack_modifier &&
	    (!field || field->filter_type != FILTER_STACKTRACE)) {
		hist_err(tr, HIST_ERR_BAD_FIELD_MODIFIER, errpos(field_str));

so expr_field_str() renders "common_stacktrace.stacktrace", a spelling that cannot be parsed back.

Report the modifier only when there is a field to report it for.

hist_field_print(), the other caller of get_hist_field_flags(), excludes HIST_FIELD_FL_STACKTRACE before it calls, so this is confined to expr_field_str(), whose only key renderer arrives in the next patch.

Fixes a5e70ba87ca8 ("tracing: Fix memory corruption from the histogram stacktrace modifier")
Assisted-by Claude:claude-fable-5
---
 kernel/trace/trace_events_hist.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/trace/trace_events_hist.c +1 -1
index 1cd3d0552db83..64d89f5fb9d93 100644
@@ -1725,7 +1725,7 @@ static const char *get_hist_field_flags(struct hist_field *hist_field)
 		flags_str = "percent";
 	else if (hist_field->flags & HIST_FIELD_FL_GRAPH)
 		flags_str = "graph";
-	else if (hist_field->flags & HIST_FIELD_FL_STACKTRACE)
+	else if (hist_field->flags & HIST_FIELD_FL_STACKTRACE && hist_field->field)
 		flags_str = "stacktrace";
 
 	return flags_str;
Signature · 1 line
2.53.0
author maintainer
#2028 lore raw

PATCH 2008/2651 tracing: Clamp the printed end of a histogram bucket at U64_MAX

In reply to Greg Kroah-Hartman

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

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

From: Donggeun Yoo <[email protected]>

[ Upstream commit 289e2a775de434ccab2d107076bc78362ce288bd ]

A key with the ".buckets=N" modifier is stored as the start of its bucket, and hist_trigger_print_key() prints the range it covers as start to start + N - 1. That addition overflows once the start is within N of U64_MAX:

  # echo 'hist:keys=offset.buckets=10' >> \
      events/syscalls/sys_enter_lseek/trigger
  # ./seeker 5 -1                      # lseek(0, 5) and lseek(0, -1)
  # cat events/syscalls/sys_enter_lseek/hist
  ...
  { offset: ~ 18446744073709551610-3 } hitcount:          1
  { offset: ~ 0-9 } hitcount:          1
  ...

18446744073709551610 + 10 - 1 does not fit in 64 bits, so the range ends below where it starts.

The bucket does end at U64_MAX: it holds every value hist_field_bucket() maps onto its start, and there is no value above U64_MAX. Clamp the printed end there. Printed honestly the group is shorter than the size asked for, which histogram.rst does not mention, so say it there.

Fixes de9a48a360b7 ("tracing: Add linear buckets to histogram logic")
Assisted-by Claude:claude-fable-5
---
 Documentation/trace/histogram.rst | 3 +++
 kernel/trace/trace_events_hist.c  | 7 ++++++-
 2 files changed, 9 insertions(+), 1 deletion(-)
Documentation/trace/histogram.rst +3 -0
index 340bcb5099e7a..97b67f05f5eae 100644
@@ -1943,6 +1943,9 @@ the ".buckets" modifier and specify a size (in this case groups of 10)::
       Entries: 16
       Dropped: 0
 
+Keys are 64-bit, so the group holding the largest values is truncated where
+that range ends and can be smaller than the size asked for.
+
 To save stacktraces, create a synthetic event with a field of type "unsigned long[]"
 or even just "long[]". For example, to see how long a task is blocked in an
 uninterruptible state::
kernel/trace/trace_events_hist.c +6 -1
index 64d89f5fb9d93..3cda5d3131b18 100644
@@ -5568,9 +5568,14 @@ static void hist_trigger_print_key(struct seq_file *m,
 				   *(u64 *)(key + key_field->offset));
 		} else if (key_field->flags & HIST_FIELD_FL_BUCKET) {
 			unsigned long buckets = key_field->buckets;
+			u64 end;
+
 			uval = *(u64 *)(key + key_field->offset);
+			end = uval + buckets - 1;
+			if (end < uval)
+				end = U64_MAX;
 			seq_printf(m, "%s: ~ %llu-%llu", field_name,
-				   uval, uval + buckets -1);
+				   uval, end);
 		} else if (key_field->flags & HIST_FIELD_FL_STRING) {
 			seq_printf(m, "%s: %-50s", field_name,
 				   (char *)(key + key_field->offset));
Signature · 1 line
2.53.0
author maintainer
#2029 lore raw

PATCH 2009/2651 tracing: Avoid BTF lookup in atomic context

In reply to Greg Kroah-Hartman

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

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

From: pengdonglin <[email protected]>

[ Upstream commit 42643ba35deb8ad1821acfc0577b445ee7ad7548 ]

The function graph trace formatter can be called from ftrace_dump_one() with interrupts disabled. When ftrace_dump_on_oops is enabled, the trace panic notifier can reach ftrace_dump() from the panic path, including the nmi_panic() path used by the hard lockup detector.

btf_find_func_proto() calls bpf_find_btf_id(), which may initialize vmlinux BTF under a mutex. Skip the BTF lookup when running in an atomic context or with interrupts disabled, and fall back to the existing return value formatting.

Fixes ebeed8d4a555 ("tracing/probes: Move finding func-proto API and getting func-param API to trace_btf")
---
 kernel/trace/trace_btf.c | 3 +++
 1 file changed, 3 insertions(+)
kernel/trace/trace_btf.c +3 -0
index ee7a04886bf67..b8370ae9bd547 100644
@@ -15,6 +15,9 @@ const struct btf_type *btf_find_func_proto(const char *func_name, struct btf **b
 	const struct btf_type *t;
 	s32 id;
 
+	if (unlikely(in_atomic() || irqs_disabled()))
+		return NULL;
+
 	id = bpf_find_btf_id(func_name, BTF_KIND_FUNC, btf_p);
 	if (id < 0)
 		return NULL;
Signature · 1 line
2.53.0
author maintainer
#2030 lore raw

PATCH 2010/2651 f2fs: quota: fix quota flush failure during filesystem freeze

In reply to Greg Kroah-Hartman

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

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

From: Jianan Huang <[email protected]>

[ Upstream commit f6f8f34480c78eade6542faea6386c47c9b4c6b3 ]

Quota flush retries can be exhausted during filesystem freeze.

freeze_super() and the quota checkpoint may race as below.

freeze_super() f2fs_ckpt
- down_write(&sb->s_umount)
- sb->s_writers.frozen = SB_FREEZE_PAGEFAULT
- sync_filesystem()
- f2fs_sync_fs()
- f2fs_issue_checkpoint()
- queue CP_SYNC -----------------> - block_operations()
- down_read_trylock(s_umount) : fails; freeze holds write lock
- quota flush retries exhausted
- set CP_QUOTA_NEED_FSCK_FLAG

During the PAGEFAULT sync pass, freeze_super() holds s_umount for write, but umount_lock_holder is not set until f2fs_freeze(). Thus quota writeback tries to acquire s_umount again and can exhaust retries.

With checkpoint merge enabled, f2fs_issue_checkpoint() may dispatch CP_SYNC to f2fs_ckpt. That thread also cannot acquire the freeze lock.

Record current as umount_lock_holder around the VFS PAGEFAULT sync so checkpoint runs in the freeze caller and quota flush uses its existing s_umount write lock.

Fixes eb85c2410d6f ("f2fs: quota: fix to avoid warning in dquot_writeback_dquots()")
---
 fs/f2fs/super.c | 21 ++++++++++++++++++++-
 1 file changed, 20 insertions(+), 1 deletion(-)
fs/f2fs/super.c +20 -1
index 070a0bfdbb015..09bc78f2d0b58 100644
@@ -2154,6 +2154,25 @@ int f2fs_sync_fs(struct super_block *sb, int sync)
 	return err;
 }
 
+static int f2fs_sync_fs_super(struct super_block *sb, int sync)
+{
+	struct f2fs_sb_info *sbi = F2FS_SB(sb);
+	bool freeze_sync = sync &&
+			sb->s_writers.frozen == SB_FREEZE_PAGEFAULT;
+	int err;
+
+	/* freeze_super() holds s_umount for write during this sync pass. */
+	if (freeze_sync)
+		sbi->umount_lock_holder = current;
+
+	err = f2fs_sync_fs(sb, sync);
+
+	if (freeze_sync)
+		sbi->umount_lock_holder = NULL;
+
+	return err;
+}
+
 static int f2fs_freeze(struct super_block *sb)
 {
 	struct f2fs_sb_info *sbi = F2FS_SB(sb);
@@ -3776,7 +3795,7 @@ static const struct super_operations f2fs_sops = {
 #endif
 	.evict_inode	= f2fs_evict_inode,
 	.put_super	= f2fs_put_super,
-	.sync_fs	= f2fs_sync_fs,
+	.sync_fs	= f2fs_sync_fs_super,
 	.freeze_fs	= f2fs_freeze,
 	.unfreeze_fs	= f2fs_unfreeze,
 	.statfs		= f2fs_statfs,
Signature · 1 line
2.53.0
author maintainer
#2031 lore raw

PATCH 2011/2651 net/smc: hold a reference on net_device returned by pnet_find_base_ndev()

In reply to Greg Kroah-Hartman

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

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

From: Atharva Vartak <[email protected]>

[ Upstream commit e6435b2cc5fdf008cdb67ad9a811a266e8ac9c1e ]

pnet_find_base_ndev() resolves the base net_device for stacked devices under RTNL, then drops the lock and returns the raw pointer without taking a reference. All three callers dereference the pointer after RTNL has been released, creating a use-after-free window if the device is concurrently unregistered.

Take a reference with netdev_hold() before dropping RTNL and add the matching netdev_put() in every return path of the three callers:

- smc_pnet_add_eth()
- smc_pnet_find_roce_by_pnetid()
- smc_pnet_find_ism_by_pnetid()

Found by code analysis, confirmed with a proof-of-concept that triggers a KASAN slab-use-after-free report.

Fixes 0afff91c6f5e ("net/smc: add pnetid support")
Fixes 1619f770589a ("net/smc: add pnetid support for SMC-D and ISM")
Cc "D. Wythe" <[email protected]>
Cc Dust Li <[email protected]>
Cc Sidraya Jayagond <[email protected]>
Cc Mahanta Jambigi <[email protected]>
Cc Tony Lu <[email protected]>
Cc Wen Gu <[email protected]>
Cc Willy Tarreau <[email protected]>
---
 net/smc/smc_pnet.c | 29 ++++++++++++++++++++++-------
 1 file changed, 22 insertions(+), 7 deletions(-)
net/smc/smc_pnet.c +22 -7
index ff9c9c35cc2f5..61ef1d697eee4 100644
@@ -30,7 +30,8 @@
 #include "smc_core.h"
 
 static struct net_device *__pnet_find_base_ndev(struct net_device *ndev);
-static struct net_device *pnet_find_base_ndev(struct net_device *ndev);
+static struct net_device *pnet_find_base_ndev(struct net_device *ndev,
+					      netdevice_tracker *tracker);
 
 static const struct nla_policy smc_pnet_policy[SMC_PNETID_MAX + 1] = {
 	[SMC_PNETID_NAME] = {
@@ -356,6 +357,7 @@ static int smc_pnet_add_eth(struct smc_pnettable *pnettable, struct net *net,
 	struct smc_pnetentry *tmp_pe, *new_pe;
 	struct net_device *ndev, *base_ndev;
 	u8 ndev_pnetid[SMC_MAX_PNETID_LEN];
+	netdevice_tracker base_tracker;
 	bool new_netdev;
 	int rc;
 
@@ -365,10 +367,13 @@ static int smc_pnet_add_eth(struct smc_pnettable *pnettable, struct net *net,
 	rc = -EEXIST;
 	ndev = dev_get_by_name(net, eth_name);	/* dev_hold() */
 	if (ndev) {
-		base_ndev = pnet_find_base_ndev(ndev);
+		base_ndev = pnet_find_base_ndev(ndev, &base_tracker);
 		if (!smc_pnetid_by_dev_port(base_ndev->dev.parent,
-					    base_ndev->dev_port, ndev_pnetid))
+					    base_ndev->dev_port, ndev_pnetid)) {
+			netdev_put(base_ndev, &base_tracker);
 			goto out_put;
+		}
+		netdev_put(base_ndev, &base_tracker);
 	}
 
 	/* add a new netdev entry to the pnet table if there isn't one */
@@ -945,10 +950,13 @@ static struct net_device *__pnet_find_base_ndev(struct net_device *ndev)
  * (for instance with bonding slaves), just the first device
  * is used to reach a base device.
  */
-static struct net_device *pnet_find_base_ndev(struct net_device *ndev)
+static struct net_device *pnet_find_base_ndev(struct net_device *ndev,
+					      netdevice_tracker *tracker)
 {
 	rtnl_lock();
 	ndev = __pnet_find_base_ndev(ndev);
+	/* keep ndev alive after dropping RTNL, callers must netdev_put() */
+	netdev_hold(ndev, tracker, GFP_KERNEL);
 	rtnl_unlock();
 	return ndev;
 }
@@ -1085,17 +1093,20 @@ static void smc_pnet_find_roce_by_pnetid(struct net_device *ndev,
 {
 	u8 ndev_pnetid[SMC_MAX_PNETID_LEN];
 	struct net_device *base_ndev;
+	netdevice_tracker base_tracker;
 	struct net *net;
 
-	base_ndev = pnet_find_base_ndev(ndev);
+	base_ndev = pnet_find_base_ndev(ndev, &base_tracker);
 	net = dev_net(ndev);
 	if (smc_pnetid_by_dev_port(base_ndev->dev.parent, base_ndev->dev_port,
 				   ndev_pnetid) &&
 	    smc_pnet_find_ndev_pnetid_by_table(base_ndev, ndev_pnetid) &&
 	    smc_pnet_find_ndev_pnetid_by_table(ndev, ndev_pnetid)) {
 		smc_pnet_find_rdma_dev(base_ndev, ini);
+		netdev_put(base_ndev, &base_tracker);
 		return; /* pnetid could not be determined */
 	}
+	netdev_put(base_ndev, &base_tracker);
 	_smc_pnet_find_roce_by_pnetid(ndev_pnetid, ini, NULL, net);
 }
 
@@ -1103,13 +1114,16 @@ static void smc_pnet_find_ism_by_pnetid(struct net_device *ndev,
 					struct smc_init_info *ini)
 {
 	u8 ndev_pnetid[SMC_MAX_PNETID_LEN];
+	netdevice_tracker base_tracker;
 	struct smcd_dev *ismdev;
 
-	ndev = pnet_find_base_ndev(ndev);
+	ndev = pnet_find_base_ndev(ndev, &base_tracker);
 	if (smc_pnetid_by_dev_port(ndev->dev.parent, ndev->dev_port,
 				   ndev_pnetid) &&
-	    smc_pnet_find_ndev_pnetid_by_table(ndev, ndev_pnetid))
+	    smc_pnet_find_ndev_pnetid_by_table(ndev, ndev_pnetid)) {
+		netdev_put(ndev, &base_tracker);
 		return; /* pnetid could not be determined */
+	}
 
 	mutex_lock(&smcd_dev_list.mutex);
 	list_for_each_entry(ismdev, &smcd_dev_list.list, list) {
@@ -1123,6 +1137,7 @@ static void smc_pnet_find_ism_by_pnetid(struct net_device *ndev,
 		}
 	}
 	mutex_unlock(&smcd_dev_list.mutex);
+	netdev_put(ndev, &base_tracker);
 }
 
 /* PNET table analysis for a given sock:
Signature · 1 line
2.53.0
author maintainer
#2032 lore raw

PATCH 2012/2651 tracing: Print a signed histogram key as signed

In reply to Greg Kroah-Hartman

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

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

From: Donggeun Yoo <[email protected]>

[ Upstream commit d3e0dfc1ba49a0ab6aeddbb4bcde4bfc0e171a02 ]

A histogram sorts its rows by the key named in sort=, and for a key over a signed event field it sorts them signed: create_tracing_map_fields() picks the comparison function with

	else
		cmp_fn = tracing_map_cmp_num(field->size,
					     field->is_signed);

hist_trigger_print_key() does not look at is_signed at all. Every numeric key is printed with %llu, so a sorted histogram over a signed field comes out looking unsorted. syscalls/sys_exit_lseek carries "long ret", which SYSCALL_FIELD() marks signed and which is negative on every error:

  # echo 'hist:keys=ret:sort=ret' > events/syscalls/sys_exit_lseek/trigger
  # echo 1 > events/syscalls/sys_exit_lseek/enable
  # (five lseek(2) calls returning -ESPIPE, -EINVAL, -EBADF, 0 and 100)
  # cat events/syscalls/sys_exit_lseek/hist
  { ret: 18446744073709551587 } hitcount:          1
  { ret: 18446744073709551594 } hitcount:          1
  { ret: 18446744073709551607 } hitcount:          1

{ ret: 0 } hitcount: 1
{ ret: 100 } hitcount: 1

The rows are in ascending order and the numbers are not, because the three leading ones are -29, -22 and -9 rendered as their two's complement.

Take the rendering from the same place the sort order comes from: the event field when the key has one, and the hist_field itself when it does not. The same histogram then reads

  { ret:        -29 } hitcount:          1
  { ret:        -22 } hitcount:          1
  { ret:         -9 } hitcount:          1
  { ret:          0 } hitcount:          1
  { ret:        100 } hitcount:          1

A ".buckets" key stays unsigned here, and not because it is right. hist_field_bucket() divides as unsigned, so the group holding S64_MAX also holds S64_MIN, reported at

https://lore.kernel.org/all/[email protected]/

Printing that group signed would name a range that does not contain S64_MIN, so the grouping has to be fixed with it, in a patch of its own.

Fixes 7ef224d1d0e3 ("tracing: Add 'hist' event trigger command")
---
 kernel/trace/trace_events_hist.c | 14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)
kernel/trace/trace_events_hist.c +13 -1
index 3cda5d3131b18..642b354d23b0d 100644
@@ -279,6 +279,14 @@ static u64 hist_field_pstring(struct hist_field *hist_field,
 	return (u64)(unsigned long)*addr;
 }
 
+static bool hist_field_is_signed(struct hist_field *hist_field)
+{
+	if (hist_field->field)
+		return hist_field->field->is_signed;
+
+	return hist_field->is_signed;
+}
+
 static u64 hist_field_log2(struct hist_field *hist_field,
 			   struct tracing_map_elt *elt,
 			   struct trace_buffer *buffer,
@@ -5581,7 +5589,11 @@ static void hist_trigger_print_key(struct seq_file *m,
 				   (char *)(key + key_field->offset));
 		} else {
 			uval = *(u64 *)(key + key_field->offset);
-			seq_printf(m, "%s: %10llu", field_name, uval);
+			if (hist_field_is_signed(key_field))
+				seq_printf(m, "%s: %10lld", field_name,
+					   (s64)uval);
+			else
+				seq_printf(m, "%s: %10llu", field_name, uval);
 		}
 	}
 
Signature · 1 line
2.53.0
author maintainer
#2033 lore raw

PATCH 2013/2651 ublk: allow a NULL io->cmd in the cancel callback

In reply to Greg Kroah-Hartman

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

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

From: Ming Lei <[email protected]>

[ Upstream commit 4915dc0a1834457520ef0592bfd454b26901614f ]

A cancel from the control path, like STOP_DEV's ublk_cancel_dev() after dropping ub->mutex, takes the command and clears io->cmd under cancel_lock, then completes it with io_uring_cmd_done(), which takes uring_lock to remove it from the cancelable list. The server's io_uring cancel runs ublk_uring_cmd_cancel_fn() under uring_lock in between:

control path cancel io_uring cancel (uring_lock)
io->cmd = NULL, CANCELED
io_uring_cmd_done()
waits for uring_lock cmd still on the list
ublk_uring_cmd_cancel_fn(cmd)
io->cmd == NULL: WARN

ublk_cancel_cmd() then sees CANCELED and leaves the command alone, so nothing is wrong; only warn if io->cmd holds another command.

Fixes ab03a61c6614 ("ublk: have a per-io daemon instead of a per-queue daemon")
---
 drivers/block/ublk_drv.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/block/ublk_drv.c +4 -1
index ca4cb9d760353..d806c6104c74d 100644
@@ -2910,6 +2910,7 @@ static void ublk_uring_cmd_cancel_fn(struct io_uring_cmd *cmd,
 {
 	struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd);
 	struct ublk_queue *ubq = pdu->ubq;
+	struct io_uring_cmd *cur;
 	struct task_struct *task;
 	struct ublk_io *io;
 
@@ -2926,7 +2927,9 @@ static void ublk_uring_cmd_cancel_fn(struct io_uring_cmd *cmd,
 
 	ublk_start_cancel(ubq->dev);
 
-	WARN_ON_ONCE(io->cmd != cmd);
+	/* NULL if a cancel from the control path took it meanwhile */
+	cur = READ_ONCE(io->cmd);
+	WARN_ON_ONCE(cur && cur != cmd);
 	ublk_cancel_cmd(ubq, pdu->tag, issue_flags);
 }
 
Signature · 1 line
2.53.0
author maintainer
#2034 lore raw

PATCH 2014/2651 ublk: use global index for reported zones

In reply to Greg Kroah-Hartman

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

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

From: Li RongQing <[email protected]>

[ Upstream commit 80897c7e5ae5c56f37a2eb004328edcb4da7cdd1 ]

ublk_report_zones() may split a zone report into multiple requests when the number of zones exceeds the temporary buffer capacity. The index passed to disk_report_zone() must refer to the zone position in the whole report, rather than the position within the current request.

Currently, the per-request loop index is used as the callback index, causing each chunk after the first one to restart from zero. This can make userspace callbacks receive duplicate zone indices and may result in blk_revalidate_disk_zones() updating incorrect entries in its zone state array.

Use the number of zones already reported as the base index for each request so that zone indices remain continuous across all chunks.

---
 drivers/block/ublk_drv.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/block/ublk_drv.c +1 -1
index d806c6104c74d..cc4e72fd5d4df 100644
@@ -696,7 +696,7 @@ static int ublk_report_zones(struct gendisk *disk, sector_t sector,
 			if (!zone->len)
 				break;
 
-			ret = disk_report_zone(disk, zone, i, args);
+			ret = disk_report_zone(disk, zone, done_zones, args);
 			if (ret)
 				goto out;
 
Signature · 1 line
2.53.0
author maintainer
#2035 lore raw

PATCH 2015/2651 selftests/bpf: Fix prog_tests framework subtest count checks

In reply to Greg Kroah-Hartman

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

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

From: KaFai Wan <[email protected]>

[ Upstream commit c87652656a55e5e8cf994364314a75fa95fb2d69 ]

The hardcoded expected skip_cnt/error_cnt in test_prog_tests_framework() mismatch the real count when the binary is run with -t or -n filters, since some subtests are not selected. Count the executed subtests and compare against that value instead.

Fixes 2324257dbd68 ("selftests/bpf: Refactor prog_tests logging and test execution")
---
 .../selftests/bpf/prog_tests/prog_tests_framework.c    | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
tools/testing/selftests/bpf/prog_tests/prog_tests_framework.c +8 -2
index 7607cfc2408c2..1dc112e5b9719 100644
@@ -13,6 +13,7 @@ static void clear_test_state(struct test_state *state)
 void test_prog_tests_framework(void)
 {
 	struct test_state *state = env.test_state;
+	int subtest_cnt;
 
 	/* in all the ASSERT calls below we need to return on the first
 	 * error due to the fact that we are cleaning the test state after
@@ -30,25 +31,30 @@ void test_prog_tests_framework(void)
 		return;
 	clear_test_state(state);
 
+	subtest_cnt = 0;
 	if (test__start_subtest("test_skip_subtest")) {
 		test__skip();
 		test__end_subtest();
+		subtest_cnt++;
 	}
 	if (test__start_subtest("test_skip_subtest")) {
 		test__skip();
 		test__end_subtest();
+		subtest_cnt++;
 	}
-	if (!ASSERT_EQ(state->skip_cnt, 2, "skip_cnt_check"))
+	if (!ASSERT_EQ(state->skip_cnt, subtest_cnt, "skip_cnt_check"))
 		return;
 	if (!ASSERT_EQ(state->subtest_num, 3, "subtest_num_check"))
 		return;
 	clear_test_state(state);
 
+	subtest_cnt = 0;
 	if (test__start_subtest("test_fail_subtest")) {
 		test__fail();
 		test__end_subtest();
+		subtest_cnt++;
 	}
-	if (!ASSERT_EQ(state->error_cnt, 1, "error_cnt_check"))
+	if (!ASSERT_EQ(state->error_cnt, subtest_cnt, "error_cnt_check"))
 		return;
 	if (!ASSERT_EQ(state->subtest_num, 4, "subtest_num_check"))
 		return;
Signature · 1 line
2.53.0
author maintainer
#2036 lore raw

PATCH 2016/2651 selftests/bpf: Skip expected_msgs subtests when stdout is not saved

In reply to Greg Kroah-Hartman

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

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

From: KaFai Wan <[email protected]>

[ Upstream commit cc4b1c161d92992544cc571a2475baa5b072e120 ]

stdio_hijack_init() does not set subtest_state->stdout_saved when running with -v in non-parallel mode, since output goes straight to stdout. In that case subtest_state->log_buf is left NULL, so the expected-messages subtests crash when inspecting it. Skip them when stdout was not saved.

Fixes 34c513be3dad ("selftests/bpf: __not_msg() tag for test_loader framework")
---
 .../testing/selftests/bpf/prog_tests/prog_tests_framework.c | 6 ++++++
 1 file changed, 6 insertions(+)
tools/testing/selftests/bpf/prog_tests/prog_tests_framework.c +6 -0
index 1dc112e5b9719..274568abc052b 100644
@@ -169,6 +169,12 @@ void test_prog_tests_framework_expected_msgs(void)
 
 	for (i = 0; i < ARRAY_SIZE(cases); i++) {
 		if (test__start_subtest(cases[i].name)) {
+			if (!env.subtest_state->stdout_saved) {
+				test__skip();
+				test__end_subtest();
+				continue;
+			}
+
 			error_cnt = env.subtest_state->error_cnt;
 			msgs.patterns = cases[i].pats;
 			msgs.cnt = 0;
Signature · 1 line
2.53.0
author maintainer
#2037 lore raw

PATCH 2017/2651 bpf: Fix NULL task dereference in task work cancellation

In reply to Greg Kroah-Hartman

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

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

From: Yun Lu <[email protected]>

[ Upstream commit c961f7b41a108313a4705baac7b27d2174cc8035 ]

bpf_task_work_irq() publishes ctx->work with task_work_add() before changing the context from SCHEDULING to SCHEDULED. The target task can run the callback on another CPU before the handler reaches its final state transition.

The handler then reloads ctx->task for cancellation if its final cmpxchg observes FREED. By that point the callback or context destruction may already have cleared ctx->task, causing task_work_cancel() to dereference a NULL task pointer.

One concrete interleaving is:

1. CPU 0 changes PENDING to SCHEDULING and successfully queues

     ctx->work with task_work_add(), but has not attempted the final
     state cmpxchg.

2. The target task on CPU 1 runs the callback. It changes SCHEDULING to RUNNING, executes the BPF subprogram, resets ctx->task, publishes STANDBY and drops the callback's context reference.

3. CPU 2 deletes the map value. It changes STANDBY to FREED and drops the map's context reference without queuing asynchronous cancellation.

4. CPU 0 resumes. Its SCHEDULING-to-SCHEDULED cmpxchg observes FREED, and the cancellation attempt passes NULL to task_work_cancel().

If deletion publishes FREED before the callback claims RUNNING, the callback takes its FREED exit and drops its context reference. Context destruction can then clear ctx->task before CPU 0 attempts cancellation.

A controlled reproducer with a delay before the final cmpxchg triggered the following fault on a v7.3-rc3 based x86-64 KVM guest:

  BUG: kernel NULL pointer dereference, address: 0000000000000890
  RIP: 0010:task_work_cancel+0xd/0xa0
  RDI: 0000000000000000
  CR2: 0000000000000890
  Call Trace:
   <IRQ>
   bpf_task_work_irq+0x95/0x100
   irq_work_run_list+0x4f/0x90
   irq_work_run+0x18/0x50
   </IRQ>

0x890 is the task_struct::task_works offset in that build, read through the NULL task argument.

Capture ctx->task before task_work_add() publishes the callback and use that pointer for the handler's cancellation attempt. The round still holds its task reference when the pointer is captured. Releasing that reference uses bpf_task_release(), which calls put_task_struct_rcu_user(), so the handler's existing RCU read-side section keeps the captured task alive even if ctx->task is subsequently cleared.

The asynchronous cancellation path reads ctx->task directly, which is safe there: queuing it requires deletion to observe SCHEDULED, and that xchg wins against the callback's transition to RUNNING, so the callback takes its FREED exit without resetting ctx->task, while the map reference transferred to the cancellation handler prevents context destruction until cancellation completes.

The handler-tail and asynchronous cancellation attempts are mutually
exclusive: asynchronous cancellation is queued only if deletion observes SCHEDULED after the scheduling handler's final cmpxchg has succeeded. If that cmpxchg instead observes FREED, the scheduling handler attempts cancellation with the captured pointer.

---
 kernel/bpf/helpers.c | 40 +++++++++++++++++++++++++++++++---------
 1 file changed, 31 insertions(+), 9 deletions(-)
kernel/bpf/helpers.c +31 -9
index 712dca5a2c5bd..bd823e17ae696 100644
@@ -4437,15 +4437,21 @@ static void bpf_task_work_ctx_put(struct bpf_task_work_ctx *ctx)
 	}
 }
 
-static void bpf_task_work_cancel(struct bpf_task_work_ctx *ctx)
+static void bpf_task_work_cancel(struct bpf_task_work_ctx *ctx,
+				 struct task_struct *task)
 {
 	/*
 	 * Scheduled task_work callback holds ctx ref, so if we successfully
 	 * cancelled, we put that ref on callback's behalf. If we couldn't
 	 * cancel, callback will inevitably run or has already completed
 	 * running, and it would have taken care of its ctx ref itself.
+	 *
+	 * The caller passes the task explicitly: the scheduling handler must
+	 * not read ctx->task after the work is published (the callback may
+	 * have reset it), while in the asynchronous cancellation path
+	 * ctx->task is stable, see bpf_task_work_cancel_scheduled().
 	 */
-	if (task_work_cancel(ctx->task, &ctx->work))
+	if (task_work_cancel(task, &ctx->work))
 		bpf_task_work_ctx_put(ctx);
 }
 
@@ -4486,6 +4492,7 @@ static void bpf_task_work_callback(struct callback_head *cb)
 static void bpf_task_work_irq(struct irq_work *irq_work)
 {
 	struct bpf_task_work_ctx *ctx = container_of(irq_work, struct bpf_task_work_ctx, irq_work);
+	struct task_struct *task;
 	enum bpf_task_work_state state;
 	int err;
 
@@ -4496,7 +4503,16 @@ static void bpf_task_work_irq(struct irq_work *irq_work)
 		return;
 	}
 
-	err = task_work_add(ctx->task, &ctx->work, ctx->mode);
+	/*
+	 * Capture the task pointer before the work is published: once the
+	 * callback runs, it may reset ctx->task. The capture happens while
+	 * this round's task reference is held, and every path that can
+	 * release it runs after this handler entered its rcu read-side
+	 * section. bpf_task_release() is put_task_struct_rcu_user(), so the
+	 * task_struct itself cannot be freed before this section ends.
+	 */
+	task = ctx->task;
+	err = task_work_add(task, &ctx->work, ctx->mode);
 	if (err) {
 		bpf_task_work_ctx_reset(ctx);
 		/*
@@ -4510,14 +4526,14 @@ static void bpf_task_work_irq(struct irq_work *irq_work)
 
 	/*
 	 * It's technically possible for just scheduled task_work callback to
-	 * complete running by now, going SCHEDULING -> RUNNING and then
-	 * dropping its ctx refcount. Instead of capturing an extra ref just
-	 * to protect below ctx->state access, we rely on rcu_read_lock
-	 * above to prevent kfree_rcu from freeing ctx before we return.
+	 * complete running by now, going SCHEDULING -> RUNNING, resetting
+	 * ctx->task and dropping its ctx refcount. The rcu read-side section
+	 * above keeps both the ctx memory and the captured task pointer
+	 * valid until this handler returns.
 	 */
 	state = cmpxchg(&ctx->state, BPF_TW_SCHEDULING, BPF_TW_SCHEDULED);
 	if (state == BPF_TW_FREED)
-		bpf_task_work_cancel(ctx); /* clean up if we switched into FREED state */
+		bpf_task_work_cancel(ctx, task); /* clean up if we switched into FREED state */
 }
 
 static struct bpf_task_work_ctx *bpf_task_work_fetch_ctx(struct bpf_task_work *tw,
@@ -4777,7 +4793,13 @@ static void bpf_task_work_cancel_scheduled(struct irq_work *irq_work)
 {
 	struct bpf_task_work_ctx *ctx = container_of(irq_work, struct bpf_task_work_ctx, irq_work);
 
-	bpf_task_work_cancel(ctx); /* this might put task_work callback's ref */
+	/*
+	 * Deletion observed SCHEDULED and won against the callback's
+	 * transition to RUNNING. The callback takes its FREED exit without
+	 * resetting ctx->task, and the transferred map reference prevents
+	 * destruction until cancellation completes.
+	 */
+	bpf_task_work_cancel(ctx, ctx->task); /* this might put task_work callback's ref */
 	bpf_task_work_ctx_put(ctx); /* and here we put map's own ref that was transferred to us */
 }
 
Signature · 1 line
2.53.0
author maintainer
#2038 lore raw

PATCH 2018/2651 bpf: Prevent task work context reuse while irq_work is busy

In reply to Greg Kroah-Hartman

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

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

From: Yun Lu <[email protected]>

[ Upstream commit a36d9afe8d923ca00dd2001409f420202ee672da ]

A bpf_task_work context can return to STANDBY before its scheduling irq_work handler returns. Both callback completion and task_work_add() failure can publish STANDBY while the irq_work is still BUSY. A new round can then reinitialize and queue the same irq_work on another CPU while the old handler is still running.

One concrete interleaving is:

1. CPU 0 successfully queues ctx->work with task_work_add() and pauses before its SCHEDULING-to-SCHEDULED cmpxchg.

2. The target task on CPU 1 completes the callback, resets ctx->task and publishes STANDBY.

3. CPU 2 starts a new round, changes STANDBY to PENDING and queues the same irq_work. The new handler changes PENDING to SCHEDULING, but task_work_add() returns -ESRCH because its target task has exited. The handler has not yet reset the context or rolled back the state.

4. CPU 0 resumes and changes the new round's SCHEDULING to SCHEDULED, even though no task work was queued for that round.

5. The new handler resets ctx->task, but its SCHEDULING-to-STANDBY cmpxchg fails. The context remains SCHEDULED with a NULL task, and subsequent attempts to acquire this context fail with -EBUSY.

6. Map-value deletion observes SCHEDULED and queues asynchronous

     cancellation, which passes the NULL ctx->task to task_work_cancel().

Overlapping invocations also share one BUSY bit. An invocation can clear that bit while the other invocation is still running.

Initialize the scheduling irq_work when the context is created and stop reinitializing it for each round. After claiming the context with the STANDBY-to-PENDING cmpxchg, check BUSY and reject reuse with -EBUSY if a previous invocation is still in progress. Checking after the cmpxchg orders the BUSY read after the STANDBY publication.

No irq_work has been queued for the attempted round at this point, so the rejection can roll PENDING back to STANDBY. Use cmpxchg for that rollback to preserve FREED if a concurrent deletion has published it. Once BUSY clears, scheduling can be retried.

---
 kernel/bpf/helpers.c | 14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)
kernel/bpf/helpers.c +13 -1
index bd823e17ae696..2a5af794968b1 100644
@@ -4553,6 +4553,7 @@ static struct bpf_task_work_ctx *bpf_task_work_fetch_ctx(struct bpf_task_work *t
 	memset(ctx, 0, sizeof(*ctx));
 	refcount_set(&ctx->refcnt, 1); /* map's own ref */
 	ctx->state = BPF_TW_STANDBY;
+	init_irq_work(&ctx->irq_work, bpf_task_work_irq);
 
 	old_ctx = cmpxchg(&twk->ctx, NULL, ctx);
 	if (old_ctx) {
@@ -4595,6 +4596,18 @@ static struct bpf_task_work_ctx *bpf_task_work_acquire_ctx(struct bpf_task_work
 		bpf_task_work_ctx_put(ctx);
 		return ERR_PTR(-EBUSY);
 	}
+	/*
+	 * STANDBY can be published before the previous scheduling irq_work
+	 * returns. Claim PENDING before checking BUSY to order the check after
+	 * that publication. No irq_work has been queued for this attempt yet,
+	 * so reject reuse and roll back to STANDBY while BUSY is set. Preserve
+	 * FREED if deletion wins the rollback race.
+	 */
+	if (unlikely(irq_work_is_busy(&ctx->irq_work))) {
+		(void)cmpxchg(&ctx->state, BPF_TW_PENDING, BPF_TW_STANDBY);
+		bpf_task_work_ctx_put(ctx);
+		return ERR_PTR(-EBUSY);
+	}
 
 	/*
 	 * If no process or bpffs is holding a reference to the map, no new callbacks should be
@@ -4644,7 +4657,6 @@ static int bpf_task_work_schedule(struct task_struct *task, struct bpf_task_work
 	ctx->map = map;
 	ctx->map_val = (void *)tw - map->record->task_work_off;
 	init_task_work(&ctx->work, bpf_task_work_callback);
-	init_irq_work(&ctx->irq_work, bpf_task_work_irq);
 
 	irq_work_queue(&ctx->irq_work);
 	return 0;
Signature · 1 line
2.53.0
author maintainer
#2039 lore raw

PATCH 2019/2651 macsec: prevent AES-GCM nonce reuse after packet number wrap

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit 94d51c59f0a872c57cb8daa1964ec033d77a79fb ]

After allocating the last valid packet number, MACsec wraps next_pn to zero and deactivates the transmit SA. This happens for both 32- and 64-bit types of packet numbers (at values 0xffffffff and 0xffffffffffffffff, respectively).

TX packets that were still getting processed during deactivation keep being processed and then receive packet numbers. The first gets 0 and is correctly dropped, but next_pn is incremented to 1, which makes the next packet take number 1. It then does not get dropped and may induce a reuse of the AES-GCM nonce corresponding to value 1.

This race affects TX packets that have already passed the SA activity
check: packets that observe the inactive SA are correctly dropped. Reactivating the SA after PN wrap without a packet number can also cause nonce reuse. Keep next_pn at 0 after wrap, even if the SA is reactivated, so further packet number allocations return 0 and the corresponding packets are dropped.

Fixes c09440f7dcb3 ("macsec: introduce IEEE 802.1AE driver")
---
 drivers/net/macsec.c | 5 +++++
 1 file changed, 5 insertions(+)
drivers/net/macsec.c +5 -0
index 78a19b1346321..233391acebb0f 100644
@@ -486,6 +486,9 @@ static pn_t tx_sa_update_pn(struct macsec_tx_sa *tx_sa,
 	spin_lock_bh(&tx_sa->lock);
 
 	pn = tx_sa->next_pn_halves;
+	if (unlikely(pn.full64 == 0))
+		goto out;
+
 	if (secy->xpn)
 		tx_sa->next_pn++;
 	else
@@ -493,6 +496,8 @@ static pn_t tx_sa_update_pn(struct macsec_tx_sa *tx_sa,
 
 	if (tx_sa->next_pn == 0)
 		__macsec_pn_wrapped(secy, tx_sa);
+
+out:
 	spin_unlock_bh(&tx_sa->lock);
 
 	return pn;
Signature · 1 line
2.53.0
author maintainer
#2040 lore raw

PATCH 2020/2651 net: usb: lan78xx: reject invalid EEPROM write requests

In reply to Greg Kroah-Hartman

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

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

From: Stefano Munari <[email protected]>

[ Upstream commit 9272297df14124fe603c81e40b52ff0c5dd88652 ]

The runtime PM handling removed the -EINVAL return for invalid EEPROM/OTP write requests. These requests now return zero from a successful usb_autopm_get_interface() call, even though no data is written.

Set ret to -EINVAL for invalid requests while preserving the runtime PM reference release.

---
 drivers/net/usb/lan78xx.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
drivers/net/usb/lan78xx.c +6 -3
index 5655941f14783..2fed938fc7f41 100644
@@ -1712,13 +1712,16 @@ static int lan78xx_ethtool_set_eeprom(struct net_device *netdev,
 	/* Invalid EEPROM_INDICATOR at offset zero will result in a failure
 	 * to load data from EEPROM
 	 */
-	if (ee->magic == LAN78XX_EEPROM_MAGIC)
+	if (ee->magic == LAN78XX_EEPROM_MAGIC) {
 		ret = lan78xx_write_raw_eeprom(dev, ee->offset, ee->len, data);
-	else if ((ee->magic == LAN78XX_OTP_MAGIC) &&
+	} else if ((ee->magic == LAN78XX_OTP_MAGIC) &&
 		 (ee->offset == 0) &&
 		 (ee->len == 512) &&
-		 (data[0] == OTP_INDICATOR_1))
+		 (data[0] == OTP_INDICATOR_1)) {
 		ret = lan78xx_write_raw_otp(dev, ee->offset, ee->len, data);
+	} else {
+		ret = -EINVAL;
+	}
 
 	usb_autopm_put_interface(dev->intf);
 
Signature · 1 line
2.53.0
author maintainer
#2041 lore raw

PATCH 2021/2651 dax/bus: Return errors for invalid mapping targets

In reply to Greg Kroah-Hartman

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

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

From: Muchun Song <[email protected]>

[ Upstream commit df6cc0a24717c38ac81b5ba1e839c35e74e667dc ]

After the DAX configuration locking was converted to rwsems, successful lock acquisition leaves rc set to zero in mapping_store(). Two error paths can return this stale value: an unbound region driver and a misaligned range size. The sysfs write therefore reports success without allocating the requested range.

Return -ENXIO when the region driver is not bound and -EINVAL when the range size is misaligned.

Fixes c05ae9d85b47 ("dax/bus.c: replace driver-core lock usage by a local rwsem")
Assisted-by LLM
---
 drivers/dax/bus.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
drivers/dax/bus.c +6 -2
index b809e1a264afa..e40c25401cf06 100644
@@ -1192,7 +1192,7 @@ static ssize_t mapping_store(struct device *dev, struct device_attribute *attr,
 		return rc;
 	if (!dax_region->dev->driver) {
 		up_write(&dax_region_rwsem);
-		return rc;
+		return -ENXIO;
 	}
 	rc = down_write_killable(&dax_dev_rwsem);
 	if (rc) {
@@ -1201,8 +1201,12 @@ static ssize_t mapping_store(struct device *dev, struct device_attribute *attr,
 	}
 
 	to_alloc = range_len(&r);
-	if (alloc_is_aligned(dev_dax, to_alloc))
+	if (!alloc_is_aligned(dev_dax, to_alloc)) {
+		dev_dbg(dev, "%s: size: %zu misaligned\n", __func__, to_alloc);
+		rc = -EINVAL;
+	} else {
 		rc = alloc_dev_dax_range(dev_dax, r.start, to_alloc);
+	}
 	up_write(&dax_dev_rwsem);
 	up_write(&dax_region_rwsem);
 
Signature · 1 line
2.53.0
author maintainer
#2042 lore raw

PATCH 2022/2651 bnx2x: fix header length calculation for encapsulated TSO

In reply to Greg Kroah-Hartman

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

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

From: George Melikov <[email protected]>

[ Upstream commit 4fc1d5bb448dfab391a96f949d02ad03ad8cda5c ]

Commit 80bfab79b835 ("net: adopt skb_network_offset() and similar helpers") replaced the difference between the inner transport header and the outer network header with skb_inner_transport_offset().
The helper is relative to skb->data, so the new calculation incorrectly includes the outer Ethernet header in fw_ip_hdr_to_payload_w.

On a BCM57810 transmitting TCP over VXLAN with an outer MTU of 1500, hardware segmentation emits packets declaring an outer IPv4 total length of 1514 while the actual IP packet is only 1500 bytes long. The receiver drops these malformed packets, severely degrading TCP connectivity.

Subtract skb_network_offset() to restore the original calculation of the length from the outer network header to the inner TCP payload.

Reproduced with plain kernel VXLAN and one TCP flow on kernel 7.0.0-31-generic: 50 of 200 captured packets had an invalid outer IP length with the original driver, versus none with this fix. Disabling TSO/GSO on the test VXLAN device also eliminated the error with the original driver.

Fixes 80bfab79b835 ("net: adopt skb_network_offset() and similar helpers")
---
 drivers/net/ethernet/broadcom/bnx2x/bnx2x_cmn.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/net/ethernet/broadcom/bnx2x/bnx2x_cmn.c +2 -1
index 5a9742fd3ddfb..6fb0619731aee 100644
@@ -3666,7 +3666,8 @@ static void bnx2x_update_pbds_gso_enc(struct sk_buff *skb,
 	u8 outerip_off, outerip_len = 0;
 
 	/* from outer IP to transport */
-	hlen_w = skb_inner_transport_offset(skb) >> 1;
+	hlen_w = (skb_inner_transport_offset(skb) -
+		  skb_network_offset(skb)) >> 1;
 
 	/* transport len */
 	hlen_w += inner_tcp_hdrlen(skb) >> 1;
Signature · 1 line
2.53.0
author maintainer
#2043 lore raw

PATCH 2023/2651 ipv4: use RCU protection in inet_netconf_get_devconf()

In reply to Greg Kroah-Hartman

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

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

From: Eric Dumazet <[email protected]>

[ Upstream commit b2039a6dd36b5c89142bfb95bc0205be8abcc600 ]

inet_netconf_get_devconf() runs without RTNL. It uses dev_get_by_index() and in_dev_get() to pin the device and its in_device while the reply is allocated and filled.

in_dev_get() is not safe for a lockless caller. Since commit 9d40c84cf5bc ("net: devinet: Reduce refcount before grace period"), inetdev_destroy() drops the final reference before the RCU grace period. A reader can load dev->ip_ptr, then call refcount_inc() on a zero refcount after in_dev_free_rcu() has been queued, and keep using the in_device once it has been freed.

None of these references are needed. An in_device is freed after an RCU grace period, ipv4_devconf is embedded in it, and inet_netconf_fill_devconf() does not sleep.

Allocate the skb first, then perform the lookup and the fill under rcu_read_lock(), using dev_get_by_index_rcu() and __in_dev_get_rcu(), like inet_netconf_dump_devconf() already does.

---
 net/ipv4/devinet.c | 35 +++++++++++++++++------------------
 1 file changed, 17 insertions(+), 18 deletions(-)
net/ipv4/devinet.c +17 -18
index 5b6b11c943e45..f9a361621f74b 100644
@@ -2379,8 +2379,8 @@ static int inet_netconf_get_devconf(struct sk_buff *in_skb,
 	struct net *net = sock_net(in_skb->sk);
 	struct nlattr *tb[NETCONFA_MAX + 1];
 	const struct ipv4_devconf *devconf;
-	struct in_device *in_dev = NULL;
-	struct net_device *dev = NULL;
+	struct in_device *in_dev;
+	struct net_device *dev;
 	struct sk_buff *skb;
 	int ifindex;
 	int err;
@@ -2392,7 +2392,13 @@ static int inet_netconf_get_devconf(struct sk_buff *in_skb,
 	if (!tb[NETCONFA_IFINDEX])
 		return -EINVAL;
 
+	skb = nlmsg_new(inet_netconf_msgsize_devconf(NETCONFA_ALL), GFP_KERNEL);
+	if (!skb)
+		return -ENOBUFS;
+
 	ifindex = nla_get_s32(tb[NETCONFA_IFINDEX]);
+
+	rcu_read_lock();
 	switch (ifindex) {
 	case NETCONFA_IFINDEX_ALL:
 		devconf = net->ipv4.devconf_all;
@@ -2402,36 +2408,29 @@ static int inet_netconf_get_devconf(struct sk_buff *in_skb,
 		break;
 	default:
 		err = -ENODEV;
-		dev = dev_get_by_index(net, ifindex);
-		if (dev)
-			in_dev = in_dev_get(dev);
+		dev = dev_get_by_index_rcu(net, ifindex);
+		if (!dev)
+			goto out_unlock;
+		in_dev = __in_dev_get_rcu(dev);
 		if (!in_dev)
-			goto errout;
+			goto out_unlock;
 		devconf = &in_dev->cnf;
 		break;
 	}
 
-	err = -ENOBUFS;
-	skb = nlmsg_new(inet_netconf_msgsize_devconf(NETCONFA_ALL), GFP_KERNEL);
-	if (!skb)
-		goto errout;
-
 	err = inet_netconf_fill_devconf(skb, ifindex, devconf,
 					NETLINK_CB(in_skb).portid,
 					nlh->nlmsg_seq, RTM_NEWNETCONF, 0,
 					NETCONFA_ALL);
+out_unlock:
+	rcu_read_unlock();
 	if (err < 0) {
 		/* -EMSGSIZE implies BUG in inet_netconf_msgsize_devconf() */
 		WARN_ON(err == -EMSGSIZE);
 		kfree_skb(skb);
-		goto errout;
+		return err;
 	}
-	err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
-errout:
-	if (in_dev)
-		in_dev_put(in_dev);
-	dev_put(dev);
-	return err;
+	return rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
 }
 
 static int inet_netconf_dump_devconf(struct sk_buff *skb,
Signature · 1 line
2.53.0
author maintainer
#2044 lore raw

PATCH 2024/2651 net: use the full socket in sk_mc_loop()

In reply to Greg Kroah-Hartman

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

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

From: Theodor Arsenij Larionov Trichkine <[email protected]>

[ Upstream commit 31b564f70d8819a1c11d0fd504fe582fc0e0f0cf ]

sk_mc_loop() is called from ip_mc_output() and ip6_finish_output2() with skb->sk, which is not always a full socket:

- Since commit ca6fb0651883 ("tcp: attach SYNACK messages to request sockets instead of listener"), a SYNACK is attached to its request socket.

- Since commit 79636038d37e ("ipv4: tcp: give socket pointer to control skbs"), an ACK or RST sent by ip_send_unicast_reply() on behalf of a TIME_WAIT socket is attached to the timewait socket.

When such a packet uses a multicast route, inet_test_bit(MC_LOOP, sk) reads inet_flags past the end of the request or timewait socket.

This happens for instance when a SYN with a multicast source address reaches a listener, after being looped back with its dst attached, so that ip_rcv_finish_core() skips the martian source check. A raw IP_HDRINCL socket sending to a local address does this, as does re-injection by nft dup or the iptables TEE target. The destination can also come from a source route option, or from a route of type multicast covering a unicast prefix.

BUG: KASAN: slab-out-of-bounds in sk_mc_loop+0x111/0x170
Read of size 8 at addr ffff88800f2b7f10 by task repro-raw/470
Call Trace:
 <IRQ>
 sk_mc_loop+0x111/0x170
 ip_mc_output+0x355/0x930
 ip_build_and_send_pkt+0xb87/0xc50
 tcp_v4_send_synack+0x500/0x6f0
 tcp_conn_request+0x2135/0x2d90
 tcp_v4_conn_request+0xa5/0x210
 tcp_rcv_state_process+0x136e/0x6920
 tcp_v4_do_rcv+0x339/0xb10
 tcp_v4_rcv+0x34ab/0x3ab0
 ip_protocol_deliver_rcu+0x6e/0x3e0
 ip_local_deliver_finish+0x34d/0x510
 ip_local_deliver+0x1bc/0x310
 ip_rcv+0x390/0x410
 __netif_receive_skb_one_core+0x199/0x1e0
 process_backlog+0x239/0x680
 __napi_poll+0xb5/0x650
 net_rx_action+0x980/0xd60
 handle_softirqs+0x17f/0x590
 do_softirq+0x3f/0x60
 </IRQ>

The buggy address belongs to the object at ffff88800f2b7d60
 which belongs to the cache request_sock_TCP of size 312

The buggy address is located 120 bytes to the right of
allocated 312-byte region [ffff88800f2b7d60, ffff88800f2b7e98)

Use sk_const_to_full_sk(), which restores the behavior from before the two commits above: a request socket uses the setting of its listener, and a timewait socket gets the default (loop back), as the per-cpu control socket used before had.

Fixes ca6fb0651883 ("tcp: attach SYNACK messages to request sockets instead of listener")
Fixes 79636038d37e ("ipv4: tcp: give socket pointer to control skbs")
[edumazet: rewrote the changelog, added the TIME_WAIT case]
---
 net/core/sock.c | 1 +
 1 file changed, 1 insertion(+)
net/core/sock.c +1 -0
index 5b7ee5c76dae6..a74be1cc93024 100644
@@ -769,6 +769,7 @@ bool sk_mc_loop(const struct sock *sk)
 {
 	if (dev_recursion_level())
 		return false;
+	sk = sk_const_to_full_sk(sk);
 	if (!sk)
 		return true;
 	/* IPV6_ADDRFORM can change sk->sk_family under us. */
Signature · 1 line
2.53.0
author maintainer
#2045 lore raw

PATCH 2025/2651 tcp: use the echoed source route in cookie_v4_check()

In reply to Greg Kroah-Hartman

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

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

From: Eric Dumazet <[email protected]>

[ Upstream commit 54d574d4afd9de820c8a017665c8095f0f5fdbaa ]

When the ACK carries a source route option, cookie_v4_check() routes the new socket to opt->faddr, where opt points to the options of the received packet.

ip_options_compile() only fills faddr for options given by setsockopt() (when called without an skb), so on receive faddr is 0 and the lookup is done for daddr 0, which gives a local route.

Use the options echoed by tcp_v4_save_options() instead, as inet_csk_route_req() and inet_csk_route_child_sock() do with ireq->ireq_opt. Read them after security_inet_conn_request(), since CIPSO can replace ireq->ireq_opt there.

The route now goes to the first hop of the source route, so also refuse a strict source route through a gateway, as inet_csk_route_req() does.

Found by sashiko while reviewing the sk_mc_loop() fix.

---
 net/ipv4/syncookies.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
net/ipv4/syncookies.c +10 -2
index 4b2d2713653b7..4e0ff3b820627 100644
@@ -406,12 +406,12 @@ static struct request_sock *cookie_tcp_check(struct net *net, struct sock *sk,
  */
 struct sock *cookie_v4_check(struct sock *sk, struct sk_buff *skb)
 {
-	struct ip_options *opt = &TCP_SKB_CB(skb)->header.h4.opt;
 	const struct tcphdr *th = tcp_hdr(skb);
 	struct tcp_sock *tp = tcp_sk(sk);
 	struct inet_request_sock *ireq;
 	struct net *net = sock_net(sk);
 	struct tcp_request_sock *treq;
+	struct ip_options_rcu *opt;
 	struct request_sock *req;
 	struct sock *ret = sk;
 	struct flowi4 fl4;
@@ -451,6 +451,8 @@ struct sock *cookie_v4_check(struct sock *sk, struct sk_buff *skb)
 		SKB_DR_SET(reason, SECURITY_HOOK);
 		goto out_free;
 	}
+	/* Load ireq->ireq_opt after the LSM hook, which can replace it. */
+	opt = rcu_dereference_protected(ireq->ireq_opt, true);
 
 	tcp_ao_syncookie(sk, skb, req, AF_INET);
 
@@ -463,7 +465,7 @@ struct sock *cookie_v4_check(struct sock *sk, struct sk_buff *skb)
 	flowi4_init_output(&fl4, ireq->ir_iif, ireq->ir_mark,
 			   ip_sock_rt_tos(sk), ip_sock_rt_scope(sk),
 			   IPPROTO_TCP, inet_sk_flowi_flags(sk),
-			   opt->srr ? opt->faddr : ireq->ir_rmt_addr,
+			   (opt && opt->opt.srr) ? opt->opt.faddr : ireq->ir_rmt_addr,
 			   ireq->ir_loc_addr, th->source, th->dest,
 			   sk_uid(sk));
 	security_req_classify_flow(req, flowi4_to_flowi_common(&fl4));
@@ -472,6 +474,12 @@ struct sock *cookie_v4_check(struct sock *sk, struct sk_buff *skb)
 		SKB_DR_SET(reason, IP_OUTNOROUTES);
 		goto out_free;
 	}
+	/* Same check as in inet_csk_route_req(). */
+	if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway) {
+		ip_rt_put(rt);
+		SKB_DR_SET(reason, IP_OUTNOROUTES);
+		goto out_free;
+	}
 
 	/* Try to redo what tcp_v4_send_synack did. */
 	req->rsk_window_clamp = READ_ONCE(tp->window_clamp) ? :
Signature · 1 line
2.53.0
author maintainer
#2046 lore raw

PATCH 2026/2651 selftests/bpf: Keep the bpffs of cgroup_hierarchical_stats private

In reply to Greg Kroah-Hartman

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

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

From: Qiliang Yuan <[email protected]>

[ Upstream commit 3c824dfd17e6e918e45a6a96bda0d020ddec8287 ]

setup_hierarchy() mounts a bpffs on /sys/fs/bpf with setup_bpffs(), and then sets up the cgroups with setup_cgroups(), which moves the test into a private mount namespace.

The bpffs thus lands in the mount namespace that test_progs shares with the tests running in parallel, on top of the bpffs already there, and hides what they pin. cleanup_bpffs() later runs in the private mount namespace and can't unmount it, so it stays there for good. bpftool_maps_access then fails to pin an iterator because /sys/fs/bpf/test_bpftool_map doesn't exist anymore, and bpftool_metadata can't find the program it pinned in /sys/fs/bpf/test_metadata.

Set up the cgroups first, so that the bpffs is mounted in the private mount namespace.

Fixes 88886309d2e8 ("selftests/bpf: add a selftest for cgroup hierarchical stats collection")
---
 .../selftests/bpf/prog_tests/cgroup_hierarchical_stats.c        | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c +1 -1
index 3bd27d2ea668c..ad19d6d41918a 100644
@@ -151,7 +151,7 @@ static void cleanup_cgroups(void)
 /* Sets up cgroup hiearchary, returns 0 on success. */
 static int setup_hierarchy(void)
 {
-	return setup_bpffs() || setup_cgroups();
+	return setup_cgroups() || setup_bpffs();
 }
 
 static void destroy_hierarchy(void)
Signature · 1 line
2.53.0
author maintainer
#2047 lore raw

PATCH 2027/2651 selftests/bpf: Unmount the bpffs that cgroup_hierarchical_stats mounted

In reply to Greg Kroah-Hartman

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

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

From: Qiliang Yuan <[email protected]>

[ Upstream commit e0645cfd0e1b2ae7b8ad989bef00a30016b16b5f ]

setup_bpffs() mounts a bpffs on /sys/fs/bpf and records in mounted_bpffs whether it did, so that cleanup_bpffs() unmounts only a bpffs that the test mounted itself.

cleanup_bpffs() checks the flag the other way around. As mounting on /sys/fs/bpf succeeds even when a bpffs is already there, the test never unmounts the bpffs it mounted, and every run leaves another one stacked on /sys/fs/bpf of the mount namespace that the test_progs worker keeps running later tests in.

Unmount the bpffs only when setup_bpffs() mounted it.

---
 .../selftests/bpf/prog_tests/cgroup_hierarchical_stats.c        | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c +1 -1
index ad19d6d41918a..cc6ab2c263da1 100644
@@ -110,7 +110,7 @@ static void cleanup_bpffs(void)
 	ASSERT_OK(rmdir(BPFFS_ATTACH_COUNTERS), "rmdir "BPFFS_ATTACH_COUNTERS);
 
 	/* Unmount bpffs, if it wasn't already mounted when we started */
-	if (mounted_bpffs)
+	if (!mounted_bpffs)
 		return;
 
 	ASSERT_OK(umount(BPFFS_ROOT), "unmount bpffs");
Signature · 1 line
2.53.0
author maintainer
#2048 lore raw

PATCH 2028/2651 sched/cputime: Dont account idle time twice after dyntick-idle

In reply to Greg Kroah-Hartman

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

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

From: Stian Halseth <[email protected]>

[ Upstream commit 96a494c9cfd8f4bb7b1a7a70275426db71cf98aa ]

On idle exit the dyntick-idle accounting accounts the time up to now, then the tick is restarted on its old period. The first tick accounts a whole TICK_NSEC to whatever runs, although the part of that period before the idle exit has just been accounted as idle time, or with IRQ_TIME_ACCOUNTING as IRQ time. That is up to a full tick per idle exit, and /proc/stat reports more idle time than wall time.

Record how much of the current tick period dyntick-idle has accounted, and leave it out of the tick that ends the period.

---
 include/linux/kernel_stat.h |  7 +++++--
 kernel/sched/cputime.c      | 39 +++++++++++++++++++++++++++++++------
 kernel/time/tick-sched.c    | 22 ++++++++++++++++-----
 3 files changed, 55 insertions(+), 13 deletions(-)
include/linux/kernel_stat.h +5 -2
index 9ca6c2259dfea..6e252048b5ade 100644
@@ -40,6 +40,9 @@ struct kernel_cpustat {
 	seqcount_t	idle_sleeptime_seq;
 	u64		idle_entrytime;
 	u64		idle_stealtime[2];
+	u64		idle_dyntick_entry;
+	u64		idle_tick_period;
+	u64		idle_tick_overlap;
 #endif
 	u64		cpustat[NR_STATS];
 };
@@ -111,7 +114,7 @@ static inline unsigned long kstat_cpu_irqs_sum(unsigned int cpu)
 #ifdef CONFIG_HAVE_VIRT_CPU_ACCOUNTING_IDLE
 
 static inline void kcpustat_dyntick_start(u64 now) { }
-static inline void kcpustat_dyntick_stop(u64 now) { }
+static inline void kcpustat_dyntick_stop(u64 now, u64 tick_start) { }
 static inline void kcpustat_irq_enter(u64 now) { }
 static inline void kcpustat_irq_exit(u64 now) { }
 static inline bool kcpustat_idle_dyntick(void) { return false; }
@@ -132,7 +135,7 @@ static inline u64 kcpustat_field_iowait(int cpu)
 #else /* !CONFIG_HAVE_VIRT_CPU_ACCOUNTING_IDLE */
 
 extern void kcpustat_dyntick_start(u64 now);
-extern void kcpustat_dyntick_stop(u64 now);
+extern void kcpustat_dyntick_stop(u64 now, u64 tick_start);
 extern void kcpustat_irq_enter(u64 now);
 extern void kcpustat_irq_exit(u64 now);
 extern u64 kcpustat_field_idle(int cpu);
kernel/sched/cputime.c +33 -6
index 06bddaa738e52..faac7c2066d84 100644
@@ -381,9 +381,9 @@ void thread_group_cputime(struct task_struct *tsk, struct task_cputime *times)
  * softirq as those do not count in task exec_runtime any more.
  */
 static void irqtime_account_process_tick(struct task_struct *p, int user_tick,
-					 int ticks)
+					 u64 cputime)
 {
-	u64 other, cputime = TICK_NSEC * ticks;
+	u64 other;
 
 	/*
 	 * When returning from idle, many ticks can get accounted at
@@ -418,7 +418,7 @@ static void irqtime_account_process_tick(struct task_struct *p, int user_tick,
 
 #else /* !CONFIG_IRQ_TIME_ACCOUNTING: */
 static inline void irqtime_account_process_tick(struct task_struct *p, int user_tick,
-						int nr_ticks) { }
+						u64 cputime) { }
 #endif /* !CONFIG_IRQ_TIME_ACCOUNTING */
 
 #if defined(CONFIG_NO_HZ_COMMON) && !defined(CONFIG_HAVE_VIRT_CPU_ACCOUNTING_IDLE)
@@ -468,18 +468,38 @@ static void kcpustat_idle_start(struct kernel_cpustat *kc, u64 now)
 	write_seqcount_end(&kc->idle_sleeptime_seq);
 }
 
-void kcpustat_dyntick_stop(u64 now)
+void kcpustat_dyntick_stop(u64 now, u64 tick_start)
 {
 	struct kernel_cpustat *kc = kcpustat_this_cpu;
 
 	if (!vtime_generic_enabled_this_cpu()) {
 		WARN_ON_ONCE(!kc->idle_dyntick);
+		if (kc->idle_tick_period != tick_start) {
+			kc->idle_tick_period = tick_start;
+			kc->idle_tick_overlap = 0;
+		}
+		tick_start = max(tick_start, kc->idle_dyntick_entry);
+		if (!WARN_ON_ONCE(now < tick_start))
+			kc->idle_tick_overlap += now - tick_start;
 		kcpustat_idle_stop(kc, now);
 		kc->idle_dyntick = false;
 		vtime_dyntick_stop();
 	}
 }
 
+/*
+ * The first tick after dyntick-idle covers a period that the dyntick-idle
+ * accounting may already have accounted in part.
+ */
+static inline u64 kcpustat_tick_overlap(void)
+{
+	struct kernel_cpustat *kc = kcpustat_this_cpu;
+	u64 overlap = kc->idle_tick_overlap;
+
+	kc->idle_tick_overlap = 0;
+	return overlap;
+}
+
 void kcpustat_dyntick_start(u64 now)
 {
 	struct kernel_cpustat *kc = kcpustat_this_cpu;
@@ -487,6 +507,7 @@ void kcpustat_dyntick_start(u64 now)
 	if (!vtime_generic_enabled_this_cpu()) {
 		vtime_dyntick_start();
 		kc->idle_dyntick = true;
+		kc->idle_dyntick_entry = now;
 		kcpustat_idle_start(kc, now);
 	}
 }
@@ -555,6 +576,11 @@ u64 kcpustat_field_iowait(int cpu)
 }
 EXPORT_SYMBOL_GPL(kcpustat_field_iowait);
 #else
+static inline u64 kcpustat_tick_overlap(void)
+{
+	return 0;
+}
+
 static u64 kcpustat_field_dyntick(int cpu, enum cpu_usage_stat idx,
 				  bool compute_delta, ktime_t now)
 {
@@ -695,12 +721,13 @@ void account_process_tick(struct task_struct *p, int user_tick)
 	if (kcpustat_idle_dyntick())
 		return;
 
+	cputime = TICK_NSEC - kcpustat_tick_overlap();
+
 	if (irqtime_enabled()) {
-		irqtime_account_process_tick(p, user_tick, 1);
+		irqtime_account_process_tick(p, user_tick, cputime);
 		return;
 	}
 
-	cputime = TICK_NSEC;
 	steal = steal_account_process_time(ULONG_MAX);
 
 	if (steal >= cputime)
kernel/time/tick-sched.c +17 -5
index baa3ac9b48f88..6546e196645f2 100644
@@ -775,12 +775,18 @@ static ktime_t tick_forward_now(ktime_t expires, ktime_t now)
 	return expires + TICK_NSEC;
 }
 
+static void tick_nohz_forward_last_tick(struct tick_sched *ts, ktime_t now)
+{
+	if (now >= ts->last_tick)
+		ts->last_tick = tick_forward_now(ts->last_tick, now);
+}
+
 static void tick_nohz_restart(struct tick_sched *ts, ktime_t now)
 {
-	ktime_t expires = ts->last_tick;
+	ktime_t expires;
 
-	if (now >= expires)
-		expires = tick_forward_now(expires, now);
+	tick_nohz_forward_last_tick(ts, now);
+	expires = ts->last_tick;
 
 	if (tick_sched_flag_test(ts, TS_FLAG_HIGHRES)) {
 		hrtimer_start(&ts->sched_timer,	expires, HRTIMER_MODE_ABS_PINNED_HARD);
@@ -1341,6 +1347,12 @@ unsigned long tick_nohz_get_idle_calls_cpu(int cpu)
 	return ts->idle_calls;
 }
 
+static void tick_nohz_dyntick_stop(struct tick_sched *ts, ktime_t now)
+{
+	tick_nohz_forward_last_tick(ts, now);
+	kcpustat_dyntick_stop(now, ts->last_tick - TICK_NSEC);
+}
+
 void tick_nohz_idle_restart_tick(void)
 {
 	struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
@@ -1353,7 +1365,7 @@ void tick_nohz_idle_restart_tick(void)
 		 * no tiny amount of idle time is accounted twice.
 		 */
 		ts->idle_entrytime = ktime_get();
-		kcpustat_dyntick_stop(ts->idle_entrytime);
+		tick_nohz_dyntick_stop(ts, ts->idle_entrytime);
 		tick_nohz_restart_sched_tick(ts, ts->idle_entrytime);
 	}
 }
@@ -1397,7 +1409,7 @@ void tick_nohz_idle_exit(void)
 
 	if (tick_sched_flag_test(ts, TS_FLAG_STOPPED)) {
 		now = ktime_get();
-		kcpustat_dyntick_stop(now);
+		tick_nohz_dyntick_stop(ts, now);
 		tick_nohz_idle_update_tick(ts, now);
 	}
 
Signature · 1 line
2.53.0
author maintainer
#2049 lore raw

PATCH 2029/2651 sched/cache: Avoid publishing partial LLC utilization

In reply to Greg Kroah-Hartman

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

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

From: Jemmy Wong <[email protected]>

[ Upstream commit fcceb7da94659695d6cba97190e18e87d9cce82c ]

update_sg_lb_stats() sums utilization over the CPUs in both sched_group_span(group) and env->cpus, but takes capacity from group->sgc->capacity for the whole group. record_sg_llc_stats() publishes both.

Rejecting an all-affinity-pinned source runqueue removes that CPU from env->cpus and retries group selection. The retry can publish the partial utilization with the full capacity.

can_migrate_llc() then treats a busy preferred LLC as having spare capacity. More tasks can aggregate into it, migrations out can be blocked, and two busy LLCs may not fall back to generic balancing. This increases CPU contention and task latency. Found by inspection.

Skip publication on affinity retries using LBF_ALL_PINNED, retaining the first-pass snapshots and avoiding repeated cpumask checks. On the first pass, publish either shared LLC statistic only when env->cpus covers the whole group. Load balancing still uses the affinity-filtered statistics.

The same window exists during CPU hotplug. env->cpus drops a CPU at set_cpu_active(false), but the group span and sgc->capacity still include it until cpuset_cpu_inactive() rebuilds the domains. Keeping the previous snapshot avoids the mismatched publish. After the rebuild, the next periodic balance records both statistics again.

Fixes f025ef275388 ("sched/cache: Record per LLC utilization to guide cache aware scheduling decisions")
---
 kernel/sched/fair.c | 8 ++++++++
 1 file changed, 8 insertions(+)
kernel/sched/fair.c +8 -0
index 913630c0b0590..548a28e37d0e7 100644
@@ -12128,6 +12128,14 @@ static void record_sg_llc_stats(struct lb_env *env,
 	if (env->sd->child != rcu_dereference_all(per_cpu(sd_llc, env->dst_cpu)))
 		return;
 
+	/*
+	 * A redo repeats stats published on the first pass. Hotplug can
+	 * still leave env->cpus partial, so util would not match capacity.
+	 */
+	if ((env->flags & LBF_ALL_PINNED) ||
+	    !cpumask_subset(sched_group_span(group), env->cpus))
+		return;
+
 	/*
 	 * At this point we know this group spans a LLC domain.
 	 * Record the statistic of this group in its corresponding
Signature · 1 line
2.53.0
author maintainer
#2050 lore raw

PATCH 2030/2651 drm/appletbdrm: Add suspend and resume support

In reply to Greg Kroah-Hartman

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

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

From: Vasilij Markin <[email protected]>

[ Upstream commit 6f6a6b9ae0b481b97dac141ae86becdf7bd0b471 ]

The driver has no USB power management callbacks, so the USB core unbinds it before system suspend and binds it again on resume. The DRM device is unregistered and registered again on every suspend and resume cycle, userspace driving the Touch Bar through it (such as tiny-dfr) loses its device, and the Touch Bar stays dark after resume.

Implement suspend and resume with drm_mode_config_helper_suspend() and drm_mode_config_helper_resume(), so the device stays registered and the last committed state is restored on resume. If the device was reset while suspended, repeat the probe-time handshake first.

Fixes 0670c2f56e45 ("drm/tiny: add driver for Apple Touch Bars in x86 Macs")
Assisted-by Claude:claude-opus-5-5
---
 drivers/gpu/drm/tiny/appletbdrm.c | 46 +++++++++++++++++++++++++++++++
 1 file changed, 46 insertions(+)
drivers/gpu/drm/tiny/appletbdrm.c +46 -0
index ef71b99579619..9a5288acbffca 100644
@@ -30,6 +30,7 @@
 #include <drm/drm_gem_atomic_helper.h>
 #include <drm/drm_gem_framebuffer_helper.h>
 #include <drm/drm_gem_shmem_helper.h>
+#include <drm/drm_modeset_helper.h>
 #include <drm/drm_plane.h>
 #include <drm/drm_print.h>
 #include <drm/drm_probe_helper.h>
@@ -821,6 +822,48 @@ static void appletbdrm_shutdown(struct usb_interface *intf)
 	drm_atomic_helper_shutdown(&adev->drm);
 }
 
+static int appletbdrm_suspend(struct usb_interface *intf, pm_message_t message)
+{
+	struct appletbdrm_device *adev = usb_get_intfdata(intf);
+
+	return drm_mode_config_helper_suspend(&adev->drm);
+}
+
+static int appletbdrm_resume(struct usb_interface *intf)
+{
+	struct appletbdrm_device *adev = usb_get_intfdata(intf);
+
+	return drm_mode_config_helper_resume(&adev->drm);
+}
+
+static int appletbdrm_reset_resume(struct usb_interface *intf)
+{
+	struct appletbdrm_device *adev = usb_get_intfdata(intf);
+	struct drm_device *drm = &adev->drm;
+	int ret, resume_ret;
+
+	/*
+	 * A reset puts the device back into its initial state, where it
+	 * expects the same handshake as during probe. Resume the DRM side
+	 * even if the handshake fails, so that the state saved on suspend
+	 * is released.
+	 */
+	ret = appletbdrm_get_information(adev);
+	if (ret) {
+		drm_err(drm, "Failed to get display information\n");
+		goto resume;
+	}
+
+	ret = appletbdrm_signal_readiness(adev);
+	if (ret)
+		drm_err(drm, "Failed to signal readiness\n");
+
+resume:
+	resume_ret = drm_mode_config_helper_resume(drm);
+
+	return ret ? ret : resume_ret;
+}
+
 static const struct usb_device_id appletbdrm_usb_id_table[] = {
 	{ USB_DEVICE_INTERFACE_CLASS(0x05ac, 0x8302, USB_CLASS_AUDIO_VIDEO) },
 	{}
@@ -832,6 +875,9 @@ static struct usb_driver appletbdrm_usb_driver = {
 	.probe		= appletbdrm_probe,
 	.disconnect	= appletbdrm_disconnect,
 	.shutdown	= appletbdrm_shutdown,
+	.suspend	= appletbdrm_suspend,
+	.resume		= appletbdrm_resume,
+	.reset_resume	= appletbdrm_reset_resume,
 	.id_table	= appletbdrm_usb_id_table,
 };
 module_usb_driver(appletbdrm_usb_driver);
Signature · 1 line
2.53.0
author maintainer
#2051 lore raw

PATCH 2031/2651 ALSA: vmaster: Protect follower lookup and setup

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit db2db2dec96e24d067cc5692ac5eec35830ee8d9 ]

A control selected by snd_ctl_add_followers() must remain alive until _snd_ctl_add_follower() has copied it and installed its wrapper. The lookup returns a raw pointer without retaining the control, and neither the short-lived list lookup lock nor the fast lookup protects later use.

If a kernel client adds followers to a live virtual master while another client removes or replaces a published follower, the following order is possible, with the card and master kept alive:

Follower setup Control removal
snd_ctl_add_followers()

    snd_ctl_find_id_mixer()
      return follower
                                      snd_ctl_remove()
                                        down_write(controls_rwsem)
                                        __snd_ctl_remove()
                                          unlink follower
                                          snd_ctl_free_one(follower)
                                        up_write(controls_rwsem)
    _snd_ctl_add_follower()
      read follower->count

Removal completes after lookup returns and before setup reads the control. Since setup holds neither controls_rwsem nor a reference, the count read and subsequent control copies can access freed memory.

Hold controls_rwsem for writing across the lookup and follower setup. This prevents removal or replacement from freeing the selected control until wrapper installation is complete. Write ownership also excludes control callbacks while setup changes the callback and private fields.

KASAN report as below:

    BUG: KASAN: slab-use-after-free in _snd_ctl_add_follower+0x452/0x520
    Read of size 4 at addr ffff888107957d50 by task loadmodule/491

    CPU: 3 UID: 0 PID: 491 Comm: loadmodule Tainted: G           O        7.2.0-rc6-pmb-bt-functional-v1+ #1 PREEMPT(lazy)
    Tainted: [O]=OOT_MODULE
    Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
    Call Trace:
     <TASK>
     dump_stack_lvl+0x93/0xd0
     print_report+0xce/0x630
     ? _snd_ctl_add_follower+0x452/0x520
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __virt_addr_valid+0x20d/0x410
     ? _snd_ctl_add_follower+0x452/0x520
     kasan_report+0xe0/0x110
     ? _snd_ctl_add_follower+0x452/0x520
     _snd_ctl_add_follower+0x452/0x520
     snd_ctl_add_followers+0x153/0x2b0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx_snd_ctl_add_followers+0x10/0x10
     ? __might_fault+0x135/0x190
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __might_fault+0x14e/0x190
     ? __pfx_fixture_write+0x10/0x10 [pmbd_vmaster_fixture]
     fixture_write+0x174/0x1f0 [pmbd_vmaster_fixture]
     ? __pfx_fixture_write+0x10/0x10 [pmbd_vmaster_fixture]
     ? __pfx___might_resched+0x10/0x10
     proc_reg_write+0x1fb/0x2d0
     vfs_write+0x25a/0x1010
     ? __pfx_proc_reg_write+0x10/0x10
     ? kmem_cache_free+0x242/0x580
     ? __pfx_vfs_write+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? putname+0x93/0xe0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? do_sys_openat2+0x12a/0x1b0
     ? __pfx_do_sys_openat2+0x10/0x10
     ksys_write+0x111/0x200
     ? __pfx_ksys_write+0x10/0x10
     ? irqentry_exit+0xbe/0x820
     ? srso_alias_return_thunk+0x5/0xfbef5
     do_syscall_64+0x115/0x6a0
     entry_SYSCALL_64_after_hwframe+0x77/0x7f
    RIP: 0033:0x7f0b835a9687
    Code: 48 89 fa 4c 89 df e8 58 b3 00 00 8b 93 08 03 00 00 59 5e 48 83 f8 fc 74 1a 5b c3 0f 1f 84 00 00 00 00 00 48 8b 44 24 10 0f 05 <5b> c3 0f 1f 80 00 00 00 00 83 e2 39 83 fa 08 75 de e8 23 ff ff ff
    RSP: 002b:00007ffc82ea0360 EFLAGS: 00000202 ORIG_RAX: 0000000000000001
    RAX: ffffffffffffffda RBX: 00007f0b83517780 RCX: 00007f0b835a9687
    RDX: 0000000000000005 RSI: 0000564f8a21d074 RDI: 0000000000000003
    RBP: 0000000000000003 R08: 0000000000000000 R09: 0000000000000000
    R10: 0000000000000000 R11: 0000000000000202 R12: 0000000000000000
    R13: 00007ffc82ea04f0 R14: 00007f0b83755000 R15: 0000564f8a21ed78
     </TASK>

    Allocated by task 485:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     __kasan_kmalloc+0xaa/0xb0
     __kmalloc_noprof+0x2d7/0x770
     snd_ctl_new+0x51/0x190
     snd_ctl_new1+0x13c/0x650
     0xffffffffc04011b5
     do_one_initcall+0xf3/0x4e0
     do_init_module+0x281/0x8e0
     load_module+0x658c/0x7cc0
     init_module_from_file+0x15b/0x180
     idempotent_init_module+0x22d/0x770
     __x64_sys_finit_module+0xd2/0x160
     do_syscall_64+0x115/0x6a0
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    Freed by task 492:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     kasan_save_free_info+0x3b/0x60
     __kasan_slab_free+0x5f/0x80
     kfree+0x307/0x580
     __snd_ctl_remove+0x2ac/0x3d0
     snd_ctl_remove+0x46/0x70
     fixture_write+0x1ae/0x1f0 [pmbd_vmaster_fixture]
     proc_reg_write+0x1fb/0x2d0
     vfs_write+0x25a/0x1010
     ksys_write+0x111/0x200
     do_syscall_64+0x115/0x6a0
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    The buggy address belongs to the object at ffff888107957d00
     which belongs to the cache kmalloc-192 of size 192
    The buggy address is located 80 bytes inside of
     freed 192-byte region [ffff888107957d00, ffff888107957dc0)

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

    Memory state around the buggy address:
     ffff888107957c00: fa fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
     ffff888107957c80: fb fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
    >ffff888107957d00: fa fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
                                                     ^
     ffff888107957d80: fb fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
     ffff888107957e00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
    ==================================================================
Fixes ae07eb9bf23e ("ALSA: vmaster: Add snd_ctl_add_followers() helper")
Assisted-by LLM
---
 sound/core/vmaster.c | 3 +++
 1 file changed, 3 insertions(+)
sound/core/vmaster.c +3 -0
index 3d57182031d93..f43144ba27978 100644
@@ -287,6 +287,8 @@ EXPORT_SYMBOL(_snd_ctl_add_follower);
  *
  * Adds the multiple follower kcontrols with the given names.
  * Returns 0 for success or a negative error code.
+ *
+ * Note that this function takes card->controls_rwsem lock internally.
  */
 int snd_ctl_add_followers(struct snd_card *card, struct snd_kcontrol *master,
 			  const char * const *list)
@@ -294,6 +296,7 @@ int snd_ctl_add_followers(struct snd_card *card, struct snd_kcontrol *master,
 	struct snd_kcontrol *follower;
 	int err;
 
+	guard(rwsem_write)(&card->controls_rwsem);
 	for (; *list; list++) {
 		follower = snd_ctl_find_id_mixer(card, *list);
 		if (follower) {
Signature · 1 line
2.53.0
author maintainer
#2052 lore raw

PATCH 2032/2651 selftests/bpf: Record only the test ICMP echo in tc8 of tc_netkit_scrub

In reply to Greg Kroah-Hartman

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

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

From: Qiliang Yuan <[email protected]>

[ Upstream commit 17f6fc3ad257b0ad7a11f276a5c0f57e0bdf3f4a ]

tc_netkit_scrub attaches tc8 to the primary netkit device, sends an ICMP echo with a mark and a priority through it, and checks the mark and the priority that tc8 saw against what the scrub mode lets through.

tc8 records the mark and priority of every packet it sees, and the device also carries what the system sends on its own once the device is up, like IPv6 neighbor discovery or the mDNS of avahi-daemon. When such a packet goes out after the echo, it overwrites what tc8 recorded, and the test finds a mark and a priority of 0. Record only IPv4 ICMP packets in tc8.

tc_netkit_scrub run 100 times on a bpf-next kernel with KASAN enabled, x86_64 VM with 32 vCPUs and avahi-daemon running, before and after this patch:
before after
outcome 2 of 100 failed (mark and priority 0) 0 of 100 failed

---
 tools/testing/selftests/bpf/progs/test_tc_link.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
tools/testing/selftests/bpf/progs/test_tc_link.c +10 -0
index 630f12e51b075..2a91793674dd5 100644
@@ -4,6 +4,8 @@
 
 #include <linux/bpf.h>
 #include <linux/if_ether.h>
+#include <linux/in.h>
+#include <linux/ip.h>
 #include <linux/stddef.h>
 #include <linux/if_packet.h>
 #include <bpf/bpf_endian.h>
@@ -119,11 +121,19 @@ SEC("tc/egress")
 int tc8(struct __sk_buff *skb)
 {
 	struct net_device *dev = BPF_CORE_READ((struct sk_buff *)skb, dev);
+	struct iphdr iph = {};
 
+	if (skb->protocol != __bpf_constant_htons(ETH_P_IP))
+		goto out;
+	if (bpf_skb_load_bytes(skb, sizeof(struct ethhdr), &iph, sizeof(iph)))
+		goto out;
+	if (iph.protocol != IPPROTO_ICMP)
+		goto out;
 	seen_tc8 = true;
 	mark = skb->mark;
 	prio = skb->priority;
 	headroom = BPF_CORE_READ(dev, needed_headroom);
 	tailroom = BPF_CORE_READ(dev, needed_tailroom);
+out:
 	return TCX_PASS;
 }
Signature · 1 line
2.53.0
author maintainer
#2053 lore raw

PATCH 2033/2651 HID: asus: document and harden the worker teardown

In reply to Greg Kroah-Hartman

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

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

From: Denis Benato <[email protected]>

[ Upstream commit 6f2204e35a164cb593929918112bb3f217f7ae84 ]

asus_work() executes actions against the device: they send feature reports with hid_hw_raw_request() and, for the Fn+F5 fan key fallback, re-inject the raw report into the HID core with hid_report_raw_event().

For this reason the worker must be quiesced before hid_hw_stop(): after the low level driver has stopped, the transport is gone (usbhid_stop() frees the URBs and the I/O buffers) and re-injected reports would race against the input devices being unregistered by hid_disconnect().

Make so that the teardown cannot race to a use-after-free: every site queueing an action holds worker->lock across the .removed check, the list insertion and schedule_work(), and asus_worker_stop() sets .removed and drains the queue under that same lock before calling cancel_work_sync(). An action that passed the check is caught by the latter while any later attempt is discarded by asus_worker_schedule().

Fixes 47669bec44fe ("HID: asus: refactor the two workqueues and init sequence")
Assisted-by zcode:glm-5.3-flash
---
 drivers/hid/hid-asus.c | 28 ++++++++++++++++++++++++++--
 1 file changed, 26 insertions(+), 2 deletions(-)
drivers/hid/hid-asus.c +26 -2
index 7dc6417fe2622..baa8589d45ae2 100644
@@ -765,9 +765,14 @@ static void asus_work(struct work_struct *work)
 	struct asus_work_action *action = NULL;
 	unsigned long flags;
 
-	/* Save the action to be performed and clear the flag */
+	/*
+	 * Dequeue the next action, if any. Once teardown has begun .removed
+	 * is set and asus_worker_stop() drains the queue: leave the queued
+	 * actions alone, they are dropped instead of being executed against
+	 * a device that is being removed.
+	 */
 	spin_lock_irqsave(&worker->lock, flags);
-	if (!list_empty(&worker->actions)) {
+	if (!worker->removed && !list_empty(&worker->actions)) {
 		action = list_first_entry(&worker->actions,
 					  struct asus_work_action, node);
 		list_del(&action->node);
@@ -817,6 +822,25 @@ static int asus_worker_create(struct hid_device *hdev, struct asus_drvdata *drvd
 	return 0;
 }
 
+/**
+ * asus_worker_stop - quiesce the worker
+ * @worker: the worker to quiesce
+ *
+ * Once this function returns no more actions can be queued and no instance
+ * of asus_work() is running or pending.
+ *
+ * Callers must do this before hid_hw_stop(): actions are executed while the
+ * device is fully operational, since they send raw requests to it and, in
+ * the fan-key fallback path, re-inject raw reports into the HID core. After
+ * hid_hw_stop() the transport is gone (usbhid_stop() frees the URBs and the
+ * I/O buffers) and the input devices have been unregistered.
+ *
+ * The quiescing is race free because every site that queues an action holds
+ * worker->lock across the .removed check, the list insertion and
+ * schedule_work(): anything scheduled before .removed is set here is caught
+ * by the cancel_work_sync() below, anything after it is discarded by
+ * asus_worker_schedule().
+ */
 static void asus_worker_stop(struct asus_worker *worker)
 {
 	struct asus_work_action *action, *tmp;
Signature · 1 line
2.53.0
author maintainer
#2054 lore raw

PATCH 2034/2651 HID: magicmouse: fix null pointer dereference in magicmouse_event()

In reply to Greg Kroah-Hartman

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

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

From: Nehuen Lian Bova <[email protected]>

[ Upstream commit 5b66b65cfd6f697b1addb6159cbece53d20db2fc ]

Add a guard clause to check if 'msc' and 'msc->input' is NULL before attempting to access its fields, preventing a general protection fault.

Fixes b8d56ef91cc3 ("HID: magicmouse: Apple Magic Mouse 2 USB-C support")
Reported-by [email protected]
---
 drivers/hid/hid-magicmouse.c | 4 ++++
 1 file changed, 4 insertions(+)
drivers/hid/hid-magicmouse.c +4 -0
index d637c04773799..e6d4d49305268 100644
@@ -553,6 +553,10 @@ static int magicmouse_event(struct hid_device *hdev, struct hid_field *field,
 		struct hid_usage *usage, __s32 value)
 {
 	struct magicmouse_sc *msc = hid_get_drvdata(hdev);
+
+	if (!msc || !msc->input)
+		return 0;
+
 	if ((msc->input->id.product == USB_DEVICE_ID_APPLE_MAGICMOUSE2 ||
 	     msc->input->id.product == USB_DEVICE_ID_APPLE_MAGICMOUSE2_USBC) &&
 	    field->report->id == MOUSE2_REPORT_ID) {
Signature · 1 line
2.53.0