Skip to contentSkip to conversation

6.18.66-rc1 review

PATCH In review Greg Kroah-Hartman 3 participants 995 messages Nov 25 Page 3 of 9

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

PATCH 199/990 xfrm: iptfs: fix skb leak on error in __input_process_payload()

In reply to Greg Kroah-Hartman

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

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

From: Eric Dumazet <[email protected]>

[ Upstream commit 64e45ed926cdd017c9816c8006d9117a7194c7e9 ]

syzbot reported a memory leak of the received skb (and its sec_path extension) in the IP-TFS receive path.

__input_process_payload() parses the inner packets of an IP-TFS payload and queues them on @sublist, which is only sent after the parsing loop. Three error paths inside the loop (skb_copy_seq_read() failure, invalid inner IPv4 header length, unknown IP version) jump to the "done" label, which is placed after the code sending @sublist.

Any skb already queued on @sublist is then neither delivered nor freed. This includes skbs added by iptfs_reassem_cont() before the call, newly allocated inner packets, and, since the received skb can be reused for the first inner packet, the received skb itself.

Move the "done" label before the trim/send code, so that inner packets parsed before the error are delivered as on the normal exit path. The received skb is then still freed (or consumed) as before when it was not reused.

---
 net/xfrm/xfrm_iptfs.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
net/xfrm/xfrm_iptfs.c +2 -1
index 4d3489acb099a..9a539618cb8fd 100644
@@ -1183,6 +1183,7 @@ static bool __input_process_payload(struct xfrm_state *x, u32 data,
 		/* this should not happen from the above code */
 		XFRM_INC_STATS(net, LINUX_MIB_XFRMINIPTFSERROR);
 
+done:
 	if (first_skb && first_iplen && !defer && !first_skb_partial) {
 		/* first_skb is queued b/c !defer and not partial */
 		if (pskb_trim(first_skb, first_iplen)) {
@@ -1199,7 +1200,7 @@ static bool __input_process_payload(struct xfrm_state *x, u32 data,
 		if (xfrm_input(skb, 0, 0, -2))
 			kfree_skb(skb);
 	}
-done:
+
 	skb = skbseq->root_skb;
 	skb_abort_seq_read(skbseq);
 
Signature · 1 line
2.53.0
author maintainer
#201 lore raw

PATCH 200/990 power: sequencing: qcom-wcn: increase WCN7850 power-up delay

In reply to Greg Kroah-Hartman

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

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

From: Shuai Zhang <[email protected]>

[ Upstream commit bd60a639b621453fe37b780df4b6d3a13f981f13 ]

When the WCN7850 is powered up from the Bluetooth side first, i.e. BT_EN is asserted while WLAN_EN is still low, the chip starts from a cold state and is not ready to accept the first HCI command 50 ms after BT_EN goes high. The first command (0xfc00, read QCA version) is lost, hci_qca does not resend it and fails after the 2 s command timeout:

Bluetooth: hci0: Reading QCA version information failed (-110)

When WLAN is powered first, 50 ms is sufficient, so the failure only shows up in the BT-first ordering. Measured on the affected board by which enable pin rose first:

  pwup_delay_ms   BT-first boots   with -110
  50              9                9
  75              23               0
  100             21               0
  300             20               0

Raise the power-up delay of WCN7850 to 100 ms. The delay is shared by the Bluetooth and WLAN targets, so WLAN power-up also waits 50 ms longer.

Fixes 2f1630f437df ("power: pwrseq: add a driver for the PMU module on the QCom WCN chipsets")
---
 drivers/power/sequencing/pwrseq-qcom-wcn.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/power/sequencing/pwrseq-qcom-wcn.c +1 -1
index 663d9a5370653..4720cf0ffb664 100644
@@ -324,7 +324,7 @@ static const char *const pwrseq_wcn7850_vregs[] = {
 static const struct pwrseq_qcom_wcn_pdata pwrseq_wcn7850_of_data = {
 	.vregs = pwrseq_wcn7850_vregs,
 	.num_vregs = ARRAY_SIZE(pwrseq_wcn7850_vregs),
-	.pwup_delay_ms = 50,
+	.pwup_delay_ms = 100,
 	.targets = pwrseq_qcom_wcn_targets,
 };
 
Signature · 1 line
2.53.0
author maintainer
#202 lore raw

PATCH 201/990 vhost-scsi: validate event queue descriptor direction

In reply to Greg Kroah-Hartman

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

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

From: Linfeng Sun <[email protected]>

[ Upstream commit 3d8c5b714c186d08c8fe8c8cfd1f9b89525ab067 ]

vhost_get_vq_desc() returns the number of device readable (output) and device writable (input) iovec segments. A guest can submit an eventq descriptor chain that fills vq->iov with output segments, setting out to ARRAY_SIZE(vq->iov) and in to zero.

When the host later queues a vhost-scsi event, vhost_scsi_do_evt_work() uses out as the index of the first input segment. This accesses one element beyond vq->iov and triggers an array-index-out-of-bounds report. With panic_on_warn enabled, the report panics the host.

The event queue accepts device writable buffers only. Reject chains that contain output segments or lack an input segment before using out as an index. The input check prevents the out-of-bounds access, while the output check validates the eventq descriptor direction.

I found the descriptor direction issue myself, though the patch was written with AI assistance. The out-of-bounds read with an output-only chain was separately reported by Jia Jia.

Fixes a6c9af87363c ("tcm_vhost: Add hotplug/hotunplug support")
Assisted-by OpenAI-Codex:GPT-5

Message-ID: <20261009-fix-arrary-index-out-of-bounds-in-vhost_scsi_complete_events-v2-1-1f7689a54735@gmail.com>

---
 drivers/vhost/scsi.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
drivers/vhost/scsi.c +10 -0
index 4c2964dcb78c8..ba5e454ef2667 100644
@@ -607,6 +607,16 @@ vhost_scsi_do_evt_work(struct vhost_scsi *vs, struct vhost_scsi_evt *evt)
 		return;
 	}
 
+	/*
+	 * Eventq buffers are device-writable only. A nonzero in count
+	 * guarantees that out is within the bounds of vq->iov.
+	 */
+	if (unlikely(out || !in)) {
+		vq_err(vq, "Invalid event buffer: out %u, in %u\n", out, in);
+		vs->vs_events_missed = true;
+		return;
+	}
+
 	if ((vq->iov[out].iov_len != sizeof(struct virtio_scsi_event))) {
 		vq_err(vq, "Expecting virtio_scsi_event, got %zu bytes\n",
 				vq->iov[out].iov_len);
Signature · 1 line
2.53.0
author maintainer
#203 lore raw

PATCH 202/990 virtio_ring: code cleanup in detach_buf_split

In reply to Greg Kroah-Hartman

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

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

From: [email protected] <[email protected]>

[ Upstream commit 4b7bf8d5503287ed3bd661207b9d061999ac494e ]

Since the return value of vring_unmap_one_split() is exactly vq->split.desc_extra[i].next, 'i = vq->split.desc_extra[i].next' is redundant. Assign vring_unmap_one_split() to i instead.

Since vq->split.desc_extra is assigned to extra, use extra[i].next instead of vq->split.desc_extra[i].next to improve readability.

No change in functionality.

Message-Id: <[email protected]>
Stable-dep-of: e498eb93f961 ("virtio_ring: use shadow flags when detaching split descriptors")

---
 drivers/virtio/virtio_ring.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
drivers/virtio/virtio_ring.c +2 -3
index 5c0139f3b9811..c51a6fc187f26 100644
@@ -764,13 +764,12 @@ static void detach_buf_split(struct vring_virtqueue *vq, unsigned int head,
 	i = head;
 
 	while (vq->split.vring.desc[i].flags & nextflag) {
-		vring_unmap_one_split(vq, &extra[i]);
-		i = vq->split.desc_extra[i].next;
+		i = vring_unmap_one_split(vq, &extra[i]);
 		vq->vq.num_free++;
 	}
 
 	vring_unmap_one_split(vq, &extra[i]);
-	vq->split.desc_extra[i].next = vq->free_head;
+	extra[i].next = vq->free_head;
 	vq->free_head = head;
 
 	/* Plus final descriptor */
Signature · 1 line
2.53.0
author maintainer
#204 lore raw

PATCH 203/990 virtio_ring: factor out split indirect detaching logic

In reply to Greg Kroah-Hartman

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

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

From: Jason Wang <[email protected]>

[ Upstream commit 9dc6b944f16c0904331903ba0ec36e558e1a3537 ]

Factor out the split indirect descriptor detaching logic in order to allow it to be reused by the in order support.

Message-Id: <[email protected]>
Stable-dep-of: e498eb93f961 ("virtio_ring: use shadow flags when detaching split descriptors")

---
 drivers/virtio/virtio_ring.c | 62 ++++++++++++++++++++----------------
 1 file changed, 34 insertions(+), 28 deletions(-)
drivers/virtio/virtio_ring.c +34 -28
index c51a6fc187f26..09b9b6a17f5f0 100644
@@ -748,11 +748,41 @@ static bool virtqueue_kick_prepare_split(struct virtqueue *_vq)
 	return needs_kick;
 }
 
+static void detach_indirect_split(struct vring_virtqueue *vq,
+				  unsigned int head)
+{
+	struct vring_desc_extra *extra = vq->split.desc_extra;
+	struct vring_desc *indir_desc = vq->split.desc_state[head].indir_desc;
+	unsigned int j;
+	u32 len, num;
+
+	/* Free the indirect table, if any, now that it's unmapped. */
+	if (!indir_desc)
+		return;
+	len = vq->split.desc_extra[head].len;
+
+	BUG_ON(!(vq->split.desc_extra[head].flags &
+			VRING_DESC_F_INDIRECT));
+	BUG_ON(len == 0 || len % sizeof(struct vring_desc));
+
+	num = len / sizeof(struct vring_desc);
+
+	extra = (struct vring_desc_extra *)&indir_desc[num];
+
+	if (vq->use_map_api) {
+		for (j = 0; j < num; j++)
+			vring_unmap_one_split(vq, &extra[j]);
+	}
+
+	kfree(indir_desc);
+	vq->split.desc_state[head].indir_desc = NULL;
+}
+
 static void detach_buf_split(struct vring_virtqueue *vq, unsigned int head,
 			     void **ctx)
 {
 	struct vring_desc_extra *extra;
-	unsigned int i, j;
+	unsigned int i;
 	__virtio16 nextflag = cpu_to_virtio16(vq->vq.vdev, VRING_DESC_F_NEXT);
 
 	/* Clear data ptr. */
@@ -775,34 +805,10 @@ static void detach_buf_split(struct vring_virtqueue *vq, unsigned int head,
 	/* Plus final descriptor */
 	vq->vq.num_free++;
 
-	if (vq->indirect) {
-		struct vring_desc *indir_desc =
-				vq->split.desc_state[head].indir_desc;
-		u32 len, num;
-
-		/* Free the indirect table, if any, now that it's unmapped. */
-		if (!indir_desc)
-			return;
-		len = vq->split.desc_extra[head].len;
-
-		BUG_ON(!(vq->split.desc_extra[head].flags &
-				VRING_DESC_F_INDIRECT));
-		BUG_ON(len == 0 || len % sizeof(struct vring_desc));
-
-		num = len / sizeof(struct vring_desc);
-
-		extra = (struct vring_desc_extra *)&indir_desc[num];
-
-		if (vq->use_map_api) {
-			for (j = 0; j < num; j++)
-				vring_unmap_one_split(vq, &extra[j]);
-		}
-
-		kfree(indir_desc);
-		vq->split.desc_state[head].indir_desc = NULL;
-	} else if (ctx) {
+	if (vq->indirect)
+		detach_indirect_split(vq, head);
+	else if (ctx)
 		*ctx = vq->split.desc_state[head].indir_desc;
-	}
 }
 
 static bool more_used_split(const struct vring_virtqueue *vq)
Signature · 1 line
2.53.0
author maintainer
#205 lore raw

PATCH 204/990 virtio_ring: use shadow flags when detaching split descriptors

In reply to Greg Kroah-Hartman

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

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

From: sungbyeongchan <[email protected]>

[ Upstream commit e498eb93f961db1a1dfdabd373500f0d4019c9a4 ]

Split virtqueues save descriptor flags and next indexes in desc_extra before publishing descriptors to the device. The detach path uses the shadow next index, but decides whether to continue by rereading the NEXT flag from the shared descriptor.

Use the shadow flags for the continuation decision as well. This keeps all detach metadata in the same driver-owned snapshot and avoids an unnecessary shared-ring read.

Fixes 72b5e8958738 ("virtio-ring: store DMA metadata in desc_extra for split virtqueue")
Assisted-by LLM

Message-ID: <[email protected]>

---
 drivers/virtio/virtio_ring.c | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
drivers/virtio/virtio_ring.c +1 -2
index 09b9b6a17f5f0..089a3dc2e626f 100644
@@ -783,7 +783,6 @@ static void detach_buf_split(struct vring_virtqueue *vq, unsigned int head,
 {
 	struct vring_desc_extra *extra;
 	unsigned int i;
-	__virtio16 nextflag = cpu_to_virtio16(vq->vq.vdev, VRING_DESC_F_NEXT);
 
 	/* Clear data ptr. */
 	vq->split.desc_state[head].data = NULL;
@@ -793,7 +792,7 @@ static void detach_buf_split(struct vring_virtqueue *vq, unsigned int head,
 	/* Put back on free list: unmap first-level descriptors and find end */
 	i = head;
 
-	while (vq->split.vring.desc[i].flags & nextflag) {
+	while (extra[i].flags & VRING_DESC_F_NEXT) {
 		i = vring_unmap_one_split(vq, &extra[i]);
 		vq->vq.num_free++;
 	}
Signature · 1 line
2.53.0
author maintainer
#206 lore raw

PATCH 205/990 vhost-scsi: reject delayed virtqueue setup

In reply to Greg Kroah-Hartman

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

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

From: Linfeng Sun <[email protected]>

[ Upstream commit a543346b96a174fcee6812ac2764acc8dc993358 ]

vhost_scsi_set_endpoint() allocates command pools only for I/O virtqueues that are already set up, but publishes the backend for every virtqueue. Userspace can complete a skipped queue after attaching the endpoint, then kick it with scsi_tags uninitialized and trigger the alloc_hint warning in sbitmap_get().

Delayed virtqueue setup is not supported. Leave skipped I/O virtqueues inactive and reject changes to the vring size or addresses while an endpoint is attached. Userspace must clear the endpoint before changing the vring configuration.

I found this bug myself, though the patch was written with AI assistance.

Fixes 25b98b64e284 ("vhost scsi: alloc cmds per vq instead of session")
Assisted-by OpenAI-Codex:GPT-5.6

Message-ID: <[email protected]>

---
 drivers/vhost/scsi.c | 15 ++++++++++++---
 1 file changed, 12 insertions(+), 3 deletions(-)
drivers/vhost/scsi.c +12 -3
index ba5e454ef2667..cec46ed853572 100644
@@ -2109,6 +2109,9 @@ vhost_scsi_set_endpoint(struct vhost_scsi *vs,
 
 		for (i = 0; i < vs->dev.nvqs; i++) {
 			vq = &vs->vqs[i].vq;
+			if (i >= VHOST_SCSI_VQ_IO && !vs->vqs[i].scsi_cmds)
+				continue;
+
 			mutex_lock(&vq->mutex);
 			vhost_vq_set_backend(vq, vs_tpg);
 			vhost_vq_init_access(vq);
@@ -2478,10 +2481,16 @@ vhost_scsi_ioctl(struct file *f,
 	default:
 		mutex_lock(&vs->dev.mutex);
 		r = vhost_dev_ioctl(&vs->dev, ioctl, argp);
-		if (r == -ENOIOCTLCMD)
-			r = vhost_vring_ioctl(&vs->dev, ioctl, argp);
-		else
+		if (r == -ENOIOCTLCMD) {
+			if (vs->vs_tpg &&
+			    (ioctl == VHOST_SET_VRING_NUM ||
+			     ioctl == VHOST_SET_VRING_ADDR))
+				r = -EBUSY;
+			else
+				r = vhost_vring_ioctl(&vs->dev, ioctl, argp);
+		} else {
 			vhost_scsi_flush(vs);
+		}
 		mutex_unlock(&vs->dev.mutex);
 		return r;
 	}
Signature · 1 line
2.53.0
author maintainer
#207 lore raw

PATCH 206/990 vhost: reject backend enable without a kick file

In reply to Greg Kroah-Hartman

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

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

From: Linfeng Sun <[email protected]>

[ Upstream commit 509f6bd229e94fc39506e01be692c4aa22338b49 ]

Enabling a backend without VHOST_SET_VRING_KICK dereferences a NULL vq->kick in vhost_poll_start(). Reject the request with -EINVAL.

Fixes 264ee5aa81ec ("tools/virtio: Add --reset")
Assisted-by OpenAI-Codex:GPT-5.6

Message-ID: <20261011-fix-null-pointer-in-vhost_test_set_backend-v1-1-60b2f12d64c6@gmail.com>

---
 drivers/vhost/test.c | 4 ++++
 1 file changed, 4 insertions(+)
drivers/vhost/test.c +4 -0
index 42c955a5b2111..997f869284377 100644
@@ -281,6 +281,10 @@ static long vhost_test_set_backend(struct vhost_test *n, unsigned index, int fd)
 		r = -EFAULT;
 		goto err_vq;
 	}
+	if (enable && !vq->kick) {
+		r = -EINVAL;
+		goto err_vq;
+	}
 	if (!enable) {
 		vhost_poll_stop(&vq->poll);
 		backend = vhost_vq_get_backend(vq);
Signature · 1 line
2.53.0
author maintainer
#208 lore raw

PATCH 207/990 vhost-vdpa: initialize state before publishing cdev

In reply to Greg Kroah-Hartman

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

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

From: Linfeng Sun <[email protected]>

[ Upstream commit 4b03d1e7f13613af708441a061556de99891a516 ]

Initialize the completion and as hash buckets before cdev_device_add() makes the device accessible.

Fixes 4c8cf31885f6 ("vhost: introduce vDPA-based backend")
Assisted-by OpenAI-Codex:GPT-5.6

Message-ID: <20261011-fix-null-pointer-in-vhost_vdpa_release-v2-1-66ba929971ce@gmail.com>

---
 drivers/vhost/vdpa.c | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)
drivers/vhost/vdpa.c +5 -4
index 665739ba03f8e..9014ee30861ff 100644
@@ -1705,7 +1705,7 @@ static int vhost_vdpa_probe(struct vdpa_device *vdpa)
 		return minor;
 	}
 
-	atomic_set(&v->opened, 0);
+	atomic_set(&v->opened, 1);
 	spin_lock_init(&v->config_lock);
 	v->minor = minor;
 	v->vdpa = vdpa;
@@ -1729,16 +1729,17 @@ static int vhost_vdpa_probe(struct vdpa_device *vdpa)
 
 	cdev_init(&v->cdev, &vhost_vdpa_fops);
 	v->cdev.owner = THIS_MODULE;
+	init_completion(&v->completion);
+	for (i = 0; i < VHOST_VDPA_IOTLB_BUCKETS; i++)
+		INIT_HLIST_HEAD(&v->as[i]);
 
 	r = cdev_device_add(&v->cdev, &v->dev);
 	if (r)
 		goto err;
 
-	init_completion(&v->completion);
 	vdpa_set_drvdata(vdpa, v);
 
-	for (i = 0; i < VHOST_VDPA_IOTLB_BUCKETS; i++)
-		INIT_HLIST_HEAD(&v->as[i]);
+	atomic_set_release(&v->opened, 0);
 
 	return 0;
 
Signature · 1 line
2.53.0
author maintainer
#209 lore raw

PATCH 208/990 virtio_balloon: initialize wakeup_lock before virtqueues are set up

In reply to Greg Kroah-Hartman

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

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

From: Mingbing Zhai <[email protected]>

[ Upstream commit 161aa708b02cc997a51701c342f3cebade0b5164 ]

Since c578123e63da ("virtio_balloon: Treat stats requests as wakeup events") the stats_request() virtqueue callback takes vb->wakeup_lock via start_wakeup_event(). init_vqs() registers that callback and even primes and kicks the stats queue, so the lock is reachable from irq context as soon as init_vqs() returns, long before the driver sets
DRIVER_OK: vring_interrupt() dispatches to the callback without any DRIVER_OK check unless CONFIG_VIRTIO_HARDEN_NOTIFICATION is set, and that option depends on BROKEN. syzbot hit it from a threaded irq:

INFO: trying to register non-static key in stats_request
...
assign_lock_key
register_lock_class
lock_acquire
rt_spin_lock

  start_wakeup_event drivers/virtio/virtio_balloon.c:150 [inline]
  stats_request drivers/virtio/virtio_balloon.c:435

The lock is only initialized near the end of virtballoon_probe(), after init_vqs() and several steps that can still fail and unwind through del_vqs(), where a racing interrupt still finds the callback registered. Until then it is whatever kzalloc() left in vb: lockdep complains about the unregistered lock class, and wakeup_signal_mask and processing_wakeup_event get updated from irq context while probe is still running.

The rt_spin_lock() in the report is just spin_lock() on PREEMPT_RT; any PROVE_LOCKING build takes the same path.

stop_update_lock(), which the same callback also acquires, is already initialized before init_vqs(); do the same for wakeup_lock.

Fixes c578123e63da ("virtio_balloon: Treat stats requests as wakeup events")
Reported-by [email protected]

Message-ID: <[email protected]>

---
 drivers/virtio/virtio_balloon.c | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
drivers/virtio/virtio_balloon.c +1 -2
index 0386e7b459bb1..cf53c1cf674b3 100644
@@ -963,6 +963,7 @@ static int virtballoon_probe(struct virtio_device *vdev)
 	INIT_WORK(&vb->update_balloon_stats_work, update_balloon_stats_func);
 	INIT_WORK(&vb->update_balloon_size_work, update_balloon_size_func);
 	spin_lock_init(&vb->stop_update_lock);
+	spin_lock_init(&vb->wakeup_lock);
 	mutex_init(&vb->balloon_lock);
 	init_waitqueue_head(&vb->acked);
 	vb->vdev = vdev;
@@ -1068,8 +1069,6 @@ static int virtballoon_probe(struct virtio_device *vdev)
 			goto out_unregister_oom;
 	}
 
-	spin_lock_init(&vb->wakeup_lock);
-
 	/*
 	 * The virtio balloon itself can't wake up the device, but it is
 	 * responsible for processing wakeup events passed up from the transport
Signature · 1 line
2.53.0
author maintainer
#210 lore raw

PATCH 209/990 vhost-scsi: fix page reference leak in misaligned I/O fallback

In reply to Greg Kroah-Hartman

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

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

From: Jia Jia <[email protected]>

[ Upstream commit 058fc59326af3350c6e830858e56d2aeecabe0a2 ]

iov_iter_get_pages2() returns a byte count that excludes the offset into the first page, but also returns a reference to that page in pages[].

On the misaligned-I/O fallback, vhost_scsi_revert_map_iov_to_sgl() puts pages already added to the SG list. The cleanup loop starts at pages[npages], but accounts for its first page as PAGE_SIZE bytes rather than PAGE_SIZE - offset. If the remaining data starts at a non-zero offset, it can finish one page early and leave a page reference behind.

Use PAGE_SIZE - offset for the first remaining page and clear offset for later pages, as in the mapping loop. Without this, each affected request leaks one page reference.

Fixes bca939d5bcd0 ("vhost-scsi: Dynamically allocate scatterlists")

Message-ID: <[email protected]>

---
 drivers/vhost/scsi.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
drivers/vhost/scsi.c +6 -1
index cec46ed853572..e1ea548a651b5 100644
@@ -869,11 +869,16 @@ vhost_scsi_map_to_sgl(struct vhost_scsi_cmd *cmd,
 	vhost_scsi_revert_map_iov_to_sgl(iter, *sgl, sg);
 
 	iov_iter_revert(iter, bytes);
+	/*
+	 * pages[npages] is the first page not added to the SG list.
+	 * The remaining data starts at offset in that page.
+	 */
 	while (bytes) {
-		n = min_t(unsigned int, PAGE_SIZE, bytes);
+		n = min_t(unsigned int, PAGE_SIZE - offset, bytes);
 
 		put_page(pages[npages++]);
 		bytes -= n;
+		offset = 0;
 	}
 
 	return -EINVAL;
Signature · 1 line
2.53.0
author maintainer
#211 lore raw

PATCH 210/990 ext2: only flush DIRSYNC directories on every change

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 3f57fc2c49ed05ccfc56e4dc9eda41be95925bbd ]

Every change of an ext2 directory is written to disk before the system call returns, whether the directory is DIRSYNC or not: its pages with filemap_write_and_wait() and its inode with sync_inode_metadata().

Writes which reach the device for 2000 files, and 200 directories, in a directory without DIRSYNC, with the flusher turned off:

create rename unlink mkdir
before 4000 8000 4000 800
after 0 0 0 0

In a directory with chattr +D the numbers are those of "before", before and after.

commit bc943f4872a7 ("ext2: Don't flush page immediately for DIRSYNC directories") moved the flush from ext2_commit_chunk() to the new ext2_handle_dirsync(). The IS_DIRSYNC() check which was around it didn't move along.

Fix by putting the check into ext2_handle_dirsync().

Fixes bc943f4872a7 ("ext2: Don't flush page immediately for DIRSYNC directories")
---
 fs/ext2/dir.c | 3 +++
 1 file changed, 3 insertions(+)
fs/ext2/dir.c +3 -0
index b07b3b369710c..3143983f31284 100644
@@ -441,6 +441,9 @@ static int ext2_handle_dirsync(struct inode *dir)
 {
 	int err;
 
+	if (!IS_DIRSYNC(dir))
+		return 0;
+
 	err = filemap_write_and_wait(dir->i_mapping);
 	if (!err)
 		err = sync_inode_metadata(dir, 1);
Signature · 1 line
2.53.0
author maintainer
#212 lore raw

PATCH 211/990 printk: Avoid multiple unregistration in unregister_console_locked()

In reply to Greg Kroah-Hartman

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

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

From: John Ogness <[email protected]>

[ Upstream commit 8a7f26aa072a4e63bc3b1adfe649546709db722e ]

unregister_console_locked() is called from within hlist_for_each_entry_safe(console_list) loops. This would be safe if unregister_console_locked() only unregistered the specified console. After all, that is what the _safe variant is for.

However, unregister_console_locked() calls printk_kthreads_check_locked(), which can unregister _multiple_ consoles if kthreads fail to start. This could lead to hlist_for_each_entry_safe() use-after-free scenarios because not only was the list entry removed, but possibly the following entry as well (the @n temporary storage of the next entry).

Move the call to printk_kthreads_check_locked() outside of unregister_console_locked(). Add comments to both functions to clarify if they are safe to be used in hlist_for_each_entry_safe(console_list) loops.

---
 kernel/printk/printk.c | 34 ++++++++++++++++++++++++++++++----
 1 file changed, 30 insertions(+), 4 deletions(-)
kernel/printk/printk.c +30 -4
index d555d05ffa8d4..124e7790f8447 100644
@@ -3747,6 +3747,13 @@ static struct syscore printk_syscore = {
  * If appropriate, start nbcon kthreads and set @printk_kthreads_running.
  * If any kthreads fail to start, those consoles are unregistered.
  *
+ * Called after consoles are registered or unregistered.
+ *
+ * This MUST NOT be called within an hlist_for_each_entry_safe(console_list)
+ * loop because it can unregister multiple consoles if any kthreads fail to
+ * start. That would lead to use-after-free scenarios within the
+ * hlist_for_each_entry_safe(console_list) loop of the caller.
+ *
  * Must be called under console_list_lock().
  */
 static void printk_kthreads_check_locked(void)
@@ -4188,7 +4195,20 @@ void register_console(struct console *newcon)
 }
 EXPORT_SYMBOL(register_console);
 
-/* Must be called under console_list_lock(). */
+/*
+ * Unregister the specified console.
+ *
+ * This can be called safely from within an
+ * hlist_for_each_entry_safe(console_list) loop because it unregisters
+ * _only_ the specified console.
+ *
+ * Afterwards the caller should call printk_kthreads_check_locked() since
+ * unregistering a console may require printer threads to start/stop. Note
+ * that printk_kthreads_check_locked() cannot be called safely from within
+ * an hlist_for_each_entry_safe(console_list) loop.
+ *
+ * Must be called under console_list_lock().
+ */
 static int unregister_console_locked(struct console *console)
 {
 	bool use_device_lock = (console->flags & CON_NBCON) && console->write_atomic;
@@ -4280,9 +4300,6 @@ static int unregister_console_locked(struct console *console)
 	if (console->exit)
 		res = console->exit(console);
 
-	/* Changed console list, may require printer threads to start/stop. */
-	printk_kthreads_check_locked();
-
 	return res;
 }
 
@@ -4291,7 +4308,12 @@ int unregister_console(struct console *console)
 	int res;
 
 	console_list_lock();
+
 	res = unregister_console_locked(console);
+
+	/* Changed console list, may require printer threads to start/stop. */
+	printk_kthreads_check_locked();
+
 	console_list_unlock();
 	return res;
 }
@@ -4415,6 +4437,10 @@ static int __init printk_late_init(void)
 			unregister_console_locked(con);
 		}
 	}
+
+	/* Changed console list, may require printer threads to start/stop. */
+	printk_kthreads_check_locked();
+
 	console_list_unlock();
 
 	ret = cpuhp_setup_state_nocalls(CPUHP_PRINTK_DEAD, "printk:dead", NULL,
Signature · 1 line
2.53.0
author maintainer
#213 lore raw

PATCH 212/990 block: convert nr_requests to unsigned int

In reply to Greg Kroah-Hartman

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

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

From: Yu Kuai <[email protected]>

[ Upstream commit 9fc7900b14727d39457bd3724f26e6e3faca3efd ]

This value represents the number of requests for elevator tags, or drivers tags if elevator is none. The max value for elevator tags is 2048, and in drivers at most 16 bits is used for tag.

Stable-dep-of: 3a9892bca4dd ("blk-mq: reset queue state on scheduler teardown")

---
 include/linux/blkdev.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
include/linux/blkdev.h +1 -1
index 0299d62886ed1..5d073a96324aa 100644
@@ -545,7 +545,7 @@ struct request_queue {
 	/*
 	 * queue settings
 	 */
-	unsigned long		nr_requests;	/* Max # of requests */
+	unsigned int		nr_requests;	/* Max # of requests */
 
 #ifdef CONFIG_BLK_INLINE_ENCRYPTION
 	struct blk_crypto_profile *crypto_profile;
Signature · 1 line
2.53.0
author maintainer
#214 lore raw

PATCH 213/990 blk-mq: add a new queue sysfs attribute async_depth

In reply to Greg Kroah-Hartman

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

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

From: Yu Kuai <[email protected]>

[ Upstream commit f98afe4f31bb8b07fea318606c08030c2049587e ]

Add a new field async_depth to request_queue and related APIs, this is currently not used, following patches will convert elevators to use this instead of internal async_depth.

Stable-dep-of: 3a9892bca4dd ("blk-mq: reset queue state on scheduler teardown")

---
 block/blk-core.c       |  1 +
 block/blk-mq.c         |  6 ++++++
 block/blk-sysfs.c      | 42 ++++++++++++++++++++++++++++++++++++++++++
 block/elevator.c       |  1 +
 include/linux/blkdev.h |  1 +
 5 files changed, 51 insertions(+)
block/blk-core.c +1 -0
index c2300b201d4ff..0eba4243ebfd8 100644
@@ -463,6 +463,7 @@ struct request_queue *blk_alloc_queue(struct queue_limits *lim, int node_id)
 	fs_reclaim_release(GFP_KERNEL);
 
 	q->nr_requests = BLKDEV_DEFAULT_RQ;
+	q->async_depth = BLKDEV_DEFAULT_RQ;
 
 	return q;
 
block/blk-mq.c +6 -0
index 7bdc9b1d7b746..530be27759c0e 100644
@@ -4704,6 +4704,7 @@ int blk_mq_init_allocated_queue(struct blk_mq_tag_set *set,
 	spin_lock_init(&q->requeue_lock);
 
 	q->nr_requests = set->queue_depth;
+	q->async_depth = set->queue_depth;
 
 	blk_mq_init_cpu_queues(q, set->nr_hw_queues);
 	blk_mq_map_swqueue(q);
@@ -5083,6 +5084,11 @@ struct elevator_tags *blk_mq_update_nr_requests(struct request_queue *q,
 		q->elevator->et = et;
 	}
 
+	/*
+	 * Preserve relative value, both nr and async_depth are at most 16 bit
+	 * value, no need to worry about overflow.
+	 */
+	q->async_depth = max(q->async_depth * nr / q->nr_requests, 1);
 	q->nr_requests = nr;
 	if (q->elevator && q->elevator->type->ops.depth_updated)
 		q->elevator->type->ops.depth_updated(q);
block/blk-sysfs.c +42 -0

60 lines not on this page · raw message

block/elevator.c +1 -0
index 7a97998cd8bd7..3bcd37c2aa340 100644
@@ -589,6 +589,7 @@ static int elevator_switch(struct request_queue *q, struct elv_change_ctx *ctx)
 		blk_queue_flag_clear(QUEUE_FLAG_SQ_SCHED, q);
 		q->elevator = NULL;
 		q->nr_requests = q->tag_set->queue_depth;
+		q->async_depth = q->tag_set->queue_depth;
 	}
 	blk_add_trace_msg(q, "elv switch: %s", ctx->name);
 
include/linux/blkdev.h +1 -0
index 5d073a96324aa..620093f1e5449 100644
@@ -546,6 +546,7 @@ struct request_queue {
 	 * queue settings
 	 */
 	unsigned int		nr_requests;	/* Max # of requests */
+	unsigned int		async_depth;	/* Max # of async requests */
 
 #ifdef CONFIG_BLK_INLINE_ENCRYPTION
 	struct blk_crypto_profile *crypto_profile;
Signature · 1 line
2.53.0
author maintainer
#215 lore raw

PATCH 214/990 blk-mq: reset queue state on scheduler teardown

In reply to Greg Kroah-Hartman

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

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

From: Jianan Huang <[email protected]>

[ Upstream commit 3a9892bca4dd0182db61702e131cad569b1d71e6 ]

We observed I/O timeouts with requests stalled in per-CPU software queues.

The affected queue had no elevator, but QUEUE_FLAG_SQ_SCHED remained set. A failed elevator switch can leave this state when falling back to none without clearing the flag. With empty hctx dispatch lists, a queue-wide restart on CPU4 would skip requests pending in ctx5/ctx7:

CPU4: blk_mq_run_hw_queues(q)
sq_hctx = hctx4

  hctx4: no pending requests   -> selected
  hctx5: 9 reads in ctx5       -> skipped
  hctx7: 3 writes in ctx7      -> skipped

The pending requests may remain undispatched until another event runs their hardware queues.

Clear the flag and restore nr_requests and async_depth to the driver queue depth in the common scheduler teardown path, covering both scheduler exit and failed initialization.

Fixes 4d337cebcb1c ("blk-mq: avoid to touch q->elevator without any protection")
Assisted-by LLM
---
 block/blk-mq-sched.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
block/blk-mq-sched.c +5 -1
index 128f2be9d4207..d18175ffa1b18 100644
@@ -374,7 +374,7 @@ bool blk_mq_sched_try_insert_merge(struct request_queue *q, struct request *rq,
 }
 EXPORT_SYMBOL_GPL(blk_mq_sched_try_insert_merge);
 
-/* called in queue's release handler, tagset has gone away */
+/* Clear scheduler tags and reset queue state. */
 static void blk_mq_sched_tags_teardown(struct request_queue *q, unsigned int flags)
 {
 	struct blk_mq_hw_ctx *hctx;
@@ -385,6 +385,10 @@ static void blk_mq_sched_tags_teardown(struct request_queue *q, unsigned int fla
 
 	if (blk_mq_is_shared_tags(flags))
 		q->sched_shared_tags = NULL;
+
+	blk_queue_flag_clear(QUEUE_FLAG_SQ_SCHED, q);
+	q->nr_requests = q->tag_set->queue_depth;
+	q->async_depth = q->tag_set->queue_depth;
 }
 
 void blk_mq_sched_reg_debugfs(struct request_queue *q)
Signature · 1 line
2.53.0
author maintainer
#216 lore raw

PATCH 215/990 virtio-blk: Fix zone append sector reporting in batched completion

In reply to Greg Kroah-Hartman

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

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

From: Shao Mingyin <[email protected]>

[ Upstream commit 08a6572441a4e646c96c2b8d8ead9eea0e458332 ]

For zone append, the block layer copies req->__sector back into the bio in blk_zone_append_update_request_bio(), so the driver must update req->__sector with the sector reported by the device. virtblk_request_done() does that, but the batched completion path used by virtblk_poll() only unmaps and cleans up the requests before calling blk_mq_end_request_batch().

A zone append completed through polling therefore keeps the sector that was assigned at submission time, and the file system or application sees the wrong LBA for the written data.

Move the sector update into a helper and call it from both completion paths.

---
 drivers/block/virtio_blk.c | 20 +++++++++++++++-----
 1 file changed, 15 insertions(+), 5 deletions(-)
drivers/block/virtio_blk.c +15 -5
index 29317945a7c00..8ee96de512395 100644
@@ -331,18 +331,25 @@ static inline u8 virtblk_vbr_status(struct virtblk_req *vbr)
 	return *((u8 *)&vbr->in_hdr + vbr->in_hdr_len - 1);
 }
 
+static inline void virtblk_update_zone_append_sector(struct request *req,
+						     struct virtblk_req *vbr)
+{
+	struct virtio_blk *vblk = req->mq_hctx->queue->queuedata;
+
+	if (req_op(req) == REQ_OP_ZONE_APPEND)
+		req->__sector = virtio64_to_cpu(vblk->vdev,
+						vbr->in_hdr.zone_append.sector);
+}
+
 static inline void virtblk_request_done(struct request *req)
 {
 	struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
 	blk_status_t status = virtblk_result(virtblk_vbr_status(vbr));
-	struct virtio_blk *vblk = req->mq_hctx->queue->queuedata;
 
 	virtblk_unmap_data(req, vbr);
 	virtblk_cleanup_cmd(req);
 
-	if (req_op(req) == REQ_OP_ZONE_APPEND)
-		req->__sector = virtio64_to_cpu(vblk->vdev,
-						vbr->in_hdr.zone_append.sector);
+	virtblk_update_zone_append_sector(req, vbr);
 
 	blk_mq_end_request(req, status);
 }
@@ -1213,8 +1220,11 @@ static void virtblk_complete_batch(struct io_comp_batch *iob)
 	struct request *req;
 
 	rq_list_for_each(&iob->req_list, req) {
-		virtblk_unmap_data(req, blk_mq_rq_to_pdu(req));
+		struct virtblk_req *vbr = blk_mq_rq_to_pdu(req);
+
+		virtblk_unmap_data(req, vbr);
 		virtblk_cleanup_cmd(req);
+		virtblk_update_zone_append_sector(req, vbr);
 	}
 	blk_mq_end_request_batch(iob);
 }
Signature · 1 line
2.53.0
author maintainer
#217 lore raw

PATCH 216/990 block: partitions: reject GPT entries with starting_lba > ending_lba

In reply to Greg Kroah-Hartman

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

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

From: Zizhi Wo <[email protected]>

[ Upstream commit 7e3801d12ebabaa3db6e2685ccc80b6e6f6d1ff7 ]

A GPT entry whose starting_lba is greater than its ending_lba is accepted, and the kernel creates a partition with a bogus size. The bogus sector count defeats the end-of-device check, so I/O through that partition is not confined to it and can access sectors outside the partition on the same disk.

is_pte_valid() only rejects an entry when its type is NULL or when starting_lba or ending_lba is greater than lastlba; it never checks that starting_lba <= ending_lba. For a reversed entry both field checks still pass, but efi_partition() computes size = ending_lba - starting_lba + 1 in u64, which underflows to a huge value. That value also wraps in the end-of-device check in blk_add_partition() (from + size) and does not fit the signed i_size, which turns negative.

Reject entries with starting_lba > ending_lba in is_pte_valid(), matching the head-level check against last_usable_lba < first_usable_lba.

---
 block/partitions/efi.c | 1 +
 1 file changed, 1 insertion(+)
block/partitions/efi.c +1 -0
index 7acba66eed481..d88321f6400ab 100644
@@ -461,6 +461,7 @@ static inline int
 is_pte_valid(const gpt_entry *pte, const u64 lastlba)
 {
 	if ((!efi_guidcmp(pte->partition_type_guid, NULL_GUID)) ||
+	    le64_to_cpu(pte->starting_lba) > le64_to_cpu(pte->ending_lba) ||
 	    le64_to_cpu(pte->starting_lba) > lastlba         ||
 	    le64_to_cpu(pte->ending_lba)   > lastlba)
 		return 0;
Signature · 1 line
2.53.0
author maintainer
#218 lore raw

PATCH 217/990 block: report the correct discard alignment in sysfs

In reply to Greg Kroah-Hartman

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

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

From: Avi Weiss <[email protected]>

[ Upstream commit 2516f0413f8704a7370ef8a2eeae26c9bc438978 ]

disk_discard_alignment_show() reports the physical I/O alignment offset instead of the discard alignment. Devices can specify these offsets independently, so the discard_alignment sysfs attribute can report the wrong value.

Use bdev_discard_alignment() for the whole-disk attribute, as is already done for partitions.

---
 block/genhd.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
block/genhd.c +1 -1
index 6ba0e22ce9dff..2bba931bd10aa 100644
@@ -1146,7 +1146,7 @@ static ssize_t disk_discard_alignment_show(struct device *dev,
 {
 	struct gendisk *disk = dev_to_disk(dev);
 
-	return sysfs_emit(buf, "%d\n", bdev_alignment_offset(disk->part0));
+	return sysfs_emit(buf, "%u\n", bdev_discard_alignment(disk->part0));
 }
 
 static ssize_t diskseq_show(struct device *dev,
Signature · 1 line
2.53.0
author maintainer
#219 lore raw

PATCH 218/990 zloop: fix the error code in the blk_mq_alloc_disk message

In reply to Greg Kroah-Hartman

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

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

From: Shao Mingyin <[email protected]>

[ Upstream commit 703f6aee8d8d1cb6227af56169be6b1dc4d3c4d5 ]

When blk_mq_alloc_disk() fails, "ret" still holds the zero returned by the preceding blk_mq_alloc_tag_set() call, so the error message always reports "err=0". Save PTR_ERR(zlo->disk) in "ret" before printing it, like the blk_mq_alloc_tag_set() and add_disk() failure paths do.

---
 drivers/block/zloop.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/block/zloop.c +1 -1
index 9986cfff47d6d..a49170a6565a2 100644
@@ -1024,8 +1024,8 @@ static int zloop_ctl_add(struct zloop_options *opts)
 
 	zlo->disk = blk_mq_alloc_disk(&zlo->tag_set, &lim, zlo);
 	if (IS_ERR(zlo->disk)) {
-		pr_err("blk_mq_alloc_disk failed (err=%d)\n", ret);
 		ret = PTR_ERR(zlo->disk);
+		pr_err("blk_mq_alloc_disk failed (err=%d)\n", ret);
 		goto out_cleanup_tags;
 	}
 	zlo->disk->flags = GENHD_FL_NO_PART;
Signature · 1 line
2.53.0
author maintainer
#220 lore raw

PATCH 219/990 zloop: reject mismatched conventional zone files on restore

In reply to Greg Kroah-Hartman

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

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

From: Shao Mingyin <[email protected]>

[ Upstream commit 09c2e203e0ea8b68e7c9500401fa0ab60baf1a9d ]

When restoring a zloop device, zloop_init_zone() checks that the size of each conventional zone file matches the configured zone size. The check prints an error and then jumps to out_fput, which releases the zone file and returns the value left in "ret" by the preceding vfs_getattr() call, that is, zero. zloop_ctl_add() therefore treats the zone as initialized and continues with a zone->file pointer that was already released; any I/O to that zone then dereferences it.

Return -EINVAL, like the sequential zone path does for the same kind of inconsistency.

While at it, print the zone size that is actually compared instead of the zone capacity, which may be smaller and only made the message confusing.

---
 drivers/block/zloop.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/block/zloop.c +2 -1
index a49170a6565a2..8c80231c0873c 100644
@@ -865,7 +865,8 @@ static int zloop_init_zone(struct zloop_device *zlo, struct zloop_options *opts,
 
 		if (restore && file_sectors != zlo->zone_size) {
 			pr_err("Invalid conventional zone %u file size (%llu sectors != %llu)\n",
-			       zone_no, file_sectors, zlo->zone_capacity);
+			       zone_no, file_sectors, zlo->zone_size);
+			ret = -EINVAL;
 			goto out_fput;
 		}
 
Signature · 1 line
2.53.0
author maintainer
#221 lore raw

PATCH 220/990 vsock: reject negative tv_usec in SO_VM_SOCKETS_CONNECT_TIMEOUT

In reply to Greg Kroah-Hartman

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

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

From: Nguyen Dinh Phi <[email protected]>

[ Upstream commit c0ef6144b4d60afb90bc6d8db3ffdac043cd6ffc ]

The timeval validation checks tv_usec < USEC_PER_SEC but not tv_usec >= 0, so a negative tv_usec makes the timeout computation wrap into a bogus value, later tripping "schedule_timeout: wrong timeout value" instead of being rejected.

---
 net/vmw_vsock/af_vsock.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
net/vmw_vsock/af_vsock.c +2 -1
index 999b18f2d17f1..391ac6d2435b6 100644
@@ -1986,7 +1986,8 @@ static int vsock_connectible_setsockopt(struct socket *sock,
 					     optname == SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD);
 		if (err)
 			break;
-		if (tv.tv_sec >= 0 && tv.tv_usec < USEC_PER_SEC &&
+		if (tv.tv_sec >= 0 && tv.tv_usec >= 0 &&
+		    tv.tv_usec < USEC_PER_SEC &&
 		    tv.tv_sec < (MAX_SCHEDULE_TIMEOUT / HZ - 1)) {
 			vsk->connect_timeout = tv.tv_sec * HZ +
 				DIV_ROUND_UP((unsigned long)tv.tv_usec, (USEC_PER_SEC / HZ));
Signature · 1 line
2.53.0
author maintainer
#222 lore raw

PATCH 221/990 null_blk: fix opening closed zones at the active zone limit

In reply to Greg Kroah-Hartman

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

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

From: Niklas Cassel <[email protected]>

[ Upstream commit 6f2b59737bf9cf3623719857ac149f0d431db109 ]

When the open zone limit is reached, null_check_open() closes an implicitly open zone only if the active zone limit is not reached.

Closing an implicitly open zone does not change the number of active zones, so this check is wrong. For an empty zone, the active zone limit was already checked by null_check_zone_resources(). For a closed zone, the check makes writing to, opening or finishing the zone fail with BLK_STS_ZONE_OPEN_RESOURCE at the active zone limit, whereas ZBC-3 (4.5.3.2.7.2) and NVMe ZNS (2.1.1.4.1) require closing an implicitly open zone instead.

Remove the check, and update the comment above
null_check_zone_resources() accordingly.

Fixes dc4d137ee3b7 ("null_blk: add support for max open/active zone limit for zoned devices")
---
 drivers/block/null_blk/zoned.c | 13 +++++++------
 1 file changed, 7 insertions(+), 6 deletions(-)
drivers/block/null_blk/zoned.c +7 -6
index 48d0f30694c73..cbeaec5a0a1eb 100644
@@ -311,10 +311,8 @@ static blk_status_t null_check_open(struct nullb_device *dev)
 		return BLK_STS_OK;
 
 	if (dev->nr_zones_imp_open) {
-		if (null_check_active(dev) == BLK_STS_OK) {
-			null_close_imp_open_zone(dev);
-			return BLK_STS_OK;
-		}
+		null_close_imp_open_zone(dev);
+		return BLK_STS_OK;
 	}
 
 	return BLK_STS_ZONE_OPEN_RESOURCE;
@@ -330,8 +328,11 @@ static blk_status_t null_check_open(struct nullb_device *dev)
  *
  * ZBC states that an implicit open zone shall be closed only if there is not
  * room within the open limit. However, with the addition of an active limit,
- * it is not certain that closing an implicit open zone will allow a new zone
- * to be opened, since we might already be at the active limit capacity.
+ * it is not certain that closing an implicit open zone will allow an empty
+ * zone to be opened, since we might already be at the active limit capacity.
+ * Therefore, the active limit is checked first for an empty zone. A closed
+ * zone already holds an active zone resource, so only the open limit has to
+ * be checked for a closed zone.
  */
 static blk_status_t null_check_zone_resources(struct nullb_device *dev,
 					      struct nullb_zone *zone)
Signature · 1 line
2.53.0
author maintainer
#223 lore raw

PATCH 222/990 null_blk: dont finish zones to set them read-only or offline

In reply to Greg Kroah-Hartman

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

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

From: Niklas Cassel <[email protected]>

[ Upstream commit 973bf587d79f061beffdd392e77012a07f25fcd6 ]

null_set_zone_cond() calls null_finish_zone() to release the zone resources held by a zone before setting it read-only or offline.

For an empty or closed zone, null_finish_zone() first runs the zone resource checks, which can close an unrelated implicitly open zone, or fail. As the error is ignored, a failure for a closed zone leaks nr_zones_closed, permanently lowering the effective active zone limit.

Setting a zone read-only or offline requires no zone resources, so release the zone resources held by the zone directly instead, using a new helper, null_release_zone_resources().

Fixes d3a5738849e0 ("null_blk: support read-only and offline zone conditions")
---
 drivers/block/null_blk/zoned.c | 35 +++++++++++++++++++++++++++++-----
 1 file changed, 30 insertions(+), 5 deletions(-)
drivers/block/null_blk/zoned.c +30 -5
index cbeaec5a0a1eb..ed0f066c7f78f 100644
@@ -743,6 +743,33 @@ blk_status_t null_process_zoned_cmd(struct nullb_cmd *cmd, enum req_op op,
 	}
 }
 
+/*
+ * Release the zone resources held by a zone, before changing the condition of
+ * the zone to a condition that does not hold any zone resources.
+ */
+static void null_release_zone_resources(struct nullb_device *dev,
+					struct nullb_zone *zone)
+{
+	if (!dev->need_zone_res_mgmt)
+		return;
+
+	spin_lock(&dev->zone_res_lock);
+	switch (zone->cond) {
+	case BLK_ZONE_COND_IMP_OPEN:
+		dev->nr_zones_imp_open--;
+		break;
+	case BLK_ZONE_COND_EXP_OPEN:
+		dev->nr_zones_exp_open--;
+		break;
+	case BLK_ZONE_COND_CLOSED:
+		dev->nr_zones_closed--;
+		break;
+	default:
+		break;
+	}
+	spin_unlock(&dev->zone_res_lock);
+}
+
 /*
  * Set a zone in the read-only or offline condition.
  */
@@ -759,8 +786,8 @@ static void null_set_zone_cond(struct nullb_device *dev,
 	 * If the read-only condition is requested again to zones already in
 	 * read-only condition, restore back normal empty condition. Do the same
 	 * if the offline condition is requested for offline zones. Otherwise,
-	 * set the specified zone condition to the zones. Finish the zones
-	 * beforehand to free up zone resources.
+	 * set the specified zone condition to the zones. Release the zone
+	 * resources held by the zones beforehand.
 	 */
 	if (zone->cond == cond) {
 		zone->cond = BLK_ZONE_COND_EMPTY;
@@ -768,9 +795,7 @@ static void null_set_zone_cond(struct nullb_device *dev,
 		if (dev->memory_backed)
 			null_handle_discard(dev, zone->start, zone->len);
 	} else {
-		if (zone->cond != BLK_ZONE_COND_READONLY &&
-		    zone->cond != BLK_ZONE_COND_OFFLINE)
-			null_finish_zone(dev, zone);
+		null_release_zone_resources(dev, zone);
 		zone->cond = cond;
 		zone->wp = NULL_ZONE_INVALID_WP;
 	}
Signature · 1 line
2.53.0
author maintainer
#224 lore raw

PATCH 223/990 tcp: wait for TIME_WAIT teardown before freeing per-netns ehash

In reply to Greg Kroah-Hartman

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

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

From: Kyle Zeng <[email protected]>

[ Upstream commit 647b81ddefc6364290e67bf33c89d54971f8995e ]

inet_twsk_kill() removes a TIME_WAIT socket from the established hash before it finishes using the ehash lock, hashinfo and bind tables, and before it drops the death-row reference. A running timer can therefore unhash its socket before inet_twsk_purge() reaches it. The purge cannot synchronize with that timer, and tcp_sk_exit_batch() can free the private ehash and hashinfo while inet_twsk_kill() is still using them.

An unprivileged reproducer using user and network namespaces, a private TCP ehash and a FIN_WAIT2 timer triggers a KASAN slab-use-after-free in inet_twsk_kill(). The allocation and free stacks point to inet_pernet_hashinfo_alloc() and inet_pernet_hashinfo_free().

Wait for an RCU grace period after purging the whole batch, if one netns in the batch uses a private ehash. TIME_WAIT removal runs with bottom halves disabled, so this also waits for removers that were already invisible to the purge. Keep the wait under tcp_exit_batch_mutex, before freeing any private hashinfo.

The same window exists with the shared tcp_hashinfo. There, the hashinfo memory stays valid, but tcp_sk_exit_batch() can decrement tcp_death_row.tw_refcount from 2 to 1 before inet_twsk_kill() drops its own reference. This triggers the WARN_ON_ONCE() in tcp_sk_exit_batch(), then a refcount_t "decrement hit 0" warning from inet_twsk_kill().

Adding a grace period for the shared case would be costly on busy hosts. It is not needed: struct net is freed by a later cleanup_net(), after the synchronize_rcu() in ops_undo_list(), so inet_twsk_kill() can safely drop the last tw_refcount reference itself.
Use refcount_dec_if_one() and only warn if tw_refcount is not 1 after a grace period.

Fixes d1e5e6408b30 ("tcp: Introduce optional per-netns ehash.")

[edumazet: only call synchronize_net() if one netns in the batch uses a private ehash,
use refcount_dec_if_one() to avoid a false WARN with the shared ehash]

---
 net/ipv4/tcp_ipv4.c | 21 ++++++++++++++++++++-
 1 file changed, 20 insertions(+), 1 deletion(-)
net/ipv4/tcp_ipv4.c +20 -1
index b5517f9af5465..fa5437b405207 100644
@@ -3700,6 +3700,7 @@ static int __net_init tcp_sk_init(struct net *net)
 
 static void __net_exit tcp_sk_exit_batch(struct list_head *net_exit_list)
 {
+	bool synced = false;
 	struct net *net;
 
 	/* make sure concurrent calls to tcp_sk_exit_batch from net_cleanup_work
@@ -3714,9 +3715,27 @@ static void __net_exit tcp_sk_exit_batch(struct list_head *net_exit_list)
 
 	tcp_twsk_purge(net_exit_list);
 
+	/* inet_twsk_kill() unhashes a twsk before it is done with ehash
+	 * and bhash, and before it drops its tw_refcount reference,
+	 * so tcp_twsk_purge() can miss it. Such callers run with BH
+	 * disabled: wait for them before freeing a private ehash.
+	 */
+	list_for_each_entry(net, net_exit_list, exit_list) {
+		if (net->ipv4.tcp_death_row.hashinfo->pernet) {
+			synchronize_net();
+			synced = true;
+			break;
+		}
+	}
+
 	list_for_each_entry(net, net_exit_list, exit_list) {
 		inet_pernet_hashinfo_free(net->ipv4.tcp_death_row.hashinfo);
-		WARN_ON_ONCE(!refcount_dec_and_test(&net->ipv4.tcp_death_row.tw_refcount));
+		/* Without a grace period, a concurrent inet_twsk_kill() might
+		 * still hold a tw_refcount reference. Let it drop it: struct net
+		 * is freed by a later cleanup_net(), after an RCU grace period.
+		 */
+		if (!refcount_dec_if_one(&net->ipv4.tcp_death_row.tw_refcount))
+			WARN_ON_ONCE(synced);
 		tcp_fastopen_ctx_destroy(net);
 	}
 
Signature · 1 line
2.53.0
author maintainer
#225 lore raw

PATCH 224/990 nvmet: fix arbitration burst field mask

In reply to Greg Kroah-Hartman

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

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

From: James Fantin-Hardesty <[email protected]>

[ Upstream commit 6976a9b8dc71bb3b6e5dd563e35510461bea29d4 ]

The Arbitration Burst (AB) field of the Arbitration feature is CDW11 bits 2:0 (NVMe Base Specification 2.1, Feature 01h), but nvmet incorrectly masks it with 0x3. Use 0x7 for both set and get.

Fixes a0ed77d4c9a7 ("nvmet: Implement arbitration feature support")
---
 drivers/nvme/target/admin-cmd.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/nvme/target/admin-cmd.c +2 -2
index 007029eaca39b..c8c7961beadb4 100644
@@ -1341,7 +1341,7 @@ static u16 nvmet_set_feat_arbitration(struct nvmet_req *req)
 		.hpw = (cdw11 >> 24) & 0xff,
 		.mpw = (cdw11 >> 16) & 0xff,
 		.lpw = (cdw11 >> 8) & 0xff,
-		.ab = cdw11 & 0x3,
+		.ab = cdw11 & 0x7,
 	};
 
 	if (!ctrl->ops->set_feature) {
@@ -1496,7 +1496,7 @@ static u16 nvmet_get_feat_arbitration(struct nvmet_req *req)
 			 ((u32)arb.hpw << 24) |
 			 ((u32)arb.mpw << 16) |
 			 ((u32)arb.lpw << 8) |
-			 (arb.ab & 0x3));
+			 (arb.ab & 0x7));
 
 	return NVME_SC_SUCCESS;
 }
Signature · 1 line
2.53.0
author maintainer
#226 lore raw

PATCH 225/990 net: dsa: b53: Enable IGMP and MLD control packet CPU copies

In reply to Greg Kroah-Hartman

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

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

From: Florian Fainelli <[email protected]>

[ Upstream commit 3362cb822ea750399a15b741713181fd8560bd17 ]

IGMPv2 reports and MLDv1 reports are addressed to the multicast group itself. Once the first listener is installed in the ARL table, subsequent reports can follow that entry without reaching the CPU. The bridge then fails to learn additional listeners, although static MDB forwarding works.

Enable the high-level protocol classifiers so that IGMP and MLD control packets are copied to the CPU independently of the multicast ARL lookup. Retain normal L2 forwarding by clearing the CPU-only forwarding modes, and preserve unrelated protocol-control fields.

Handle the BCM5395's 16-bit register and different classifier fields separately from the 32-bit layout on the BCM531xx, BCM5301x and newer integrated RoboSwitch families, including BCM7445, BCM7278 and BCM4908. Export the helper and call it from bcm_sf2_sw_setup() as well, since SF2 uses its own setup operation instead of b53_setup(). This also restores the classifiers after the switch reset on resume. Leave older devices with different IGMP controls untouched, and propagate register access failures during setup.

The SF2 setup integration and BCM4908 chip gate were updated with assistance from OpenAI Codex in response to review feedback.

Fixes 5d65b64a3d97 ("net: dsa: b53: Add support for MDB")
---
 drivers/net/dsa/b53/b53_common.c | 57 ++++++++++++++++++++++++++++++++
 drivers/net/dsa/b53/b53_priv.h   |  1 +
 drivers/net/dsa/b53/b53_regs.h   | 17 ++++++++++
 drivers/net/dsa/bcm_sf2.c        |  5 +++
 4 files changed, 80 insertions(+)
drivers/net/dsa/b53/b53_common.c +57 -0
index 508b46237011d..af73a9f70773d 100644
@@ -816,6 +816,59 @@ void b53_brcm_hdr_setup(struct dsa_switch *ds, int port)
 }
 EXPORT_SYMBOL(b53_brcm_hdr_setup);
 
+int b53_enable_mcast_snooping(struct b53_device *dev)
+{
+	u16 val16;
+	u32 val;
+	int ret;
+
+	/* Older switches use different IGMP controls, not HL_PRTC_CTRL. */
+	if (is5325(dev) || is5365(dev) || dev->chip_id == BCM5389_DEVICE_ID ||
+	    is5397_98(dev) || is63xx(dev))
+		return 0;
+
+	/* IGMPv2 and MLDv1 reports use the group's destination MAC. Once
+	 * the first listener is offloaded, ordinary multicast forwarding
+	 * can keep subsequent reports from reaching the bridge CPU.
+	 */
+
+	/* BCM5395 has a narrower register and a single IGMP classifier.
+	 * Its ICMPv6 classifier also covers MLD.
+	 */
+	if (dev->chip_id == BCM5395_DEVICE_ID) {
+		ret = b53_read16(dev, B53_MGMT_PAGE, B53_HL_PRTC_CTRL, &val16);
+		if (ret)
+			return ret;
+
+		val16 |= HL_PRTC_IGMP_IP_EN_5395 | HL_PRTC_ICMPV6_EN;
+		/* Zero forwarding modes copy control traffic to the CPU
+		 * independently of the ARL lookup, retaining L2 forwarding.
+		 */
+		val16 &= ~(HL_PRTC_IGMP_FWD_MODE_5395 |
+			   HL_PRTC_ICMPV6_FWD_MODE);
+
+		return b53_write16(dev, B53_MGMT_PAGE, B53_HL_PRTC_CTRL,
+				   val16);
+	}
+
+	ret = b53_read32(dev, B53_MGMT_PAGE, B53_HL_PRTC_CTRL, &val);
+	if (ret)
+		return ret;
+
+	val |= HL_PRTC_IGMP_RPTLVE_EN | HL_PRTC_IGMP_QRY_EN |
+	       HL_PRTC_IGMP_UKN_EN | HL_PRTC_MLD_RPTDONE_EN |
+	       HL_PRTC_MLD_QRY_EN;
+	/* Zero forwarding modes copy control traffic to the CPU
+	 * independently of the ARL lookup, retaining L2 forwarding.
+	 */
+	val &= ~(HL_PRTC_IGMP_RPTLVE_FWD_MODE | HL_PRTC_IGMP_QRY_FWD_MODE |
+		 HL_PRTC_IGMP_UKN_FWD_MODE | HL_PRTC_MLD_RPTDONE_FWD_MODE |
+		 HL_PRTC_MLD_QRY_FWD_MODE);
+
+	return b53_write32(dev, B53_MGMT_PAGE, B53_HL_PRTC_CTRL, val);
+}
+EXPORT_SYMBOL(b53_enable_mcast_snooping);
+
 static void b53_enable_cpu_port(struct b53_device *dev, int port)
 {
 	u8 port_ctrl;
@@ -1316,6 +1369,10 @@ static int b53_setup(struct dsa_switch *ds)
 			b53_disable_port(ds, port);
 	}
 
+	ret = b53_enable_mcast_snooping(dev);
+	if (ret)
+		return ret;
+
 	return b53_setup_devlink_resources(ds);
 }
 
drivers/net/dsa/b53/b53_priv.h +1 -0
index bd6849e5bb939..dce06110deb8b 100644
@@ -490,6 +490,7 @@ static inline int b53_switch_get_reset_gpio(struct b53_device *dev)
 /* Exported functions towards other drivers */
 void b53_imp_vlan_setup(struct dsa_switch *ds, int cpu_port);
 int b53_configure_vlan(struct dsa_switch *ds);
+int b53_enable_mcast_snooping(struct b53_device *dev);
 void b53_get_strings(struct dsa_switch *ds, int port, u32 stringset,
 		     uint8_t *data);
 void b53_get_ethtool_stats(struct dsa_switch *ds, int port, uint64_t *data);
drivers/net/dsa/b53/b53_regs.h +17 -0
index b6fe7d207a2c1..a9414851ea287 100644
@@ -270,6 +270,23 @@
 /* Revision ID register (8 bit) */
 #define B53_REV_ID			0x40
 
+/* High-level protocol control (16 bit on BCM5395, otherwise 32 bit) */
+#define B53_HL_PRTC_CTRL			0x50
+#define   HL_PRTC_ICMPV6_EN		BIT(4)
+#define   HL_PRTC_ICMPV6_FWD_MODE		BIT(5)
+#define   HL_PRTC_IGMP_IP_EN_5395		BIT(6)
+#define   HL_PRTC_IGMP_FWD_MODE_5395	BIT(8)
+#define   HL_PRTC_IGMP_RPTLVE_EN		BIT(9)
+#define   HL_PRTC_IGMP_RPTLVE_FWD_MODE	BIT(10)
+#define   HL_PRTC_IGMP_QRY_EN		BIT(11)
+#define   HL_PRTC_IGMP_QRY_FWD_MODE	BIT(12)
+#define   HL_PRTC_IGMP_UKN_EN		BIT(13)
+#define   HL_PRTC_IGMP_UKN_FWD_MODE	BIT(14)
+#define   HL_PRTC_MLD_RPTDONE_EN		BIT(15)
+#define   HL_PRTC_MLD_RPTDONE_FWD_MODE	BIT(16)
+#define   HL_PRTC_MLD_QRY_EN		BIT(17)
+#define   HL_PRTC_MLD_QRY_FWD_MODE		BIT(18)
+
 /* Broadcom header RX control (16 bit) */
 #define B53_BRCM_HDR_RX_DIS		0x60
 
drivers/net/dsa/bcm_sf2.c +5 -0
index de3efa3ce9a75..f3b56ea87b07b 100644
@@ -1059,6 +1059,7 @@ static int bcm_sf2_sw_setup(struct dsa_switch *ds)
 {
 	struct bcm_sf2_priv *priv = bcm_sf2_to_priv(ds);
 	unsigned int port;
+	int ret;
 
 	/* Enable all valid ports and disable those unused */
 	for (port = 0; port < priv->hw_params.num_ports; port++) {
@@ -1074,6 +1075,10 @@ static int bcm_sf2_sw_setup(struct dsa_switch *ds)
 	b53_configure_vlan(ds);
 	bcm_sf2_enable_acb(ds);
 
+	ret = b53_enable_mcast_snooping(priv->dev);
+	if (ret)
+		return ret;
+
 	return b53_setup_devlink_resources(ds);
 }
 
Signature · 1 line
2.53.0
author maintainer
#227 lore raw

PATCH 226/990 net: ethernet: mediatek: preserve sibling PPE bindings

In reply to Greg Kroah-Hartman

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

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

From: Alexander Goodkind <[email protected]>

[ Upstream commit 34cc22a9ce6ae0228dcd09a57df23aea62e22b04 ]

__mtk_ppe_check_skb() clears entry->hash for flows bound to other hardware slots in the same software hash bucket. mtk_flow_offload_stats() then skips their hardware counter updates. L2 cleanup also frees sibling subflows without invalidating their hardware rules.

Restrict both cleanup paths to entries assigned to the inspected slot.

Two UDP trials reproduced the counter failure on a GL-MT3000/MT7981 running unmodified OpenWrt 25.12.5 with Linux 6.12.94:

1. Start a UDP connection.
2. Add a control connection in a different hash bucket.
3. Add a connection in the first connection's hash bucket.

AI code review of the original patch identified the cleanup problem in L2 subflows.

Full ARM64 builds with allmodconfig and allyesconfig passed before and after the patch using GCC 14.2.0 and W=1, without new warnings. The builds used CONFIG_WERROR=n because the unmodified ARM64 kernel already emits warnings. Hardware testing has not run for this revision.

Fixes c4f033d9e03e ("net: ethernet: mtk_eth_soc: rework hardware flow table management")
Fixes 33fc42de3327 ("net: ethernet: mtk_eth_soc: support creating mac address based offload entries")
---
 drivers/net/ethernet/mediatek/mtk_ppe.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
drivers/net/ethernet/mediatek/mtk_ppe.c +2 -3
index bb01a7355932a..fc1362cd821cd 100644
@@ -754,8 +754,7 @@ void __mtk_ppe_check_skb(struct mtk_ppe *ppe, struct sk_buff *skb, u16 hash)
 
 	hlist_for_each_entry_safe(entry, n, head, list) {
 		if (entry->type == MTK_FLOW_TYPE_L2_SUBFLOW) {
-			if (unlikely(FIELD_GET(MTK_FOE_IB1_STATE, hwe->ib1) ==
-				     MTK_FOE_STATE_BIND))
+			if (entry->hash != hash)
 				continue;
 
 			entry->hash = 0xffff;
@@ -764,7 +763,7 @@ void __mtk_ppe_check_skb(struct mtk_ppe *ppe, struct sk_buff *skb, u16 hash)
 		}
 
 		if (found || !mtk_flow_entry_match(ppe->eth, entry, hwe)) {
-			if (entry->hash != 0xffff)
+			if (entry->hash == hash)
 				entry->hash = 0xffff;
 			continue;
 		}
Signature · 1 line
2.53.0
author maintainer
#228 lore raw

PATCH 227/990 nvmet-loop: do not alloc admin tag set during reset

In reply to Greg Kroah-Hartman

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

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

From: Maurizio Lombardi <[email protected]>

[ Upstream commit 233bbeb4a47cbead8c0471c0b8daec141033eae4 ]

Currently, resetting a loopback controller unconditionally invokes nvme_alloc_admin_tag_set() inside nvme_loop_configure_admin_queue(). Doing so drops the old queue and allocates a new one. Consequently, this reverts the admin queue's timeout (q->rq_timeout) back to the module default (NVME_ADMIN_TIMEOUT), completely wiping out any custom timeout values the user may have configured via sysfs and potentially racing against the sysfs nvme_admin_timeout_store() function that may dereference the admin_q pointer during the RESETTING state.

Decouple the admin tag set lifecycle from the admin queue configuration and destruction paths, which are executed during resets; Specifically:

* Move nvme_alloc_admin_tag_set() into nvme_loop_create_ctrl() so it is only allocated once during the initial controller creation.

* Defer the destruction of the admin tag set to nvme_loop_delete_ctrl_host() and the terminal error-handling paths of nvme_loop_reset_ctrl_work() and nvme_loop_create_ctrl().

Stable-dep-of: bc2170d36586 ("nvme-loop: delete the controller if a reset fails")

---
 drivers/nvme/target/loop.c | 31 ++++++++++++++++---------------
 1 file changed, 16 insertions(+), 15 deletions(-)
drivers/nvme/target/loop.c +16 -15
index 13bb80582b578..c096953194a00 100644
@@ -272,7 +272,6 @@ static void nvme_loop_destroy_admin_queue(struct nvme_loop_ctrl *ctrl)
 
 	nvmet_sq_destroy(&ctrl->queues[0].nvme_sq);
 	nvmet_cq_put(&ctrl->queues[0].nvme_cq);
-	nvme_remove_admin_tag_set(&ctrl->ctrl);
 }
 
 static void nvme_loop_free_ctrl(struct nvme_ctrl *nctrl)
@@ -373,25 +372,18 @@ static int nvme_loop_configure_admin_queue(struct nvme_loop_ctrl *ctrl)
 	}
 	ctrl->ctrl.queue_count = 1;
 
-	error = nvme_alloc_admin_tag_set(&ctrl->ctrl, &ctrl->admin_tag_set,
-			&nvme_loop_admin_mq_ops,
-			sizeof(struct nvme_loop_iod) +
-			NVME_INLINE_SG_CNT * sizeof(struct scatterlist));
-	if (error)
-		goto out_free_sq;
-
 	/* reset stopped state for the fresh admin queue */
 	clear_bit(NVME_CTRL_ADMIN_Q_STOPPED, &ctrl->ctrl.flags);
 
 	error = nvmf_connect_admin_queue(&ctrl->ctrl);
 	if (error)
-		goto out_cleanup_tagset;
+		goto out_free_sq;
 
 	set_bit(NVME_LOOP_Q_LIVE, &ctrl->queues[0].flags);
 
 	error = nvme_enable_ctrl(&ctrl->ctrl);
 	if (error)
-		goto out_cleanup_tagset;
+		goto out_free_sq;
 
 	ctrl->ctrl.max_hw_sectors =
 		(NVME_LOOP_MAX_SEGMENTS - 1) << PAGE_SECTORS_SHIFT;
@@ -400,14 +392,12 @@ static int nvme_loop_configure_admin_queue(struct nvme_loop_ctrl *ctrl)
 
 	error = nvme_init_ctrl_finish(&ctrl->ctrl, false);
 	if (error)
-		goto out_cleanup_tagset;
+		goto out_free_sq;
 
 	return 0;
 
-out_cleanup_tagset:
-	clear_bit(NVME_LOOP_Q_LIVE, &ctrl->queues[0].flags);
-	nvme_remove_admin_tag_set(&ctrl->ctrl);
 out_free_sq:
+	clear_bit(NVME_LOOP_Q_LIVE, &ctrl->queues[0].flags);
 	nvmet_sq_destroy(&ctrl->queues[0].nvme_sq);
 	nvmet_cq_put(&ctrl->queues[0].nvme_cq);
 	return error;
@@ -432,6 +422,7 @@ static void nvme_loop_shutdown_ctrl(struct nvme_loop_ctrl *ctrl)
 static void nvme_loop_delete_ctrl_host(struct nvme_ctrl *ctrl)
 {
 	nvme_loop_shutdown_ctrl(to_loop_ctrl(ctrl));
+	nvme_remove_admin_tag_set(ctrl);
 }
 
 static void nvme_loop_delete_ctrl(struct nvmet_ctrl *nctrl)
@@ -494,6 +485,7 @@ static void nvme_loop_reset_ctrl_work(struct work_struct *work)
 	nvme_cancel_admin_tagset(&ctrl->ctrl);
 	nvme_loop_destroy_admin_queue(ctrl);
 out_disable:
+	nvme_remove_admin_tag_set(&ctrl->ctrl);
 	dev_warn(ctrl->ctrl.device, "Removing after reset failure\n");
 	nvme_uninit_ctrl(&ctrl->ctrl);
 }
@@ -595,10 +587,17 @@ static struct nvme_ctrl *nvme_loop_create_ctrl(struct device *dev,
 	if (!ctrl->queues)
 		goto out_uninit_ctrl;
 
-	ret = nvme_loop_configure_admin_queue(ctrl);
+	ret = nvme_alloc_admin_tag_set(&ctrl->ctrl, &ctrl->admin_tag_set,
+			&nvme_loop_admin_mq_ops,
+			sizeof(struct nvme_loop_iod) +
+			NVME_INLINE_SG_CNT * sizeof(struct scatterlist));
 	if (ret)
 		goto out_free_queues;
 
+	ret = nvme_loop_configure_admin_queue(ctrl);
+	if (ret)
+		goto out_remove_admin_tagset;
+
 	if (opts->queue_size > ctrl->ctrl.maxcmd) {
 		/* warn if maxcmd is lower than queue_size */
 		dev_warn(ctrl->ctrl.device,
@@ -634,6 +633,8 @@ static struct nvme_ctrl *nvme_loop_create_ctrl(struct device *dev,
 	nvme_quiesce_admin_queue(&ctrl->ctrl);
 	nvme_cancel_admin_tagset(&ctrl->ctrl);
 	nvme_loop_destroy_admin_queue(ctrl);
+out_remove_admin_tagset:
+	nvme_remove_admin_tag_set(&ctrl->ctrl);
 out_free_queues:
 	kfree(ctrl->queues);
 out_uninit_ctrl:
Signature · 1 line
2.53.0
author maintainer
#229 lore raw

PATCH 228/990 nvme-loop: delete the controller if a reset fails

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit bc2170d365861d29dce20f982093873baad09804 ]

If the reconnect of a reset fails, nvme_loop_reset_ctrl_work() tears the controller down by hand with nvme_uninit_ctrl(). Since that was split from nvme_stop_ctrl() it no longer removes the namespaces, which hold references to the controller. A reset while the target no longer accepts the host (allow_any_host 0) is enough to get there: a sysfs reset hangs in kernfs_drain(), an ioctl reset leaves a controller stuck in CONNECTING with its block devices, the cntlid can't be reused, and module unload deletes the controller a second time and hits a use-after-free.

Do what the other fabrics drivers do and call nvme_delete_ctrl(). The delete path quiesces the admin queue and only unquiesces it if the queue is live, which it isn't after a failed reset, so unquiesce it unconditionally before destroying it so a stuck request can't block the freeze.

Fixes d09f2b45f346 ("nvme: split nvme_uninit_ctrl into stop and uninit")
Cc Christoph Hellwig <[email protected]>
Cc Sagi Grimberg <[email protected]>
Cc Chaitanya Kulkarni <[email protected]>
---
 drivers/nvme/target/loop.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/nvme/target/loop.c +3 -2
index c096953194a00..ed1c48472e017 100644
@@ -422,6 +422,8 @@ static void nvme_loop_shutdown_ctrl(struct nvme_loop_ctrl *ctrl)
 static void nvme_loop_delete_ctrl_host(struct nvme_ctrl *ctrl)
 {
 	nvme_loop_shutdown_ctrl(to_loop_ctrl(ctrl));
+	/* Left quiesced if a failed reset has left no admin queue behind */
+	nvme_unquiesce_admin_queue(ctrl);
 	nvme_remove_admin_tag_set(ctrl);
 }
 
@@ -485,9 +487,8 @@ static void nvme_loop_reset_ctrl_work(struct work_struct *work)
 	nvme_cancel_admin_tagset(&ctrl->ctrl);
 	nvme_loop_destroy_admin_queue(ctrl);
 out_disable:
-	nvme_remove_admin_tag_set(&ctrl->ctrl);
 	dev_warn(ctrl->ctrl.device, "Removing after reset failure\n");
-	nvme_uninit_ctrl(&ctrl->ctrl);
+	nvme_delete_ctrl(&ctrl->ctrl);
 }
 
 static const struct nvme_ctrl_ops nvme_loop_ctrl_ops = {
Signature · 1 line
2.53.0
author maintainer
#230 lore raw

PATCH 229/990 nvmet-tcp: ask for the TLS record type on every receive

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 77f72de389e3774dc95d7cd03a98a73e47013abd ]

nvmet_tcp_alloc_cmd() points recv_msg.msg_control at recv_cbuf once. The first receive that stores a record type there advances msg_control and leaves msg_controllen at 0 for the lifetime of the command. From then on nvmet_tcp_try_recv_data() sees the record type of that first
receive: if it was an alert, all later data is dropped as alerts and the queue stalls, if it was data, a later alert can't be reported and tls_sw_recvmsg() fails with -EIO.

Set up the control buffer before each receive, like the other receive paths do.

Fixes a1c5dd8355b1 ("nvmet-tcp: control messages for recvmsg()")
Cc Christoph Hellwig <[email protected]>
Cc Sagi Grimberg <[email protected]>
Cc Chaitanya Kulkarni <[email protected]>
---
 drivers/nvme/target/tcp.c | 5 +++++
 1 file changed, 5 insertions(+)
drivers/nvme/target/tcp.c +5 -0
index 6f8d5c268a221..c059a671a1d59 100644
@@ -1324,6 +1324,11 @@ static int nvmet_tcp_try_recv_data(struct nvmet_tcp_queue *queue)
 	int len, ret;
 
 	while (msg_data_left(&cmd->recv_msg)) {
+		if (queue->tls_pskid) {
+			/* The last receive has used it up */
+			cmd->recv_msg.msg_control = cmd->recv_cbuf;
+			cmd->recv_msg.msg_controllen = sizeof(cmd->recv_cbuf);
+		}
 		len = sock_recvmsg(cmd->queue->sock, &cmd->recv_msg,
 			cmd->recv_msg.msg_flags);
 		if (len <= 0)
Signature · 1 line
2.53.0
author maintainer
#231 lore raw

PATCH 230/990 nvme-auth: add NVME_AUTH_MAX_DIGEST_SIZE constant

In reply to Greg Kroah-Hartman

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

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

From: Eric Biggers <[email protected]>

[ Upstream commit 9100a28c8bb4270744942cf834efcd80f1acda7d ]

Define a NVME_AUTH_MAX_DIGEST_SIZE constant and use it in the appropriate places.

Stable-dep-of: 41ad4af45ac9 ("nvmet-auth: keep the old keys if the new ones fail")

---
 drivers/nvme/common/auth.c | 6 ++----
 drivers/nvme/host/auth.c   | 6 +++---
 include/linux/nvme.h       | 5 +++++
 3 files changed, 10 insertions(+), 7 deletions(-)
drivers/nvme/common/auth.c +2 -4
index 1f51fbebd9fac..aab06fc8ac774 100644
@@ -15,8 +15,6 @@
 #include <linux/nvme.h>
 #include <linux/nvme-auth.h>
 
-#define HKDF_MAX_HASHLEN 64
-
 static u32 nvme_dhchap_seqnum;
 static DEFINE_MUTEX(nvme_dhchap_mutex);
 
@@ -769,7 +767,7 @@ int nvme_auth_derive_tls_psk(int hmac_id, u8 *psk, size_t psk_len,
 	struct crypto_shash *hmac_tfm;
 	const char *hmac_name;
 	const char *label = "nvme-tls-psk";
-	static const char default_salt[HKDF_MAX_HASHLEN];
+	static const char default_salt[NVME_AUTH_MAX_DIGEST_SIZE];
 	size_t prk_len;
 	const char *ctx;
 	unsigned char *prk, *tls_key;
@@ -798,7 +796,7 @@ int nvme_auth_derive_tls_psk(int hmac_id, u8 *psk, size_t psk_len,
 		goto out_free_shash;
 	}
 
-	if (WARN_ON(prk_len > HKDF_MAX_HASHLEN)) {
+	if (WARN_ON(prk_len > NVME_AUTH_MAX_DIGEST_SIZE)) {
 		ret = -EINVAL;
 		goto out_free_prk;
 	}
drivers/nvme/host/auth.c +3 -3
index 38506314248f6..044f6cc6493bf 100644
@@ -39,9 +39,9 @@ struct nvme_dhchap_queue_context {
 	u8 hash_id;
 	u8 sc_c;
 	size_t hash_len;
-	u8 c1[64];
-	u8 c2[64];
-	u8 response[64];
+	u8 c1[NVME_AUTH_MAX_DIGEST_SIZE];
+	u8 c2[NVME_AUTH_MAX_DIGEST_SIZE];
+	u8 response[NVME_AUTH_MAX_DIGEST_SIZE];
 	u8 *ctrl_key;
 	u8 *host_key;
 	u8 *sess_key;
include/linux/nvme.h +5 -0
index 2a5d2d941d845..8aa83abc78638 100644
@@ -1837,6 +1837,11 @@ enum {
 	NVME_AUTH_HASH_INVALID	= 0xff,
 };
 
+/* Maximum digest size for any NVME_AUTH_HASH_* value */
+enum {
+	NVME_AUTH_MAX_DIGEST_SIZE = 64,
+};
+
 /* Defined Diffie-Hellman group identifiers for DH-HMAC-CHAP authentication */
 enum {
 	NVME_AUTH_DHGROUP_NULL		= 0x00,
Signature · 1 line
2.53.0
author maintainer
#232 lore raw

PATCH 231/990 nvme-auth: use proper argument types

In reply to Greg Kroah-Hartman

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

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

From: Eric Biggers <[email protected]>

[ Upstream commit bf0e2567a639c455110f9be5db8c92032175e222 ]

For input parameters, use pointer to const. This makes it easier to understand which parameters are inputs and which are outputs.

In addition, consistently use char for strings and u8 for binary. This makes it easier to understand what is a string and what is binary data.

Stable-dep-of: 41ad4af45ac9 ("nvmet-auth: keep the old keys if the new ones fail")

---
 drivers/nvme/common/auth.c  | 47 ++++++++++++++++++++-----------------
 drivers/nvme/host/auth.c    |  3 ++-
 drivers/nvme/target/auth.c  |  5 ++--
 drivers/nvme/target/nvmet.h |  2 +-
 include/linux/nvme-auth.h   | 26 ++++++++++----------
 5 files changed, 44 insertions(+), 39 deletions(-)
drivers/nvme/common/auth.c +25 -22
index aab06fc8ac774..854711bff7f9a 100644
@@ -159,11 +159,10 @@ u32 nvme_auth_key_struct_size(u32 key_len)
 }
 EXPORT_SYMBOL_GPL(nvme_auth_key_struct_size);
 
-struct nvme_dhchap_key *nvme_auth_extract_key(unsigned char *secret,
-					      u8 key_hash)
+struct nvme_dhchap_key *nvme_auth_extract_key(const char *secret, u8 key_hash)
 {
 	struct nvme_dhchap_key *key;
-	unsigned char *p;
+	const char *p;
 	u32 crc;
 	int ret, key_len;
 	size_t allocated_len = strlen(secret);
@@ -181,14 +180,14 @@ struct nvme_dhchap_key *nvme_auth_extract_key(unsigned char *secret,
 		pr_debug("base64 key decoding error %d\n",
 			 key_len);
 		ret = key_len;
-		goto out_free_secret;
+		goto out_free_key;
 	}
 
 	if (key_len != 36 && key_len != 52 &&
 	    key_len != 68) {
 		pr_err("Invalid key len %d\n", key_len);
 		ret = -EINVAL;
-		goto out_free_secret;
+		goto out_free_key;
 	}
 
 	/* The last four bytes is the CRC in little-endian format */
@@ -203,12 +202,12 @@ struct nvme_dhchap_key *nvme_auth_extract_key(unsigned char *secret,
 		pr_err("key crc mismatch (key %08x, crc %08x)\n",
 		       get_unaligned_le32(key->key + key_len), crc);
 		ret = -EKEYREJECTED;
-		goto out_free_secret;
+		goto out_free_key;
 	}
 	key->len = key_len;
 	key->hash = key_hash;
 	return key;
-out_free_secret:
+out_free_key:
 	nvme_auth_free_key(key);
 	return ERR_PTR(ret);
 }
@@ -236,7 +235,7 @@ void nvme_auth_free_key(struct nvme_dhchap_key *key)
 EXPORT_SYMBOL_GPL(nvme_auth_free_key);
 
 struct nvme_dhchap_key *nvme_auth_transform_key(
-		struct nvme_dhchap_key *key, char *nqn)
+		const struct nvme_dhchap_key *key, const char *nqn)
 {
 	const char *hmac_name;
 	struct crypto_shash *key_tfm;
@@ -302,7 +301,8 @@ struct nvme_dhchap_key *nvme_auth_transform_key(
 }
 EXPORT_SYMBOL_GPL(nvme_auth_transform_key);
 
-static int nvme_auth_hash_skey(int hmac_id, u8 *skey, size_t skey_len, u8 *hkey)
+static int nvme_auth_hash_skey(int hmac_id, const u8 *skey, size_t skey_len,
+			       u8 *hkey)
 {
 	const char *digest_name;
 	struct crypto_shash *tfm;
@@ -327,8 +327,8 @@ static int nvme_auth_hash_skey(int hmac_id, u8 *skey, size_t skey_len, u8 *hkey)
 	return ret;
 }
 
-int nvme_auth_augmented_challenge(u8 hmac_id, u8 *skey, size_t skey_len,
-		u8 *challenge, u8 *aug, size_t hlen)
+int nvme_auth_augmented_challenge(u8 hmac_id, const u8 *skey, size_t skey_len,
+				  const u8 *challenge, u8 *aug, size_t hlen)
 {
 	struct crypto_shash *tfm;
 	u8 *hashed_key;
@@ -409,7 +409,7 @@ int nvme_auth_gen_pubkey(struct crypto_kpp *dh_tfm,
 EXPORT_SYMBOL_GPL(nvme_auth_gen_pubkey);
 
 int nvme_auth_gen_shared_secret(struct crypto_kpp *dh_tfm,
-		u8 *ctrl_key, size_t ctrl_key_len,
+		const u8 *ctrl_key, size_t ctrl_key_len,
 		u8 *sess_key, size_t sess_key_len)
 {
 	struct kpp_request *req;
@@ -436,7 +436,7 @@ int nvme_auth_gen_shared_secret(struct crypto_kpp *dh_tfm,
 }
 EXPORT_SYMBOL_GPL(nvme_auth_gen_shared_secret);
 
-int nvme_auth_generate_key(u8 *secret, struct nvme_dhchap_key **ret_key)
+int nvme_auth_generate_key(const char *secret, struct nvme_dhchap_key **ret_key)
 {
 	struct nvme_dhchap_key *key;
 	u8 key_hash;
@@ -484,8 +484,9 @@ EXPORT_SYMBOL_GPL(nvme_auth_generate_key);
  * Returns 0 on success with a valid generated PSK pointer in @ret_psk and
  * the length of @ret_psk in @ret_len, or a negative error number otherwise.
  */
-int nvme_auth_generate_psk(u8 hmac_id, u8 *skey, size_t skey_len,
-		u8 *c1, u8 *c2, size_t hash_len, u8 **ret_psk, size_t *ret_len)
+int nvme_auth_generate_psk(u8 hmac_id, const u8 *skey, size_t skey_len,
+			   const u8 *c1, const u8 *c2, size_t hash_len,
+			   u8 **ret_psk, size_t *ret_len)
 {
 	struct crypto_shash *tfm;
 	SHASH_DESC_ON_STACK(shash, tfm);
@@ -582,12 +583,14 @@ EXPORT_SYMBOL_GPL(nvme_auth_generate_psk);
  * Returns 0 on success with a valid digest pointer in @ret_digest, or a
  * negative error number on failure.
  */
-int nvme_auth_generate_digest(u8 hmac_id, u8 *psk, size_t psk_len,
-		char *subsysnqn, char *hostnqn, u8 **ret_digest)
+int nvme_auth_generate_digest(u8 hmac_id, const u8 *psk, size_t psk_len,
+			      const char *subsysnqn, const char *hostnqn,
+			      char **ret_digest)
 {
 	struct crypto_shash *tfm;
 	SHASH_DESC_ON_STACK(shash, tfm);
-	u8 *digest, *enc;
+	u8 *digest;
+	char *enc;
 	const char *hmac_name;
 	size_t digest_len, hmac_len;
 	int ret;
@@ -761,16 +764,16 @@ static int hkdf_expand_label(struct crypto_shash *hmac_tfm,
  * Returns 0 on success with a valid psk pointer in @ret_psk or a negative
  * error number otherwise.
  */
-int nvme_auth_derive_tls_psk(int hmac_id, u8 *psk, size_t psk_len,
-		u8 *psk_digest, u8 **ret_psk)
+int nvme_auth_derive_tls_psk(int hmac_id, const u8 *psk, size_t psk_len,
+			     const char *psk_digest, u8 **ret_psk)
 {
 	struct crypto_shash *hmac_tfm;
 	const char *hmac_name;
 	const char *label = "nvme-tls-psk";
-	static const char default_salt[NVME_AUTH_MAX_DIGEST_SIZE];
+	static const u8 default_salt[NVME_AUTH_MAX_DIGEST_SIZE];
 	size_t prk_len;
 	const char *ctx;
-	unsigned char *prk, *tls_key;
+	u8 *prk, *tls_key;
 	int ret;
 
 	hmac_name = nvme_auth_hmac_name(hmac_id);
drivers/nvme/host/auth.c +2 -1
index 044f6cc6493bf..d0c3679acdc19 100644
@@ -722,7 +722,8 @@ EXPORT_SYMBOL_GPL(nvme_auth_revoke_tls_key);
 static int nvme_auth_secure_concat(struct nvme_ctrl *ctrl,
 				   struct nvme_dhchap_queue_context *chap)
 {
-	u8 *psk, *digest, *tls_psk;
+	u8 *psk, *tls_psk;
+	char *digest;
 	struct key *tls_key;
 	size_t psk_len;
 	int ret = 0;
drivers/nvme/target/auth.c +3 -2
index eb2b6c7a80838..99f16b1a7e886 100644
@@ -539,7 +539,7 @@ int nvmet_auth_ctrl_exponential(struct nvmet_req *req,
 }
 
 int nvmet_auth_ctrl_sesskey(struct nvmet_req *req,
-			    u8 *pkey, int pkey_size)
+			    const u8 *pkey, int pkey_size)
 {
 	struct nvmet_ctrl *ctrl = req->sq->ctrl;
 	int ret;
@@ -565,7 +565,8 @@ int nvmet_auth_ctrl_sesskey(struct nvmet_req *req,
 void nvmet_auth_insert_psk(struct nvmet_sq *sq)
 {
 	int hash_len = nvme_auth_hmac_hash_len(sq->ctrl->shash_id);
-	u8 *psk, *digest, *tls_psk;
+	u8 *psk, *tls_psk;
+	char *digest;
 	size_t psk_len;
 	int ret;
 #ifdef CONFIG_NVME_TARGET_TCP_TLS
drivers/nvme/target/nvmet.h +1 -1
index 9abf67fae1882..232768f1b24f1 100644
@@ -932,7 +932,7 @@ static inline bool nvmet_has_auth(struct nvmet_ctrl *ctrl, struct nvmet_sq *sq)
 int nvmet_auth_ctrl_exponential(struct nvmet_req *req,
 				u8 *buf, int buf_size);
 int nvmet_auth_ctrl_sesskey(struct nvmet_req *req,
-			    u8 *buf, int buf_size);
+			    const u8 *pkey, int pkey_size);
 void nvmet_auth_insert_psk(struct nvmet_sq *sq);
 #else
 static inline u8 nvmet_setup_auth(struct nvmet_ctrl *ctrl,
include/linux/nvme-auth.h +13 -13
index 60e069a6757ff..a4b248c24ccf6 100644
@@ -25,27 +25,27 @@ size_t nvme_auth_hmac_hash_len(u8 hmac_id);
 u8 nvme_auth_hmac_id(const char *hmac_name);
 
 u32 nvme_auth_key_struct_size(u32 key_len);
-struct nvme_dhchap_key *nvme_auth_extract_key(unsigned char *secret,
-					      u8 key_hash);
+struct nvme_dhchap_key *nvme_auth_extract_key(const char *secret, u8 key_hash);
 void nvme_auth_free_key(struct nvme_dhchap_key *key);
 struct nvme_dhchap_key *nvme_auth_alloc_key(u32 len, u8 hash);
 struct nvme_dhchap_key *nvme_auth_transform_key(
-				struct nvme_dhchap_key *key, char *nqn);
-int nvme_auth_generate_key(u8 *secret, struct nvme_dhchap_key **ret_key);
-int nvme_auth_augmented_challenge(u8 hmac_id, u8 *skey, size_t skey_len,
-				  u8 *challenge, u8 *aug, size_t hlen);
+		const struct nvme_dhchap_key *key, const char *nqn);
+int nvme_auth_generate_key(const char *secret, struct nvme_dhchap_key **ret_key);
+int nvme_auth_augmented_challenge(u8 hmac_id, const u8 *skey, size_t skey_len,
+				  const u8 *challenge, u8 *aug, size_t hlen);
 int nvme_auth_gen_privkey(struct crypto_kpp *dh_tfm, u8 dh_gid);
 int nvme_auth_gen_pubkey(struct crypto_kpp *dh_tfm,
 			 u8 *host_key, size_t host_key_len);
 int nvme_auth_gen_shared_secret(struct crypto_kpp *dh_tfm,
-				u8 *ctrl_key, size_t ctrl_key_len,
+				const u8 *ctrl_key, size_t ctrl_key_len,
 				u8 *sess_key, size_t sess_key_len);
-int nvme_auth_generate_psk(u8 hmac_id, u8 *skey, size_t skey_len,
-			   u8 *c1, u8 *c2, size_t hash_len,
+int nvme_auth_generate_psk(u8 hmac_id, const u8 *skey, size_t skey_len,
+			   const u8 *c1, const u8 *c2, size_t hash_len,
 			   u8 **ret_psk, size_t *ret_len);
-int nvme_auth_generate_digest(u8 hmac_id, u8 *psk, size_t psk_len,
-		char *subsysnqn, char *hostnqn, u8 **ret_digest);
-int nvme_auth_derive_tls_psk(int hmac_id, u8 *psk, size_t psk_len,
-		u8 *psk_digest, u8 **ret_psk);
+int nvme_auth_generate_digest(u8 hmac_id, const u8 *psk, size_t psk_len,
+			      const char *subsysnqn, const char *hostnqn,
+			      char **ret_digest);
+int nvme_auth_derive_tls_psk(int hmac_id, const u8 *psk, size_t psk_len,
+			     const char *psk_digest, u8 **ret_psk);
 
 #endif /* _NVME_AUTH_H */
Signature · 1 line
2.53.0
author maintainer
#233 lore raw

PATCH 232/990 nvme-auth: common: add KUnit tests for TLS key derivation

In reply to Greg Kroah-Hartman

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

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

From: Eric Biggers <[email protected]>

[ Upstream commit f990ad67f0febc51274adb604d5bdeab0d06d024 ]

Unit-test the sequence of function calls that derive tls_psk, so that we can be more confident that changes in the implementation don't break it.

Since the NVMe specification doesn't seem to include any test vectors for this (nor does its description of the algorithm seem to match what was actually implemented, for that matter), I just set the expected values to the values that the code currently produces. In the case of SHA-512, nvme_auth_generate_digest() currently returns -EINVAL, so for now the test tests for that too. If it is later determined that some other behavior is needed, the test can be updated accordingly.

Tested with:

    tools/testing/kunit/kunit.py run --kunitconfig drivers/nvme/common/

Stable-dep-of: 41ad4af45ac9 ("nvmet-auth: keep the old keys if the new ones fail")

---
 drivers/nvme/common/.kunitconfig       |   6 +
 drivers/nvme/common/Kconfig            |   8 ++
 drivers/nvme/common/Makefile           |   2 +
 drivers/nvme/common/tests/auth_kunit.c | 175 +++++++++++++++++++++++++
 4 files changed, 191 insertions(+)
 create mode 100644 drivers/nvme/common/.kunitconfig
 create mode 100644 drivers/nvme/common/tests/auth_kunit.c
drivers/nvme/common/.kunitconfig new file +6 -0
new file mode 100644
index 0000000000000..60a038dc9423d
@@ -0,0 +1,6 @@
+CONFIG_KUNIT=y
+CONFIG_PCI=y
+CONFIG_BLOCK=y
+CONFIG_BLK_DEV_NVME=y
+CONFIG_NVME_HOST_AUTH=y
+CONFIG_NVME_AUTH_KUNIT_TEST=y
drivers/nvme/common/Kconfig +8 -0
index da963e4f3f1f8..d19988c13af5f 100644
@@ -13,3 +13,11 @@ config NVME_AUTH
 	select CRYPTO_DH
 	select CRYPTO_DH_RFC7919_GROUPS
 	select CRYPTO_HKDF
+
+config NVME_AUTH_KUNIT_TEST
+	tristate "KUnit tests for NVMe authentication" if !KUNIT_ALL_TESTS
+	depends on KUNIT && NVME_AUTH
+	default KUNIT_ALL_TESTS
+	help
+	  Enable KUnit tests for some of the common code for NVMe over Fabrics
+	  In-Band Authentication.
drivers/nvme/common/Makefile +2 -0
index 681514cf2e2f5..fd9d01a609463 100644
@@ -7,3 +7,5 @@ obj-$(CONFIG_NVME_KEYRING)	+= nvme-keyring.o
 
 nvme-auth-y			+= auth.o
 nvme-keyring-y			+= keyring.o
+
+obj-$(CONFIG_NVME_AUTH_KUNIT_TEST) += tests/auth_kunit.o
drivers/nvme/common/tests/auth_kunit.c new file +175 -0

175 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#234 lore raw

PATCH 233/990 nvme-auth: common: add HMAC helper functions

In reply to Greg Kroah-Hartman

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

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

From: Eric Biggers <[email protected]>

[ Upstream commit 4263ca1cae5cebc09ba95375c4a8927bf4b39d49 ]

Add some helper functions for computing HMAC-SHA256, HMAC-SHA384, or HMAC-SHA512 values using the crypto library instead of crypto_shash. These will enable some significant simplifications and performance improvements in nvme-auth.

Stable-dep-of: 41ad4af45ac9 ("nvmet-auth: keep the old keys if the new ones fail")

---
 drivers/nvme/common/Kconfig |  2 ++
 drivers/nvme/common/auth.c  | 66 +++++++++++++++++++++++++++++++++++++
 include/linux/nvme-auth.h   | 14 ++++++++
 3 files changed, 82 insertions(+)
drivers/nvme/common/Kconfig +2 -0
index d19988c13af5f..1ec507d1f9b5f 100644
@@ -13,6 +13,8 @@ config NVME_AUTH
 	select CRYPTO_DH
 	select CRYPTO_DH_RFC7919_GROUPS
 	select CRYPTO_HKDF
+	select CRYPTO_LIB_SHA256
+	select CRYPTO_LIB_SHA512
 
 config NVME_AUTH_KUNIT_TEST
 	tristate "KUnit tests for NVMe authentication" if !KUNIT_ALL_TESTS
drivers/nvme/common/auth.c +66 -0

78 lines not on this page · raw message

include/linux/nvme-auth.h +14 -0
index a4b248c24ccf6..4f9a6599077cc 100644
@@ -7,6 +7,7 @@
 #define _NVME_AUTH_H
 
 #include <crypto/kpp.h>
+#include <crypto/sha2.h>
 
 struct nvme_dhchap_key {
 	size_t len;
@@ -23,6 +24,19 @@ const char *nvme_auth_hmac_name(u8 hmac_id);
 const char *nvme_auth_digest_name(u8 hmac_id);
 size_t nvme_auth_hmac_hash_len(u8 hmac_id);
 u8 nvme_auth_hmac_id(const char *hmac_name);
+struct nvme_auth_hmac_ctx {
+	u8 hmac_id;
+	union {
+		struct hmac_sha256_ctx sha256;
+		struct hmac_sha384_ctx sha384;
+		struct hmac_sha512_ctx sha512;
+	};
+};
+int nvme_auth_hmac_init(struct nvme_auth_hmac_ctx *hmac, u8 hmac_id,
+			const u8 *key, size_t key_len);
+void nvme_auth_hmac_update(struct nvme_auth_hmac_ctx *hmac, const u8 *data,
+			   size_t data_len);
+void nvme_auth_hmac_final(struct nvme_auth_hmac_ctx *hmac, u8 *out);
 
 u32 nvme_auth_key_struct_size(u32 key_len);
 struct nvme_dhchap_key *nvme_auth_extract_key(const char *secret, u8 key_hash);
Signature · 1 line
2.53.0
author maintainer
#235 lore raw

PATCH 234/990 nvme-auth: common: use crypto library in nvme_auth_augmented_challenge()

In reply to Greg Kroah-Hartman

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

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

From: Eric Biggers <[email protected]>

[ Upstream commit a67d096fe9761e3e503f40643228bca6d69c7c4e ]

For the hash and HMAC computations in nvme_auth_augmented_challenge(), use the crypto library instead of crypto_shash. This is simpler, faster, and more reliable. Notably, this eliminates two crypto transformation object allocations for every call, which was very slow.

Stable-dep-of: 41ad4af45ac9 ("nvmet-auth: keep the old keys if the new ones fail")

---
 drivers/nvme/common/auth.c | 96 ++++++++++++++------------------------
 1 file changed, 36 insertions(+), 60 deletions(-)
drivers/nvme/common/auth.c +36 -60
index a8e205b0411bf..28e3de1584611 100644
@@ -300,6 +300,37 @@ void nvme_auth_hmac_final(struct nvme_auth_hmac_ctx *hmac, u8 *out)
 }
 EXPORT_SYMBOL_GPL(nvme_auth_hmac_final);
 
+static int nvme_auth_hmac(u8 hmac_id, const u8 *key, size_t key_len,
+			  const u8 *data, size_t data_len, u8 *out)
+{
+	struct nvme_auth_hmac_ctx hmac;
+	int ret;
+
+	ret = nvme_auth_hmac_init(&hmac, hmac_id, key, key_len);
+	if (ret == 0) {
+		nvme_auth_hmac_update(&hmac, data, data_len);
+		nvme_auth_hmac_final(&hmac, out);
+	}
+	return ret;
+}
+
+static int nvme_auth_hash(u8 hmac_id, const u8 *data, size_t data_len, u8 *out)
+{
+	switch (hmac_id) {
+	case NVME_AUTH_HASH_SHA256:
+		sha256(data, data_len, out);
+		return 0;
+	case NVME_AUTH_HASH_SHA384:
+		sha384(data, data_len, out);
+		return 0;
+	case NVME_AUTH_HASH_SHA512:
+		sha512(data, data_len, out);
+		return 0;
+	}
+	pr_warn("%s: invalid hash algorithm %d\n", __func__, hmac_id);
+	return -EINVAL;
+}
+
 struct nvme_dhchap_key *nvme_auth_transform_key(
 		const struct nvme_dhchap_key *key, const char *nqn)
 {
@@ -367,72 +398,17 @@ struct nvme_dhchap_key *nvme_auth_transform_key(
 }
 EXPORT_SYMBOL_GPL(nvme_auth_transform_key);
 
-static int nvme_auth_hash_skey(int hmac_id, const u8 *skey, size_t skey_len,
-			       u8 *hkey)
-{
-	const char *digest_name;
-	struct crypto_shash *tfm;
-	int ret;
-
-	digest_name = nvme_auth_digest_name(hmac_id);
-	if (!digest_name) {
-		pr_debug("%s: failed to get digest for %d\n", __func__,
-			 hmac_id);
-		return -EINVAL;
-	}
-	tfm = crypto_alloc_shash(digest_name, 0, 0);
-	if (IS_ERR(tfm))
-		return -ENOMEM;
-
-	ret = crypto_shash_tfm_digest(tfm, skey, skey_len, hkey);
-	if (ret < 0)
-		pr_debug("%s: Failed to hash digest len %zu\n", __func__,
-			 skey_len);
-
-	crypto_free_shash(tfm);
-	return ret;
-}
-
 int nvme_auth_augmented_challenge(u8 hmac_id, const u8 *skey, size_t skey_len,
 				  const u8 *challenge, u8 *aug, size_t hlen)
 {
-	struct crypto_shash *tfm;
-	u8 *hashed_key;
-	const char *hmac_name;
+	u8 hashed_key[NVME_AUTH_MAX_DIGEST_SIZE];
 	int ret;
 
-	hashed_key = kmalloc(hlen, GFP_KERNEL);
-	if (!hashed_key)
-		return -ENOMEM;
-
-	ret = nvme_auth_hash_skey(hmac_id, skey,
-				  skey_len, hashed_key);
-	if (ret < 0)
-		goto out_free_key;
-
-	hmac_name = nvme_auth_hmac_name(hmac_id);
-	if (!hmac_name) {
-		pr_warn("%s: invalid hash algorithm %d\n",
-			__func__, hmac_id);
-		ret = -EINVAL;
-		goto out_free_key;
-	}
-
-	tfm = crypto_alloc_shash(hmac_name, 0, 0);
-	if (IS_ERR(tfm)) {
-		ret = PTR_ERR(tfm);
-		goto out_free_key;
-	}
-
-	ret = crypto_shash_setkey(tfm, hashed_key, hlen);
+	ret = nvme_auth_hash(hmac_id, skey, skey_len, hashed_key);
 	if (ret)
-		goto out_free_hash;
-
-	ret = crypto_shash_tfm_digest(tfm, challenge, hlen, aug);
-out_free_hash:
-	crypto_free_shash(tfm);
-out_free_key:
-	kfree_sensitive(hashed_key);
+		return ret;
+	ret = nvme_auth_hmac(hmac_id, hashed_key, hlen, challenge, hlen, aug);
+	memzero_explicit(hashed_key, sizeof(hashed_key));
 	return ret;
 }
 EXPORT_SYMBOL_GPL(nvme_auth_augmented_challenge);
Signature · 1 line
2.53.0
author maintainer
#236 lore raw

PATCH 235/990 nvme-auth: Hash DH shared secret to create session key

In reply to Greg Kroah-Hartman

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

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

From: Chris Leech <[email protected]>

[ Upstream commit bd7b7ce96db4487bb77692a85ee4489fd2c395df ]

The NVMe Base Specification 8.3.5.5.9 states that the session key Ks shall be computed from the ephemeral DH key by applying the hash function selected by the HashID parameter.

The current implementation stores the raw DH shared secret as the session key without hashing it. This causes redundant hash operations:

1. Augmented challenge computation (section 8.3.5.5.4) requires Ca = HMAC(H(g^xy mod p), C). The code compensates by hashing the unhashed session key in nvme_auth_augmented_challenge() to produce the correct result.

2. PSK generation (section 8.3.5.5.9) requires PSK = HMAC(Ks, C1 || C2) where Ks should already be H(g^xy mod p). As the DH shared secret is always larger than the HMAC block size, HMAC internally hashes it before use, accidentally producing the correct result.

When using secure channel concatenation with bidirectional authentication, this results in hashing the DH value three times: twice for augmented challenge calculations and once during PSK generation.

Fix this by:
- Modifying nvme_auth_gen_shared_secret() to hash the DH shared secret once after computation: Ks = H(g^xy mod p)
- Removing the hash operation from nvme_auth_augmented_challenge() as the session key is now already hashed
- Updating session key buffer size from DH key size to hash output size
- Adding specification references in comments

This avoid storing the raw DH shared secret and reduces the number of hash operations from three to one when using secure channel concatenation.

Stable-dep-of: 41ad4af45ac9 ("nvmet-auth: keep the old keys if the new ones fail")

---
 drivers/nvme/common/auth.c | 94 ++++++++++++++++++++++++++++++--------
 drivers/nvme/host/auth.c   | 13 +++---
 drivers/nvme/target/auth.c | 15 +++---
 include/linux/nvme-auth.h  |  6 +--
 4 files changed, 92 insertions(+), 36 deletions(-)
drivers/nvme/common/auth.c +74 -20
index 28e3de1584611..1fdceba737f7d 100644
@@ -398,18 +398,29 @@ struct nvme_dhchap_key *nvme_auth_transform_key(
 }
 EXPORT_SYMBOL_GPL(nvme_auth_transform_key);
 
+/**
+ * nvme_auth_augmented_challenge() - Compute the augmented DH-HMAC-CHAP challenge
+ * @hmac_id: Hash algorithm identifier
+ * @skey: Session key
+ * @skey_len: Length of @skey
+ * @challenge: Challenge value
+ * @aug: Output buffer for the augmented challenge
+ * @hlen: Hash output length (length of @challenge and @aug)
+ *
+ * NVMe base specification 8.3.5.5.4: The augmented challenge is computed
+ * applying the HMAC function using the hash function H() selected by the
+ * HashID parameter ... with the hash of the ephemeral DH key ... as HMAC key
+ * to the challenge C (i.e., Ca = HMAC(H(g^xy mod p), C)).
+ *
+ * As the session key skey is already H(g^xy mod p) per section 8.3.5.5.9, use
+ * it directly as the HMAC key without additional hashing.
+ *
+ * Return: 0 on success, negative errno on failure.
+ */
 int nvme_auth_augmented_challenge(u8 hmac_id, const u8 *skey, size_t skey_len,
 				  const u8 *challenge, u8 *aug, size_t hlen)
 {
-	u8 hashed_key[NVME_AUTH_MAX_DIGEST_SIZE];
-	int ret;
-
-	ret = nvme_auth_hash(hmac_id, skey, skey_len, hashed_key);
-	if (ret)
-		return ret;
-	ret = nvme_auth_hmac(hmac_id, hashed_key, hlen, challenge, hlen, aug);
-	memzero_explicit(hashed_key, sizeof(hashed_key));
-	return ret;
+	return nvme_auth_hmac(hmac_id, skey, skey_len, challenge, hlen, aug);
 }
 EXPORT_SYMBOL_GPL(nvme_auth_augmented_challenge);
 
@@ -450,33 +461,76 @@ int nvme_auth_gen_pubkey(struct crypto_kpp *dh_tfm,
 }
 EXPORT_SYMBOL_GPL(nvme_auth_gen_pubkey);
 
-int nvme_auth_gen_shared_secret(struct crypto_kpp *dh_tfm,
-		const u8 *ctrl_key, size_t ctrl_key_len,
-		u8 *sess_key, size_t sess_key_len)
+/**
+ * nvme_auth_gen_session_key() - Generate an ephemeral session key
+ * @dh_tfm: Diffie-Hellman transform with local private key already set
+ * @public_key: Peer's public key
+ * @public_key_len: Length of @public_key
+ * @sess_key: Output buffer for the session key
+ * @sess_key_len: Size of @sess_key buffer
+ * @hash_id: Hash algorithm identifier
+ *
+ * NVMe base specification 8.3.5.5.9: The session key Ks shall be computed from
+ * the ephemeral DH key (i.e., g^xy mod p) ... by applying the hash function
+ * H() selected by the HashID parameter ... (i.e., Ks = H(g^xy mod p)).
+ *
+ * Return: 0 on success, negative errno on failure.
+ */
+int nvme_auth_gen_session_key(struct crypto_kpp *dh_tfm,
+		const u8 *public_key, size_t public_key_len,
+		u8 *sess_key, size_t sess_key_len, u8 hash_id)
 {
 	struct kpp_request *req;
 	struct crypto_wait wait;
 	struct scatterlist src, dst;
+	u8 *dh_secret;
+	size_t dh_secret_len, hash_len;
 	int ret;
 
-	req = kpp_request_alloc(dh_tfm, GFP_KERNEL);
-	if (!req)
+	hash_len = nvme_auth_hmac_hash_len(hash_id);
+	if (!hash_len) {
+		pr_warn("%s: invalid hash algorithm %d\n", __func__, hash_id);
+		return -EINVAL;
+	}
+
+	if (sess_key_len != hash_len) {
+		pr_warn("%s: sess_key buffer missized (%zu != %zu)\n",
+			__func__, sess_key_len, hash_len);
+		return -EINVAL;
+	}
+
+	dh_secret_len = crypto_kpp_maxsize(dh_tfm);
+	dh_secret = kzalloc(dh_secret_len, GFP_KERNEL);
+	if (!dh_secret)
 		return -ENOMEM;
 
+	req = kpp_request_alloc(dh_tfm, GFP_KERNEL);
+	if (!req) {
+		ret = -ENOMEM;
+		goto out_free_secret;
+	}
+
 	crypto_init_wait(&wait);
-	sg_init_one(&src, ctrl_key, ctrl_key_len);
-	kpp_request_set_input(req, &src, ctrl_key_len);
-	sg_init_one(&dst, sess_key, sess_key_len);
-	kpp_request_set_output(req, &dst, sess_key_len);
+	sg_init_one(&src, public_key, public_key_len);
+	kpp_request_set_input(req, &src, public_key_len);
+	sg_init_one(&dst, dh_secret, dh_secret_len);
+	kpp_request_set_output(req, &dst, dh_secret_len);
 	kpp_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
 				 crypto_req_done, &wait);
 
 	ret = crypto_wait_req(crypto_kpp_compute_shared_secret(req), &wait);
-
 	kpp_request_free(req);
+
+	if (ret)
+		goto out_free_secret;
+
+	ret = nvme_auth_hash(hash_id, dh_secret, dh_secret_len, sess_key);
+
+out_free_secret:
+	kfree_sensitive(dh_secret);
 	return ret;
 }
-EXPORT_SYMBOL_GPL(nvme_auth_gen_shared_secret);
+EXPORT_SYMBOL_GPL(nvme_auth_gen_session_key);
 
 int nvme_auth_generate_key(const char *secret, struct nvme_dhchap_key **ret_key)
 {
drivers/nvme/host/auth.c +7 -6
index d0c3679acdc19..a64ca50e925fa 100644
@@ -652,7 +652,7 @@ static int nvme_auth_dhchap_exponential(struct nvme_ctrl *ctrl,
 	}
 
 gen_sesskey:
-	chap->sess_key_len = chap->host_key_len;
+	chap->sess_key_len = chap->hash_len;
 	chap->sess_key = kmalloc(chap->sess_key_len, GFP_KERNEL);
 	if (!chap->sess_key) {
 		chap->sess_key_len = 0;
@@ -660,16 +660,17 @@ static int nvme_auth_dhchap_exponential(struct nvme_ctrl *ctrl,
 		return -ENOMEM;
 	}
 
-	ret = nvme_auth_gen_shared_secret(chap->dh_tfm,
-					  chap->ctrl_key, chap->ctrl_key_len,
-					  chap->sess_key, chap->sess_key_len);
+	ret = nvme_auth_gen_session_key(chap->dh_tfm,
+					chap->ctrl_key, chap->ctrl_key_len,
+					chap->sess_key, chap->sess_key_len,
+					chap->hash_id);
 	if (ret) {
 		dev_dbg(ctrl->device,
-			"failed to generate shared secret, error %d\n", ret);
+			"failed to generate session key, error %d\n", ret);
 		chap->status = NVME_AUTH_DHCHAP_FAILURE_INCORRECT_PAYLOAD;
 		return ret;
 	}
-	dev_dbg(ctrl->device, "shared secret %*ph\n",
+	dev_dbg(ctrl->device, "session key %*ph\n",
 		(int)chap->sess_key_len, chap->sess_key);
 	return 0;
 }
drivers/nvme/target/auth.c +8 -7
index 99f16b1a7e886..d36cb3c0fd11d 100644
@@ -544,18 +544,19 @@ int nvmet_auth_ctrl_sesskey(struct nvmet_req *req,
 	struct nvmet_ctrl *ctrl = req->sq->ctrl;
 	int ret;
 
-	req->sq->dhchap_skey_len = ctrl->dh_keysize;
+	req->sq->dhchap_skey_len = nvme_auth_hmac_hash_len(ctrl->shash_id);
 	req->sq->dhchap_skey = kzalloc(req->sq->dhchap_skey_len, GFP_KERNEL);
 	if (!req->sq->dhchap_skey)
 		return -ENOMEM;
-	ret = nvme_auth_gen_shared_secret(ctrl->dh_tfm,
-					  pkey, pkey_size,
-					  req->sq->dhchap_skey,
-					  req->sq->dhchap_skey_len);
+	ret = nvme_auth_gen_session_key(ctrl->dh_tfm,
+					pkey, pkey_size,
+					req->sq->dhchap_skey,
+					req->sq->dhchap_skey_len,
+					ctrl->shash_id);
 	if (ret)
-		pr_debug("failed to compute shared secret, err %d\n", ret);
+		pr_debug("failed to compute session key, err %d\n", ret);
 	else
-		pr_debug("%s: shared secret %*ph\n", __func__,
+		pr_debug("%s: session key %*ph\n", __func__,
 			 (int)req->sq->dhchap_skey_len,
 			 req->sq->dhchap_skey);
 
include/linux/nvme-auth.h +3 -3
index 4f9a6599077cc..ef6d0b79e6a0e 100644
@@ -50,9 +50,9 @@ int nvme_auth_augmented_challenge(u8 hmac_id, const u8 *skey, size_t skey_len,
 int nvme_auth_gen_privkey(struct crypto_kpp *dh_tfm, u8 dh_gid);
 int nvme_auth_gen_pubkey(struct crypto_kpp *dh_tfm,
 			 u8 *host_key, size_t host_key_len);
-int nvme_auth_gen_shared_secret(struct crypto_kpp *dh_tfm,
-				const u8 *ctrl_key, size_t ctrl_key_len,
-				u8 *sess_key, size_t sess_key_len);
+int nvme_auth_gen_session_key(struct crypto_kpp *dh_tfm,
+			      const u8 *public_key, size_t public_key_len,
+			      u8 *sess_key, size_t sess_key_len, u8 hash_id);
 int nvme_auth_generate_psk(u8 hmac_id, const u8 *skey, size_t skey_len,
 			   const u8 *c1, const u8 *c2, size_t hash_len,
 			   u8 **ret_psk, size_t *ret_len);
Signature · 1 line
2.53.0
author maintainer
#237 lore raw

PATCH 236/990 nvmet-auth: Do not print DH-HMAC-CHAP secrets

In reply to Greg Kroah-Hartman

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

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

From: Hannes Reinecke <[email protected]>

[ Upstream commit a891962ae5e48fb5476c23631df759482e62ab16 ]

Quoted 1 line

From a security standpoint we should not allow to print out the DH-HMAC-CHAP

secrets, but at the same time having them is useful for debugging authentication failures.
So add a Kconfig option NVME_TARGET_AUTH_DEBUG to only enable debugging if explictly requested at build time.

Stable-dep-of: 41ad4af45ac9 ("nvmet-auth: keep the old keys if the new ones fail")

---
 drivers/nvme/target/Kconfig |  9 +++++++++
 drivers/nvme/target/auth.c  | 13 ++++++++-----
 2 files changed, 17 insertions(+), 5 deletions(-)
drivers/nvme/target/Kconfig +9 -0
index 4904097dfd490..69bde270115e2 100644
@@ -117,6 +117,15 @@ config NVME_TARGET_AUTH
 
 	  If unsure, say N.
 
+config NVME_TARGET_AUTH_DEBUG
+	bool "NVMe over Fabrics In-band Authentication debug messages"
+	depends on NVME_TARGET_AUTH
+	help
+	  This enables additional debug messages including the generated
+	  DH-HMAC-CHAP secrets to help debugging authentication failures.
+
+	  If unsure, say N.
+
 config NVME_TARGET_PCI_EPF
 	tristate "NVMe PCI Endpoint Function target support"
 	depends on NVME_TARGET && PCI_ENDPOINT
drivers/nvme/target/auth.c +8 -5
index d36cb3c0fd11d..1cb821a18532f 100644
@@ -154,7 +154,6 @@ u8 nvmet_setup_auth(struct nvmet_ctrl *ctrl, struct nvmet_sq *sq, bool reset)
 		goto out_unlock;
 
 	list_for_each_entry(p, &ctrl->subsys->hosts, entry) {
-		pr_debug("check %s\n", nvmet_host_name(p->host));
 		if (strcmp(nvmet_host_name(p->host), ctrl->hostnqn))
 			continue;
 		host = p->host;
@@ -199,11 +198,12 @@ u8 nvmet_setup_auth(struct nvmet_ctrl *ctrl, struct nvmet_sq *sq, bool reset)
 		ctrl->host_key = NULL;
 		goto out_free_hash;
 	}
+#ifdef CONFIG_NVME_TARGET_AUTH_DEBUG
 	pr_debug("%s: using hash %s key %*ph\n", __func__,
 		 ctrl->host_key->hash > 0 ?
 		 nvme_auth_hmac_name(ctrl->host_key->hash) : "none",
 		 (int)ctrl->host_key->len, ctrl->host_key->key);
-
+#endif
 	nvme_auth_free_key(ctrl->ctrl_key);
 	if (!host->dhchap_ctrl_secret) {
 		ctrl->ctrl_key = NULL;
@@ -217,11 +217,12 @@ u8 nvmet_setup_auth(struct nvmet_ctrl *ctrl, struct nvmet_sq *sq, bool reset)
 		ctrl->ctrl_key = NULL;
 		goto out_free_hash;
 	}
+#ifdef CONFIG_NVME_TARGET_AUTH_DEBUG
 	pr_debug("%s: using ctrl hash %s key %*ph\n", __func__,
 		 ctrl->ctrl_key->hash > 0 ?
 		 nvme_auth_hmac_name(ctrl->ctrl_key->hash) : "none",
 		 (int)ctrl->ctrl_key->len, ctrl->ctrl_key->key);
-
+#endif
 out_free_hash:
 	if (ret) {
 		if (ctrl->host_key) {
@@ -355,7 +356,6 @@ int nvmet_auth_host_hash(struct nvmet_req *req, u8 *response,
 		if (ret)
 			goto out;
 	}
-
 	pr_debug("ctrl %d qid %d host response seq %u transaction %d\n",
 		 ctrl->cntlid, req->sq->qid, req->sq->dhchap_s1,
 		 req->sq->dhchap_tid);
@@ -531,8 +531,10 @@ int nvmet_auth_ctrl_exponential(struct nvmet_req *req,
 		ret = -EINVAL;
 	} else {
 		memcpy(buf, ctrl->dh_key, buf_size);
+#ifdef CONFIG_NVME_TARGET_AUTH_DEBUG
 		pr_debug("%s: ctrl %d public key %*ph\n", __func__,
 			 ctrl->cntlid, (int)buf_size, buf);
+#endif
 	}
 
 	return ret;
@@ -555,11 +557,12 @@ int nvmet_auth_ctrl_sesskey(struct nvmet_req *req,
 					ctrl->shash_id);
 	if (ret)
 		pr_debug("failed to compute session key, err %d\n", ret);
+#ifdef CONFIG_NVME_TARGET_AUTH_DEBUG
 	else
 		pr_debug("%s: session key %*ph\n", __func__,
 			 (int)req->sq->dhchap_skey_len,
 			 req->sq->dhchap_skey);
-
+#endif
 	return ret;
 }
 
Signature · 1 line
2.53.0
author maintainer
#238 lore raw

PATCH 237/990 nvmet-auth: keep the old keys if the new ones fail

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 41ad4af45ac90259c652135b24539a08a92a7491 ]

AUTH_Negotiate on the admin queue has nvmet_setup_auth() reload the host's keys, and it frees the old host key first. If decoding the new secret fails, or an allocation does, the controller is left without a host key, which means no authentication at all: nvmet_check_auth_status() passes everything and I/O queue Connects no longer ask for it. configfs accepts any string starting with "DHHC-1:" and a digit, so one typo while changing a secret opens the namespaces to any connected admin queue.

Decode the new keys first and only then replace the old ones.

Fixes db1312dd9548 ("nvmet: implement basic In-Band Authentication")
Cc Hannes Reinecke <[email protected]>
Cc Christoph Hellwig <[email protected]>
Cc Sagi Grimberg <[email protected]>
Cc Chaitanya Kulkarni <[email protected]>
---
 drivers/nvme/target/auth.c | 69 ++++++++++++++++----------------------
 1 file changed, 28 insertions(+), 41 deletions(-)
drivers/nvme/target/auth.c +28 -41
index 1cb821a18532f..1ad1754a95516 100644
@@ -145,6 +145,7 @@ u8 nvmet_setup_auth(struct nvmet_ctrl *ctrl, struct nvmet_sq *sq, bool reset)
 	int ret = 0;
 	struct nvmet_host_link *p;
 	struct nvmet_host *host = NULL;
+	struct nvme_dhchap_key *host_key, *ctrl_key = NULL;
 
 	down_read(&nvmet_config_sem);
 	if (nvmet_is_disc_subsys(ctrl->subsys))
@@ -182,55 +183,41 @@ u8 nvmet_setup_auth(struct nvmet_ctrl *ctrl, struct nvmet_sq *sq, bool reset)
 		goto out_unlock;
 	}
 
-	if (host->dhchap_hash_id == ctrl->shash_id) {
-		pr_debug("Re-use existing hash ID %d\n",
-			 ctrl->shash_id);
-	} else {
-		ctrl->shash_id = host->dhchap_hash_id;
-	}
-
-	/* Skip the 'DHHC-1:XX:' prefix */
-	nvme_auth_free_key(ctrl->host_key);
-	ctrl->host_key = nvme_auth_extract_key(host->dhchap_secret + 10,
-					       host->dhchap_key_hash);
-	if (IS_ERR(ctrl->host_key)) {
+	/*
+	 * Skip the 'DHHC-1:XX:' prefix. Keep the old keys until the new ones
+	 * are there: a controller without a host key needs no authentication.
+	 */
+	host_key = nvme_auth_extract_key(host->dhchap_secret + 10,
+					 host->dhchap_key_hash);
+	if (IS_ERR(host_key)) {
 		ret = NVME_AUTH_DHCHAP_FAILURE_NOT_USABLE;
-		ctrl->host_key = NULL;
-		goto out_free_hash;
+		goto out_unlock;
 	}
+	if (host->dhchap_ctrl_secret) {
+		ctrl_key = nvme_auth_extract_key(host->dhchap_ctrl_secret + 10,
+						 host->dhchap_ctrl_key_hash);
+		if (IS_ERR(ctrl_key)) {
+			nvme_auth_free_key(host_key);
+			ret = NVME_AUTH_DHCHAP_FAILURE_NOT_USABLE;
+			goto out_unlock;
+		}
+	}
+	nvme_auth_free_key(ctrl->host_key);
+	ctrl->host_key = host_key;
+	nvme_auth_free_key(ctrl->ctrl_key);
+	ctrl->ctrl_key = ctrl_key;
+	ctrl->shash_id = host->dhchap_hash_id;
 #ifdef CONFIG_NVME_TARGET_AUTH_DEBUG
 	pr_debug("%s: using hash %s key %*ph\n", __func__,
 		 ctrl->host_key->hash > 0 ?
 		 nvme_auth_hmac_name(ctrl->host_key->hash) : "none",
 		 (int)ctrl->host_key->len, ctrl->host_key->key);
+	if (ctrl->ctrl_key)
+		pr_debug("%s: using ctrl hash %s key %*ph\n", __func__,
+			 ctrl->ctrl_key->hash > 0 ?
+			 nvme_auth_hmac_name(ctrl->ctrl_key->hash) : "none",
+			 (int)ctrl->ctrl_key->len, ctrl->ctrl_key->key);
 #endif
-	nvme_auth_free_key(ctrl->ctrl_key);
-	if (!host->dhchap_ctrl_secret) {
-		ctrl->ctrl_key = NULL;
-		goto out_unlock;
-	}
-
-	ctrl->ctrl_key = nvme_auth_extract_key(host->dhchap_ctrl_secret + 10,
-					       host->dhchap_ctrl_key_hash);
-	if (IS_ERR(ctrl->ctrl_key)) {
-		ret = NVME_AUTH_DHCHAP_FAILURE_NOT_USABLE;
-		ctrl->ctrl_key = NULL;
-		goto out_free_hash;
-	}
-#ifdef CONFIG_NVME_TARGET_AUTH_DEBUG
-	pr_debug("%s: using ctrl hash %s key %*ph\n", __func__,
-		 ctrl->ctrl_key->hash > 0 ?
-		 nvme_auth_hmac_name(ctrl->ctrl_key->hash) : "none",
-		 (int)ctrl->ctrl_key->len, ctrl->ctrl_key->key);
-#endif
-out_free_hash:
-	if (ret) {
-		if (ctrl->host_key) {
-			nvme_auth_free_key(ctrl->host_key);
-			ctrl->host_key = NULL;
-		}
-		ctrl->shash_id = 0;
-	}
 out_unlock:
 	up_read(&nvmet_config_sem);
 
Signature · 1 line
2.53.0
author maintainer
#239 lore raw

PATCH 238/990 nvmet-rdma: disconnect only established queues

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

[ Upstream commit 000a9f4492abad6008682b55571ddc31941963e3 ]

Over iWARP, rdma_disconnect() sleeps in iw_cm_disconnect() until the ESTABLISHED event of the connection has been handled, and iw_cm handles all events of all connections one at a time on iw_cm_wq. nvmet_rdma_destroy_port_queues(), nvmet_rdma_remove_one() and nvmet_rdma_delete_ctrl() walk the queue list with nvmet_rdma_queue_mutex held and call rdma_disconnect() for each, while nvmet_rdma_cm_handler() takes the same mutex. If the walk sleeps on a queue whose ESTABLISHED is queued behind another queue's event, both are stuck and iWARP connection handling is dead until reboot. A peer sets that up by connecting in a loop, or over siw by asking for MPA peer-to-peer mode and then staying silent, which delays ESTABLISHED indefinitely.

Only call rdma_disconnect() for a queue in NVMET_RDMA_Q_LIVE, which the handler sets when it gets ESTABLISHED. A queue that never got there is left to the release work: ib_drain_qp() moves the QP to the error state, which ends the connection, and rdma_destroy_id() tells the peer. Over IB and RoCE the skipped call did nothing more than that.

Fixes f1d4ef7d8883 ("nvmet-rdma: register ib_client to not deadlock in device removal")
Fixes fcf73a804c7d ("nvmet-rdma: fix use-after-free when a port is removed")
Cc Christoph Hellwig <[email protected]>
Cc Sagi Grimberg <[email protected]>
Cc Chaitanya Kulkarni <[email protected]>
---
 drivers/nvme/target/rdma.c | 15 +++++++++++++--
 1 file changed, 13 insertions(+), 2 deletions(-)
drivers/nvme/target/rdma.c +13 -2
index 20e574a4eac64..338933d15b38e 100644
@@ -1691,7 +1691,7 @@ static void nvmet_rdma_queue_established(struct nvmet_rdma_queue *queue)
 
 static void __nvmet_rdma_queue_disconnect(struct nvmet_rdma_queue *queue)
 {
-	bool disconnect = false;
+	bool disconnect = false, live = false;
 	unsigned long flags;
 
 	pr_debug("cm_id= %p queue->state= %d\n", queue->cm_id, queue->state);
@@ -1710,6 +1710,7 @@ static void __nvmet_rdma_queue_disconnect(struct nvmet_rdma_queue *queue)
 		}
 		fallthrough;
 	case NVMET_RDMA_Q_LIVE:
+		live = queue->state == NVMET_RDMA_Q_LIVE;
 		queue->state = NVMET_RDMA_Q_DISCONNECTING;
 		disconnect = true;
 		break;
@@ -1719,7 +1720,17 @@ static void __nvmet_rdma_queue_disconnect(struct nvmet_rdma_queue *queue)
 	spin_unlock_irqrestore(&queue->state_lock, flags);
 
 	if (disconnect) {
-		rdma_disconnect(queue->cm_id);
+		/*
+		 * Over iWARP rdma_disconnect() sleeps until the CM has handled
+		 * the ESTABLISHED event of this connection. The CM handles the
+		 * events of all connections one at a time, and our handler
+		 * takes nvmet_rdma_queue_mutex, which callers of this function
+		 * hold. So a queue that has not seen the event is left to the
+		 * release work: ib_drain_qp() moves the queue pair to the error
+		 * state, which ends the connection.
+		 */
+		if (live)
+			rdma_disconnect(queue->cm_id);
 		queue_work(nvmet_wq, &queue->release_work);
 	}
 }
Signature · 1 line
2.53.0
author maintainer
#240 lore raw

PATCH 239/990 nvmet-tcp: limit the connections accepted per work run

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit a029f1b2fb13e6ac6e1c2f27fba1d80b6e7cac51 ]

nvmet_tcp_accept_work() loops until there's nothing left to accept, and anyone opening and closing connections fast enough keeps it running indefinitely, since tearing down a dead connection takes long enough for more to arrive. Whoever flushes nvmet_wq waits for it: removing any other port of the target does in nvmet_port_release(), and so does unloading the rdma and fc modules.

Accept a bounded number of connections per run and requeue the work. A flush doesn't wait for work queued behind it.

Fixes 872d26a391da ("nvmet-tcp: add NVMe over TCP target driver")
Cc Christoph Hellwig <[email protected]>
Cc Sagi Grimberg <[email protected]>
Cc Chaitanya Kulkarni <[email protected]>
---
 drivers/nvme/target/tcp.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
drivers/nvme/target/tcp.c +6 -2
index c059a671a1d59..72e928c38aa2a 100644
@@ -102,6 +102,7 @@ MODULE_PARM_DESC(tls_handshake_timeout,
 #define NVMET_TCP_RECV_BUDGET		8
 #define NVMET_TCP_SEND_BUDGET		8
 #define NVMET_TCP_IO_WORK_BUDGET	64
+#define NVMET_TCP_ACCEPT_BUDGET		16
 
 enum nvmet_tcp_send_state {
 	NVMET_TCP_SEND_DATA_PDU,
@@ -2095,9 +2096,9 @@ static void nvmet_tcp_accept_work(struct work_struct *w)
 	struct nvmet_tcp_port *port =
 		container_of(w, struct nvmet_tcp_port, accept_work);
 	struct socket *newsock;
-	int ret;
+	int ret, i;
 
-	while (true) {
+	for (i = 0; i < NVMET_TCP_ACCEPT_BUDGET; i++) {
 		ret = kernel_accept(port->sock, &newsock, O_NONBLOCK);
 		if (ret < 0) {
 			if (ret != -EAGAIN)
@@ -2106,6 +2107,9 @@ static void nvmet_tcp_accept_work(struct work_struct *w)
 		}
 		nvmet_tcp_alloc_queue(port, newsock);
 	}
+
+	/* There may be more. Come to an end for those who flush nvmet_wq. */
+	queue_work(nvmet_wq, &port->accept_work);
 }
 
 static void nvmet_tcp_listen_data_ready(struct sock *sk)
Signature · 1 line
2.53.0
author maintainer
#241 lore raw

PATCH 240/990 nvmet-rdma: take a device off the list last

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

[ Upstream commit 86ae3841aea4e29d7ac08d5614ca3823dc8dfbc9 ]

nvmet_rdma_remove_one() disconnects the queues of a device and flushes nvmet-wq, but since commit a3dd7d0022c3 it returns right away if the device isn't on device_list. nvmet_rdma_free_dev(), run by the release work of the last queue, takes the device off that list first and frees the SRQs and the PD afterwards. A device removal in between finds nothing on the list, returns, and the RDMA core frees the device under ib_dealloc_pd().

Free the SRQs and the PD first and unlist the device last, so the remove callback finds it and its flush waits for the release work.

Fixes a3dd7d0022c3 ("nvmet-rdma: Don't flush system_wq by default during remove_one")
Cc Christoph Hellwig <[email protected]>
Cc Sagi Grimberg <[email protected]>
Cc Chaitanya Kulkarni <[email protected]>
---
 drivers/nvme/target/rdma.c | 11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)
drivers/nvme/target/rdma.c +8 -3
index 338933d15b38e..816ad550d1fc8 100644
@@ -1197,13 +1197,18 @@ static void nvmet_rdma_free_dev(struct kref *ref)
 	struct nvmet_rdma_device *ndev =
 		container_of(ref, struct nvmet_rdma_device, ref);
 
+	nvmet_rdma_destroy_srqs(ndev);
+	ib_dealloc_pd(ndev->pd);
+
+	/*
+	 * Only delete from the device list once all RDMA resources are torn
+	 * down because nvmet_rdma_remove_one waits for the release work only
+	 * if the device still is on the list.
+	 */
 	mutex_lock(&device_list_mutex);
 	list_del(&ndev->entry);
 	mutex_unlock(&device_list_mutex);
 
-	nvmet_rdma_destroy_srqs(ndev);
-	ib_dealloc_pd(ndev->pd);
-
 	kfree(ndev);
 }
 
Signature · 1 line
2.53.0
author maintainer
#242 lore raw

PATCH 241/990 nvmet-rdma: queue the release work under the mutex

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

[ Upstream commit 80095787f776967361cca76357f19e5445e0cd75 ]

nvmet_rdma_remove_one() takes the queue mutex, unlists each queue of the device and queues its release work, then flushes nvmet-wq. So a queue that still holds objects on the device must either be on the list or have its release work queued. nvmet_rdma_queue_disconnect() breaks that: it unlists the queue under the mutex, drops it, and only then calls __nvmet_rdma_queue_disconnect() to queue the work. A device removal in that window finds nothing to wait for, and the release work then destroys the QP and CQ share on a freed device.

Queue the work before dropping the mutex, as nvmet_rdma_remove_one() itself does. That's safe now that rdma_disconnect() no longer sleeps on an iWARP event that needs the same mutex.

Fixes f1d4ef7d8883 ("nvmet-rdma: register ib_client to not deadlock in device removal")
Cc Christoph Hellwig <[email protected]>
Cc Sagi Grimberg <[email protected]>
Cc Chaitanya Kulkarni <[email protected]>
---
 drivers/nvme/target/rdma.c | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
drivers/nvme/target/rdma.c +6 -6
index 816ad550d1fc8..58fc89b22c98c 100644
@@ -1742,17 +1742,17 @@ static void __nvmet_rdma_queue_disconnect(struct nvmet_rdma_queue *queue)
 
 static void nvmet_rdma_queue_disconnect(struct nvmet_rdma_queue *queue)
 {
-	bool disconnect = false;
-
+	/*
+	 * Queue the release work with &nvmet_rdma_queue_mutex held, so that
+	 * nvmet_rdma_remove_one() either finds the queue on the list or the
+	 * work has already been queued.
+	 */
 	mutex_lock(&nvmet_rdma_queue_mutex);
 	if (!list_empty(&queue->queue_list)) {
 		list_del_init(&queue->queue_list);
-		disconnect = true;
+		__nvmet_rdma_queue_disconnect(queue);
 	}
 	mutex_unlock(&nvmet_rdma_queue_mutex);
-
-	if (disconnect)
-		__nvmet_rdma_queue_disconnect(queue);
 }
 
 static void nvmet_rdma_queue_connect_fail(struct rdma_cm_id *cm_id,
Signature · 1 line
2.53.0
author maintainer
#243 lore raw

PATCH 242/990 nvmet-rdma: disconnect a queue on device removal

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

[ Upstream commit a4387799d4228866dc1746b466cd17e1c638d050 ]

cma_remove_one() sends DEVICE_REMOVAL to the owner of every cm_id on the device and then waits, without timeout, until they're all destroyed. nvmet_rdma_device_removal() does nothing for a queue cm_id and leaves the queues to nvmet_rdma_remove_one(), which only works if that runs first. As a module it does, nvmet-rdma registers after rdma_cm. Built in, both register at the same initcall level and drivers/Makefile lists nvme/ ahead of infiniband/, so cma_remove_one() runs first and waits for cm_ids that only the later callback would destroy. Since the RDMA CM drops all later events for a cm_id once it has sent DEVICE_REMOVAL, a peer closing its connection doesn't help either. One connection from anyone who can reach the port hangs "rdma link delete" until something else ends the queue.

Call nvmet_rdma_queue_disconnect() for the queue. It unlists the queue and queues the release work, which destroys the cm_id. Don't wait for it, rdma_destroy_id() waits for the handler to return, which was the deadlock before commit f1d4ef7d8883.

Fixes f1d4ef7d8883 ("nvmet-rdma: register ib_client to not deadlock in device removal")
Cc Christoph Hellwig <[email protected]>
Cc Sagi Grimberg <[email protected]>
Cc Chaitanya Kulkarni <[email protected]>
---
 drivers/nvme/target/rdma.c | 17 ++++++++---------
 1 file changed, 8 insertions(+), 9 deletions(-)
drivers/nvme/target/rdma.c +8 -9
index 58fc89b22c98c..7cbba255de206 100644
@@ -1779,10 +1779,13 @@ static void nvmet_rdma_queue_connect_fail(struct rdma_cm_id *cm_id,
  * queue cm_id and/or a device bound listener cm_id (where in this
  * case queue will be null).
  *
- * We registered an ib_client to handle device removal for queues,
- * so we only need to handle the listening port cm_ids. In this case
- * we nullify the priv to prevent double cm_id destruction and destroying
- * the cm_id implicitly by returning a non-zero rc to the callout.
+ * The RDMA CM waits until each cm_id of the device is destroyed, so a queue
+ * has to go now. Our ib_client also removes the queues, but it cannot be
+ * relied on here: built in, it is called after the RDMA CM's client.
+ *
+ * For a listening port cm_id we nullify the priv to prevent double cm_id
+ * destruction and destroying the cm_id implicitly by returning a non-zero
+ * rc to the callout.
  */
 static int nvmet_rdma_device_removal(struct rdma_cm_id *cm_id,
 		struct nvmet_rdma_queue *queue)
@@ -1790,11 +1793,7 @@ static int nvmet_rdma_device_removal(struct rdma_cm_id *cm_id,
 	struct nvmet_rdma_port *port;
 
 	if (queue) {
-		/*
-		 * This is a queue cm_id. we have registered
-		 * an ib_client to handle queues removal
-		 * so don't interfere and just return.
-		 */
+		nvmet_rdma_queue_disconnect(queue);
 		return 0;
 	}
 
Signature · 1 line
2.53.0
author maintainer
#244 lore raw

PATCH 243/990 ASoC: rockchip_i2s: select REGMAP_MMIO

In reply to Greg Kroah-Hartman

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

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

From: Jude Gyimah <[email protected]>

[ Upstream commit 1c57404bf9bad3e05d5686d91c208bf4e2b733d8 ]

rockchip_i2s calls __devm_regmap_init_mmio_clk, which drivers/base/regmap/regmap-mmio.c provides under REGMAP_MMIO.

rockchip_i2s.c:(.text+0x418): undefined reference to

    `__devm_regmap_init_mmio_clk'

The driver can be built into vmlinux while REGMAP_MMIO is a module, in which case the symbol is not there at link time.

Select rather than depend on: REGMAP_MMIO has no prompt of its own and is only ever enabled by a select, so a depends on would leave SND_SOC_ROCKCHIP_I2S unselectable.

Reproduced on v7.3, x86_64, with CONFIG_SND_SOC_ROCKCHIP_I2S=y and CONFIG_REGMAP_MMIO=m.

Found with kreach, a static check that compares what Kconfig allows against the symbols the compiled objects actually reference.

Fixes 4495c89fcf26 ("ASoC: add driver for Rockchip RK3xxx I2S controller")
---
 sound/soc/rockchip/Kconfig | 1 +
 1 file changed, 1 insertion(+)
sound/soc/rockchip/Kconfig +1 -0
index bd210fafe9fea..e09325aaba534 100644
@@ -5,6 +5,7 @@ menu "Rockchip"
 
 config SND_SOC_ROCKCHIP_I2S
 	tristate "Rockchip I2S Device Driver"
+	select REGMAP_MMIO
 	select SND_SOC_GENERIC_DMAENGINE_PCM
 	help
 	  Say Y or M if you want to add support for I2S driver for
Signature · 1 line
2.53.0
author maintainer
#245 lore raw

PATCH 244/990 ASoC: rockchip_i2s_tdm: select REGMAP_MMIO

In reply to Greg Kroah-Hartman

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

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

From: Jude Gyimah <[email protected]>

[ Upstream commit b8284f2b73f8de157be52b48d9968645f4ad6f7c ]

rockchip_i2s_tdm calls __devm_regmap_init_mmio_clk, which drivers/base/regmap/regmap-mmio.c provides under REGMAP_MMIO.

rockchip_i2s_tdm.c:1304:(.text+0x14b1b6): undefined reference to

    `__devm_regmap_init_mmio_clk'

The driver can be built into vmlinux while REGMAP_MMIO is a module, in which case the symbol is not there at link time.

Select rather than depend on: REGMAP_MMIO has no prompt of its own and is only ever enabled by a select, so a depends on would leave SND_SOC_ROCKCHIP_I2S_TDM unselectable.

Reproduced on v7.3, x86_64, with CONFIG_SND_SOC_ROCKCHIP_I2S_TDM=y and CONFIG_REGMAP_MMIO=m.

Found with kreach, a static check that compares what Kconfig allows against the symbols the compiled objects actually reference.

Fixes 081068fd6414 ("ASoC: rockchip: add support for i2s-tdm controller")
---
 sound/soc/rockchip/Kconfig | 1 +
 1 file changed, 1 insertion(+)
sound/soc/rockchip/Kconfig +1 -0
index e09325aaba534..4df880cc4b319 100644
@@ -14,6 +14,7 @@ config SND_SOC_ROCKCHIP_I2S
 
 config SND_SOC_ROCKCHIP_I2S_TDM
 	tristate "Rockchip I2S/TDM Device Driver"
+	select REGMAP_MMIO
 	select SND_SOC_GENERIC_DMAENGINE_PCM
 	help
 	  Say Y or M if you want to add support for the I2S/TDM driver for
Signature · 1 line
2.53.0
author maintainer
#246 lore raw

PATCH 245/990 ASoC: rockchip_pdm: select REGMAP_MMIO

In reply to Greg Kroah-Hartman

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

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

From: Jude Gyimah <[email protected]>

[ Upstream commit 420c7918a61b97b8cd99e402e7e5a857edb097ee ]

rockchip_pdm calls __devm_regmap_init_mmio_clk, which drivers/base/regmap/regmap-mmio.c provides under REGMAP_MMIO.

rockchip_pdm.c:(.text+0xef4): undefined reference to

    `__devm_regmap_init_mmio_clk'

The driver can be built into vmlinux while REGMAP_MMIO is a module, in which case the symbol is not there at link time.

Select rather than depend on: REGMAP_MMIO has no prompt of its own and is only ever enabled by a select, so a depends on would leave SND_SOC_ROCKCHIP_PDM unselectable.

Reproduced on v7.3, x86_64, with CONFIG_SND_SOC_ROCKCHIP_PDM=y and CONFIG_REGMAP_MMIO=m.

Found with kreach, a static check that compares what Kconfig allows against the symbols the compiled objects actually reference.

Fixes fc05a5b22253 ("ASoC: rockchip: add support for pdm controller")
---
 sound/soc/rockchip/Kconfig | 1 +
 1 file changed, 1 insertion(+)
sound/soc/rockchip/Kconfig +1 -0
index 4df880cc4b319..e96d1a95bb10c 100644
@@ -25,6 +25,7 @@ config SND_SOC_ROCKCHIP_I2S_TDM
 
 config SND_SOC_ROCKCHIP_PDM
 	tristate "Rockchip PDM Controller Driver"
+	select REGMAP_MMIO
 	select SND_SOC_GENERIC_DMAENGINE_PCM
 	select RATIONAL
 	help
Signature · 1 line
2.53.0
author maintainer
#247 lore raw

PATCH 246/990 ASoC: rockchip_sai: select REGMAP_MMIO

In reply to Greg Kroah-Hartman

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

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

From: Jude Gyimah <[email protected]>

[ Upstream commit 829904994e7a54fa89cf550e50dbcd58a09602eb ]

rockchip_sai calls __devm_regmap_init_mmio_clk, which drivers/base/regmap/regmap-mmio.c provides under REGMAP_MMIO.

rockchip_sai.c:1424:(.text+0x153060): undefined reference to

    `__devm_regmap_init_mmio_clk'

The driver can be built into vmlinux while REGMAP_MMIO is a module, in which case the symbol is not there at link time.

Select rather than depend on: REGMAP_MMIO has no prompt of its own and is only ever enabled by a select, so a depends on would leave SND_SOC_ROCKCHIP_SAI unselectable.

Reproduced on v7.3, x86_64, with CONFIG_SND_SOC_ROCKCHIP_SAI=y and CONFIG_REGMAP_MMIO=m.

Found with kreach, a static check that compares what Kconfig allows against the symbols the compiled objects actually reference.

Fixes cc78d1eaabad ("ASoC: rockchip: add Serial Audio Interface (SAI) driver")
---
 sound/soc/rockchip/Kconfig | 1 +
 1 file changed, 1 insertion(+)
sound/soc/rockchip/Kconfig +1 -0
index e96d1a95bb10c..625390ee4ad6f 100644
@@ -35,6 +35,7 @@ config SND_SOC_ROCKCHIP_PDM
 
 config SND_SOC_ROCKCHIP_SAI
 	tristate "Rockchip SAI Controller Driver"
+	select REGMAP_MMIO
 	select SND_SOC_GENERIC_DMAENGINE_PCM
 	help
 	  Say Y or M if you want to add support for the Rockchip Serial Audio
Signature · 1 line
2.53.0
author maintainer
#248 lore raw

PATCH 247/990 ASoC: rockchip: spdif: Add support for set mclk rate

In reply to Greg Kroah-Hartman

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

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

From: Sugar Zhang <[email protected]>

[ Upstream commit 298082783a0d6d07109f8ce09ab410a1de12876d ]

Allow setting the mclk rate from the machine driver.

Stable-dep-of: 67a7e2073909 ("ASoC: rockchip_spdif: select REGMAP_MMIO")

---
 sound/soc/rockchip/rockchip_spdif.c | 34 +++++++++++++++++++----------
 sound/soc/rockchip/rockchip_spdif.h |  2 +-
 2 files changed, 24 insertions(+), 12 deletions(-)
sound/soc/rockchip/rockchip_spdif.c +23 -11
index 7a15f680de2fe..cf6935dc40f2b 100644
@@ -110,12 +110,15 @@ static int rk_spdif_hw_params(struct snd_pcm_substream *substream,
 			      struct snd_soc_dai *dai)
 {
 	struct rk_spdif_dev *spdif = snd_soc_dai_get_drvdata(dai);
+	unsigned int mclk_rate = clk_get_rate(spdif->mclk);
 	unsigned int val = SPDIF_CFGR_HALFWORD_ENABLE;
-	int srate, mclk;
+	int bmc, div;
 	int ret;
 
-	srate = params_rate(params);
-	mclk = srate * 128;
+	/* bmc = 128fs */
+	bmc = 128 * params_rate(params);
+	div = DIV_ROUND_CLOSEST(mclk_rate, bmc);
+	val |= SPDIF_CFGR_CLK_DIV(div);
 
 	switch (params_format(params)) {
 	case SNDRV_PCM_FORMAT_S16_LE:
@@ -131,14 +134,6 @@ static int rk_spdif_hw_params(struct snd_pcm_substream *substream,
 		return -EINVAL;
 	}
 
-	/* Set clock and calculate divider */
-	ret = clk_set_rate(spdif->mclk, mclk);
-	if (ret != 0) {
-		dev_err(spdif->dev, "Failed to set module clock rate: %d\n",
-			ret);
-		return ret;
-	}
-
 	ret = regmap_update_bits(spdif->regmap, SPDIF_CFGR,
 				 SPDIF_CFGR_CLK_DIV_MASK |
 				 SPDIF_CFGR_HALFWORD_ENABLE |
@@ -201,7 +196,24 @@ static int rk_spdif_dai_probe(struct snd_soc_dai *dai)
 	return 0;
 }
 
+static int rk_spdif_set_sysclk(struct snd_soc_dai *dai,
+			       int clk_id, unsigned int freq, int dir)
+{
+	struct rk_spdif_dev *spdif = snd_soc_dai_get_drvdata(dai);
+	int ret;
+
+	if (!freq)
+		return 0;
+
+	ret = clk_set_rate(spdif->mclk, freq);
+	if (ret)
+		dev_err(spdif->dev, "Failed to set mclk: %d\n", ret);
+
+	return ret;
+}
+
 static const struct snd_soc_dai_ops rk_spdif_dai_ops = {
+	.set_sysclk = rk_spdif_set_sysclk,
 	.probe = rk_spdif_dai_probe,
 	.hw_params = rk_spdif_hw_params,
 	.trigger = rk_spdif_trigger,
sound/soc/rockchip/rockchip_spdif.h +1 -1
index d8be9aae5b195..fcc28b6c4f586 100644
@@ -15,7 +15,7 @@
 */
 #define SPDIF_CFGR_CLK_DIV_SHIFT	(16)
 #define SPDIF_CFGR_CLK_DIV_MASK		(0xff << SPDIF_CFGR_CLK_DIV_SHIFT)
-#define SPDIF_CFGR_CLK_DIV(x)		(x << SPDIF_CFGR_CLK_DIV_SHIFT)
+#define SPDIF_CFGR_CLK_DIV(x)		((x-1) << SPDIF_CFGR_CLK_DIV_SHIFT)
 
 #define SPDIF_CFGR_HALFWORD_SHIFT	2
 #define SPDIF_CFGR_HALFWORD_DISABLE	(0 << SPDIF_CFGR_HALFWORD_SHIFT)
Signature · 1 line
2.53.0
author maintainer
#249 lore raw

PATCH 248/990 ASoC: rockchip: spdif: Add support for format S32_LE

In reply to Greg Kroah-Hartman

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

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

From: Sugar Zhang <[email protected]>

[ Upstream commit c43ec509019842c0b836e858dc486c216b51b087 ]

Treat 32 bit sample width as if it was 24 bits using only the 24 most significant bits.

[I've merged the channel-swapping fix from Zohn Ni into Sugar Zhang's patch introducing the problem in the first place]

Stable-dep-of: 67a7e2073909 ("ASoC: rockchip_spdif: select REGMAP_MMIO")

---
 sound/soc/rockchip/rockchip_spdif.c | 22 ++++++++++++++++++++--
 sound/soc/rockchip/rockchip_spdif.h |  8 ++++++++
 2 files changed, 28 insertions(+), 2 deletions(-)
sound/soc/rockchip/rockchip_spdif.c +20 -2
index cf6935dc40f2b..7acc6408a5245 100644
@@ -123,21 +123,38 @@ static int rk_spdif_hw_params(struct snd_pcm_substream *substream,
 	switch (params_format(params)) {
 	case SNDRV_PCM_FORMAT_S16_LE:
 		val |= SPDIF_CFGR_VDW_16;
+		val |= SPDIF_CFGR_ADJ_RIGHT_J;
 		break;
 	case SNDRV_PCM_FORMAT_S20_3LE:
 		val |= SPDIF_CFGR_VDW_20;
+		val |= SPDIF_CFGR_ADJ_RIGHT_J;
 		break;
 	case SNDRV_PCM_FORMAT_S24_LE:
 		val |= SPDIF_CFGR_VDW_24;
+		val |= SPDIF_CFGR_ADJ_RIGHT_J;
+		break;
+	case SNDRV_PCM_FORMAT_S32_LE:
+		val |= SPDIF_CFGR_VDW_24;
+		val |= SPDIF_CFGR_ADJ_LEFT_J;
 		break;
 	default:
 		return -EINVAL;
 	}
 
+	/*
+	 * clear MCLK domain logic before setting Fmclk and Fsdo to ensure
+	 * that switching between S16_LE and S32_LE audio does not result
+	 * in accidential channels swap.
+	 */
+	regmap_update_bits(spdif->regmap, SPDIF_CFGR, SPDIF_CFGR_CLR_MASK,
+			   SPDIF_CFGR_CLR_EN);
+	udelay(1);
+
 	ret = regmap_update_bits(spdif->regmap, SPDIF_CFGR,
 				 SPDIF_CFGR_CLK_DIV_MASK |
 				 SPDIF_CFGR_HALFWORD_ENABLE |
-				 SDPIF_CFGR_VDW_MASK, val);
+				 SDPIF_CFGR_VDW_MASK |
+				 SPDIF_CFGR_ADJ_MASK, val);
 
 	return ret;
 }
@@ -231,7 +248,8 @@ static struct snd_soc_dai_driver rk_spdif_dai = {
 			  SNDRV_PCM_RATE_192000),
 		.formats = (SNDRV_PCM_FMTBIT_S16_LE |
 			    SNDRV_PCM_FMTBIT_S20_3LE |
-			    SNDRV_PCM_FMTBIT_S24_LE),
+			    SNDRV_PCM_FMTBIT_S24_LE |
+			    SNDRV_PCM_FMTBIT_S32_LE),
 	},
 	.ops = &rk_spdif_dai_ops,
 };
sound/soc/rockchip/rockchip_spdif.h +8 -0
index fcc28b6c4f586..acf64986a2e09 100644
@@ -17,6 +17,14 @@
 #define SPDIF_CFGR_CLK_DIV_MASK		(0xff << SPDIF_CFGR_CLK_DIV_SHIFT)
 #define SPDIF_CFGR_CLK_DIV(x)		((x-1) << SPDIF_CFGR_CLK_DIV_SHIFT)
 
+#define SPDIF_CFGR_CLR_MASK		BIT(7)
+#define SPDIF_CFGR_CLR_EN		BIT(7)
+#define SPDIF_CFGR_CLR_DIS		0
+
+#define SPDIF_CFGR_ADJ_MASK		BIT(3)
+#define SPDIF_CFGR_ADJ_LEFT_J		BIT(3)
+#define SPDIF_CFGR_ADJ_RIGHT_J		0
+
 #define SPDIF_CFGR_HALFWORD_SHIFT	2
 #define SPDIF_CFGR_HALFWORD_DISABLE	(0 << SPDIF_CFGR_HALFWORD_SHIFT)
 #define SPDIF_CFGR_HALFWORD_ENABLE	(1 << SPDIF_CFGR_HALFWORD_SHIFT)
Signature · 1 line
2.53.0
author maintainer
#250 lore raw

PATCH 249/990 ASoC: rockchip: spdif: Fill IEC958 CS info per params

In reply to Greg Kroah-Hartman

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

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

From: Sugar Zhang <[email protected]>

[ Upstream commit 07a791020be9b190d4a57b5ee823ede1e98df493 ]

Add support to fill IEC958 channel status information.

Stable-dep-of: 67a7e2073909 ("ASoC: rockchip_spdif: select REGMAP_MMIO")

---
 sound/soc/rockchip/Kconfig          |  1 +
 sound/soc/rockchip/rockchip_spdif.c | 45 ++++++++++++++++++++++++++---
 sound/soc/rockchip/rockchip_spdif.h |  8 +++++
 3 files changed, 50 insertions(+), 4 deletions(-)
sound/soc/rockchip/Kconfig +1 -0
index 625390ee4ad6f..aba9a518d3b26 100644
@@ -45,6 +45,7 @@ config SND_SOC_ROCKCHIP_SAI
 
 config SND_SOC_ROCKCHIP_SPDIF
 	tristate "Rockchip SPDIF Device Driver"
+	select SND_PCM_IEC958
 	select SND_SOC_GENERIC_DMAENGINE_PCM
 	help
 	  Say Y or M if you want to add support for SPDIF driver for
sound/soc/rockchip/rockchip_spdif.c +41 -4

81 lines not on this page · raw message

sound/soc/rockchip/rockchip_spdif.h +8 -0
index acf64986a2e09..b837b1f8d57f3 100644
@@ -21,6 +21,10 @@
 #define SPDIF_CFGR_CLR_EN		BIT(7)
 #define SPDIF_CFGR_CLR_DIS		0
 
+#define SPDIF_CFGR_CSE_MASK		BIT(6)
+#define SPDIF_CFGR_CSE_EN		BIT(6)
+#define SPDIF_CFGR_CSE_DIS		0
+
 #define SPDIF_CFGR_ADJ_MASK		BIT(3)
 #define SPDIF_CFGR_ADJ_LEFT_J		BIT(3)
 #define SPDIF_CFGR_ADJ_RIGHT_J		0
@@ -64,5 +68,9 @@
 #define SPDIF_INTSR	(0x0010)
 #define SPDIF_XFER	(0x0018)
 #define SPDIF_SMPDR	(0x0020)
+#define SPDIF_VLDFRn(x)	(0x0060 + (x) * 4)
+#define SPDIF_USRDRn(x)	(0x0090 + (x) * 4)
+#define SPDIF_CHNSRn(x)	(0x00c0 + (x) * 4)
+#define SPDIF_VERSION	(0x01c0)
 
 #endif /* _ROCKCHIP_SPDIF_H */
Signature · 1 line
2.53.0
author maintainer
#251 lore raw

PATCH 250/990 ASoC: rockchip_spdif: select REGMAP_MMIO

In reply to Greg Kroah-Hartman

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

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

From: Jude Gyimah <[email protected]>

[ Upstream commit 67a7e2073909e948c3cbd86c28d17e86c2958dd6 ]

rockchip_spdif calls __devm_regmap_init_mmio_clk, which drivers/base/regmap/regmap-mmio.c provides under REGMAP_MMIO.

rockchip_spdif.c:(.text+0xf67): undefined reference to

    `__devm_regmap_init_mmio_clk'

The driver can be built into vmlinux while REGMAP_MMIO is a module, in which case the symbol is not there at link time.

Select rather than depend on: REGMAP_MMIO has no prompt of its own and is only ever enabled by a select, so a depends on would leave SND_SOC_ROCKCHIP_SPDIF unselectable.

Reproduced on v7.3, x86_64, with CONFIG_SND_SOC_ROCKCHIP_SPDIF=y and CONFIG_REGMAP_MMIO=m.

Found with kreach, a static check that compares what Kconfig allows against the symbols the compiled objects actually reference.

Fixes f874b80e1571 ("ASoC: rockchip: Add rockchip SPDIF transceiver driver")
---
 sound/soc/rockchip/Kconfig | 1 +
 1 file changed, 1 insertion(+)
sound/soc/rockchip/Kconfig +1 -0
index aba9a518d3b26..0e5110125c140 100644
@@ -45,6 +45,7 @@ config SND_SOC_ROCKCHIP_SAI
 
 config SND_SOC_ROCKCHIP_SPDIF
 	tristate "Rockchip SPDIF Device Driver"
+	select REGMAP_MMIO
 	select SND_PCM_IEC958
 	select SND_SOC_GENERIC_DMAENGINE_PCM
 	help
Signature · 1 line
2.53.0
author maintainer
#252 lore raw

PATCH 251/990 net: ethernet: ti: am65-cpts: adjust perout genf following ptp changes

In reply to Greg Kroah-Hartman

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

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

From: James Clark <[email protected]>

[ Upstream commit 3f1054a0cb09552dd54db024694f74747f9f1d49 ]

A periodic output requested by PTP_PEROUT_REQUEST2 drifts away from the PHC as soon as the PHC frequency is adjusted, for example by ptp4l or ts2phc: at +10 ppm each edge is 10 us later than the one before.

The GenF that generates the output counts its period in ref_clk cycles, which the PPM correction of the CPTS clock does not reach; each GenF has its own PPM registers. am65_cpts_ptp_adjfine() programs them only for the GenF used for PPS, and am65_cpts_perout_enable_hw() starts every GenF with them cleared, so a GenF used for a periodic output is never corrected.

Commit eb9233ce6751 ("net: ethernet: ti: am65-cpts: adjust pps following ptp changes") added the correction for the PPS GenF, and commit 7849c42da2ca ("net: ethernet: ti: am65-cpts: adjust estf following ptp changes") passed the same values to the ESTFs.

In am65_cpts_ptp_adjfine(), update every enabled GenF the way the PPS GenF was updated: read its control register, set or clear the PPM direction bit and write it back with the PPM value. The PPS GenF and the ESTFs get exactly the values they got before. In am65_cpts_perout_enable_hw(), start a GenF with the current correction instead of none; this applies to the PPS GenF too.

Tested on a BeagleY-AI (J722S) with the GENF0 output looped back to the HW1_TS_PUSH input (EXTTS 0). With the PHC frequency adjusted by +10 ppm before the periodic output is started, the edges drift 10 us per second against the PHC without this patch (290 us after 29 s); with it, they stay 20 to 23 ns after the PHC second. This also works if the frequency is adjusted after the periodic output has started.

Fixes f6bd59526ca5 ("net: ethernet: ti: introduce am654 common platform time sync driver")
---
 drivers/net/ethernet/ti/am65-cpts.c | 67 +++++++++++++++++++----------
 1 file changed, 45 insertions(+), 22 deletions(-)
drivers/net/ethernet/ti/am65-cpts.c +45 -22
index 73adb822bc075..e87bb01f9aed2 100644
@@ -176,6 +176,9 @@ struct am65_cpts {
 	struct mutex ptp_clk_lock; /* PHC access sync */
 	u64 timestamp;
 	u32 genf_enable;
+	bool genf_neg_adj;
+	u32 genf_ppm_hi;
+	u32 genf_ppm_low;
 	u32 hw_ts_enable;
 	u32 estf_enable;
 	struct sk_buff_head txq;
@@ -436,9 +439,11 @@ static int am65_cpts_ptp_adjfine(struct ptp_clock_info *ptp, long scaled_ppm)
 {
 	struct am65_cpts *cpts = container_of(ptp, struct am65_cpts, ptp_info);
 	u32 estf_ctrl_val = 0, estf_ppm_hi = 0, estf_ppm_low = 0;
+	u32 genf_ctrl_val[AM65_CPTS_GENF_MAX_NUM];
+	u32 genf_ppm_hi, genf_ppm_low;
 	s32 ppb = scaled_ppm_to_ppb(scaled_ppm);
 	int pps_index = cpts->pps_genf_idx;
-	u64 adj_period, pps_adj_period;
+	u64 adj_period, genf_adj_period;
 	u32 ctrl_val, ppm_hi, ppm_low;
 	unsigned long flags;
 	int neg_adj = 0, i;
@@ -470,20 +475,33 @@ static int am65_cpts_ptp_adjfine(struct ptp_clock_info *ptp, long scaled_ppm)
 	ppm_hi = upper_32_bits(adj_period) & 0x3FF;
 	ppm_low = lower_32_bits(adj_period);
 
+	/* GenF PPM will do correction using cpts refclk tick which is
+	 * (cpts->ts_add_val + 1) ns, so GenF length PPM adj period
+	 * need to be corrected.
+	 */
+	genf_adj_period = adj_period * (cpts->ts_add_val + 1);
+	genf_ppm_hi = upper_32_bits(genf_adj_period) & 0x3FF;
+	genf_ppm_low = lower_32_bits(genf_adj_period);
+	cpts->genf_neg_adj = neg_adj;
+	cpts->genf_ppm_hi = genf_ppm_hi;
+	cpts->genf_ppm_low = genf_ppm_low;
+
+	for (i = 0; i < AM65_CPTS_GENF_MAX_NUM; i++) {
+		if (cpts->genf_enable & BIT(i)) {
+			genf_ctrl_val[i] = am65_cpts_read32(cpts,
+							    genf[i].control);
+			if (neg_adj)
+				genf_ctrl_val[i] &= ~BIT(1);
+			else
+				genf_ctrl_val[i] |= BIT(1);
+		}
+	}
+
 	if (cpts->pps_enabled) {
-		estf_ctrl_val = am65_cpts_read32(cpts, genf[pps_index].control);
-		if (neg_adj)
-			estf_ctrl_val &= ~BIT(1);
-		else
-			estf_ctrl_val |= BIT(1);
-
-		/* GenF PPM will do correction using cpts refclk tick which is
-		 * (cpts->ts_add_val + 1) ns, so GenF length PPM adj period
-		 * need to be corrected.
-		 */
-		pps_adj_period = adj_period * (cpts->ts_add_val + 1);
-		estf_ppm_hi = upper_32_bits(pps_adj_period) & 0x3FF;
-		estf_ppm_low = lower_32_bits(pps_adj_period);
+		/* am65_cpts_perout_enable_hw() sets pps_index in genf_enable */
+		estf_ctrl_val = genf_ctrl_val[pps_index];
+		estf_ppm_hi = genf_ppm_hi;
+		estf_ppm_low = genf_ppm_low;
 	}
 
 	spin_lock_irqsave(&cpts->lock, flags);
@@ -500,10 +518,13 @@ static int am65_cpts_ptp_adjfine(struct ptp_clock_info *ptp, long scaled_ppm)
 	am65_cpts_write32(cpts, ppm_hi, ts_ppm_hi);
 	am65_cpts_write32(cpts, ppm_low, ts_ppm_low);
 
-	if (cpts->pps_enabled) {
-		am65_cpts_write32(cpts, estf_ctrl_val, genf[pps_index].control);
-		am65_cpts_write32(cpts, estf_ppm_hi, genf[pps_index].ppm_hi);
-		am65_cpts_write32(cpts, estf_ppm_low, genf[pps_index].ppm_low);
+	for (i = 0; i < AM65_CPTS_GENF_MAX_NUM; i++) {
+		if (cpts->genf_enable & BIT(i)) {
+			am65_cpts_write32(cpts, genf_ctrl_val[i],
+					  genf[i].control);
+			am65_cpts_write32(cpts, genf_ppm_hi, genf[i].ppm_hi);
+			am65_cpts_write32(cpts, genf_ppm_low, genf[i].ppm_low);
+		}
 	}
 
 	for (i = 0; i < AM65_CPTS_ESTF_MAX_NUM; i++) {
@@ -513,7 +534,6 @@ static int am65_cpts_ptp_adjfine(struct ptp_clock_info *ptp, long scaled_ppm)
 			am65_cpts_write32(cpts, estf_ppm_low, estf[i].ppm_low);
 		}
 	}
-	/* All GenF/EstF can be updated here the same way */
 	spin_unlock_irqrestore(&cpts->lock, flags);
 
 	mutex_unlock(&cpts->ptp_clk_lock);
@@ -679,9 +699,12 @@ static void am65_cpts_perout_enable_hw(struct am65_cpts *cpts,
 		val = lower_32_bits(cycles);
 		am65_cpts_write32(cpts, val, genf[req->index].length);
 
-		am65_cpts_write32(cpts, 0, genf[req->index].control);
-		am65_cpts_write32(cpts, 0, genf[req->index].ppm_hi);
-		am65_cpts_write32(cpts, 0, genf[req->index].ppm_low);
+		am65_cpts_write32(cpts, cpts->genf_neg_adj ? 0 : BIT(1),
+				  genf[req->index].control);
+		am65_cpts_write32(cpts, cpts->genf_ppm_hi,
+				  genf[req->index].ppm_hi);
+		am65_cpts_write32(cpts, cpts->genf_ppm_low,
+				  genf[req->index].ppm_low);
 
 		cpts->genf_enable |= BIT(req->index);
 	} else {
Signature · 1 line
2.53.0
author maintainer
#253 lore raw

PATCH 252/990 isofs: handle Rock Ridge long-form dates before 1900

In reply to Greg Kroah-Hartman

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

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

From: Hungyu Lin <[email protected]>

[ Upstream commit 0cbfc16fe49629f5c1fc3628405661c2b938ec61 ]

iso_date() stores the year relative to 1900 and rejects negative values. Rock Ridge LONG_FORM timestamps encode calendar years from 1 to 9999, so valid years before 1900 are returned as seconds since the Unix epoch equal to zero instead of their recorded dates. For example, an 1899 timestamp on an image produced by xorriso is reported as 1970 by stat, and cp -p preserves that incorrect time.

Use the calendar year for both timestamp formats and pass it directly to mktime64(). Keep the epoch fallback for year zero, while allowing valid long-form years before 1900. Short-form dates are unchanged.

Fixes 5ea45f54c8d6 ("isofs: fix Y2038 and Y2156 issues in Rock Ridge TF entry")
---
 fs/isofs/util.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
fs/isofs/util.c +4 -4
index 42f479da0b282..6f9a90e58a890 100644
@@ -25,7 +25,7 @@ struct timespec64 iso_date(u8 *p, int flags)
 		year = (p[0] - '0') * 1000 +
 		       (p[1] - '0') * 100 +
 		       (p[2] - '0') * 10 +
-		       (p[3] - '0') - 1900;
+		       (p[3] - '0');
 		month = ((p[4] - '0') * 10 + (p[5] - '0'));
 		day = ((p[6] - '0') * 10 + (p[7] - '0'));
 		hour = ((p[8] - '0') * 10 + (p[9] - '0'));
@@ -34,7 +34,7 @@ struct timespec64 iso_date(u8 *p, int flags)
 		ts.tv_nsec = ((p[14] - '0') * 10 + (p[15] - '0')) * 10000000;
 		tz = p[16];
 	} else {
-		year = p[0];
+		year = p[0] + 1900;
 		month = p[1];
 		day = p[2];
 		hour = p[3];
@@ -45,10 +45,10 @@ struct timespec64 iso_date(u8 *p, int flags)
 		tz = flags & ISO_DATE_HIGH_SIERRA ? 0 : p[6];
 	}
 
-	if (year < 0) {
+	if (year < 1) {
 		ts.tv_sec = 0;
 	} else {
-		ts.tv_sec = mktime64(year+1900, month, day, hour, minute, second);
+		ts.tv_sec = mktime64(year, month, day, hour, minute, second);
 
 		/* sign extend */
 		if (tz & 0x80)
Signature · 1 line
2.53.0
author maintainer
#254 lore raw

PATCH 253/990 tcp: Fix dup-ack detection on non-SACK bidirectional data transfer.

In reply to Greg Kroah-Hartman

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

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

From: Guillaume Nault <[email protected]>

[ Upstream commit 11140c51df12e594d6bf2c8d2af5dec63b0219ac ]

When receiving a pure ack from a peer that also sends data, we can have SEG.SEQ > SND.WL1, even though the segment contains no data. This makes tcp_may_update_window() return true (because of the "after(ack_seq, tp->snd_wl1)" condition), and tcp_ack_update_window() then adds FLAG_WIN_UPDATE to the segment set of flags, even when there's no window update.

Since FLAG_WIN_UPDATE prevents the segment from being considered as dup-ack (as it's part of FLAG_NOT_DUP), this can inhibit fast retransmit on non-SACK connections, making recovery very slow as it now entirely relies on RTO.

The "DUPLICATE ACKNOWLEDGMENT" definition of RFC 5681, section 2, says that lack of window update is a necessary condition for a dup ack:
"(e) the advertised window in the incoming acknowledgment equals the advertised window in the last incoming acknowledgment.". Spurious window updates can thus prevent dup ack detection and, in the end, fast retransmit.

Avoid this scenario by setting FLAG_WIN_UPDATE only when a window update actually occurs. Pure acks with SEG.SEQ > SND.WL1 can now be detected as dup-ack and trigger fast retransmission.

Also, stop setting FLAG_WIN_UPDATE in tcp_ack()'s header prediction path. One of the conditions for header prediction to happen is that received segments don't trigger a window update. This flag update was thus wrong to begin with. Now that tcp_ack_update_window() sets FLAG_WIN_UPDATE only if a window update actually occurred, we need the header prediction path to stop reporting spurious window updates too. Otherwise BPF programs would get inconsistent window update information (CA_ACK_WIN_UPDATE) between fast an slow paths.

Finally, add FLAG_SND_UNA_ADVANCED to the definition of FLAG_NOT_DUP. This is necessary for the case where an incoming segment acknowledges less than a full segment of the retransmit queue. Such segments were not considered dubious by tcp_ack_is_dubious() because of the spurious FLAG_WIN_UPDATE flag, which prevented the segment from being seen as a duplicate ack. Now that FLAG_WIN_UPDATE doesn't cover this scenario anymore, we need another way to mark these acks as non-duplicate. Adding FLAG_SND_UNA_ADVANCED to FLAG_NOT_DUP is the natural way of doing this, since, by definition, a segment advancing SND.UNA, even by a small amount, cannot be a duplicate ack.

A side effect of this patch is that repeated zero window acks received from peer can now be considered duplicate acks (because of the the "|| !win" condition in tcp_may_update_window()). Therefore, they can now trigger fast retransmission and fast recovery, including congestion window reduction, when the peer is stalled. This is RFC compliant and shouldn't have any negative effect.

Add packetdrill selftest. Before this patch, the 1001:2001 segment was retransmitted upon RTO, now it's sent right after reception of the third duplicate ack.

Thanks to Tom Williams for the investigation help and initial reproducer.

---
 net/ipv4/tcp_input.c                          |  6 +--
 .../tcp_bidir_fast_retransmit_nosack.pkt      | 42 +++++++++++++++++++
 2 files changed, 45 insertions(+), 3 deletions(-)
 create mode 100644 tools/testing/selftests/net/packetdrill/tcp_bidir_fast_retransmit_nosack.pkt
net/ipv4/tcp_input.c +3 -3
index 5d8da3c23e2c8..5e73232873fab 100644
@@ -107,7 +107,8 @@ int sysctl_tcp_max_orphans __read_mostly = NR_FILE;
 #define FLAG_TS_PROGRESS	0x40000 /* Positive timestamp delta */
 
 #define FLAG_ACKED		(FLAG_DATA_ACKED|FLAG_SYN_ACKED)
-#define FLAG_NOT_DUP		(FLAG_DATA|FLAG_WIN_UPDATE|FLAG_ACKED)
+#define FLAG_NOT_DUP		(FLAG_DATA|FLAG_WIN_UPDATE|FLAG_ACKED|	\
+				 FLAG_SND_UNA_ADVANCED)
 #define FLAG_CA_ALERT		(FLAG_DATA_SACKED|FLAG_ECE|FLAG_DSACKING_ACK)
 #define FLAG_FORWARD_PROGRESS	(FLAG_ACKED|FLAG_DATA_SACKED)
 
@@ -3741,11 +3742,11 @@ static int tcp_ack_update_window(struct sock *sk, const struct sk_buff *skb, u32
 		nwin <<= tp->rx_opt.snd_wscale;
 
 	if (tcp_may_update_window(tp, ack, ack_seq, nwin)) {
-		flag |= FLAG_WIN_UPDATE;
 		tcp_update_wl(tp, ack_seq);
 
 		if (tp->snd_wnd != nwin) {
 			tp->snd_wnd = nwin;
+			flag |= FLAG_WIN_UPDATE;
 
 			/* Note, it is the only place, where
 			 * fast path is recovered for sending TCP.
@@ -4093,7 +4094,6 @@ static int tcp_ack(struct sock *sk, const struct sk_buff *skb, int flag)
 		 */
 		tcp_update_wl(tp, ack_seq);
 		tcp_snd_una_update(tp, ack);
-		flag |= FLAG_WIN_UPDATE;
 
 		NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPHPACKS);
 	} else {
tools/testing/selftests/net/packetdrill/tcp_bidir_fast_retransmit_nosack.pkt new file +42 -0

42 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#255 lore raw

PATCH 254/990 cpufreq: Hold the policy write lock when changing boost state

In reply to Greg Kroah-Hartman

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

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

From: Christian Loehle <[email protected]>

[ Upstream commit e6f50e602e373583423654ec000cad8b8d08f7bc ]

The per-policy boost sysfs handler calls policy_set_boost() under policy->rwsem, but the global boost handler and cpufreq_online() do not. Consequently, global and per-policy boost changes can concurrently update policy->boost_enabled, invoke the driver callback and update the boost frequency QoS request. The driver callbacks also access policy state, e.g. CPPC updates cpuinfo.max_freq that assumes policy->rw_sem held.

Take policy->rwsem around policy_set_boost() in both unlocked callers. Keep locking at the call sites because the per-policy sysfs handler already holds the lock.

Fixes 218a06a79d9a ("cpufreq: Support per-policy performance boost")
---
 drivers/cpufreq/cpufreq.c | 6 ++++++
 1 file changed, 6 insertions(+)
drivers/cpufreq/cpufreq.c +6 -0
index ec577a20567b1..002afd47d2d59 100644
@@ -597,6 +597,8 @@ static int policy_set_boost(struct cpufreq_policy *policy, bool enable)
 {
 	int ret;
 
+	lockdep_assert_held_write(&policy->rwsem);
+
 	if (policy->boost_enabled == enable)
 		return 0;
 
@@ -1631,6 +1633,8 @@ static int cpufreq_online(unsigned int cpu)
 	 */
 	if (cpufreq_driver->set_boost && policy->boost_supported &&
 	    (new_policy || !cpufreq_boost_enabled())) {
+		guard(cpufreq_policy_write)(policy);
+
 		ret = policy_set_boost(policy, cpufreq_boost_enabled());
 		if (ret) {
 			/* If the set_boost fails, the online operation is not affected */
@@ -2821,6 +2825,8 @@ static int cpufreq_boost_trigger_state(int state)
 		if (!policy->boost_supported)
 			continue;
 
+		guard(cpufreq_policy_write)(policy);
+
 		ret = policy_set_boost(policy, state);
 		if (ret)
 			goto err_reset_state;
Signature · 1 line
2.53.0
author maintainer
#256 lore raw

PATCH 255/990 net: skbuff: reject zero MPLS TTL before decrementing

In reply to Greg Kroah-Hartman

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

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

From: Avi Weiss <[email protected]>

[ Upstream commit 24614e72df484ad50ecba98aaa88c7df2448c122 ]

skb_mpls_dec_ttl() decrements the u8 TTL before checking whether it expired. An incoming TTL of zero wraps to 255, causing the TC MPLS dec_ttl action to pass an expired packet instead of dropping it.

Reject a zero TTL before the decrement while preserving the existing behavior for TTL one and valid TTL values.

Fixes 2a2ea50870ba ("net: sched: add mpls manipulation actions to TC")
---
 net/core/skbuff.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/core/skbuff.c +1 -1
index e28802a46fd29..f1b0045667124 100644
@@ -6713,7 +6713,7 @@ int skb_mpls_dec_ttl(struct sk_buff *skb)
 
 	lse = be32_to_cpu(mpls_hdr(skb)->label_stack_entry);
 	ttl = (lse & MPLS_LS_TTL_MASK) >> MPLS_LS_TTL_SHIFT;
-	if (!--ttl)
+	if (!ttl || !--ttl)
 		return -EINVAL;
 
 	lse &= ~MPLS_LS_TTL_MASK;
Signature · 1 line
2.53.0
author maintainer
#257 lore raw

PATCH 256/990 PM: runtime: Fix check_flush_dependency warning from pm_runtime_remove

In reply to Greg Kroah-Hartman

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

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

From: Zhou Minqiang <[email protected]>

[ Upstream commit 1f65b45f0f16e1c80a68a5757c9556f78bb39f19 ]

When a WQ_MEM_RECLAIM workqueue (e.g. iscsi_ctrl) triggers device removal via device_del -> pm_runtime_remove, the unconditional flush_work inside pm_runtime_remove can trigger a check_flush_dependency warning:

CPU1: pm_wq worker CPU2: iscsi_ctrl wq
-------- --------

pm_runtime_work(starget) pm_runtime_remove(starget)

    spin_lock_irq(&starget->lock)      __pm_runtime_disable(starget, false)
    request_pending = false              spin_lock_irq(&starget->lock)
                                         (blocked, CPU1 holds the lock)

    rpm_suspend(starget, RPM_NOWAIT)
      status = RPM_SUSPENDING
      rpm_callback(cb, starget)
        spin_unlock_irq(&starget->lock)
                                         (acquires lock)
                                         disable_depth 0→1
                                         __pm_runtime_barrier():
                                           request_pending == false
                                             → skip cancel_work_sync
                                           status == RPM_SUSPENDING
                                             → enter wait_queue, sleep
                                           spin_unlock_irq(&starget->lock)
        cb(starget) → 0
        spin_lock_irq(&starget->lock)
      status = RPM_SUSPENDED
      wake_up_all(&wait_queue)
                                           (woken up, waiting for lock)
      spin_unlock(&starget->lock)          spin_lock_irq(&starget->lock)
                                             status == RPM_SUSPENDED
      spin_lock(&parent->lock)                → exit wait_queue
      rpm_idle(parent, RPM_ASYNC)        barrier returns
      spin_unlock(&parent->lock)       flush_work(&starget->work)
      spin_lock(&starget->lock)          __flush_work(from_cancel=false)
      spin_unlock_irq(&starget->lock)      check_flush_dependency()
                                            ← WARNING!

Replace flush_work with cancel_work_sync in pm_runtime_remove. cancel_work_sync internally calls __flush_work with from_cancel=true, which causes check_flush_dependency to return early before the warning. This preserves the use-after-free fix from commit 29ab76827761 ("PM: runtime: Fix a race condition related to device removal") without the warning.

Fixes 29ab76827761 ("PM: runtime: Fix a race condition related to device removal")
---
 drivers/base/power/runtime.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/base/power/runtime.c +1 -1
index 04f620e340b3d..5842cd58040cf 100644
@@ -1900,7 +1900,7 @@ void pm_runtime_reinit(struct device *dev)
 void pm_runtime_remove(struct device *dev)
 {
 	__pm_runtime_disable(dev, false);
-	flush_work(&dev->power.work);
+	cancel_work_sync(&dev->power.work);
 	pm_runtime_reinit(dev);
 }
 
Signature · 1 line
2.53.0
author maintainer
#258 lore raw

PATCH 257/990 ipv6: Flush exception route while replacing nexthop.

In reply to Greg Kroah-Hartman

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

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

From: Kuniyuki Iwashima <[email protected]>

[ Upstream commit 9401b428b5d4dfe1fd5752973fd02b4e9cd05536 ]

The following creates a cyclic reference between IPv6 route and nexthop:

1. create a nexthop A
2. create a nexthop group w/ A
3. create an IPv6 route with the nexthop group
4. create an exception route w/ A
5. replace A with a new nexthop B in the nexthop group
6. remove the IPv6 route
7. replace B with A in the nexthop group
8. remove the nexthop group

Then, removing a device tied to the route gets stuck and triggers the splat below. [0]

At 5., fib6_nh_release_dsts() is called, but it does not flush exception routes, so the nexthop A continues to grab the IPv6 route reference.

nh_A->rt6i_exception_bucket[] -> rt6_ex->rt6i->from

At 6., fib6_purge_rt() calls rt6_flush_exceptions(), but it only purges exceptions tied to nexthop B. Also, the route is unlinked from the nexthop group by list_del_init(&rt->nh_list).

-> f6i->nh -> nhg->nh_entries[]

At 8., __remove_nexthop_fib() cannot find the IPv6 route, and remove_nexthop_group() calls list_del_init(&nhge->nh_list) to unlink the group from the nexthop A's nhe->grp_list.

nhg->nh_entries[] -> nh_A -> ... -> f6i

Here, the nexthop A is reachable from net->nexthop.devhash[], but remove_nexthop_from_groups() cannot find the nexthop group, leaking the whole chain.

Let's call fib6_nh_flush_exceptions() in fib6_nh_release_dsts().

[0]:
unregister_netdevice: waiting for gre6 to become free. Usage count = 4
ref_tracker: netdev@000000009652f190 has 1/3 users at

     dst_alloc+0x14b/0x490
     ip6_rt_cache_alloc+0x27b/0x670
     __ip6_rt_update_pmtu+0x572/0x850
     ip6_tnl_xmit+0x8c5/0x1b70
     __gre6_xmit+0x7af/0xaa0
     ip6gre_tunnel_xmit+0x685/0xdc0
     dev_hard_start_xmit+0x204/0x5a0
     __dev_queue_xmit+0xe8a/0x2550
     ip6_finish_output+0x232/0x570
     ip6_output+0x226/0x3b0
     ip6_send_skb+0x133/0x250
     rawv6_push_pending_frames+0x503/0x6f0
     rawv6_sendmsg+0xdf0/0x1310
     sock_sendmsg_nosec+0xde/0x130
     __sys_sendto+0x27f/0x320
     __x64_sys_sendto+0xd9/0xf0
---
 net/ipv6/route.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
net/ipv6/route.c +4 -2
index af376b9568e2f..c11cf3c65c9f7 100644
@@ -3733,9 +3733,10 @@ void fib6_nh_release(struct fib6_nh *fib6_nh)
 {
 	struct rt6_exception_bucket *bucket;
 
+	fib6_nh_release_dsts(fib6_nh);
+
 	rcu_read_lock();
 
-	fib6_nh_flush_exceptions(fib6_nh, NULL);
 	bucket = fib6_nh_get_excptn_bucket(fib6_nh, NULL);
 	if (bucket) {
 		rcu_assign_pointer(fib6_nh->rt6i_exception_bucket, NULL);
@@ -3744,7 +3745,6 @@ void fib6_nh_release(struct fib6_nh *fib6_nh)
 
 	rcu_read_unlock();
 
-	fib6_nh_release_dsts(fib6_nh);
 	free_percpu(fib6_nh->rt6i_pcpu);
 
 	fib_nh_common_release(&fib6_nh->nh_common);
@@ -3754,6 +3754,8 @@ void fib6_nh_release_dsts(struct fib6_nh *fib6_nh)
 {
 	int cpu;
 
+	fib6_nh_flush_exceptions(fib6_nh, NULL);
+
 	if (!fib6_nh->rt6i_pcpu)
 		return;
 
Signature · 1 line
2.53.0
author maintainer
#259 lore raw

PATCH 258/990 ipv4: Call rt_add_uncached_list() if !do_cache in ip_route_input_slow().

In reply to Greg Kroah-Hartman

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

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

From: Kuniyuki Iwashima <[email protected]>

[ Upstream commit 4019af3afd72864ec6abbfde2d76e416a64456c2 ]

Since the cited commit, ip_route_input_slow() could call rt_dst_alloc() with vrf in the local_input: path.

If res->fi != NULL and one of the following is true,

- a non-zero itag from fib_validate_source_reason() (realms/classid)
- RTN_BROADCAST with BC_FORWARDING enabled

do_cache is set to false.

Then, the route is not added to rt_uncached_list, so the route cannot be removed from rt_flush_dev().

If the route is cached in sk->sk_rx_dst, removing the vrf device gets stuck. [0]

Let's call rt_add_uncached_list() if !do_cache in
ip_route_input_slow().

[0]:
unregister_netdevice: waiting for vrf0 to become free. Usage count = 2
ref_tracker: netdev@000000008b304ac4 has 1/1 users at

     dst_alloc+0x14b/0x490
     ip_route_input_rcu+0x1540/0x2530
     ip_route_input_noref+0x5a/0x90
     ip_rcv_finish_core+0x4b0/0x1140
     ip_rcv_finish+0xe6/0x190
     ip_rcv+0x6c/0x130
     __netif_receive_skb+0x121/0x300
     process_backlog+0x2df/0x5e0
     __napi_poll+0x8c/0x380
     net_rx_action+0x43c/0xab0
     handle_softirqs+0x19f/0x520
     do_softirq+0x46/0x60
     __local_bh_enable_ip+0x79/0x80
     __dev_queue_xmit+0x1b0e/0x24c0
     ip_finish_output2+0x8b2/0xcd0
     ip_output+0xf2/0x1e0
Fixes f5a0aab84b74 ("net: ipv4: dst for local input routes should use l3mdev if relevant")
---
 net/ipv4/route.c | 2 ++
 1 file changed, 2 insertions(+)
net/ipv4/route.c +2 -0
index e6276896f3ad4..489d3b2cb612b 100644
@@ -2485,6 +2485,8 @@ ip_route_input_slow(struct sk_buff *skb, __be32 daddr, __be32 saddr,
 
 		if (unlikely(!rt_cache_route(nhc, rth)))
 			rt_add_uncached_list(rth);
+	} else {
+		rt_add_uncached_list(rth);
 	}
 	skb_dst_set(skb, &rth->dst);
 	reason = SKB_NOT_DROPPED_YET;
Signature · 1 line
2.53.0
author maintainer
#260 lore raw

PATCH 259/990 tcp: ipv6: do not read ireq->pktopts from tcp_v6_send_synack()

In reply to Greg Kroah-Hartman

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

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

From: Eric Dumazet <[email protected]>

[ Upstream commit 8e069fd3fd396b89af417e50b359bc9892dd41cd ]

When IPV6_FL_F_REFLECT is set on a listener, or the net.ipv6.flowlabel_reflect sysctl has FLOWLABEL_REFLECT_ESTABLISHED, tcp_v6_send_synack() reflects the flowlabel of the SYN packet, reading it from the skb stored in ireq->pktopts.

Since commit 079096f103fa ("tcp/dccp: install syn_recv requests into ehash table"), request sockets are processed without holding the listener lock. A cpu can then process a retransmitted SYN for a request socket, and send a SYNACK from tcp_check_req(), while another cpu receives the ACK completing the 3WHS. tcp_v6_syn_recv_sock() consumes ireq->pktopts when it wins the hashdance, and the first cpu reads a freed skb:

  BUG: KASAN: slab-use-after-free in tcp_v6_send_synack (include/linux/skbuff.h:3152 include/linux/ipv6.h:110 net/ipv6/tcp_ipv6.c:582)
  Read of size 8 at addr ffff88802b08b608 by task poc-ipv6-pktopt/5076

  Call Trace:
   <IRQ>
   tcp_v6_send_synack (include/linux/skbuff.h:3152 include/linux/ipv6.h:110 net/ipv6/tcp_ipv6.c:582)
   tcp_rtx_synack (net/ipv4/tcp_output.c:4719)
   tcp_check_req (net/ipv4/tcp_minisocks.c:762)
   tcp_v6_rcv (net/ipv6/tcp_ipv6.c:1826)
   ip6_protocol_deliver_rcu (net/ipv6/ip6_input.c:479)
   ip6_input_finish (net/ipv6/ip6_input.c:534)
   ip6_input (include/linux/netfilter.h:325 include/linux/netfilter.h:319 net/ipv6/ip6_input.c:545)
   ipv6_rcv (include/net/dst.h:481 net/ipv6/ip6_input.c:119 include/linux/netfilter.h:325 include/linux/netfilter.h:319 net/ipv6/ip6_input.c:351)

  Freed by task 5074 on cpu 0 at 15.412249s:
   kmem_cache_free (include/linux/kasan.h:235 mm/slub.c:2780 mm/slub.c:6630 mm/slub.c:6757)
   tcp_v6_syn_recv_sock (net/ipv6/tcp_ipv6.c:1528)
   tcp_check_req (net/ipv4/tcp_minisocks.c:934)
   tcp_v6_rcv (net/ipv6/tcp_ipv6.c:1826)
   ip6_protocol_deliver_rcu (net/ipv6/ip6_input.c:479)
   ip6_input_finish (net/ipv6/ip6_input.c:534)

Request socket migration has the same issue: reqsk_migrate_reset() transfers ireq->pktopts to the clone, which can be freed while another cpu holding a reference on the old request socket is still sending a SYNACK.

The SYNACK timer itself is not an issue, because inet_csk_reqsk_queue_drop() calls timer_delete_sync().

Save the flowlabel of the SYN in the request socket instead, so that tcp_v6_send_synack() no longer needs ireq->pktopts.

As a side effect, the flowlabel is also reflected for SYN packets reusing a TIME_WAIT socket, as ireq->pktopts is not set in this case.

Fixes e994b2f0fb92 ("tcp: do not lock listener to process SYN packets")
Fixes 079096f103fa ("tcp/dccp: install syn_recv requests into ehash table")
Fixes c905dee62232 ("tcp: Migrate TCP_NEW_SYN_RECV requests at retransmitting SYN+ACKs.")
---
 include/linux/tcp.h | 3 +++
 net/ipv6/tcp_ipv6.c | 5 +++--
 2 files changed, 6 insertions(+), 2 deletions(-)
include/linux/tcp.h +3 -0
index 8e1266cf8ef69..c718516bcbee3 100644
@@ -179,6 +179,9 @@ struct tcp_request_sock {
 	u8				ao_rcv_next;
 	bool				used_tcp_ao;
 #endif
+#if IS_ENABLED(CONFIG_IPV6)
+	__be32				syn_flowlabel;
+#endif
 };
 
 static inline struct tcp_request_sock *tcp_rsk(const struct request_sock *req)
net/ipv6/tcp_ipv6.c +3 -2
index 027413fe37a41..fade3907b05da 100644
@@ -554,8 +554,8 @@ static int tcp_v6_send_synack(const struct sock *sk, struct dst_entry *dst,
 				    &ireq->ir_v6_rmt_addr);
 
 		fl6->daddr = ireq->ir_v6_rmt_addr;
-		if (inet6_test_bit(REPFLOW, sk) && ireq->pktopts)
-			fl6->flowlabel = ip6_flowlabel(ipv6_hdr(ireq->pktopts));
+		if (inet6_test_bit(REPFLOW, sk))
+			fl6->flowlabel = tcp_rsk(req)->syn_flowlabel;
 
 		tclass = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_reflect_tos) ?
 				(tcp_rsk(req)->syn_tos & ~INET_ECN_MASK) |
@@ -808,6 +808,7 @@ static void tcp_v6_init_req(struct request_sock *req,
 	ireq->ir_v6_loc_addr = ipv6_hdr(skb)->daddr;
 	ireq->ir_rmt_addr = LOOPBACK4_IPV6;
 	ireq->ir_loc_addr = LOOPBACK4_IPV6;
+	tcp_rsk(req)->syn_flowlabel = ip6_flowlabel(ipv6_hdr(skb));
 
 	/* So that link locals have meaning */
 	if ((!sk_listener->sk_bound_dev_if || l3_slave) &&
Signature · 1 line
2.53.0
author maintainer
#261 lore raw

PATCH 260/990 drm/amd/pm: track BACO state in the SMU v11 ArmD3 sequence

In reply to Greg Kroah-Hartman

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

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

From: Mario Limonciello <[email protected]>

[ Upstream commit a26ec190925733dd205507493e936e59dbcd2b19 ]

On Navi1x/Sienna Cichlid with runtime PM, when the audio function is enabled, BACO entry and exit are delegated to PMFW by sending SMU_MSG_ArmD3 instead of going through smu_v11_0_baco_set_state(). Unlike the v13/v14/v15 helpers, smu_v11_0_baco_set_armd3_sequence() does not update smu_baco->state, so the driver keeps reporting SMU_BACO_STATE_EXIT while the ASIC is armed for / sitting in BACO.

At runtime resume amdgpu_device_baco_exit() checks amdgpu_device_supports_baco(), which ends up in smu_v11_0_get_bamaco_support(). Since the state never reads ENTER, the "already in BACO" shortcut is skipped and the live BACO feature bit is consulted instead. PMFW clears that bit once ArmD3(BACO) is armed, so the check reports "supported but not enabled", the exit fails with -ENOTSUPP and the ULPS ArmD3 message is never sent. The runtime resume caller ignores the error, and a later secondary bus reset leaves the device unreachable. This shows up on a Navi 23 being handed from amdgpu to vfio-pci:

baco_enter: in_runpm=1 audio_enabled=1 armd3=1 baco_state=1 ret=0
bamaco: state=1 ... feat supported=1 enabled=0 in_runpm=1
baco_exit: supports=0 ...
runtime resume: baco_exit ret=-524

Update smu_baco->state in the helper, mirroring the v13 implementation, so the capability check short-circuits while in BACO.

Fixes 13d75eadfa1a ("drm/amd/pm: correct the runpm handling for BACO supported ASIC")
(cherry picked from commit d515b2694eab5b35533c7fb7af5bddff53ff60d3)
---
 .../gpu/drm/amd/pm/swsmu/smu11/smu_v11_0.c    | 20 ++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)
drivers/gpu/drm/amd/pm/swsmu/smu11/smu_v11_0.c +19 -1
index 48bf000f12e5c..42a4ba9965081 100644
@@ -1559,7 +1559,25 @@ int smu_v11_0_set_azalia_d3_pme(struct smu_context *smu)
 int smu_v11_0_baco_set_armd3_sequence(struct smu_context *smu,
 				      enum smu_baco_seq baco_seq)
 {
-	return smu_cmn_send_smc_msg_with_param(smu, SMU_MSG_ArmD3, baco_seq, NULL);
+	struct smu_baco_context *smu_baco = &smu->smu_baco;
+	int ret;
+
+	ret = smu_cmn_send_smc_msg_with_param(smu, SMU_MSG_ArmD3, baco_seq, NULL);
+	if (ret)
+		return ret;
+
+	/*
+	 * PMFW owns the BACO transition once armed, so keep the driver's view
+	 * in sync.  Otherwise smu_v11_0_get_bamaco_support() falls back to the
+	 * live BACO feature bit, which PMFW clears when armed, and the runtime
+	 * resume wrongly concludes BACO is unsupported and skips the exit.
+	 */
+	if (baco_seq == BACO_SEQ_BAMACO || baco_seq == BACO_SEQ_BACO)
+		smu_baco->state = SMU_BACO_STATE_ENTER;
+	else
+		smu_baco->state = SMU_BACO_STATE_EXIT;
+
+	return 0;
 }
 
 int smu_v11_0_get_bamaco_support(struct smu_context *smu)
Signature · 1 line
2.53.0
author maintainer
#262 lore raw

PATCH 261/990 firmware: cs_dsp: Fix memory leak on cs_dsp_power_up() error path

In reply to Greg Kroah-Hartman

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

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

From: Richard Fitzgerald <[email protected]>

[ Upstream commit 39d31f76ad1b12f1b5e6ef4c15f89e6b3c3f603a ]

If cs_dsp_power_up() fails on or after cs_dsp_load() mark the controls disabled and free the alg regions.

Fixes f6bc909e7673c ("firmware: cs_dsp: add driver to support firmware loading on Cirrus Logic DSPs")
---
 drivers/firmware/cirrus/cs_dsp.c | 6 ++++++
 1 file changed, 6 insertions(+)
drivers/firmware/cirrus/cs_dsp.c +6 -0
index 15710c97f9fb0..0e20f72cfdfcf 100644
@@ -2745,6 +2745,7 @@ int cs_dsp_power_up(struct cs_dsp *dsp,
 		    const struct firmware *coeff_firmware, const char *coeff_filename,
 		    const char *fw_name)
 {
+	struct cs_dsp_coeff_ctl *ctl;
 	int ret;
 
 	mutex_lock(&dsp->pwr_lock);
@@ -2789,6 +2790,11 @@ int cs_dsp_power_up(struct cs_dsp *dsp,
 
 	return 0;
 err_ena:
+	list_for_each_entry(ctl, &dsp->ctl_list, list)
+		ctl->enabled = 0;
+
+	cs_dsp_free_alg_regions(dsp);
+
 	if (dsp->ops->disable_core)
 		dsp->ops->disable_core(dsp);
 err_mem:
Signature · 1 line
2.53.0
author maintainer
#263 lore raw

PATCH 262/990 ACPI: scan: Print the offline failure message in acpi_bus_offline()

In reply to Greg Kroah-Hartman

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

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

[ Upstream commit b9ea1e921c2721546f53270cffdc6866e20576dd ]

When a physical node of an ACPI device being hot-removed cannot be offlined, acpi_bus_offline() passes the physical device back to acpi_scan_try_to_offline() through ret_p and the latter prints "Offline failed." for it after the namespace walk. By then physical_node_lock is not held anymore, so the device may have been unbound from its ACPI companion and freed in the meantime.

Print the message in acpi_bus_offline() when device_offline() fails in the second pass, while physical_node_lock keeps the device bound to its ACPI companion and so the reference taken by acpi_bind_one() is still held. acpi_scan_try_to_offline() only needs to know that something could not be offlined, so pass the ACPI device back through ret_p instead, like in the "Offline disabled." case.

Fixes 303bfdb1a14d ("ACPI / scan: Add second pass of companion offlining to hot-remove code")
---
 drivers/acpi/scan.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/acpi/scan.c +2 -2
index 3893e44005f40..e4bca03a4e476 100644
@@ -165,8 +165,9 @@ static acpi_status acpi_bus_offline(acpi_handle handle, u32 lvl, void *data,
 		if (ret >= 0) {
 			pn->put_online = !ret;
 		} else {
-			*ret_p = pn->dev;
+			*ret_p = &device->dev;
 			if (second_pass) {
+				dev_warn(pn->dev, "Offline failed.\n");
 				status = AE_ERROR;
 				break;
 			}
@@ -235,7 +236,6 @@ static int acpi_scan_try_to_offline(struct acpi_device *device)
 					 (void **)&errdev);
 
 		if (errdev) {
-			dev_warn(errdev, "Offline failed.\n");
 			acpi_bus_online(handle, 0, NULL, NULL);
 			acpi_walk_namespace(ACPI_TYPE_ANY, handle,
 					    ACPI_UINT32_MAX, acpi_bus_online,
Signature · 1 line
2.53.0
author maintainer
#264 lore raw

PATCH 263/990 ACPI: scan: Do not hold physical_node_lock across device_offline() and device_online()

In reply to Greg Kroah-Hartman

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

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

[ Upstream commit 17654aa629cba9a70e31cc1b7226a4fc1a1c801a ]

acpi_bus_offline() and acpi_bus_online() hold the physical_node_lock of the ACPI device being hot-removed while they call device_offline() and device_online() for its physical nodes. Offlining a CPU this way takes cpu_add_remove_lock and the CPU hotplug lock under physical_node_lock, and lockdep connects that to the uevent attribute of platform devices, whose store method takes physical_node_lock in acpi_primary_dev_companion():

physical_node_lock (acpi_bus_offline())

    -> cpu_add_remove_lock -> cpu_hotplug_lock
    -> cpuhp_state-down (mce_cpu_pre_down() unregistering a device)
    -> device_links_lock (device_links_purge())
    -> kn->active of a uevent attribute (device link unregistration)
    -> physical_node_lock (uevent_store() -> acpi_companion_match())

syzbot has reported this cycle twice. The uevent attribute waited for in the link unregistration is the device link's, not a platform device's, and the physical_node_lock taken at the end is that of the platform device's ACPI companion, not of the processor being ejected, so lockdep only connects them because they share lock classes and this is unlikely to deadlock. However, lockdep turns itself off after reporting it.

It can be reproduced in a QEMU guest by writing to the uevent attribute of an ACPI-enumerated platform device, reading the uevent attribute of a device link while the link is removed, offlining a CPU and ejecting one through sysfs.

physical_node_lock protects the list of physical nodes. Since acpi_unbind_one() blocks on it, holding it also keeps device_offline() and device_online() from running in parallel with whatever happens to a device after it has been unbound from its ACPI companion, but that is not
necessary: a reference to each device is held while the lock is dropped, and the removal of the devices that can actually be taken offline here (CPUs, memory blocks and containers) is serialized by the device hotplug lock or acpi_scan_lock, both of which acpi_device_hotplug() holds throughout.

So drop physical_node_lock around device_offline() and device_online(). Mark the nodes to offline with a new offline_pending flag, hold a reference to each device while the lock is dropped, and look its node up again afterwards to record whether it needs to be put back online, because it may have been unbound in the meantime. Physical nodes added while the lock is not held are not offlined by the current pass, which is no different from adding them right after it.

Since acpi_container_offline() no longer runs under the container's physical_node_lock, the nesting annotation added to acpi_scan_is_offline() by commit 4c533c801d1c ("ACPI / scan: Annotate physical_node_lock in acpi_scan_is_offline()") is not needed anymore, so drop it.

---
 drivers/acpi/scan.c     | 106 +++++++++++++++++++++++++++++++++-------
 include/acpi/acpi_bus.h |   1 +
 2 files changed, 88 insertions(+), 19 deletions(-)
drivers/acpi/scan.c +87 -19
index e4bca03a4e476..ab8382c812e8f 100644
@@ -114,11 +114,7 @@ bool acpi_scan_is_offline(struct acpi_device *adev, bool uevent)
 	bool offline = true;
 	char *envp[] = { "EVENT=offline", NULL };
 
-	/*
-	 * acpi_container_offline() calls this for all of the container's
-	 * children under the container's physical_node_lock lock.
-	 */
-	mutex_lock_nested(&adev->physical_node_lock, SINGLE_DEPTH_NESTING);
+	mutex_lock(&adev->physical_node_lock);
 
 	list_for_each_entry(pn, &adev->physical_node_list, node)
 		if (device_supports_offline(pn->dev) && !pn->dev->offline) {
@@ -133,6 +129,59 @@ bool acpi_scan_is_offline(struct acpi_device *adev, bool uevent)
 	return offline;
 }
 
+static struct acpi_device_physical_node *
+acpi_find_physical_node(struct acpi_device *adev, struct device *dev)
+{
+	struct acpi_device_physical_node *pn;
+
+	lockdep_assert_held(&adev->physical_node_lock);
+
+	list_for_each_entry(pn, &adev->physical_node_list, node)
+		if (pn->dev == dev)
+			return pn;
+
+	return NULL;
+}
+
+static struct device *acpi_next_offline_pending(struct acpi_device *adev)
+{
+	struct acpi_device_physical_node *pn;
+
+	lockdep_assert_held(&adev->physical_node_lock);
+
+	/*
+	 * Find the first physical node that is still to be offlined, clear its
+	 * offline_pending flag and return its device with a reference held.
+	 */
+	list_for_each_entry(pn, &adev->physical_node_list, node)
+		if (pn->offline_pending) {
+			pn->offline_pending = false;
+			return get_device(pn->dev);
+		}
+
+	return NULL;
+}
+
+static struct device *acpi_next_put_online(struct acpi_device *adev)
+{
+	struct acpi_device_physical_node *pn;
+
+	lockdep_assert_held(&adev->physical_node_lock);
+
+	/*
+	 * Find the first physical node that has been offlined by
+	 * acpi_bus_offline(), clear its put_online flag and return its device
+	 * with a reference held.
+	 */
+	list_for_each_entry(pn, &adev->physical_node_list, node)
+		if (pn->put_online) {
+			pn->put_online = false;
+			return get_device(pn->dev);
+		}
+
+	return NULL;
+}
+
 static acpi_status acpi_bus_offline(acpi_handle handle, u32 lvl, void *data,
 				    void **ret_p)
 {
@@ -140,6 +189,7 @@ static acpi_status acpi_bus_offline(acpi_handle handle, u32 lvl, void *data,
 	struct acpi_device_physical_node *pn;
 	bool second_pass = (bool)data;
 	acpi_status status = AE_OK;
+	struct device *dev;
 
 	if (!device)
 		return AE_OK;
@@ -152,26 +202,43 @@ static acpi_status acpi_bus_offline(acpi_handle handle, u32 lvl, void *data,
 	mutex_lock(&device->physical_node_lock);
 
 	list_for_each_entry(pn, &device->physical_node_list, node) {
-		int ret;
-
 		if (second_pass) {
 			/* Skip devices offlined by the first pass. */
-			if (pn->put_online)
-				continue;
+			pn->offline_pending = !pn->put_online;
 		} else {
+			pn->offline_pending = true;
 			pn->put_online = false;
 		}
-		ret = device_offline(pn->dev);
+	}
+
+	/*
+	 * Drop physical_node_lock around device_offline(), because the latter
+	 * acquires locks, like the CPU hotplug ones, that must not nest under
+	 * it.
+	 */
+	while ((dev = acpi_next_offline_pending(device))) {
+		int ret;
+
+		mutex_unlock(&device->physical_node_lock);
+		ret = device_offline(dev);
+		mutex_lock(&device->physical_node_lock);
+
 		if (ret >= 0) {
-			pn->put_online = !ret;
+			/* The device may have been unbound in the meantime. */
+			pn = acpi_find_physical_node(device, dev);
+			if (pn)
+				pn->put_online = !ret;
 		} else {
 			*ret_p = &device->dev;
 			if (second_pass) {
-				dev_warn(pn->dev, "Offline failed.\n");
+				dev_warn(dev, "Offline failed.\n");
 				status = AE_ERROR;
-				break;
 			}
 		}
+
+		put_device(dev);
+		if (ACPI_FAILURE(status))
+			break;
 	}
 
 	mutex_unlock(&device->physical_node_lock);
@@ -183,18 +250,19 @@ static acpi_status acpi_bus_online(acpi_handle handle, u32 lvl, void *data,
 				   void **ret_p)
 {
 	struct acpi_device *device = acpi_fetch_acpi_dev(handle);
-	struct acpi_device_physical_node *pn;
+	struct device *dev;
 
 	if (!device)
 		return AE_OK;
 
 	mutex_lock(&device->physical_node_lock);
 
-	list_for_each_entry(pn, &device->physical_node_list, node)
-		if (pn->put_online) {
-			device_online(pn->dev);
-			pn->put_online = false;
-		}
+	while ((dev = acpi_next_put_online(device))) {
+		mutex_unlock(&device->physical_node_lock);
+		device_online(dev);
+		mutex_lock(&device->physical_node_lock);
+		put_device(dev);
+	}
 
 	mutex_unlock(&device->physical_node_lock);
 
include/acpi/acpi_bus.h +1 -0
index d6b449c6ecd3a..f568089194ab2 100644
@@ -363,6 +363,7 @@ struct acpi_device_physical_node {
 	struct device *dev;
 	unsigned int node_id;
 	bool put_online:1;
+	bool offline_pending:1;
 };
 
 struct acpi_device_properties {
Signature · 1 line
2.53.0
author maintainer
#265 lore raw

PATCH 264/990 ASoC: wm_adsp: Prevent negative string length in wm_adsp_control_add()

In reply to Greg Kroah-Hartman

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

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

From: Richard Fitzgerald <[email protected]>

[ Upstream commit 4d07af76ca41cc1a03240cd3b5f44dc428856214 ]

Check that avail does not become < 1 in wm_adsp_control_add(). This prevents overflows during subsequent operations.

The main aim is to trap a negative value in avail, but a zero length would mean that the control ends up without a name, so 1 is the smallest valid value.

Fixes b7ede5af62ab6 ("ASoC: wm_adsp: Take prefix into account in control name length")
---
 sound/soc/codecs/wm_adsp.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
sound/soc/codecs/wm_adsp.c +10 -0
index 751a3c25e4f0b..7c1c2ba7a0f6f 100644
@@ -44,6 +44,9 @@
 #define adsp_dbg(_dsp, fmt, ...) \
 	dev_dbg(_dsp->cs_dsp.dev, "%s: " fmt, _dsp->cs_dsp.name, ##__VA_ARGS__)
 
+#define adsp_warn_once(_dsp, fmt, ...) \
+	dev_warn_once(_dsp->cs_dsp.dev, "%s: " fmt, _dsp->cs_dsp.name, ##__VA_ARGS__)
+
 #define compr_err(_obj, fmt, ...) \
 	adsp_err(_obj->dsp, "%s: " fmt, _obj->name ? _obj->name : "legacy", \
 		 ##__VA_ARGS__)
@@ -619,6 +622,13 @@ int wm_adsp_control_add(struct cs_dsp_coeff_ctl *cs_ctl)
 		if (dsp->component->name_prefix)
 			avail -= strlen(dsp->component->name_prefix) + 1;
 
+		if (avail < 1) {
+			adsp_warn_once(dsp,
+				       "%.*s: ALSA prefix too long: control not created\n",
+				       cs_ctl->subname_len, cs_ctl->subname);
+			return -EINVAL;
+		}
+
 		/* Truncate the subname from the start if it is too long */
 		if (cs_ctl->subname_len > avail)
 			skip = cs_ctl->subname_len - avail;
Signature · 1 line
2.53.0
author maintainer
#266 lore raw

PATCH 265/990 Bluetooth: hci_conn: Fix SCO/eSCO Transport_Unit_Size for HCI data path

In reply to Greg Kroah-Hartman

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

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

From: Zijun Hu <[email protected]>

[ Upstream commit 3efdadae3a252b14ca1f62b16e31a9aa7c5d30cf ]

Correct (Input|Output)_Transport_Unit_Size based on Core spec v6.3, Vol 4, Part E, 7.1.45:

"The Host shall set the Input_Transport_Unit_Size and
Output_Transport_Unit_Size to be equal. For HCI Host transport the Host shall set them to 0."

Fixes b2af264ad3af ("Bluetooth: Add support for HCI_Enhanced_Setup_Synchronous_Connection command")
---
 net/bluetooth/hci_conn.c | 18 ++++++++++++------
 1 file changed, 12 insertions(+), 6 deletions(-)
net/bluetooth/hci_conn.c +12 -6
index f7645dc0ad2ae..29e13da009505 100644
@@ -330,8 +330,10 @@ static int hci_enhanced_setup_sync(struct hci_dev *hdev, void *data)
 		cp.out_pcm_sample_payload_msb_pos = 0;
 		cp.in_data_path = conn->codec.data_path;
 		cp.out_data_path = conn->codec.data_path;
-		cp.in_transport_unit_size = 1;
-		cp.out_transport_unit_size = 1;
+		if (conn->codec.data_path) {
+			cp.in_transport_unit_size = 1;
+			cp.out_transport_unit_size = 1;
+		}
 		break;
 
 	case BT_CODEC_TRANSPARENT:
@@ -356,8 +358,10 @@ static int hci_enhanced_setup_sync(struct hci_dev *hdev, void *data)
 		cp.out_pcm_sample_payload_msb_pos = 0;
 		cp.in_data_path = conn->codec.data_path;
 		cp.out_data_path = conn->codec.data_path;
-		cp.in_transport_unit_size = 1;
-		cp.out_transport_unit_size = 1;
+		if (conn->codec.data_path) {
+			cp.in_transport_unit_size = 1;
+			cp.out_transport_unit_size = 1;
+		}
 		break;
 
 	case BT_CODEC_CVSD:
@@ -387,8 +391,10 @@ static int hci_enhanced_setup_sync(struct hci_dev *hdev, void *data)
 		cp.out_pcm_sample_payload_msb_pos = 0;
 		cp.in_data_path = conn->codec.data_path;
 		cp.out_data_path = conn->codec.data_path;
-		cp.in_transport_unit_size = 16;
-		cp.out_transport_unit_size = 16;
+		if (conn->codec.data_path) {
+			cp.in_transport_unit_size = 16;
+			cp.out_transport_unit_size = 16;
+		}
 		break;
 	default:
 		goto unlock;
Signature · 1 line
2.53.0
author maintainer
#267 lore raw

PATCH 266/990 Bluetooth: L2CAP: Clear request identifiers on incoming LE connections

In reply to Greg Kroah-Hartman

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

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

From: Zhao Li <[email protected]>

[ Upstream commit 15a80cc8263abd50132a05d1b06824de8e28abcb ]

Incoming LE and ECRED channels retain the peer's request identifier after an immediate response. The deferred LE response also leaves the identifier set, unlike the deferred ECRED response.

A later ECRED request can reuse that identifier and include an unrelated channel in its shared-response handling. That walk matches on the identifier alone, so an LE channel is selected too. If the old channel is closing, the checks can refuse the new connection. The check at request receipt rejects it with L2CAP_CR_LE_INVALID_PARAMS; the check before a deferred response returns L2CAP_CR_LE_AUTHORIZATION.

Store the identifier only when deferring the response, and clear it after sending the deferred LE response. Keep deferred ECRED identifiers until the shared response is sent, since a partially accepted group still needs them.

AI assistance was used.

Fixes 27e2d4c8d28b ("Bluetooth: Add basic LE L2CAP connect request receiving support")
Fixes 15f02b910562 ("Bluetooth: L2CAP: Add initial code for Enhanced Credit Based Mode")
---
 net/bluetooth/l2cap_core.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
net/bluetooth/l2cap_core.c +3 -2
index 2df5d25bfee60..eef49a65084b4 100644
@@ -3914,6 +3914,7 @@ void __l2cap_le_connect_rsp_defer(struct l2cap_chan *chan)
 
 	l2cap_send_cmd(conn, chan->ident, L2CAP_LE_CONN_RSP, sizeof(rsp),
 		       &rsp);
+	chan->ident = 0;
 }
 
 static void l2cap_ecred_list_defer(struct l2cap_chan *chan, void *data)
@@ -5162,10 +5163,10 @@ static int l2cap_le_connect_req(struct l2cap_conn *conn,
 
 	__set_chan_timer(chan, chan->ops->get_sndtimeo(chan));
 
-	chan->ident = cmd->ident;
 	chan->mode = L2CAP_MODE_LE_FLOWCTL;
 
 	if (test_bit(FLAG_DEFER_SETUP, &chan->flags)) {
+		chan->ident = cmd->ident;
 		l2cap_state_change(chan, BT_CONNECT2);
 		/* The following result value is actually not defined
 		 * for LE CoC but we use it to let the function know
@@ -5395,10 +5396,10 @@ static inline int l2cap_ecred_conn_req(struct l2cap_conn *conn,
 
 		__set_chan_timer(chan, chan->ops->get_sndtimeo(chan));
 
-		chan->ident = cmd->ident;
 		chan->mode = L2CAP_MODE_EXT_FLOWCTL;
 
 		if (test_bit(FLAG_DEFER_SETUP, &chan->flags)) {
+			chan->ident = cmd->ident;
 			l2cap_state_change(chan, BT_CONNECT2);
 			defer = true;
 			chan->ops->defer(chan);
Signature · 1 line
2.53.0
author maintainer
#268 lore raw

PATCH 267/990 Bluetooth: qca: Disable SoC debug logging for WCN3950

In reply to Greg Kroah-Hartman

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

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

From: Stanislavs Nilovs <[email protected]>

[ Upstream commit d97b618b6675516d63d55b8f31ee6cb3b164bd6b ]

Added WCN3950 module to the switch-case to disable SoC debug packets.

Fixes 590deccf4c06 ("Bluetooth: hci_qca: Disable SoC debug logging for WCN3991")
---
 drivers/bluetooth/btqca.c | 1 +
 1 file changed, 1 insertion(+)
drivers/bluetooth/btqca.c +1 -0
index 4215522e62a2c..ba0b8869b3f6e 100644
@@ -948,6 +948,7 @@ int qca_uart_setup(struct hci_dev *hdev, uint8_t baudrate,
 	switch (soc_type) {
 	case QCA_QCA2066:
 	case QCA_QCA6390:
+	case QCA_WCN3950:
 	case QCA_WCN3991:
 	case QCA_WCN6750:
 	case QCA_WCN6855:
Signature · 1 line
2.53.0
author maintainer
#269 lore raw

PATCH 268/990 net: ethernet: bgmac: preserve forced 2.5 Gbps link speed

In reply to Greg Kroah-Hartman

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

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

From: Florian Fainelli <[email protected]>

[ Upstream commit d4f3d2c04624854d27aa948cd7bfc9d946faaac5 ]

Northstar and Northstar Plus use a 2.5 Gbps internal link between the AMAC and the switch. BGMAC_FEAT_FORCE_SPEED_2500 makes bgmac_miiconfig() configure that speed, but bgmac_adjust_link() subsequently replaces it with the synthetic fixed PHY's 1 Gbps speed.

Use the forced speed when processing link changes so the MAC remains at 2.5 Gbps. Together with configuring the switch IMP port for its 2 Gbps mode, this eliminates the output queue discards that caused approximately 1000 TCP retransmissions per second during an iperf3 transmit test.

Restrict the platform forced-speed flag to Northstar Plus using the SoC compatible, since Hurricane2 shares the AMAC compatible. Other platform AMACs without a phy-handle must continue following the fixed PHY speed. The BCMA path already selects the flag only for the Northstar family.

Fixes f6a95a24957a ("net: ethernet: bgmac: Add platform device support")
---
 drivers/net/ethernet/broadcom/bgmac-platform.c | 3 ++-
 drivers/net/ethernet/broadcom/bgmac.c          | 8 ++++++--
 2 files changed, 8 insertions(+), 3 deletions(-)
drivers/net/ethernet/broadcom/bgmac-platform.c +2 -1
index 4e266ce41180b..4880b18904812 100644
@@ -243,7 +243,8 @@ static int bgmac_probe(struct platform_device *pdev)
 		bgmac->phy_connect = platform_phy_connect;
 	} else {
 		bgmac->phy_connect = bgmac_phy_connect_direct;
-		bgmac->feature_flags |= BGMAC_FEAT_FORCE_SPEED_2500;
+		if (of_machine_is_compatible("brcm,nsp"))
+			bgmac->feature_flags |= BGMAC_FEAT_FORCE_SPEED_2500;
 	}
 
 	return bgmac_enet_probe(bgmac);
drivers/net/ethernet/broadcom/bgmac.c +6 -2
index b3f0ecc583fd5..409155fe8df0d 100644
@@ -1428,11 +1428,15 @@ void bgmac_adjust_link(struct net_device *net_dev)
 {
 	struct bgmac *bgmac = netdev_priv(net_dev);
 	struct phy_device *phy_dev = net_dev->phydev;
+	int speed = phy_dev->speed;
 	bool update = false;
 
+	if (bgmac->feature_flags & BGMAC_FEAT_FORCE_SPEED_2500)
+		speed = SPEED_2500;
+
 	if (phy_dev->link) {
-		if (phy_dev->speed != bgmac->mac_speed) {
-			bgmac->mac_speed = phy_dev->speed;
+		if (speed != bgmac->mac_speed) {
+			bgmac->mac_speed = speed;
 			update = true;
 		}
 
Signature · 1 line
2.53.0
author maintainer
#270 lore raw

PATCH 269/990 net: dsa: b53: restore the NSP IMP port 2 Gbps mode

In reply to Greg Kroah-Hartman

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

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

From: Florian Fainelli <[email protected]>

[ Upstream commit 41af38324341df9d769641d6485abb67fd5209ed ]

The Northstar Plus IMP port uses the switch's proprietary 2 Gbps mode for its internal link to the AMAC. Its fixed-link description reports 1 Gbps, so applying that speed clears PORT_OVERRIDE_SPEED_2000M and leaves the two ends of the internal link configured at different speeds.

Force the 2 Gbps mode and flow control for BCM5301x and NSP CPU ports. The mismatch caused switch output queue discards on both copper and SerDes ports, with one discard for every TCP retransmission. With both ends restored to their high-speed modes, iperf3 reports no retransmissions.

Fixes b6a8a5477fe9 ("net: dsa: b53: fix resetting speed and pause on forced link")
---
 drivers/net/dsa/b53/b53_common.c | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)
drivers/net/dsa/b53/b53_common.c +9 -3
index af73a9f70773d..137bc55b86d6b 100644
@@ -1702,9 +1702,15 @@ static void b53_phylink_mac_link_up(struct phylink_config *config,
 	}
 
 	if (mode == MLO_AN_FIXED) {
-		/* Force flow control on BCM5301x's CPU port */
-		if (is5301x(dev) && dsa_is_cpu_port(ds, port))
-			tx_pause = rx_pause = true;
+		/* Force flow control and 2Gbits/sec on BCM5301x and NSP CPU
+		 * ports
+		 */
+		if ((is5301x(dev) || dev->chip_id == BCM58XX_DEVICE_ID) &&
+		    dsa_is_cpu_port(ds, port)) {
+			tx_pause = true;
+			rx_pause = true;
+			speed = 2000;
+		}
 
 		b53_force_port_config(dev, port, speed, duplex,
 				      tx_pause, rx_pause);
Signature · 1 line
2.53.0
author maintainer
#271 lore raw

PATCH 270/990 Bluetooth: Fix not updating of hdev->commands[] after reset

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit e00aa1a33f81a5e25b510f569ab9cb9f97eb41b9 ]

Read Local Supported Commands was only read once during the INIT/SETUP flow, but the supported commands bits may change at runtime, for example after a firmware change applied with vendor commands, so update hdev->commands[] every time the response is received.

Fixes 6a070e6e81ad ("Bluetooth: Store supported commands only during setup procedure")
---
 net/bluetooth/hci_event.c | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)
net/bluetooth/hci_event.c +1 -3
index 8b9b27f2d8916..3e487963eaff9 100644
@@ -792,9 +792,7 @@ static u8 hci_cc_read_local_commands(struct hci_dev *hdev, void *data,
 	if (rp->status)
 		return rp->status;
 
-	if (hci_dev_test_flag(hdev, HCI_SETUP) ||
-	    hci_dev_test_flag(hdev, HCI_CONFIG))
-		memcpy(hdev->commands, rp->commands, sizeof(hdev->commands));
+	memcpy(hdev->commands, rp->commands, sizeof(hdev->commands));
 
 	return rp->status;
 }
Signature · 1 line
2.53.0
author maintainer
#272 lore raw

PATCH 271/990 spi: cadence-quadspi: Fix race between DMA completion and transfer start

In reply to Greg Kroah-Hartman

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

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

From: Frederic Konrad <[email protected]>

[ Upstream commit 059518f775baecc9803fc97787bd0b17558f8047 ]

In cqspi_versal_indirect_read_dma(), the DMA transfer is started by writing CQSPI_REG_INDIRECTRD_START_MASK to the indirect read control register. Under certain timing conditions, the DMA completion interrupt may be triggered and complete the transfer before the completion structure is reinitialized.

This creates a race where the completion event is lost, causing wait_for_completion_timeout() to time out even though the transfer has already completed, resulting in errors such as:

spi-nor spi0.0: CS0: operation failed with -110

Fix this by reinitializing the completion structure before starting the DMA transfer, ensuring that any completion event generated after the transfer begins is correctly observed.

Fixes 1a6f854f7daa ("spi: cadence-quadspi: Add Xilinx Versal external DMA support")
---
 drivers/spi/spi-cadence-quadspi.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/spi/spi-cadence-quadspi.c +2 -2
index 441426bc232ef..f74abed42eab9 100644
@@ -957,11 +957,11 @@ static int cqspi_versal_indirect_read_dma(struct cqspi_flash_pdata *f_pdata,
 	writel(CQSPI_REG_VERSAL_DMA_DST_CTRL_VAL,
 	       reg_base + CQSPI_REG_VERSAL_DMA_DST_CTRL);
 
+	reinit_completion(&cqspi->transfer_complete);
+
 	writel(CQSPI_REG_INDIRECTRD_START_MASK,
 	       reg_base + CQSPI_REG_INDIRECTRD);
 
-	reinit_completion(&cqspi->transfer_complete);
-
 	if (!wait_for_completion_timeout(&cqspi->transfer_complete,
 					 msecs_to_jiffies(max_t(size_t, bytes_to_dma, 500)))) {
 		ret = -ETIMEDOUT;
Signature · 1 line
2.53.0
author maintainer
#273 lore raw

PATCH 272/990 drm/nouveau/fifo: map Kepler video engine contexts non-privileged

In reply to Greg Kroah-Hartman

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

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

From: Rosen Penev <[email protected]>

[ Upstream commit 0820004c342af7ca1b01d0b21e0d5d99ad5c10eb ]

Since the engine context rework, gk104_ectx_ctor() maps every engine context into the channel's VMM as a privileged page. The MSVLD, MSPDEC and MSPPP falcons on Kepler fetch their context with non-privileged requests, so the first method sent to any of them faults and the channel is killed:

fifo: fault 00 [READ] at 0000000001050000 engine 10 [MSVLD] client 0d [HUB/MSVLD] reason 05 [PRIV_VIOLATION] on channel 9
fifo: fault 00 [READ] at 0000000001051000 engine 14 [MSPDEC] client 0b [HUB/MSPDEC] reason 05 [PRIV_VIOLATION] on channel 10
fifo: fault 00 [READ] at 0000000001052000 engine 11 [MSPPP] client 0c [HUB/MSPPP] reason 05 [PRIV_VIOLATION] on channel 11

Before the rework, gk104_fifo_gpfifo_engine_ctor() mapped engine contexts without the privileged bit. Restore that for the three video engines, and keep the privileged mapping for everything else.

Fixes 8ab849d6dd4c ("drm/nouveau/fifo: add new engine context handling")
---
 drivers/gpu/drm/nouveau/nvkm/engine/fifo/gk104.c | 13 +++++++++++++
 1 file changed, 13 insertions(+)
drivers/gpu/drm/nouveau/nvkm/engine/fifo/gk104.c +13 -0
index 5655eda52a7b5..912eb6c3a13d4 100644
@@ -180,6 +180,19 @@ gk104_ectx_ctor(struct nvkm_engn *engn, struct nvkm_vctx *vctx)
 	struct gf100_vmm_map_v0 args = { .priv = 1 };
 	int ret;
 
+	/* The video falcons access their context with non-privileged
+	 * requests, and fault with PRIV_VIOLATION on a privileged mapping.
+	 */
+	switch (engn->engine->subdev.type) {
+	case NVKM_ENGINE_MSVLD:
+	case NVKM_ENGINE_MSPDEC:
+	case NVKM_ENGINE_MSPPP:
+		args.priv = 0;
+		break;
+	default:
+		break;
+	}
+
 	ret = nvkm_vmm_get(vctx->vmm, 12, vctx->inst->size, &vctx->vma);
 	if (ret)
 		return ret;
Signature · 1 line
2.53.0
author maintainer
#274 lore raw

PATCH 273/990 drm/nouveau: Fix CE channel creation on pre-Kepler GPUs

In reply to Greg Kroah-Hartman

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

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

From: Munique Feitoza <[email protected]>

[ Upstream commit a2b7b707d75e605d31fb3d85a6b27f8bb2a01413 ]

Commit 04e0481526e3 ("nouveau/dmem: Fix privileged error in copy engine channel") changed nouveau_accel_ce_init() to unconditionally request a privileged channel (priv = true) when calling nouveau_channel_new().

However, privileged channels (func->ramfc->priv) are only supported on Kepler (gk104_chan_ramfc) and newer FIFO implementations. On pre-Kepler GPUs that expose a Copy Engine runlist, func->ramfc->priv is false, which causes nvkm_chan_new_() to reject the channel creation with -EINVAL:

nouveau 0000:01:00.0: DRM: failed to create ce channel, -22

Only request a privileged CE channel when device->info.family >= NV_DEVICE_INFO_V0_KEPLER.

Fixes 04e0481526e3 ("nouveau/dmem: Fix privileged error in copy engine channel")
---
 drivers/gpu/drm/nouveau/nouveau_drm.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
drivers/gpu/drm/nouveau/nouveau_drm.c +6 -1
index d05da2db94a44..d4fe0e4f07985 100644
@@ -336,6 +336,7 @@ static void
 nouveau_accel_ce_init(struct nouveau_drm *drm)
 {
 	struct nvif_device *device = &drm->client.device;
+	bool priv;
 	u64 runm;
 	int ret = 0;
 
@@ -348,7 +349,11 @@ nouveau_accel_ce_init(struct nouveau_drm *drm)
 		return;
 	}
 
-	ret = nouveau_channel_new(&drm->client, true, runm, NvDmaFB, NvDmaTT, &drm->cechan);
+	/* priv copy engine only works on kepler and newer. */
+	priv = device->info.family >= NV_DEVICE_INFO_V0_KEPLER;
+
+	ret = nouveau_channel_new(&drm->client, priv, runm, NvDmaFB, NvDmaTT,
+				  &drm->cechan);
 	if (ret)
 		NV_ERROR(drm, "failed to create ce channel, %d\n", ret);
 }
Signature · 1 line
2.53.0
author maintainer
#275 lore raw

PATCH 274/990 ALSA: hda/core: Stop capability walk on empty capability header

In reply to Greg Kroah-Hartman

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

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

From: Michał Kopeć <[email protected]>

[ Upstream commit f65c917397c77daeb7e6d0893ebe89107ddd5692 ]

snd_hdac_bus_parse_capabilities() walks the controller's linked capability list starting at LLCH. On some platforms one of the entries reads back as all zeros. Such a header does not describe a capability, but the walk still treats it as one: it falls into the default case and reports an error, printing the raw register value instead of the capability ID:

snd_hda_intel 0000:00:1f.3: Unknown capability 0

The walk then stops anyway, because the next pointer of a zero header is 0, so the message is only noise.

Treat an all-zero header as the end of the list, the same way a failed read (-1) is already handled, and log it at debug level only. Also print the capability ID in hex for a genuinely unknown capability, instead of the full header value.

Fixes 0b00a5615dc4 ("ALSA: hdac_ext: add hdac extended controller")
---
 sound/hda/core/controller.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
sound/hda/core/controller.c +9 -1
index a7c00ad801170..fd09b4b18fd84 100644
@@ -426,6 +426,13 @@ int snd_hdac_bus_parse_capabilities(struct hdac_bus *bus)
 			break;
 		}
 
+		/* An all-zero header means no capability is present here */
+		if (!cur_cap) {
+			dev_dbg(bus->dev, "Empty capability header at offset 0x%x\n",
+				offset);
+			break;
+		}
+
 		switch ((cur_cap & AZX_CAP_HDR_ID_MASK) >> AZX_CAP_HDR_ID_OFF) {
 		case AZX_ML_CAP_ID:
 			dev_dbg(bus->dev, "Found ML capability\n");
@@ -456,7 +463,8 @@ int snd_hdac_bus_parse_capabilities(struct hdac_bus *bus)
 			break;
 
 		default:
-			dev_err(bus->dev, "Unknown capability %d\n", cur_cap);
+			dev_err(bus->dev, "Unknown capability ID 0x%x\n",
+				(cur_cap & AZX_CAP_HDR_ID_MASK) >> AZX_CAP_HDR_ID_OFF);
 			cur_cap = 0;
 			break;
 		}
Signature · 1 line
2.53.0
author maintainer
#276 lore raw

PATCH 275/990 ALSA: hda: cs35l56: Stop cs_dsp before calling cs_dsp_power_down()

In reply to Greg Kroah-Hartman

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

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

From: Richard Fitzgerald <[email protected]>

[ Upstream commit 8c63987ac7fe605c337edbf9052cf97e2a415558 ]

In cs35l56_hda_unbind() call cs_dsp_stop() before cs_dsp_power_down() if cs_dsp is in a running state.

cs35l56_hda_runtime_resume() calls cs_dsp_run() if cs_dsp_power_up() has previously run successfully. If cs35l56_hda_unbind() is then called while in this runtime-resumed state cs_dsp will be running. The code wasn't checking for this and was calling cs_dsp_power_down() while still in a running state, which is illegal. This is currently fairly harmless for the cs35l56 driver. But it doesn't comply with the API, so potentially could break with any future changes that expect the correct API use.

Fixes fb78d73dde2d4 ("ALSA: hda/cs35l56: Call cs_dsp_power_down() before calling cs_dsp_remove()")
---
 sound/hda/codecs/side-codecs/cs35l56_hda.c | 2 ++
 1 file changed, 2 insertions(+)
sound/hda/codecs/side-codecs/cs35l56_hda.c +2 -0
index baf286bf7ec83..b55391fed61ac 100644
@@ -738,6 +738,8 @@ static void cs35l56_hda_unbind(struct device *dev, struct device *master, void *
 	cs_dsp_cleanup_debugfs(&cs35l56->cs_dsp);
 	debugfs_remove_recursive(cs35l56->debugfs_root);
 #endif
+	if (cs35l56->cs_dsp.running)
+		cs_dsp_stop(&cs35l56->cs_dsp);
 
 	if (cs35l56->base.fw_patched)
 		cs_dsp_power_down(&cs35l56->cs_dsp);
Signature · 1 line
2.53.0
author maintainer
#277 lore raw

PATCH 276/990 net: 8139cp: keep Rx masked while NAPI is scheduled

In reply to Greg Kroah-Hartman

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

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

From: Colton Pawielski <[email protected]>

[ Upstream commit 547b1ae5ec50b7d81b05b4219e0db7e56279d65f ]

cp_rx_poll() calls napi_complete_done() and only then takes cp->lock with interrupts disabled to unmask the Rx interrupts. An interrupt that is not masked while polling (TxOK, TxErr, ...) can arrive in between. cp_interrupt() then sees the Rx status bits, which are still set, finds NAPI no longer scheduled, masks Rx and schedules NAPI again. cp_rx_poll() then carries on and unmasks Rx anyway.

Quoted 1 line

From that point Rx interrupts are enabled while NAPI is scheduled:

cp_interrupt() leaves the Rx bits for the poll routine, does not mask them because napi_schedule_prep() fails, and the level-triggered interrupt fires again as soon as it returns. On an SH7751 LANDISK under combined Tx/Rx load this interrupt storm was captured with a RAM trace right before the board locked up hard.

Mask Rx in cp_interrupt() whenever Rx status is pending, not only when NAPI gets scheduled. If the race leaves Rx unmasked, the next interrupt masks it again, and the pending poll unmasks it when it completes.

---
 drivers/net/ethernet/realtek/8139cp.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
drivers/net/ethernet/realtek/8139cp.c +4 -4
index 9016527e229ac..8f81dc7deef1e 100644
@@ -600,11 +600,11 @@ static irqreturn_t cp_interrupt (int irq, void *dev_instance)
 		goto out_unlock;
 	}
 
-	if (status & (RxOK | RxErr | RxEmpty | RxFIFOOvr))
-		if (napi_schedule_prep(&cp->napi)) {
-			cpw16_f(IntrMask, cp_norx_intr_mask);
+	if (status & (RxOK | RxErr | RxEmpty | RxFIFOOvr)) {
+		cpw16_f(IntrMask, cp_norx_intr_mask);
+		if (napi_schedule_prep(&cp->napi))
 			__napi_schedule(&cp->napi);
-		}
+	}
 
 	if (status & (TxOK | TxErr | TxEmpty | SWInt))
 		cp_tx(cp);
Signature · 1 line
2.53.0
author maintainer
#278 lore raw

PATCH 277/990 bonding: 3ad: dont set BOND_LINK_FAIL on a slave that is not up

In reply to Greg Kroah-Hartman

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

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

From: Timur Stukan <[email protected]>

[ Upstream commit 9a65b9c2a97594bcaaf393329807653eff895bbf ]

In 802.3ad mode, when bond_update_speed_duplex() fails on NETDEV_UP or NETDEV_CHANGE, bond_slave_netdev_event() sets the slave link to FAIL if the slave has ever been up (last_link_up != 0), and to DOWN otherwise, so that miimon can set it right once speed/duplex are valid.

last_link_up is never cleared, so a slave that is currently DOWN but was up before is set to FAIL as well. miimon then treats it as a slave that is still in use and takes it through the full down path again:
the link failure count is incremented, "link status definitely down" is logged and the 802.3ad port is disabled a second time, although the slave has not been up since it went down.

Reproduced in 802.3ad mode with miimon=100 by setting a slave down and up again. On NETDEV_UP the speed is still unknown, so the notifier sets FAIL, and the next miimon pass sees no carrier and proposes DOWN:

ip link add bond0 type bond mode 802.3ad miimon 100 lacp_rate 1 ip link set enp0s3 down
ip link set enp0s4 down
ip link set enp0s3 master bond0
ip link set enp0s4 master bond0
ip link set enp0s3 up
ip link set enp0s4 up
ip link set bond0 up
# wait for LACP to settle
ip link set enp0s3 down
ip link set enp0s3 up

procfs then shows "Link Failure Count: 2" in enp0s3 slave part. Also in dmesg wrote twice: "link status definitely down, disabling slave".

Fix this by setting FAIL only for a slave that is currently UP and leaving other states alone. An up slave that loses speed/duplex still goes through FAIL as before, and DOWN/BACK slaves are left to miimon, as in the other modes.

Fixes ea53abfab960 ("bonding/802.3ad: fix link_failure_count tracking")
---
 drivers/net/bonding/bond_main.c | 15 +++++----------
 1 file changed, 5 insertions(+), 10 deletions(-)
drivers/net/bonding/bond_main.c +5 -10
index 2e9e1b4d74da9..7066059ff3e28 100644
@@ -3964,18 +3964,13 @@ static int bond_slave_netdev_event(unsigned long event,
 	case NETDEV_CHANGE:
 		/* For 802.3ad mode only:
 		 * Getting invalid Speed/Duplex values here will put slave
-		 * in weird state. Mark it as link-fail if the link was
-		 * previously up or link-down if it hasn't yet come up, and
-		 * let link-monitoring (miimon) set it right when correct
-		 * speeds/duplex are available.
+		 * in weird state. Mark an up slave as link-fail and let
+		 * miimon set it right when correct speed/duplex are available.
 		 */
 		if (bond_update_speed_duplex(slave) &&
-		    BOND_MODE(bond) == BOND_MODE_8023AD) {
-			if (slave->last_link_up)
-				slave->link = BOND_LINK_FAIL;
-			else
-				slave->link = BOND_LINK_DOWN;
-		}
+		    BOND_MODE(bond) == BOND_MODE_8023AD &&
+		    slave->link == BOND_LINK_UP)
+			slave->link = BOND_LINK_FAIL;
 
 		if (BOND_MODE(bond) == BOND_MODE_8023AD)
 			bond_3ad_adapter_speed_duplex_changed(slave);
Signature · 1 line
2.53.0
author maintainer
#279 lore raw

PATCH 278/990 ip6mr: Serialize multicast router socket ownership

In reply to Greg Kroah-Hartman

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

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

From: Kyle Zeng <[email protected]>

[ Upstream commit c6b41de4dd9f2d6856d8d8d292348f7961034152 ]

MRT6_TABLE checks whether the socket owns its current table before acquiring RTNL. MRT6_INIT also looks up its table before taking RTNL. Consequently, concurrent TABLE and INIT calls can initialize the old table and then change the socket's selected table. Another INIT can register the same socket in the new table.

rawv6_close() calls ip6mr_sk_done(), which clears only the first table owned by the socket. After the socket's RCU-delayed free, the other table retains a dangling mroute_sk pointer. A subsequent multicast cache report passes that pointer to sock_queue_rcv_skb_reason(). This produces a KASAN slab-use-after-free in sk_filter_trim_cap().

Look up the selected table in ip6mr_sk_init() after acquiring RTNL. Likewise, re-read the current table and check its owner under RTNL in MRT6_TABLE before updating the selection. This preserves the single-table ownership invariant shared with ip6mr_sk_done(), without changing the locking of the other multicast socket options.

---
 net/ipv6/ip6mr.c | 36 +++++++++++++++++++++++++-----------
 1 file changed, 25 insertions(+), 11 deletions(-)
net/ipv6/ip6mr.c +25 -11
index f61035619cac7..53837248498a6 100644
@@ -1580,12 +1580,20 @@ static void mroute_clean_tables(struct mr_table *mrt, int flags)
 	}
 }
 
-static int ip6mr_sk_init(struct mr_table *mrt, struct sock *sk)
+static int ip6mr_sk_init(struct sock *sk)
 {
-	int err = 0;
 	struct net *net = sock_net(sk);
+	struct mr_table *mrt;
+	int err = 0;
 
 	rtnl_lock();
+	mrt = __ip6mr_get_table(net,
+				raw6_sk(sk)->ip6mr_table ? : RT6_TABLE_DFLT);
+	if (!mrt) {
+		err = -ENOENT;
+		goto out_unlock;
+	}
+
 	spin_lock(&mrt_lock);
 	if (rtnl_dereference(mrt->mroute_sk)) {
 		err = -EADDRINUSE;
@@ -1601,6 +1609,7 @@ static int ip6mr_sk_init(struct mr_table *mrt, struct sock *sk)
 					     NETCONFA_MC_FORWARDING,
 					     NETCONFA_IFINDEX_ALL,
 					     net->ipv6.devconf_all);
+out_unlock:
 	rtnl_unlock();
 
 	return err;
@@ -1699,7 +1708,7 @@ int ip6_mroute_setsockopt(struct sock *sk, int optname, sockptr_t optval,
 		if (optlen < sizeof(int))
 			return -EINVAL;
 
-		return ip6mr_sk_init(mrt, sk);
+		return ip6mr_sk_init(sk);
 
 	case MRT6_DONE:
 		return ip6mr_sk_done(sk);
@@ -1820,16 +1829,21 @@ int ip6_mroute_setsockopt(struct sock *sk, int optname, sockptr_t optval,
 		/* "pim6reg%u" should not exceed 16 bytes (IFNAMSIZ) */
 		if (v != RT_TABLE_DEFAULT && v >= 100000000)
 			return -EINVAL;
-		if (sk == rcu_access_pointer(mrt->mroute_sk))
-			return -EBUSY;
-
 		rtnl_lock();
 		ret = 0;
-		mrt = ip6mr_new_table(net, v);
-		if (IS_ERR(mrt))
-			ret = PTR_ERR(mrt);
-		else
-			raw6_sk(sk)->ip6mr_table = v;
+		mrt = __ip6mr_get_table(net,
+					raw6_sk(sk)->ip6mr_table ? : RT6_TABLE_DFLT);
+		if (!mrt) {
+			ret = -ENOENT;
+		} else if (sk == rtnl_dereference(mrt->mroute_sk)) {
+			ret = -EBUSY;
+		} else {
+			mrt = ip6mr_new_table(net, v);
+			if (IS_ERR(mrt))
+				ret = PTR_ERR(mrt);
+			else
+				raw6_sk(sk)->ip6mr_table = v;
+		}
 		rtnl_unlock();
 		return ret;
 	}
Signature · 1 line
2.53.0
author maintainer
#280 lore raw

PATCH 279/990 net: ethtool: add netif_get_link_ksettings() for correct ops-locked use

In reply to Greg Kroah-Hartman

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

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

From: Jakub Kicinski <[email protected]>

[ Upstream commit f32fe1d79a18592b96342a0016cd62cf9601a054 ]

__ethtool_get_link_ksettings() is exported and called from sysfs and many drivers. It invokes ethtool_ops->get_link_ksettings so by our own docs it should be holding netdev lock for ops locked devices. Looks like commit 2bcf4772e45a ("net: ethtool:
try to protect all callback with netdev instance lock") missed adding the ops lock here.

There's a number of callers we need to fix up so let's add the netif_get_link_ksettings() helper first, without any actual locking changes (this commit is a nop).

Not treating this as a fix because I don't think any driver cares at this point, but if we want to remove the rtnl_lock protection this will become critical.

Stable-dep-of: a76ab5e733b4 ("bonding: fix missing down path on speed/duplex failure after FAIL->UP")

---
 include/linux/ethtool.h |  2 ++
 net/ethtool/ioctl.c     | 17 ++++++++++++++---
 net/ethtool/linkinfo.c  |  4 ++--
 net/ethtool/linkmodes.c |  4 ++--
 4 files changed, 20 insertions(+), 7 deletions(-)
include/linux/ethtool.h +2 -0
index 5c9162193d269..8c850fb53530b 100644
@@ -285,6 +285,8 @@ struct ethtool_link_ksettings {
 extern int
 __ethtool_get_link_ksettings(struct net_device *dev,
 			     struct ethtool_link_ksettings *link_ksettings);
+int netif_get_link_ksettings(struct net_device *dev,
+			     struct ethtool_link_ksettings *link_ksettings);
 
 struct ethtool_keee {
 	__ETHTOOL_DECLARE_LINK_MODE_MASK(supported);
net/ethtool/ioctl.c +14 -3
index 9431e305b2333..cb5d910844589 100644
@@ -435,10 +435,10 @@ struct ethtool_link_usettings {
 };
 
 /* Internal kernel helper to query a device ethtool_link_settings. */
-int __ethtool_get_link_ksettings(struct net_device *dev,
-				 struct ethtool_link_ksettings *link_ksettings)
+int netif_get_link_ksettings(struct net_device *dev,
+			     struct ethtool_link_ksettings *link_ksettings)
 {
-	ASSERT_RTNL();
+	/* once callers fixed - assert ops locked */
 
 	if (!dev->ethtool_ops->get_link_ksettings)
 		return -EOPNOTSUPP;
@@ -449,6 +449,17 @@ int __ethtool_get_link_ksettings(struct net_device *dev,
 	memset(link_ksettings, 0, sizeof(*link_ksettings));
 	return dev->ethtool_ops->get_link_ksettings(dev, link_ksettings);
 }
+EXPORT_SYMBOL(netif_get_link_ksettings);
+
+/* Convenience helper for callers that hold only rtnl_lock(). */
+int __ethtool_get_link_ksettings(struct net_device *dev,
+				 struct ethtool_link_ksettings *link_ksettings)
+{
+	ASSERT_RTNL();
+
+	/* once callers fixed - take the ops lock around this call */
+	return netif_get_link_ksettings(dev, link_ksettings);
+}
 EXPORT_SYMBOL(__ethtool_get_link_ksettings);
 
 /* convert ethtool_link_usettings in user space to a kernel internal
net/ethtool/linkinfo.c +2 -2
index 30b8ce2751594..2d729acdaf031 100644
@@ -34,7 +34,7 @@ static int linkinfo_prepare_data(const struct ethnl_req_info *req_base,
 	ret = ethnl_ops_begin(dev);
 	if (ret < 0)
 		return ret;
-	ret = __ethtool_get_link_ksettings(dev, &data->ksettings);
+	ret = netif_get_link_ksettings(dev, &data->ksettings);
 	if (ret < 0)
 		GENL_SET_ERR_MSG(info, "failed to retrieve link settings");
 	ethnl_ops_complete(dev);
@@ -104,7 +104,7 @@ ethnl_set_linkinfo(struct ethnl_req_info *req_info, struct genl_info *info)
 	bool mod = false;
 	int ret;
 
-	ret = __ethtool_get_link_ksettings(dev, &ksettings);
+	ret = netif_get_link_ksettings(dev, &ksettings);
 	if (ret < 0) {
 		GENL_SET_ERR_MSG(info, "failed to retrieve link settings");
 		return ret;
net/ethtool/linkmodes.c +2 -2
index 259cd9ef1f2a1..4ce4f29d2a7a0 100644
@@ -39,7 +39,7 @@ static int linkmodes_prepare_data(const struct ethnl_req_info *req_base,
 	if (ret < 0)
 		return ret;
 
-	ret = __ethtool_get_link_ksettings(dev, &data->ksettings);
+	ret = netif_get_link_ksettings(dev, &data->ksettings);
 	if (ret < 0) {
 		GENL_SET_ERR_MSG(info, "failed to retrieve link settings");
 		goto out;
@@ -324,7 +324,7 @@ ethnl_set_linkmodes(struct ethnl_req_info *req_info, struct genl_info *info)
 	bool mod = false;
 	int ret;
 
-	ret = __ethtool_get_link_ksettings(dev, &ksettings);
+	ret = netif_get_link_ksettings(dev, &ksettings);
 	if (ret < 0) {
 		GENL_SET_ERR_MSG(info, "failed to retrieve link settings");
 		return ret;
Signature · 1 line
2.53.0
author maintainer
#281 lore raw

PATCH 280/990 net: bonding: dont recurse on the slaves netdev ops lock

In reply to Greg Kroah-Hartman

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

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

From: Jakub Kicinski <[email protected]>

[ Upstream commit 107b097790e903651385a96dd96f9be158702730 ]

bond_update_speed_duplex() calls __ethtool_get_link_ksettings() on the slave, which will soon take the slave's ops lock. One of its callers already holds it and the other three don't, so the function would either deadlock or run unprotected depending on the path.

Make the helper expect the slave's ops lock held and switch to netif_get_link_ksettings(). Wrap the three call sites that don't already hold it:

* bond_enslave() (rtnl held; core drops the lower's ops lock

    around ->ndo_add_slave).

* bond_miimon_commit() (rtnl_trylock'd from the mii workqueue).
* bond_ethtool_get_link_ksettings() (rtnl held via ethtool layer, bond device itself is not ops locked).

The call site which does already hold the ops lock is bond_slave_netdev_event() via NETDEV_UP / NETDEV_CHANGE notifiers, so it stays as-is.

Stable-dep-of: a76ab5e733b4 ("bonding: fix missing down path on speed/duplex failure after FAIL->UP")

---
 drivers/net/bonding/bond_main.c | 21 ++++++++++++++++-----
 1 file changed, 16 insertions(+), 5 deletions(-)
drivers/net/bonding/bond_main.c +16 -5
index 7066059ff3e28..4e6a4350a6590 100644
@@ -789,6 +789,10 @@ int bond_set_carrier(struct bonding *bond)
  * values are invalid, set speed and duplex to -1,
  * and return. Return 1 if speed or duplex settings are
  * UNKNOWN; 0 otherwise.
+ *
+ * Caller must hold the slave's netdev ops lock. The notifier path
+ * (bond_netdev_event NETDEV_CHANGE/UP) reaches us with the slave's ops
+ * lock held; other call sites take it explicitly.
  */
 static int bond_update_speed_duplex(struct slave *slave)
 {
@@ -796,7 +800,7 @@ static int bond_update_speed_duplex(struct slave *slave)
 	struct ethtool_link_ksettings ecmd;
 	int res;
 
-	res = __ethtool_get_link_ksettings(slave_dev, &ecmd);
+	res = netif_get_link_ksettings(slave_dev, &ecmd);
 	if (res < 0)
 		goto speed_duplex_unknown;
 	if (ecmd.base.speed == 0 || ecmd.base.speed == ((__u32)-1))
@@ -2114,8 +2118,10 @@ int bond_enslave(struct net_device *bond_dev, struct net_device *slave_dev,
 	new_slave->delay = 0;
 	new_slave->link_failure_count = 0;
 
-	if (bond_update_speed_duplex(new_slave) &&
-	    bond_needs_speed_duplex(bond))
+	netdev_lock_ops(slave_dev);
+	res = bond_update_speed_duplex(new_slave);
+	netdev_unlock_ops(slave_dev);
+	if (res && bond_needs_speed_duplex(bond))
 		new_slave->link = BOND_LINK_DOWN;
 
 	new_slave->last_rx = jiffies -
@@ -2780,6 +2786,7 @@ static void bond_miimon_commit(struct bonding *bond)
 	struct slave *slave, *primary, *active;
 	bool do_failover = false;
 	struct list_head *iter;
+	int err;
 
 	ASSERT_RTNL();
 
@@ -2798,8 +2805,10 @@ static void bond_miimon_commit(struct bonding *bond)
 			continue;
 
 		case BOND_LINK_UP:
-			if (bond_update_speed_duplex(slave) &&
-			    bond_needs_speed_duplex(bond)) {
+			netdev_lock_ops(slave->dev);
+			err = bond_update_speed_duplex(slave);
+			netdev_unlock_ops(slave->dev);
+			if (err && bond_needs_speed_duplex(bond)) {
 				slave->link = BOND_LINK_DOWN;
 				if (net_ratelimit())
 					slave_warn(bond->dev, slave->dev,
@@ -5857,7 +5866,9 @@ static int bond_ethtool_get_link_ksettings(struct net_device *bond_dev,
 	 */
 	bond_for_each_slave(bond, slave, iter) {
 		if (bond_slave_can_tx(slave)) {
+			netdev_lock_ops(slave->dev);
 			bond_update_speed_duplex(slave);
+			netdev_unlock_ops(slave->dev);
 			if (slave->speed != SPEED_UNKNOWN) {
 				if (BOND_MODE(bond) == BOND_MODE_BROADCAST)
 					speed = bond_mode_bcast_speed(slave,
Signature · 1 line
2.53.0
author maintainer
#282 lore raw

PATCH 281/990 bonding: fix missing down path on speed/duplex failure after FAIL->UP

In reply to Greg Kroah-Hartman

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

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

From: Timur Stukan <[email protected]>

[ Upstream commit a76ab5e733b41dede6f238a691eefb4374f99f79 ]

In bond_miimon_commit(), when a slave is proposed as BOND_LINK_UP but bond_update_speed_duplex() fails in bonding mode that needs speed/duplex (802.3ad, tlb, alb), the slave is set to BOND_LINK_DOWN directly. This bypasses bond_set_slave_link_state(), bond_miimon_link_change() and failover.

This is fine for slave that coming from BOND_LINK_BACK, which was never brought up and is not in use. But since commit 1899bb325149 ("bonding:
fix state transition issue in link monitoring") the commit phase also handles BOND_LINK_FAIL -> BOND_LINK_UP which means a slave that is still in use and may be curr_active_slave.

If the link recovers within downdelay and goes down again before the commit phase reads speed/duplex, the slave is silently marked down while remaining the active slave in worst cases. In alb/tlb the bond MAC stays on the dead port, no failover happens and TLB/RLB state is not cleaned, so the bond stops passing traffic until that link comes back even though other slaves are up. A non-active slave is affected too, in alb, RLB clients assigned to it are not reassigned and become unreachable.

Reproduced in tlb and alb mode with miimon=100 and downdelay=10000 by flapping a slave within downdelay and dropping it again before commit (a longer delay was added between inspect and commit to make window wider and easier to test):
bond0: (slave enp0s3): link status down for interface, disabling it in 10000 ms
bond0: (slave enp0s3): link status up again after 3400 ms
bond0: (slave enp0s3): failed to get link speed/duplex

procfs then shows the active slave with "MII Status: down" and "Link Failure Count: 0", and all traffic is lost.

Fix this by dropping the loop in bond_mii_monitor() that applied all proposed link states before bond_miimon_commit(). bond_miimon_commit() now applies each state itself: UP after the speed/duplex check, as it already did, DOWN in the down path, and FAIL/BACK directly. So when the speed/duplex check runs, slave->link still holds the previous state. If the check fails for a slave that is FAIL or UP, take it through the regular down path, including failover. DOWN and BACK slaves were never brought up and are still just reverted to DOWN. The down path is moved into bond_miimon_slave_down() so both callers share it.

After the fix:
bond0: (slave enp0s3): failed to get link speed/duplex
bond0: (slave enp0s3): link status definitely down, disabling slave
bond0: (slave enp0s4): making interface the new active one

Fixes 1899bb325149 ("bonding: fix state transition issue in link monitoring")
---
 drivers/net/bonding/bond_main.c | 63 +++++++++++++++++++--------------
 1 file changed, 37 insertions(+), 26 deletions(-)
drivers/net/bonding/bond_main.c +37 -26
index 4e6a4350a6590..ca2ea493c81a3 100644
@@ -2781,6 +2781,27 @@ static void bond_miimon_link_change(struct bonding *bond,
 	}
 }
 
+static bool bond_miimon_slave_down(struct bonding *bond,
+				   struct slave *slave)
+{
+	if (slave->link_failure_count < UINT_MAX)
+		slave->link_failure_count++;
+
+	bond_set_slave_link_state(slave, BOND_LINK_DOWN,
+				  BOND_SLAVE_NOTIFY_NOW);
+
+	if (BOND_MODE(bond) == BOND_MODE_ACTIVEBACKUP ||
+	    BOND_MODE(bond) == BOND_MODE_8023AD)
+		bond_set_slave_inactive_flags(slave,
+					      BOND_SLAVE_NOTIFY_NOW);
+
+	slave_info(bond->dev, slave->dev, "link status definitely down, disabling slave\n");
+
+	bond_miimon_link_change(bond, slave, BOND_LINK_DOWN);
+
+	return slave == rcu_access_pointer(bond->curr_active_slave);
+}
+
 static void bond_miimon_commit(struct bonding *bond)
 {
 	struct slave *slave, *primary, *active;
@@ -2809,10 +2830,22 @@ static void bond_miimon_commit(struct bonding *bond)
 			err = bond_update_speed_duplex(slave);
 			netdev_unlock_ops(slave->dev);
 			if (err && bond_needs_speed_duplex(bond)) {
-				slave->link = BOND_LINK_DOWN;
 				if (net_ratelimit())
 					slave_warn(bond->dev, slave->dev,
 						   "failed to get link speed/duplex\n");
+				/* Coming from FAIL/UP, the slave may still be
+				 * in use and may be curr_active_slave, so take
+				 * it through the full down path. Coming from
+				 * DOWN/BACK, it was never brought up, so just
+				 * revert it to DOWN.
+				 */
+				if (slave->link == BOND_LINK_FAIL ||
+				    slave->link == BOND_LINK_UP) {
+					if (bond_miimon_slave_down(bond, slave))
+						do_failover = true;
+					continue;
+				}
+				slave->link = BOND_LINK_DOWN;
 				continue;
 			}
 			bond_set_slave_link_state(slave, BOND_LINK_UP,
@@ -2841,28 +2874,13 @@ static void bond_miimon_commit(struct bonding *bond)
 			continue;
 
 		case BOND_LINK_DOWN:
-			if (slave->link_failure_count < UINT_MAX)
-				slave->link_failure_count++;
-
-			bond_set_slave_link_state(slave, BOND_LINK_DOWN,
-						  BOND_SLAVE_NOTIFY_NOW);
-
-			if (BOND_MODE(bond) == BOND_MODE_ACTIVEBACKUP ||
-			    BOND_MODE(bond) == BOND_MODE_8023AD)
-				bond_set_slave_inactive_flags(slave,
-							      BOND_SLAVE_NOTIFY_NOW);
-
-			slave_info(bond->dev, slave->dev, "link status definitely down, disabling slave\n");
-
-			bond_miimon_link_change(bond, slave, BOND_LINK_DOWN);
-
-			if (slave == rcu_access_pointer(bond->curr_active_slave))
+			if (bond_miimon_slave_down(bond, slave))
 				do_failover = true;
-
 			continue;
 
 		case BOND_LINK_FAIL:
 		case BOND_LINK_BACK:
+			bond_commit_link_state(slave, BOND_SLAVE_NOTIFY_LATER);
 			slave_dbg(bond->dev, slave->dev, "link_new_state %d on slave\n",
 				  slave->link_new_state);
 			continue;
@@ -2896,8 +2914,6 @@ static void bond_mii_monitor(struct work_struct *work)
 {
 	struct bonding *bond = container_of(work, struct bonding,
 					    mii_work.work);
-	struct list_head *iter;
-	struct slave *slave;
 	unsigned long delay;
 	bool commit;
 
@@ -2919,13 +2935,8 @@ static void bond_mii_monitor(struct work_struct *work)
 			goto re_arm;
 		}
 
-		if (commit) {
-			bond_for_each_slave(bond, slave, iter) {
-				bond_commit_link_state(slave,
-						       BOND_SLAVE_NOTIFY_LATER);
-			}
+		if (commit)
 			bond_miimon_commit(bond);
-		}
 
 		if (bond->send_peer_notif)
 			bond_peer_notify_may_events(bond, true);
Signature · 1 line
2.53.0
author maintainer
#283 lore raw

PATCH 282/990 net: stmmac: set XDP metadata length on the page_pool RX path

In reply to Greg Kroah-Hartman

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

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

From: Lorenzo Bianconi <[email protected]>

[ Upstream commit 6d9b7c85af57305ec2bd5907124478867edcc60b ]

stmmac_rx() initializes the XDP buffer with the metadata area valid, so an XDP program can reserve metadata with bpf_xdp_adjust_meta() and write it in [xdp->data_meta, xdp->data), for example to export the RX hardware timestamp obtained from the metadata kfunc. When such a frame is passed to the stack, the skb is built in place around the same page with napi_build_skb(), but skb_metadata_set() is never called.

napi_build_skb() clears skb_shared_info up to dataref, which includes meta_len, so skb_metadata_len() stays zero. The stack and TC BPF then see an empty metadata range even though the bytes are present in the skb headroom. The AF_XDP zero-copy path already records the length in stmmac_construct_skb_zc().

Record the metadata length after reserving the headroom and adding the frame data. No copy is needed because the skb is built over the buffer the XDP program wrote to. With the length recorded, the software VLAN stripping path can move the metadata together with the MAC header, as it already does for zero-copy frames.

---
 drivers/net/ethernet/stmicro/stmmac/stmmac_main.c | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)
drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +7 -3
index 2e7b146895ba8..0e78c1d2fcf1d 100644
@@ -5731,7 +5731,7 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue)
 		}
 
 		if (!skb) {
-			unsigned int head_pad_len;
+			unsigned int metasize;
 
 			/* XDP program may expand or reduce tail */
 			buf1_len = ctx.xdp.data_end - ctx.xdp.data;
@@ -5748,10 +5748,14 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue)
 			}
 
 			/* XDP program may adjust header */
-			head_pad_len = ctx.xdp.data - ctx.xdp.data_hard_start;
-			skb_reserve(skb, head_pad_len);
+			skb_reserve(skb,
+				    ctx.xdp.data - ctx.xdp.data_hard_start);
 			skb_put(skb, buf1_len);
 			skb_mark_for_recycle(skb);
+
+			metasize = ctx.xdp.data - ctx.xdp.data_meta;
+			if (metasize)
+				skb_metadata_set(skb, metasize);
 			buf->page = NULL;
 		} else if (buf1_len) {
 			dma_sync_single_for_cpu(priv->device, buf->addr,
Signature · 1 line
2.53.0
author maintainer
#284 lore raw

PATCH 283/990 net: bridge: disable MRP ports before the FDB flush in del_nbp()

In reply to Greg Kroah-Hartman

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

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

From: Cheng Yongkang <[email protected]>

[ Upstream commit 37dfd0efbfffc20a57e41c2eb349ac49b1ca1ff8 ]

del_nbp() flushes the port's FDB entries before it unregisters the RX handler. For a normal port, br_stp_disable_port() moves the port to BR_STATE_DISABLED before this cleanup.

That does not hold for an MRP ring port. br_set_state() ignores state changes while BR_MRP_AWARE_BIT is set, so br_stp_disable_port() leaves the port state alone. br_mrp_port_del() then restores forwarding when the bridge is up before clearing the bit. A frame received between br_fdb_cleanup_by_dst() and netdev_rx_handler_unregister() can therefore create a new FDB entry referencing the dying port. Nothing removes that entry before destroy_nbp_rcu() frees the port, so a later frame to the learned MAC can be forwarded through the freed port.

Remove the MRP and CFM instances before disabling the port, so that br_stp_disable_port() actually transitions it to BR_STATE_DISABLED. With CONFIG_BRIDGE_VLAN_FILTERING=y, synchronize_net() in nbp_vlan_group_unpublish() also drains receive paths that could still learn with the old state before the final FDB cleanup.

Found through an LLM-assisted source code analysis workflow and reproduced on net with KASAN and CONFIG_BRIDGE_VLAN_FILTERING=y in QEMU. A diagnostic switchdev module accepts MRP objects and delays the NETDEV_CHANGEUPPER callback for 1.5 s, holding del_nbp() after the FDB cleanup and before RX handler removal. The reproducer floods the MRP port with rotating source MACs, waits for the port's RCU callback through the module's rcu_barrier(), then sends frames to those MACs from another port. The unpatched kernel reports:

  BUG: KASAN: slab-use-after-free in br_forward+0xb1/0x820
  Call Trace:
   <IRQ>
   br_forward+0xb1/0x820
   br_handle_frame_finish+0x148b/0x1e50
   br_handle_frame+0x90a/0x15c0

With this patch, three runs of six cycles each reach the delay without a KASAN report.

---
 net/bridge/br_if.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
net/bridge/br_if.c +3 -3
index 5bcd1acc5da9b..63d9e28c0eda7 100644
@@ -339,13 +339,13 @@ static void del_nbp(struct net_bridge_port *p)
 
 	nbp_delete_promisc(p);
 
+	br_mrp_port_del(br, p);
+	br_cfm_port_del(br, p);
+
 	spin_lock_bh(&br->lock);
 	br_stp_disable_port(p);
 	spin_unlock_bh(&br->lock);
 
-	br_mrp_port_del(br, p);
-	br_cfm_port_del(br, p);
-
 	br_ifinfo_notify(RTM_DELLINK, NULL, p);
 
 	list_del_rcu(&p->list);
Signature · 1 line
2.53.0
author maintainer
#285 lore raw

PATCH 284/990 tcp: initialize send sequence numbers before deferring TFO

In reply to Greg Kroah-Hartman

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

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

From: Qingfang Deng <[email protected]>

[ Upstream commit 57889a8f6d49fc153aa0017d13086ab736567f8a ]

TCP_FASTOPEN_CONNECT can return from connect() before tcp_connect_init() when a cached cookie or cookieless Fast Open allows deferring the SYN. At this point write_seq contains the initial sequence number, while snd_una and snd_nxt have not been initialized to that sequence number.

Consequently, inet_diag and /proc/net/tcp{,6} report the initial sequence number as the send queue length despite no SYN or payload being queued.

Initialize snd_una and snd_nxt to write_seq before marking the connection as deferred. Both sequence-based queue lengths then remain zero until the first write starts the connection and runs tcp_connect_init().

---
 net/ipv4/tcp_fastopen.c | 2 ++
 1 file changed, 2 insertions(+)
net/ipv4/tcp_fastopen.c +2 -0
index dbd97df1b442f..1b0f367f9dfc8 100644
@@ -456,6 +456,8 @@ bool tcp_fastopen_defer_connect(struct sock *sk, int *err)
 
 	if (tp->fastopen_connect && !tp->fastopen_req) {
 		if (tcp_fastopen_cookie_check(sk, &mss, &cookie)) {
+			WRITE_ONCE(tp->snd_una, tp->write_seq);
+			WRITE_ONCE(tp->snd_nxt, tp->write_seq);
 			inet_set_bit(DEFER_CONNECT, sk);
 			return true;
 		}
Signature · 1 line
2.53.0
author maintainer
#286 lore raw

PATCH 285/990 netfilter: nft_set_rbtree: check catchall_sync return before queue_done

In reply to Greg Kroah-Hartman

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

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

From: Xingyuan Mo <[email protected]>

[ Upstream commit 1cec19d70bc282a8e7f7c42697d44046f60dc506 ]

nft_rbtree_gc_queue() passes the result of nft_trans_gc_catchall_sync() straight to nft_trans_gc_queue_sync_done(). When the catchall path flushes a full GC batch and nft_trans_gc_alloc() fails, catchall_sync returns NULL and queue_sync_done dereferences trans->net (NULL+0x10). Guard the call like the pipapo GC path already does.

Fixes 7d259f021aaa ("netfilter: nft_set_rbtree: prefer sync gc to async worker")
Assisted-by opencode:deepseek-v4
---
 net/netfilter/nft_set_rbtree.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
net/netfilter/nft_set_rbtree.c +2 -1
index 1270b472e3334..c00ac231ccda0 100644
@@ -958,7 +958,8 @@ static void nft_rbtree_gc_queue(struct nft_set *set)
 	}
 
 	gc = nft_trans_gc_catchall_sync(gc);
-	nft_trans_gc_queue_sync_done(gc);
+	if (gc)
+		nft_trans_gc_queue_sync_done(gc);
 }
 
 static u64 nft_rbtree_privsize(const struct nlattr * const nla[],
Signature · 1 line
2.53.0
author maintainer
#287 lore raw

PATCH 286/990 netfilter: bridge: use DEBUG_NET_WARN_ON_ONCE in nf_ct_bridge_refrag()

In reply to Greg Kroah-Hartman

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

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

From: Laveesh Bansal <[email protected]>

[ Upstream commit 683ff28ab18accb25268741a724645eee839d41a ]

nf_ct_bridge_refrag() warns when skb->protocol is neither IPv4 nor IPv6. A vlan filtering bridge can get there with a vlan ethertype: if the protocol of the tag of a frame differs from the vlan_protocol of the bridge, br_allowed_ingress() moves the tag back into the packet after NF_BR_PRE_ROUTING, where bridge conntrack has already defragmented it.

Anyone who can send fragments into a port of such a bridge can trigger the warning, which takes the machine down with panic_on_warn. The packet is dropped either way, so only warn on kernels built with CONFIG_DEBUG_NET.

This only avoids the warning. Such fragmented packets are still dropped. syzbot reported the warning. It keeps triggering on CONFIG_DEBUG_NET kernels until the vlan tag is handled, which is left for a follow-up:

https://syzkaller.appspot.com/bug?extid=a8ba738fe2db6b4bb27f

Fixes 3c171f496ef5 ("netfilter: bridge: add connection tracking system")
Assisted-by LLM
---
 net/bridge/netfilter/nf_conntrack_bridge.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/bridge/netfilter/nf_conntrack_bridge.c +1 -1
index b17962672ebfc..e7603a144538c 100644
@@ -359,7 +359,7 @@ nf_ct_bridge_refrag(struct sk_buff *skb, const struct nf_hook_state *state,
 		nf_br_ip6_fragment(state->net, state->sk, skb, &data, output);
 		break;
 	default:
-		WARN_ON_ONCE(1);
+		DEBUG_NET_WARN_ON_ONCE(1);
 		return NF_DROP;
 	}
 
Signature · 1 line
2.53.0
author maintainer
#288 lore raw

PATCH 287/990 netfilter: x_tables: check target name before accessing verdict

In reply to Greg Kroah-Hartman

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

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

From: Fernando Fernandez Mancera <[email protected]>

[ Upstream commit 364b200285bb2cc518e3c5efe6591951c05b8e01 ]

Non-standard targets may contain only struct xt_entry_target. mark_source_chains() nevertheless reads the target as an xt_standard_target before checking its name, potentially reading four bytes beyond a header-only target.

Check that the target is standard before reading its verdict. Non-standard targets remain handled as fallthrough rules.

See the following KASAN trace:

BUG: KASAN: slab-out-of-bounds in translate_table+0x1660/0x1a40 [ip6_tables]
Read of size 4 at addr ffff88800ed56ff8 by task rep/432

Call Trace:
 kasan_report+0xfa/0x120
 translate_table+0x1660/0x1a40 [ip6_tables]
 do_ip6t_set_ctl+0x667/0xa76 [ip6_tables]
 nf_setsockopt+0x77/0xd0
 do_sock_setsockopt+0x118/0x490
 __sys_setsockopt+0xe4/0x160
 __x64_sys_setsockopt+0xbd/0x190
 do_syscall_64+0xde/0x4f0
 entry_SYSCALL_64_after_hwframe+0x77/0x7f

Allocated by task 432:
 kasan_save_stack+0x2f/0x50
 __kasan_kmalloc+0x7f/0x90
 __kvmalloc_node_noprof+0x1b1/0x5c0
 xt_alloc_table_info+0x3c/0xa0
 do_ip6t_set_ctl+0x5ee/0xa76 [ip6_tables]
 nf_setsockopt+0x77/0xd0
 do_sock_setsockopt+0x118/0x490
 __sys_setsockopt+0xe4/0x160
 __x64_sys_setsockopt+0xbd/0x190
 do_syscall_64+0xde/0x4f0
 entry_SYSCALL_64_after_hwframe+0x77/0x7f
---
 net/ipv4/netfilter/arp_tables.c | 5 +++--
 net/ipv4/netfilter/ip_tables.c  | 5 +++--
 net/ipv6/netfilter/ip6_tables.c | 5 +++--
 3 files changed, 9 insertions(+), 6 deletions(-)
net/ipv4/netfilter/arp_tables.c +3 -2
index 0ea513bf77fb6..197d1dfa07d61 100644
@@ -372,11 +372,12 @@ static int mark_source_chains(const struct xt_table_info *newinfo,
 				e->counters.pcnt = pos;
 				pos += size;
 			} else {
-				int newpos = t->verdict;
+				int newpos;
 
 				if (strcmp(t->target.u.user.name,
 					   XT_STANDARD_TARGET) == 0 &&
-				    newpos >= 0) {
+				    t->verdict >= 0) {
+					newpos = t->verdict;
 					/* This a jump; chase it. */
 					if (!xt_find_jump_offset(offsets, newpos,
 								 newinfo->number))
net/ipv4/netfilter/ip_tables.c +3 -2
index ca8ff0ae6cdb9..b7749048e1461 100644
@@ -422,11 +422,12 @@ mark_source_chains(const struct xt_table_info *newinfo,
 				e->counters.pcnt = pos;
 				pos += size;
 			} else {
-				int newpos = t->verdict;
+				int newpos;
 
 				if (strcmp(t->target.u.user.name,
 					   XT_STANDARD_TARGET) == 0 &&
-				    newpos >= 0) {
+				    t->verdict >= 0) {
+					newpos = t->verdict;
 					/* This a jump; chase it. */
 					if (!xt_find_jump_offset(offsets, newpos,
 								 newinfo->number))
net/ipv6/netfilter/ip6_tables.c +3 -2
index 22db263682bda..9353e9105f4ac 100644
@@ -440,11 +440,12 @@ mark_source_chains(const struct xt_table_info *newinfo,
 				e->counters.pcnt = pos;
 				pos += size;
 			} else {
-				int newpos = t->verdict;
+				int newpos;
 
 				if (strcmp(t->target.u.user.name,
 					   XT_STANDARD_TARGET) == 0 &&
-				    newpos >= 0) {
+				    t->verdict >= 0) {
+					newpos = t->verdict;
 					/* This a jump; chase it. */
 					if (!xt_find_jump_offset(offsets, newpos,
 								 newinfo->number))
Signature · 1 line
2.53.0
author maintainer
#289 lore raw

PATCH 288/990 netfilter: nf_conntrack_sip: fix OOB read in ct_sip_parse_transport()

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit 7af52bda65c0bbbf40894aa3df36ac1bb5697984 ]

ct_sip_parse_transport() compares the value of the "transport=" header parameter against "TCP"/"UDP" with strncasecmp(..., 3), but it never checks that the parsed value is at least 3 bytes long.

ct_sip_parse_param() returns matchlen = end - start, where end is the next ';' or, when there is no ';', the end of the payload buffer (limit = dptr + datalen). If the "transport=" value is only 1 or 2 bytes long and runs exactly to the end of the payload (e.g. a REGISTER request whose Contact header ends in ";transport=T" with no trailing CRLF), matchlen is less than 3 while strncasecmp() still reads up to 3 bytes, reading 1-2 bytes past the end of the linearized skb data.

Add a matchlen check before the comparison, mirroring the sdp_media_type() pattern a few lines below, so short values cannot reach strncasecmp().

The bug was found by LLM-assisted manual review of the SIP helper's parsers and confirmed with a userspace ASan harness built from the verbatim parser functions, which reports a heap-buffer-overflow read of size 2 in strncasecmp() called from ct_sip_parse_transport().

Fixes ea45f12a2766d ("[NETFILTER]: nf_conntrack_sip: parse SIP headers properly")
Assisted-by Claude:claude-opus-5-5
---
 net/netfilter/nf_conntrack_sip.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
net/netfilter/nf_conntrack_sip.c +2 -2
index 449a6e53feae4..12b8c7fcca640 100644
@@ -707,9 +707,9 @@ static int ct_sip_parse_transport(struct nf_conn *ct, const char *dptr,
 
 	if (ct_sip_parse_param(ct, dptr, dataoff, datalen, "transport=",
 			       &matchoff, &matchlen)) {
-		if (!strncasecmp(dptr + matchoff, "TCP", strlen("TCP")))
+		if (matchlen >= 3 && !strncasecmp(dptr + matchoff, "TCP", 3))
 			*proto = IPPROTO_TCP;
-		else if (!strncasecmp(dptr + matchoff, "UDP", strlen("UDP")))
+		else if (matchlen >= 3 && !strncasecmp(dptr + matchoff, "UDP", 3))
 			*proto = IPPROTO_UDP;
 		else
 			return 0;
Signature · 1 line
2.53.0
author maintainer
#290 lore raw

PATCH 289/990 netfilter: nf_tables: fix memleak when rule deletion fails with hardware offload

In reply to Greg Kroah-Hartman

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

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

From: Pablo Neira Ayuso <[email protected]>

[ Upstream commit e95b3be75ae0652d40a48a210f0cf5197b3b3783 ]

Allocate flow rule object after transaction has been allocation and rule deactivation has been performed, otherwise memleak is possible. Let the transaction unwind the existing rule deactivation from the abort path, this needs to update nft_flow_rule_destroy() to skip release if flow_rule is null.

While at this, remove check for non-null flow_rule in newrule error path now that nft_flow_rule_destroy() is skipped if flow_rule is null.

Fixes 63b48c73ff56 ("netfilter: nf_tables_offload: undo updates if transaction fails")
---
 net/netfilter/nf_tables_api.c     | 21 +++++++++------------
 net/netfilter/nf_tables_offload.c |  3 +++
 2 files changed, 12 insertions(+), 12 deletions(-)
net/netfilter/nf_tables_api.c +9 -12
index 76876761698eb..a248dc75c5a0a 100644
@@ -754,16 +754,6 @@ static int nft_delrule(struct nft_ctx *ctx, struct nft_rule *rule)
 	if (trans == NULL)
 		return -ENOMEM;
 
-	if (ctx->chain->flags & NFT_CHAIN_HW_OFFLOAD) {
-		flow = nft_flow_rule_create(ctx->net, rule);
-		if (IS_ERR(flow)) {
-			nft_trans_destroy(trans);
-			return PTR_ERR(flow);
-		}
-
-		nft_trans_flow_rule(trans) = flow;
-	}
-
 	err = nf_tables_delrule_deactivate(ctx, rule);
 	if (err < 0) {
 		nft_trans_destroy(trans);
@@ -771,6 +761,14 @@ static int nft_delrule(struct nft_ctx *ctx, struct nft_rule *rule)
 	}
 	nft_rule_expr_deactivate(ctx, rule, NFT_TRANS_PREPARE);
 
+	if (ctx->chain->flags & NFT_CHAIN_HW_OFFLOAD) {
+		flow = nft_flow_rule_create(ctx->net, rule);
+		if (IS_ERR(flow))
+			return PTR_ERR(flow);
+
+		nft_trans_flow_rule(trans) = flow;
+	}
+
 	return 0;
 }
 
@@ -4527,8 +4525,7 @@ static int nf_tables_newrule(struct sk_buff *skb, const struct nfnl_info *info,
 err_destroy_flow_rule:
 	nft_use_dec_restore(&chain->use);
 err_destroy_flow:
-	if (flow)
-		nft_flow_rule_destroy(flow);
+	nft_flow_rule_destroy(flow);
 err_release_rule:
 	nft_rule_expr_deactivate(&ctx, rule, NFT_TRANS_PREPARE_ERROR);
 	nf_tables_rule_destroy(&ctx, rule);
net/netfilter/nf_tables_offload.c +3 -0
index 933a17d0f2513..853094a300c24 100644
@@ -148,6 +148,9 @@ void nft_flow_rule_destroy(struct nft_flow_rule *flow)
 	struct flow_action_entry *entry;
 	int i;
 
+	if (!flow)
+		return;
+
 	flow_action_for_each(i, entry, &flow->rule->action) {
 		switch (entry->id) {
 		case FLOW_ACTION_REDIRECT:
Signature · 1 line
2.53.0
author maintainer
#291 lore raw

PATCH 290/990 netfilter: nat: zero newrange before filling it in

In reply to Greg Kroah-Hartman

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

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

From: Florian Westphal <[email protected]>

[ Upstream commit d1bb235aa409a4e5aeba6c748d953d948625b1e9 ]

nf_nat_masquerade_ipv4(), nf_nat_masquerade_ipv6(), netmap_tg4() and netmap_tg6() each build a stack-local struct nf_nat_range2 from the caller-supplied range, inheriting range->flags unmodified. Two of them only memset() the min_addr/max_addr members, the other two don't memset() anything at all, so newrange.base_proto is left as stack garbage.

If the inherited flags include NF_NAT_RANGE_PROTO_OFFSET, nf_nat_l4proto_unique_tuple() reads range->base_proto.all to compute the NAT port offset. Neither the NETMAP nor the MASQUERADE targets mask the flags field in their checkentry callback, so this uninitialized stack value can end up feeding the NAT port selection.

The per-member memset()s are not enough: they have to enumerate every field that must be cleared, and base_proto was missed when NF_NAT_RANGE_PROTO_OFFSET/base_proto was added to the struct. memset() the whole struct instead, so every member is covered regardless of which ones get explicitly assigned afterwards.

There are other places that miss this, but those hardcode .flags so nat core won't read from the uninitialized fields.

C99 initializers would be preferrable, but this is a more intrusive change. Lets followup in nf-next and convert others as well.

This is an LLM finding.

Fixes 2eb0f624b709 ("netfilter: add NAT support for shifted portmap ranges")
---
 net/netfilter/nf_nat_masquerade.c | 4 ++--
 net/netfilter/xt_NETMAP.c         | 4 ++--
 2 files changed, 4 insertions(+), 4 deletions(-)
net/netfilter/nf_nat_masquerade.c +2 -2
index 1a506b0c6511a..2506aace39bcf 100644
@@ -62,8 +62,7 @@ nf_nat_masquerade_ipv4(struct sk_buff *skb, unsigned int hooknum,
 		nat->masq_index = out->ifindex;
 
 	/* Transfer from original range. */
-	memset(&newrange.min_addr, 0, sizeof(newrange.min_addr));
-	memset(&newrange.max_addr, 0, sizeof(newrange.max_addr));
+	memset(&newrange, 0, sizeof(newrange));
 	newrange.flags       = range->flags | NF_NAT_RANGE_MAP_IPS;
 	newrange.min_addr.ip = newsrc;
 	newrange.max_addr.ip = newsrc;
@@ -259,6 +258,7 @@ nf_nat_masquerade_ipv6(struct sk_buff *skb, const struct nf_nat_range2 *range,
 	if (nat)
 		nat->masq_index = out->ifindex;
 
+	memset(&newrange, 0, sizeof(newrange));
 	newrange.flags		= range->flags | NF_NAT_RANGE_MAP_IPS;
 	newrange.min_addr.in6	= src;
 	newrange.max_addr.in6	= src;
net/netfilter/xt_NETMAP.c +2 -2
index cb2ee80d84fa8..591a6af6c61fa 100644
@@ -42,6 +42,7 @@ netmap_tg6(struct sk_buff *skb, const struct xt_action_param *par)
 				   netmask.ip6[i];
 	}
 
+	memset(&newrange, 0, sizeof(newrange));
 	newrange.flags	= range->flags | NF_NAT_RANGE_MAP_IPS;
 	newrange.min_addr	= new_addr;
 	newrange.max_addr	= new_addr;
@@ -89,8 +90,7 @@ netmap_tg4(struct sk_buff *skb, const struct xt_action_param *par)
 		new_ip = ip_hdr(skb)->saddr & ~netmask;
 	new_ip |= mr->range[0].min_ip & netmask;
 
-	memset(&newrange.min_addr, 0, sizeof(newrange.min_addr));
-	memset(&newrange.max_addr, 0, sizeof(newrange.max_addr));
+	memset(&newrange, 0, sizeof(newrange));
 	newrange.flags	     = mr->range[0].flags | NF_NAT_RANGE_MAP_IPS;
 	newrange.min_addr.ip = new_ip;
 	newrange.max_addr.ip = new_ip;
Signature · 1 line
2.53.0
author maintainer
#292 lore raw

PATCH 291/990 gpio: regmap: Support sparsed fixed direction

In reply to Greg Kroah-Hartman

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

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

From: Linus Walleij <[email protected]>

[ Upstream commit 68d801eabda5219dcc25c9de98d3bbdb5b51b0a5 ]

On some regmapped GPIOs apparently only a sparser selection of the lines (not all) are actually fixed direction.

Support this situation by adding an optional bitmap indicating which GPIOs are actually fixed direction and which are not.

Stable-dep-of: 80415a6ff295 ("gpio: regmap: free the irqchip if adding the irq domain fails")

---
 drivers/gpio/gpio-regmap.c  | 37 +++++++++++++++++++++++++++++++++----
 include/linux/gpio/regmap.h |  7 +++++++
 2 files changed, 40 insertions(+), 4 deletions(-)
drivers/gpio/gpio-regmap.c +33 -4
index c64805dcb9f88..4f83027ab2032 100644
@@ -31,6 +31,7 @@ struct gpio_regmap {
 	unsigned int reg_clr_base;
 	unsigned int reg_dir_in_base;
 	unsigned int reg_dir_out_base;
+	unsigned long *fixed_direction_mask;
 	unsigned long *fixed_direction_output;
 
 #ifdef CONFIG_REGMAP_IRQ
@@ -128,6 +129,20 @@ static int gpio_regmap_set_with_clear(struct gpio_chip *chip,
 	return regmap_write(gpio->regmap, reg, mask);
 }
 
+static bool gpio_regmap_fixed_direction(struct gpio_regmap *gpio,
+					unsigned int offset)
+{
+	if (!gpio->fixed_direction_output)
+		return false;
+
+	/* In this case only some GPIOs are fixed as input/output */
+	if (gpio->fixed_direction_mask &&
+	    !test_bit(offset, gpio->fixed_direction_mask))
+		return false;
+
+	return true;
+}
+
 static int gpio_regmap_get_direction(struct gpio_chip *chip,
 				     unsigned int offset)
 {
@@ -135,7 +150,7 @@ static int gpio_regmap_get_direction(struct gpio_chip *chip,
 	unsigned int base, val, reg, mask;
 	int invert, ret;
 
-	if (gpio->fixed_direction_output) {
+	if (gpio_regmap_fixed_direction(gpio, offset)) {
 		if (test_bit(offset, gpio->fixed_direction_output))
 			return GPIO_LINE_DIRECTION_OUT;
 		else
@@ -292,12 +307,23 @@ struct gpio_regmap *gpio_regmap_register(const struct gpio_regmap_config *config
 			goto err_free_gpio;
 	}
 
+	if (config->fixed_direction_mask) {
+		gpio->fixed_direction_mask = bitmap_alloc(chip->ngpio,
+							    GFP_KERNEL);
+		if (!gpio->fixed_direction_mask) {
+			ret = -ENOMEM;
+			goto err_free_gpio;
+		}
+		bitmap_copy(gpio->fixed_direction_mask,
+			    config->fixed_direction_mask, chip->ngpio);
+	}
+
 	if (config->fixed_direction_output) {
 		gpio->fixed_direction_output = bitmap_alloc(chip->ngpio,
 							    GFP_KERNEL);
 		if (!gpio->fixed_direction_output) {
 			ret = -ENOMEM;
-			goto err_free_gpio;
+			goto err_free_bitmap_dirmask;
 		}
 		bitmap_copy(gpio->fixed_direction_output,
 			    config->fixed_direction_output, chip->ngpio);
@@ -319,7 +345,7 @@ struct gpio_regmap *gpio_regmap_register(const struct gpio_regmap_config *config
 
 	ret = gpiochip_add_data(chip, gpio);
 	if (ret < 0)
-		goto err_free_bitmap;
+		goto err_free_bitmap_output;
 
 #ifdef CONFIG_REGMAP_IRQ
 	if (config->regmap_irq_chip) {
@@ -345,8 +371,10 @@ struct gpio_regmap *gpio_regmap_register(const struct gpio_regmap_config *config
 
 err_remove_gpiochip:
 	gpiochip_remove(chip);
-err_free_bitmap:
+err_free_bitmap_output:
 	bitmap_free(gpio->fixed_direction_output);
+err_free_bitmap_dirmask:
+	bitmap_free(gpio->fixed_direction_mask);
 err_free_gpio:
 	kfree(gpio);
 	return ERR_PTR(ret);
@@ -366,6 +394,7 @@ void gpio_regmap_unregister(struct gpio_regmap *gpio)
 
 	gpiochip_remove(&gpio->gpio_chip);
 	bitmap_free(gpio->fixed_direction_output);
+	bitmap_free(gpio->fixed_direction_mask);
 	kfree(gpio);
 }
 EXPORT_SYMBOL_GPL(gpio_regmap_unregister);
include/linux/gpio/regmap.h +7 -0
index 87983a5f3681e..a23e1c2b933a1 100644
@@ -38,6 +38,12 @@ struct regmap;
  *			offset to a register/bitmask pair. If not
  *			given the default gpio_regmap_simple_xlate()
  *			is used.
+ * @fixed_direction_mask:
+ *			(Optional) Bitmap representing the GPIO lines that
+ *			make use of the @fixed_direction_output list to
+ *			enforce direction of the GPIO. If this is NULL
+ *			and @fixed_direction_output is defined, ALL GPIOs
+ *			are assumed to be fixed direction (out or in).
  * @fixed_direction_output:
  *			(Optional) Bitmap representing the fixed direction of
  *			the GPIO lines. Useful when there are GPIO lines with a
@@ -89,6 +95,7 @@ struct gpio_regmap_config {
 	int reg_stride;
 	int ngpio_per_reg;
 	struct irq_domain *irq_domain;
+	unsigned long *fixed_direction_mask;
 	unsigned long *fixed_direction_output;
 
 #ifdef CONFIG_REGMAP_IRQ
Signature · 1 line
2.53.0
author maintainer
#293 lore raw

PATCH 292/990 gpio: regmap: free the irqchip if adding the irq domain fails

In reply to Greg Kroah-Hartman

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

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

From: Long Zhao <[email protected]>

[ Upstream commit 80415a6ff295b03dab98ef55598c72be66945d82 ]

gpio_regmap_register() creates a regmap irqchip and then calls gpiochip_irqchip_add_domain(). If that call fails, the error path only removes the gpiochip, so the irqchip and its domain leak.

Free the irqchip there when this function allocated it. An external irq domain is not affected: irq_chip_data stays NULL and the caller owns that domain.

---
 drivers/gpio/gpio-regmap.c | 5 +++++
 1 file changed, 5 insertions(+)
drivers/gpio/gpio-regmap.c +5 -0
index 4f83027ab2032..066a5be7f8e93 100644
@@ -371,6 +371,11 @@ struct gpio_regmap *gpio_regmap_register(const struct gpio_regmap_config *config
 
 err_remove_gpiochip:
 	gpiochip_remove(chip);
+
+#ifdef CONFIG_REGMAP_IRQ
+	if (gpio->irq_chip_data)
+		regmap_del_irq_chip(gpio->regmap_irq_line, gpio->irq_chip_data);
+#endif
 err_free_bitmap_output:
 	bitmap_free(gpio->fixed_direction_output);
 err_free_bitmap_dirmask:
Signature · 1 line
2.53.0
author maintainer
#294 lore raw

PATCH 293/990 tcp: ipv6: free ireq->ipv6_opt after an RCU grace period

In reply to Greg Kroah-Hartman

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

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

From: Eric Dumazet <[email protected]>

[ Upstream commit fafbc4051123d5459ea6950899cec08ed946e278 ]

ireq->ipv6_opt is only set by calipso_req_setattr(), when a CALIPSO NetLabel mapping is configured.

Request socket migration (net.ipv4.tcp_migrate_req=1, or a BPF_SK_REUSEPORT_SELECT_OR_MIGRATE program) clones the request socket with inet_reqsk_clone(), so that the old request socket and its clone share the same ipv6_opt, then reqsk_migrate_reset() clears the pointer in the old one.

Another cpu holding a reference on the old request socket can still be using these options, sending a SYNACK from tcp_v6_send_synack() or creating a child in tcp_v6_syn_recv_sock(), when the clone is freed. tcp_v6_reqsk_destructor() frees ipv6_opt with a plain kfree(), leading to a use-after-free.

Both readers already run under RCU, like their IPv4 counterparts. Use kfree_rcu() in tcp_v6_reqsk_destructor(), as commit e3f33b0a1d89 ("ipv4: free inet_opt and ireq_opt after an RCU grace period") did for ireq_opt.

---
 net/ipv6/tcp_ipv6.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/ipv6/tcp_ipv6.c +1 -1
index fade3907b05da..b07e8d22edcfb 100644
@@ -583,7 +583,7 @@ static int tcp_v6_send_synack(const struct sock *sk, struct dst_entry *dst,
 
 static void tcp_v6_reqsk_destructor(struct request_sock *req)
 {
-	kfree(inet_rsk(req)->ipv6_opt);
+	kfree_rcu(inet_rsk(req)->ipv6_opt, rcu);
 	consume_skb(inet_rsk(req)->pktopts);
 }
 
Signature · 1 line
2.53.0
author maintainer
#295 lore raw

PATCH 294/990 MIPS: Avoid dead code/data elimination when using recordmcount

In reply to Greg Kroah-Hartman

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

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

From: Rosen Penev <[email protected]>

[ Upstream commit 255d9dbd936f7db8b963e82429f6e57cd9d48999 ]

CONFIG_LD_DEAD_CODE_DATA_ELIMINATION builds with -ffunction-sections, placing every function in its own section. recordmcount refuses to use weak symbols as section bases, as a strong definition could override them, so a weak function alone in its section, such as the generic pcibios_fixup_bus() stub, breaks the build:

Cannot find symbol for section 88: .text.pcibios_fixup_bus. drivers/pci/probe.o: failed

MIPS always records mcount locations with recordmcount, so this hits any config with the function tracer and dead code elimination enabled, e.g. malta_defconfig built with LLVM=1.

Only offer dead code elimination when recordmcount is not used, as powerpc does since commit f8b2336f15f3 ("powerpc: Avoid dead code/data elimination when using recordmcount"). In practice this makes it unavailable together with the function tracer on MIPS.

Fixes c0436b503591 ("MIPS: Enable dead code elimination")
---
 arch/mips/Kconfig | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/mips/Kconfig +1 -1
index fadaeafae98e8..cefaa55ff8bd8 100644
@@ -81,7 +81,7 @@ config MIPS
 	select HAVE_IRQ_TIME_ACCOUNTING
 	select HAVE_KPROBES
 	select HAVE_KRETPROBES
-	select HAVE_LD_DEAD_CODE_DATA_ELIMINATION
+	select HAVE_LD_DEAD_CODE_DATA_ELIMINATION if !FTRACE_MCOUNT_USE_RECORDMCOUNT
 	select HAVE_MOD_ARCH_SPECIFIC
 	select HAVE_NMI
 	select HAVE_PAGE_SIZE_4KB if !CPU_LOONGSON2EF && !CPU_LOONGSON64
Signature · 1 line
2.53.0
author maintainer
#296 lore raw

PATCH 295/990 MIPS: SGI-IP30: fix the defconfig defaults for the Bridge PROM and RTC

In reply to Greg Kroah-Hartman

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

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

From: Imre Kaloz <[email protected]>

[ Upstream commit c9c0d267002029a5bf97ee50e6b11b4d16808aca ]

The Bridge probe reads its part number from the 1-wire PROM and defers until the SGI 1-wire master and DS250x slave are present, so without them there is no PCI bus and no serial console.

The IP30 RTC is a DS1685-family part, but the defconfig, derived from ip27_defconfig, has the M48T35 driver, so there is no RTC.

Enable the 1-wire drivers and select the DS1685 family.

Also drop four lines that savedefconfig removes, as CRYPTO_CAMELLIA, CRYPTO_CTS and CRYPTO_HMAC are selected built-in and IPV6_SIT=m is the default.

Fixes bb2d63500b5c ("MIPS: config: Add ip30_defconfig")
---
 arch/mips/configs/ip30_defconfig | 9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)
arch/mips/configs/ip30_defconfig +4 -5
index 718f3060d9fa8..4f3fa1d49cd43 100644
@@ -40,7 +40,6 @@ CONFIG_INET6_AH=m
 CONFIG_INET6_ESP=m
 CONFIG_INET6_IPCOMP=m
 CONFIG_IPV6_MIP6=m
-CONFIG_IPV6_SIT=m
 CONFIG_IPV6_SIT_6RD=y
 CONFIG_IPV6_TUNNEL=m
 CONFIG_IPV6_MULTIPLE_TABLES=y
@@ -130,11 +129,14 @@ CONFIG_SERIAL_8250_IOC3=y
 CONFIG_NOZOMI=m
 CONFIG_HW_RANDOM_TIMERIOMEM=m
 # CONFIG_PTP_1588_CLOCK is not set
+CONFIG_W1=y
+CONFIG_W1_MASTER_SGI=y
+CONFIG_W1_SLAVE_DS250X=y
 # CONFIG_HWMON is not set
 CONFIG_THERMAL=y
 CONFIG_SGI_MFD_IOC3=y
 CONFIG_RTC_CLASS=y
-CONFIG_RTC_DRV_M48T35=y
+CONFIG_RTC_DRV_DS1685_FAMILY=y
 CONFIG_UIO=y
 CONFIG_UIO_AEC=m
 CONFIG_UIO_SERCOS3=m
@@ -163,17 +165,14 @@ CONFIG_NFS_FS=y
 CONFIG_SECURITYFS=y
 CONFIG_CRYPTO_CRYPTD=m
 CONFIG_CRYPTO_BLOWFISH=m
-CONFIG_CRYPTO_CAMELLIA=m
 CONFIG_CRYPTO_CAST5=m
 CONFIG_CRYPTO_CAST6=m
 CONFIG_CRYPTO_FCRYPT=m
 CONFIG_CRYPTO_SERPENT=m
 CONFIG_CRYPTO_TWOFISH=m
-CONFIG_CRYPTO_CTS=m
 CONFIG_CRYPTO_LRW=m
 CONFIG_CRYPTO_PCBC=m
 CONFIG_CRYPTO_XTS=m
-CONFIG_CRYPTO_HMAC=y
 CONFIG_CRYPTO_MD4=m
 CONFIG_CRYPTO_RMD160=m
 CONFIG_CRYPTO_WP512=m
Signature · 1 line
2.53.0
author maintainer
#297 lore raw

PATCH 296/990 MIPS: Alchemy: Save the Ethernet address before reusing PROM memory

In reply to Greg Kroah-Hartman

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

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

From: Florian Fainelli <[email protected]>

[ Upstream commit 792ac17faa0503448f3ef85b49f16456ac54ab84 ]

Alchemy keeps pointers into the firmware environment and looks up ethaddr when initializing the Ethernet devices. By that point, memory allocation can have overwritten the environment, causing prom_getenv() to pass an invalid pointer to strchr() and panic during boot.

On the MTX-1, the struct page layout change in 9ddb3c14afba reduces struct page from 40 to 32 bytes and exposes this unreserved firmware memory. Bisection and boot tests confirmed that the parent boots while the change reproduces the panic.

Parse the Ethernet address during prom_init(), before registering RAM with memblock, and keep the six bytes in kernel-owned init data. Return the saved address during device initialization, preserving the existing YAMON formats and command-line fallback without reserving a fixed low-memory region.

Fixes b93ddc4f9156 ("mips: Reserve memory for the kernel image resources")
---
 arch/mips/alchemy/common/prom.c | 23 ++++++++++++++++++++---
 1 file changed, 20 insertions(+), 3 deletions(-)
arch/mips/alchemy/common/prom.c +20 -3
index 20d30f6265cdc..c4aefeb788715 100644
@@ -46,6 +46,11 @@ int prom_argc;
 char **prom_argv;
 char **prom_envp;
 
+static char prom_ethaddr[6] __initdata;
+static bool prom_ethaddr_valid __initdata;
+
+static void __init prom_init_ethernet_addr(void);
+
 void __init prom_init_cmdline(void)
 {
 	int i;
@@ -95,6 +100,9 @@ void __init prom_init(void)
 	if (!memsize_str || kstrtoul(memsize_str, 0, &memsize))
 		memsize = SZ_64M; /* minimum memsize is 64MB RAM */
 
+	/* Save the MAC before the allocator can reuse the PROM environment. */
+	prom_init_ethernet_addr();
+
 	memblock_add(0, memsize);
 }
 
@@ -125,7 +133,7 @@ static inline void str2eaddr(unsigned char *ea, unsigned char *str)
 	}
 }
 
-int __init prom_get_ethernet_addr(char *ethernet_addr)
+static void __init prom_init_ethernet_addr(void)
 {
 	char *ethaddr_str;
 
@@ -135,12 +143,21 @@ int __init prom_get_ethernet_addr(char *ethernet_addr)
 		/* Check command line */
 		ethaddr_str = strstr(arcs_cmdline, "ethaddr=");
 		if (!ethaddr_str)
-			return -1;
+			return;
 
 		ethaddr_str += strlen("ethaddr=");
 	}
 
-	str2eaddr(ethernet_addr, ethaddr_str);
+	str2eaddr(prom_ethaddr, ethaddr_str);
+	prom_ethaddr_valid = true;
+}
+
+int __init prom_get_ethernet_addr(char *ethernet_addr)
+{
+	if (!prom_ethaddr_valid)
+		return -1;
+
+	memcpy(ethernet_addr, prom_ethaddr, sizeof(prom_ethaddr));
 
 	return 0;
 }
Signature · 1 line
2.53.0
author maintainer
#298 lore raw

PATCH 297/990 MIPS: Cobalt: Include legacy IDE ports in the PCI I/O window

In reply to Greg Kroah-Hartman

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

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

From: Florian Fainelli <[email protected]>

[ Upstream commit ff209a7294988aac52b2522b1d0d7349da4541ec ]

The Cobalt PCI I/O window starts at 0x1000, excluding the VIA IDE controller's fixed compatibility-mode ports at 0x170, 0x1f0, 0x376 and 0x3f6. Since pcibios_enable_device() was converted to pci_enable_resources(), these unclaimed resources cause pata_via to fail to probe with -EINVAL.

Start the PCI I/O window at zero to cover the southbridge legacy ports, retaining 0x1000 as the allocation minimum via PCIBIOS_MIN_IO. Register the PCI controller from plat_mem_setup(), before the VIA reservations and i8259 initialization, so the legacy resources do not conflict with the host bridge window and prevent PCI bus scanning.

Keep the VIA resource reservations in plat_mem_setup() after the PCI controller registration and use insert_resource() to nest them beneath the PCI window. The i8259 and RTC resources are also claimed beneath it.

Boot-tested on a Qube2 with a MIPS64 kernel. All seven PCI functions enumerate, both tulip devices bind, and pata_via initializes both ATA hosts and detects the ST380012A 80 GB disk. All 18 boot checks pass, including a read-only disk test and Ethernet ping.

Fixes ae81aad5c2e1 ("MIPS: PCI: Use pci_enable_resources()")
---
 arch/mips/cobalt/pci.c                     | 11 +++++------
 arch/mips/cobalt/setup.c                   |  4 +++-
 arch/mips/include/asm/mach-cobalt/cobalt.h |  1 +
 3 files changed, 9 insertions(+), 7 deletions(-)
arch/mips/cobalt/pci.c +5 -6
index 85ec9cc31d666..29fd052766b2a 100644
@@ -14,6 +14,8 @@
 
 #include <asm/gt64120.h>
 
+#include <cobalt.h>
+
 extern struct pci_ops gt64xxx_pci0_ops;
 
 static struct resource cobalt_mem_resource = {
@@ -24,7 +26,7 @@ static struct resource cobalt_mem_resource = {
 };
 
 static struct resource cobalt_io_resource = {
-	.start	= 0x1000,
+	.start	= 0,
 	.end	= 0xffffffUL,
 	.name	= "PCI I/O",
 	.flags	= IORESOURCE_IO,
@@ -38,11 +40,8 @@ static struct pci_controller cobalt_pci_controller = {
 	.io_map_base	= CKSEG1ADDR(GT_DEF_PCI0_IO_BASE),
 };
 
-static int __init cobalt_pci_init(void)
+void __init cobalt_pci_init(void)
 {
+	PCIBIOS_MIN_IO = 0x1000;
 	register_pci_controller(&cobalt_pci_controller);
-
-	return 0;
 }
-
-arch_initcall(cobalt_pci_init);
arch/mips/cobalt/setup.c +3 -1
index 9a266bf783399..502acc92969b8 100644
@@ -83,9 +83,11 @@ void __init plat_mem_setup(void)
 	/* I/O port resource */
 	ioport_resource.end = 0x01ffffff;
 
+	cobalt_pci_init();
+
 	/* These resources have been reserved by VIA SuperI/O chip. */
 	for (i = 0; i < ARRAY_SIZE(cobalt_reserved_resources); i++)
-		request_resource(&ioport_resource, cobalt_reserved_resources + i);
+		insert_resource(&ioport_resource, cobalt_reserved_resources + i);
 }
 
 /*
arch/mips/include/asm/mach-cobalt/cobalt.h +1 -0
index 97f9d5e9446d2..c7a8607cd651a 100644
@@ -19,6 +19,7 @@ extern int cobalt_board_id;
 #define COBALT_BRD_ID_QUBE2    0x5
 #define COBALT_BRD_ID_RAQ2     0x6
 
+void cobalt_pci_init(void);
 void cobalt_machine_halt(void);
 void cobalt_machine_restart(char *command);
 
Signature · 1 line
2.53.0
author maintainer
#299 lore raw

PATCH 298/990 MIPS: SB1250: Validate and update IRQ affinity

In reply to Greg Kroah-Hartman

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

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

From: Florian Fainelli <[email protected]>

[ Upstream commit 456c965ca46c59a4a241c755e6565fd883a522f4 ]

sb1250_set_affinity() selects the first online CPU in the requested affinity mask without checking whether such a CPU exists. If the intersection is empty, the resulting CPU index is invalid and must not be passed to cpu_logical_map().

Reject affinity masks containing no online CPU with -EINVAL before accessing the CPU mapping or interrupt mapper registers.

Also update the effective affinity mask to reflect the single logical CPU selected as the interrupt target.

Fixes 421d1563c662 ("mips: Validate online cpus in irq_set_affinity() callbacks")
---
 arch/mips/sibyte/sb1250/irq.c | 3 +++
 1 file changed, 3 insertions(+)
arch/mips/sibyte/sb1250/irq.c +3 -0
index 2f08ad267a11e..d7a656cd7ec0c 100644
@@ -76,6 +76,8 @@ static int sb1250_set_affinity(struct irq_data *d, const struct cpumask *mask,
 	unsigned long flags;
 
 	i = cpumask_first_and(mask, cpu_online_mask);
+	if (i >= nr_cpu_ids)
+		return -EINVAL;
 
 	/* Convert logical CPU to physical CPU */
 	cpu = cpu_logical_map(i);
@@ -103,6 +105,7 @@ static int sb1250_set_affinity(struct irq_data *d, const struct cpumask *mask,
 		____raw_writeq(cur_ints, IOADDR(A_IMR_MAPPER(cpu) +
 					R_IMR_INTERRUPT_MASK));
 	}
+	irq_data_update_effective_affinity(d, cpumask_of(i));
 	raw_spin_unlock_irqrestore(&sb1250_imr_lock, flags);
 
 	return 0;
Signature · 1 line
2.53.0
author maintainer
#300 lore raw

PATCH 299/990 introduce a flag for explicitly marking persistently pinned dentries

In reply to Greg Kroah-Hartman

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

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

From: Al Viro <[email protected]>

[ Upstream commit 8a210cacf5dc2a6210ee42aeca5cd03b2400876f ]

Some filesystems use a kinda-sorta controlled dentry refcount leak to pin dentries of created objects in dcache (and undo it when removing those). Reference is grabbed and not released, but it's not actually _stored_ anywhere. That works, but it's hard to follow and verify; among other things, we have no way to tell _which_ of the increments is intended to be an unpaired one. Worse, on removal we need to decide whether the reference had already been dropped, which can be non-trivial if that removal is on umount and we need to figure out if this dentry is pinned due to e.g. unlink() not done. Usually that is handled by using kill_litter_super() as ->kill_sb(), but there are open-coded special cases of the same (consider e.g. /proc/self).

Things get simpler if we introduce a new dentry flag (DCACHE_PERSISTENT) marking those "leaked" dentries. Having it set claims responsibility for +1 in refcount.

The end result this series is aiming for:

* get these unbalanced dget() and dput() replaced with new primitives that would, in addition to adjusting refcount, set and clear persistency flag.
* instead of having kill_litter_super() mess with removing the remaining "leaked" references (e.g. for all tmpfs files that hadn't been removed prior to umount), have the regular shrink_dcache_for_umount() strip DCACHE_PERSISTENT of all dentries, dropping the corresponding reference if it had been set. After that kill_litter_super() becomes an equivalent of kill_anon_super().

Doing that in a single step is not feasible - it would affect too many places in too many filesystems. It has to be split into a series.

Here we
* introduce the new flag
* teach shrink_dcache_for_umount() to handle it (i.e. remove
and drop refcount on anything that survives to umount with that flag still set)
* teach kill_litter_super() that anything with that flag does
*not* need to be unpinned.

Next commits will add primitives for maintaing that flag and convert the common helpers to those. After that - a long series of per-filesystem patches converting to those primitives.

Stable-dep-of: 309f7a5585ae ("libfs: walk offset directories in offset order")

---
 fs/dcache.c            | 27 ++++++++++++++++++++++-----
 include/linux/dcache.h |  1 +
 2 files changed, 23 insertions(+), 5 deletions(-)
fs/dcache.c +22 -5
index 77792a9e86737..467095024991b 100644
@@ -1526,6 +1526,15 @@ static enum d_walk_ret select_collect(void *_data, struct dentry *dentry)
 	return ret;
 }
 
+static enum d_walk_ret select_collect_umount(void *_data, struct dentry *dentry)
+{
+	if (dentry->d_flags & DCACHE_PERSISTENT) {
+		dentry->d_flags &= ~DCACHE_PERSISTENT;
+		dentry->d_lockref.count--;
+	}
+	return select_collect(_data, dentry);
+}
+
 static enum d_walk_ret select_collect2(void *_data, struct dentry *dentry)
 {
 	struct select_data *data = _data;
@@ -1554,18 +1563,20 @@ static enum d_walk_ret select_collect2(void *_data, struct dentry *dentry)
 }
 
 /**
- * shrink_dcache_parent - prune dcache
+ * shrink_dcache_tree - prune dcache
  * @parent: parent of entries to prune
+ * @for_umount: true if we want to unpin the persistent ones
  *
  * Prune the dcache to remove unused children of the parent dentry.
  */
-void shrink_dcache_parent(struct dentry *parent)
+static void shrink_dcache_tree(struct dentry *parent, bool for_umount)
 {
 	for (;;) {
 		struct select_data data = {.start = parent};
 
 		INIT_LIST_HEAD(&data.dispose);
-		d_walk(parent, &data, select_collect);
+		d_walk(parent, &data,
+			for_umount ? select_collect_umount : select_collect);
 
 		if (!list_empty(&data.dispose)) {
 			shrink_dentry_list(&data.dispose);
@@ -1590,6 +1601,11 @@ void shrink_dcache_parent(struct dentry *parent)
 			shrink_dentry_list(&data.dispose);
 	}
 }
+
+void shrink_dcache_parent(struct dentry *parent)
+{
+	shrink_dcache_tree(parent, false);
+}
 EXPORT_SYMBOL(shrink_dcache_parent);
 
 static enum d_walk_ret umount_check(void *_data, struct dentry *dentry)
@@ -1616,7 +1632,7 @@ static enum d_walk_ret umount_check(void *_data, struct dentry *dentry)
 
 static void do_one_tree(struct dentry *dentry)
 {
-	shrink_dcache_parent(dentry);
+	shrink_dcache_tree(dentry, true);
 	d_walk(dentry, dentry, umount_check);
 	d_drop(dentry);
 	dput(dentry);
@@ -3130,7 +3146,8 @@ static enum d_walk_ret d_genocide_kill(void *data, struct dentry *dentry)
 {
 	struct dentry *root = data;
 	if (dentry != root) {
-		if (d_unhashed(dentry) || !dentry->d_inode)
+		if (d_unhashed(dentry) || !dentry->d_inode ||
+		    dentry->d_flags & DCACHE_PERSISTENT)
 			return D_WALK_SKIP;
 
 		if (!(dentry->d_flags & DCACHE_GENOCIDE)) {
include/linux/dcache.h +1 -0
index c83e02b943894..94b58655322a0 100644
@@ -225,6 +225,7 @@ enum dentry_flags {
 	DCACHE_PAR_LOOKUP		= BIT(24),	/* being looked up (with parent locked shared) */
 	DCACHE_DENTRY_CURSOR		= BIT(25),
 	DCACHE_NORCU			= BIT(26),	/* No RCU delay for freeing */
+	DCACHE_PERSISTENT		= BIT(27)
 };
 
 #define DCACHE_MANAGED_DENTRY \
Signature · 1 line
2.53.0
author maintainer
#301 lore raw

PATCH 300/990 libfs: walk offset directories in offset order

In reply to Greg Kroah-Hartman

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

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

From: Christian Brauner <[email protected]>

[ Upstream commit 309f7a5585aeaf77d3d7c27304ac97e515447dac ]

offset_iterate_dir() walks d_children from the head and only uses the maple tree to map ctx->pos back to a dentry when a getdents64() call resumes. offset_dir_lookup() finds the entry at ctx->pos, or the one with the next lower offset if it is gone, and the list walk continues from there.

That only works if list order and offset order agree and quite often they don't. A rename over an existing name gives the moved dentry the offset of the name it replaced but __d_move() puts it at the head of d_children. RENAME_EXCHANGE does the same to both dentries. And once the cyclic offset allocator wraps new entries get low offsets at the head of the list.

So if the entry at ctx->pos is unlinked between two getdents64() calls we resume at the entry with the next lower offset and that one can sit anywhere in the list:

(1) If it sits further down the list everything in between is skipped. Create y, t, a, b and rename b over t. The list is now t(4) a(5) y(3). Stop the listing at t and unlink t. The next call resumes at y and a is never returned although nobody touched it.

(2) If there is no lower entry we restart at the head and return the whole directory again. Nickolai reported this for the simple case of unlinking the oldest entry while a listing is about to reach it. Ending the walk there instead turns this into (1): create a, b, c, rename c over a, stop the listing at the renamed entry, unlink it, and b is lost.

Instead of the list let's walk the maple tree itself in descending offset order. Then ctx->pos really means that everything above it has been emitted and resuming at the highest offset at or below it is right no matter where the dentry sits in d_children. Entries created or renamed to a new name after the listing started get an offset above ctx->pos and aren't returned, same as with the list walk which never went back to the head. So a readdir loop that renames or creates an entry for each one it reads still terminates.

The maple tree can't change under us as all modifications happen with the directory's i_rwsem held exclusive and offset_readdir() holds it shared. That also covers the dentries in the tree. They are all persistent and only unlink, rmdir and rename remove or rename them. And since the previous patch i_rwsem is the lock of the tree. So keep a single ma_state across the walk and emit directly from the dentry without taking rcu_read_lock(), a reference or d_lock.

This also makes the walk cheaper than the list walk was. With a million entries on tmpfs a getdents64() listing goes from 146ms to 114ms. With four processes listing the directory at the same time it goes from 470ms to 113ms per listing as they don't bounce the parent's d_lock and the dentries' lockrefs between them anymore.

                                                base     v2       this
      1M entries, getdents64 32k buffer (ms)    146      127      114
      1M entries, getdents64 1k buffer (ms)     184      156      141
      1M entries, getdents64 128b buffer (ms)   429      364      335
      1M entries, ls -f (s)                     0.259    0.239    0.228
      1M entries, LC_ALL=C ls (s)               0.482    0.467    0.455
      1M entries, 4 parallel listers (ms)       470      125      113
      18 entries, rewind and list (ns)          4107     3594     3323
      250k of 1M left, getdents64 32k (ms)      58.8     57.8     53.8
      250k of 1M left, getdents64 128b (ms)     128      114      108
Fixes b9b588f22a0c ("libfs: Use d_children list to iterate simple_offset directories")
Fixes f70681e9e606 ("libfs: Fix duplicate directory entry in offset_dir_lookup")
---
 fs/libfs.c | 85 ++++++++++++++----------------------------------------
 1 file changed, 22 insertions(+), 63 deletions(-)
fs/libfs.c +22 -63
index 52f00bfc8f7ba..cb37a117c8e5c 100644
@@ -283,6 +283,12 @@ void simple_offset_init(struct offset_ctx *octx)
  * @octx: directory offset ctx to be updated
  * @dentry: new dentry being added
  *
+ * The offset map holds no reference to @dentry. Once positive, @dentry
+ * must be pinned with d_make_persistent() for as long as it is in the
+ * map, and entries may only be added, removed or renamed with the
+ * directory's i_rwsem held exclusive: offset_readdir() emits straight
+ * from the map under the shared lock.
+ *
  * Returns zero on success. @octx and the dentry's offset are updated.
  * Otherwise, a negative errno value is returned.
  */
@@ -447,51 +453,6 @@ static loff_t offset_dir_llseek(struct file *file, loff_t offset, int whence)
 	return vfs_setpos(file, offset, LONG_MAX);
 }
 
-static struct dentry *find_positive_dentry(struct dentry *parent,
-					   struct dentry *dentry,
-					   bool next)
-{
-	struct dentry *found = NULL;
-
-	spin_lock(&parent->d_lock);
-	if (next)
-		dentry = d_next_sibling(dentry);
-	else if (!dentry)
-		dentry = d_first_child(parent);
-	hlist_for_each_entry_from(dentry, d_sib) {
-		if (!simple_positive(dentry))
-			continue;
-		spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
-		if (simple_positive(dentry))
-			found = dget_dlock(dentry);
-		spin_unlock(&dentry->d_lock);
-		if (likely(found))
-			break;
-	}
-	spin_unlock(&parent->d_lock);
-	return found;
-}
-
-static noinline_for_stack struct dentry *
-offset_dir_lookup(struct dentry *parent, loff_t offset)
-{
-	struct inode *inode = d_inode(parent);
-	struct offset_ctx *octx = inode->i_op->get_offset_ctx(inode);
-	struct dentry *child, *found = NULL;
-
-	MA_STATE(mas, &octx->mt, offset, offset);
-
-	if (offset == DIR_OFFSET_FIRST)
-		found = find_positive_dentry(parent, NULL, false);
-	else {
-		rcu_read_lock();
-		child = mas_find_rev(&mas, DIR_OFFSET_MIN);
-		found = find_positive_dentry(parent, child, false);
-		rcu_read_unlock();
-	}
-	return found;
-}
-
 static bool offset_dir_emit(struct dir_context *ctx, struct dentry *dentry)
 {
 	struct inode *inode = d_inode(dentry);
@@ -500,32 +461,30 @@ static bool offset_dir_emit(struct dir_context *ctx, struct dentry *dentry)
 			inode->i_ino, fs_umode_to_dtype(inode->i_mode));
 }
 
+/*
+ * Emit entries in descending offset order. The directory's i_rwsem is the
+ * lock of the offset tree and the persistent dentries in it only change
+ * with it held exclusive. We hold it shared, so @mas stays valid across
+ * dir_emit() and the dentries need no references.
+ */
 static void offset_iterate_dir(struct file *file, struct dir_context *ctx)
 {
-	struct dentry *dir = file->f_path.dentry;
+	struct inode *inode = file_inode(file);
+	struct offset_ctx *octx = inode->i_op->get_offset_ctx(inode);
+	loff_t start = ctx->pos == DIR_OFFSET_FIRST ? DIR_OFFSET_MAX : ctx->pos;
 	struct dentry *dentry;
 
-	dentry = offset_dir_lookup(dir, ctx->pos);
-	if (!dentry)
-		goto out_eod;
-	while (true) {
-		struct dentry *next;
+	MA_STATE(mas, &octx->mt, start, start);
 
+	for (;;) {
+		dentry = mas_find_rev(&mas, DIR_OFFSET_MIN);
+		if (!dentry)
+			break;
+		VFS_WARN_ON_ONCE(!(dentry->d_flags & DCACHE_PERSISTENT));
 		ctx->pos = dentry2offset(dentry);
 		if (!offset_dir_emit(ctx, dentry))
-			break;
-
-		next = find_positive_dentry(dir, dentry, true);
-		dput(dentry);
-
-		if (!next)
-			goto out_eod;
-		dentry = next;
+			return;
 	}
-	dput(dentry);
-	return;
-
-out_eod:
 	ctx->pos = DIR_OFFSET_EOD;
 }
 
Signature · 1 line
2.53.0
author maintainer
#302 lore raw

PATCH 301/990 libfs: end offset readdir at positions past DIR_OFFSET_EOD

In reply to Greg Kroah-Hartman

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

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

From: Christian Brauner <[email protected]>

[ Upstream commit 45eb9737058fa78a73f17a5da55c8cb482c6d5bb ]

offset_dir_llseek() takes any position up to LONG_MAX but offset_readdir() only skips the walk for DIR_OFFSET_EOD itself. For a position past it mas_find_rev() starts the walk at the highest offset in the directory. So an lseek() past the end makes the next getdents64() return the whole directory again.

Before commit b9b588f22a0c ("libfs: Use d_children list to iterate simple_offset directories") the walk went up from the position and found nothing past the end, and dcache_readdir() returns nothing there either. So only walk for positions below DIR_OFFSET_EOD.

Fixes b9b588f22a0c ("libfs: Use d_children list to iterate simple_offset directories")
---
 fs/libfs.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/libfs.c +1 -1
index cb37a117c8e5c..f210c0c642459 100644
@@ -519,7 +519,7 @@ static int offset_readdir(struct file *file, struct dir_context *ctx)
 
 	if (!dir_emit_dots(file, ctx))
 		return 0;
-	if (ctx->pos != DIR_OFFSET_EOD)
+	if (ctx->pos < DIR_OFFSET_EOD)
 		offset_iterate_dir(file, ctx);
 	return 0;
 }
Signature · 1 line
2.53.0
author maintainer
#303 lore raw

PATCH 302/990 initrd: flush deferred fput() before mounting root

In reply to Greg Kroah-Hartman

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

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

From: Abbott Liu <[email protected]>

[ Upstream commit 807c1d7125a2b3ca5705a803aa2e19f9d53d1ea3 ]

Booting an old-style initrd, i.e. a filesystem image instead of a cpio archive, with "root=/dev/ram rootfstype=squashfs" can fail to mount the root filesystem:

RAMDISK: squashfs filesystem found at block 0
RAMDISK: Loading 68449KiB [1 disk] into ram disk... done. No filesystem could mount root, tried:
squashfs
Kernel panic - not syncing: VFS: Unable to mount root fs on "/dev/ram" or unknown-block(1,0)

rd_load_image() copies the image into /dev/ram with kernel_write() and then drops the file with fput(). The data only reaches the ramdisk once the final __fput() releases the block device and bdev_release() calls sync_blockdev(). But that __fput() is deferred. Since commit 343f4c49f243 ("kthread: Don't allocate kthread_struct for init and umh") init is a user mode task, so the __fput() is queued as task work and only runs once init returns to userspace, i.e. long after mount_root(). Before that it ran as delayed fput work at least a jiffy later, which doesn't help either.

Whether the mount survives this depends on the block size. Squashfs calls sb_min_blocksize() first and set_blocksize() syncs and drops the page cache when the requested block size differs from the current one. That hides the problem for most configurations. With CONFIG_SQUASHFS_4K_DEVBLK_SIZE=y and 4K pages both block sizes are 4K because set_init_blocksize() gives a page-aligned ramdisk a PAGE_SIZE block size on the first open. So set_blocksize() does nothing and squashfs reads the superblock with bios that bypass the page cache. brd has no page for that range yet and returns zeroes, so the magic check fails and the mount returns -EINVAL. With rootfstype= naming a single filesystem there is nothing left to retry and mount_root_generic() panics.

Fixing this in squashfs would be the wrong end. Most block-backed filesystems read their superblock or their file data with bios that bypass the block device page cache, so they are exposed to the same race, just less loudly.

So flush the deferred fput() in rd_load_image() right after dropping the ramdisk file, the same way mount_root_generic() already does before it retries with another filesystem type. All deferred closes at this point belong to files the boot itself created.

Verified on arm64 QEMU with an openEuler Embedded rootfs image packed as squashfs.

Fixes 93e72b3c612a ("squashfs: migrate from ll_rw_block usage to BIO")
---
 init/do_mounts_rd.c | 5 +++++
 1 file changed, 5 insertions(+)
init/do_mounts_rd.c +5 -0
index 19d9f33dcacf8..fb7897d879b06 100644
@@ -268,6 +268,11 @@ int __init rd_load_image(char *from)
 	fput(in_file);
 noclose_input:
 	fput(out_file);
+	/*
+	 * The image only reaches the ramdisk when the deferred __fput()
+	 * syncs the block device. Flush it before mount_root() reads it.
+	 */
+	init_flush_fput();
 out:
 	kfree(buf);
 	init_unlink("/dev/ram");
Signature · 1 line
2.53.0
author maintainer
#304 lore raw

PATCH 303/990 iov_iter: take an unsigned long segment count in import_iovec()

In reply to Greg Kroah-Hartman

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

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

From: Andrea Parri <[email protected]>

[ Upstream commit 965e5e451146a19f69523fbcbc73d07e401a3775 ]

readv(), writev() and their positional variants, process_vm_readv(), process_vm_writev(), vmsplice(), process_madvise(), vectored aio and the btrfs encoded I/O ioctls all take a full-width segment count, and all of them hand it to import_iovec() or __import_iovec(). Those take an unsigned int count, so on 64-bit kernels the upper 32 bits are dropped before iovec_from_user() checks the count against UIO_MAXIOV.

A count of 0x100000001 is therefore imported as one segment: writev() on a pipe writes a byte and readv() reads it back, instead of both failing with EINVAL. A count of 0x100000000 returns 0 as an empty vector.

import_iovec() was added with an unsigned int count, but the helper it wrapped, rw_copy_check_uvector(), took an unsigned long, as does iovec_from_user() today. Until v4.1, readv(), writev(), preadv(), pwritev(), process_vm_readv(), process_vm_writev() and vectored aio therefore failed these counts with EINVAL, as did vmsplice() until v4.18.

Widen nr_segs in both import helpers so the UIO_MAXIOV check sees the count the caller passed. Callers with 32-bit counts are unaffected.

AI assistance was used to find the bug, develop the fix, and run the reproducers.

---
 include/linux/uio.h | 8 ++++----
 lib/iov_iter.c      | 6 +++---
 2 files changed, 7 insertions(+), 7 deletions(-)
include/linux/uio.h +4 -4
index 5b127043a1519..5678520f0bfb6 100644
@@ -362,11 +362,11 @@ struct iovec *iovec_from_user(const struct iovec __user *uvector,
 		unsigned long nr_segs, unsigned long fast_segs,
 		struct iovec *fast_iov, bool compat);
 ssize_t import_iovec(int type, const struct iovec __user *uvec,
-		 unsigned nr_segs, unsigned fast_segs, struct iovec **iovp,
-		 struct iov_iter *i);
+		 unsigned long nr_segs, unsigned int fast_segs,
+		 struct iovec **iovp, struct iov_iter *i);
 ssize_t __import_iovec(int type, const struct iovec __user *uvec,
-		 unsigned nr_segs, unsigned fast_segs, struct iovec **iovp,
-		 struct iov_iter *i, bool compat);
+		 unsigned long nr_segs, unsigned int fast_segs,
+		 struct iovec **iovp, struct iov_iter *i, bool compat);
 int import_ubuf(int type, void __user *buf, size_t len, struct iov_iter *i);
 
 static inline void iov_iter_ubuf(struct iov_iter *i, unsigned int direction,
lib/iov_iter.c +3 -3
index b2eb629497a92..a9918931055a8 100644
@@ -1354,8 +1354,8 @@ static ssize_t __import_iovec_ubuf(int type, const struct iovec __user *uvec,
 }
 
 ssize_t __import_iovec(int type, const struct iovec __user *uvec,
-		 unsigned nr_segs, unsigned fast_segs, struct iovec **iovp,
-		 struct iov_iter *i, bool compat)
+		 unsigned long nr_segs, unsigned int fast_segs,
+		 struct iovec **iovp, struct iov_iter *i, bool compat)
 {
 	ssize_t total_len = 0;
 	unsigned long seg;
@@ -1426,7 +1426,7 @@ ssize_t __import_iovec(int type, const struct iovec __user *uvec,
  * Return: Negative error code on error, bytes imported on success
  */
 ssize_t import_iovec(int type, const struct iovec __user *uvec,
-		 unsigned nr_segs, unsigned fast_segs,
+		 unsigned long nr_segs, unsigned int fast_segs,
 		 struct iovec **iovp, struct iov_iter *i)
 {
 	return __import_iovec(type, uvec, nr_segs, fast_segs, iovp, i,
Signature · 1 line
2.53.0
author maintainer
#305 lore raw

PATCH 304/990 vfs: preserve subsecond timestamps at filesystem time limits

In reply to Greg Kroah-Hartman

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

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

From: Hungyu Lin <[email protected]>

[ Upstream commit 55a0c91000646b008261e3b1e15d1e774f3026e4 ]

timestamp_truncate() clears tv_nsec whenever the clamped seconds equal either filesystem time limit. This also drops the fractional part of timestamps whose seconds were already within the supported range.

For example, setting a JFS mtime to 0.123456789 produces 0.000000000, although the filesystem can store the requested value. Utilities such as touch and cp -p consequently lose valid subsecond timestamps when preserving these endpoint values. Timestamps strictly between the filesystem limits are unaffected.

Only clear tv_nsec when clamping actually changes tv_sec. Continue to truncate in-range nanoseconds to the filesystem's timestamp granularity, including when the seconds equal either endpoint.

Ben Hutchings suggested comparing clamped and original seconds in the 2019 utimes review. That caller was switched to timestamp_truncate(), but the helper retained its endpoint equality check.

---
 fs/inode.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
fs/inode.c +2 -1
index b60111fad771a..a5333c9ff761d 100644
@@ -2741,9 +2741,10 @@ struct timespec64 timestamp_truncate(struct timespec64 t, struct inode *inode)
 {
 	struct super_block *sb = inode->i_sb;
 	unsigned int gran = sb->s_time_gran;
+	time64_t seconds = t.tv_sec;
 
 	t.tv_sec = clamp(t.tv_sec, sb->s_time_min, sb->s_time_max);
-	if (unlikely(t.tv_sec == sb->s_time_max || t.tv_sec == sb->s_time_min))
+	if (unlikely(t.tv_sec != seconds))
 		t.tv_nsec = 0;
 
 	/* Avoid division in the common cases 1 ns and 1 s. */
Signature · 1 line
2.53.0
author maintainer
#306 lore raw

PATCH 305/990 statx: dont leak STATX_ATTR_CHANGE_MONOTONIC in stx_attributes_mask

In reply to Greg Kroah-Hartman

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

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

From: Jeff Layton <[email protected]>

[ Upstream commit 925d238324c79bcb75ad0add1d1b9d31d5f48115 ]

STATX_ATTR_CHANGE_MONOTONIC is kernel-internal. cp_statx() strips it from stx_attributes but copies attributes_mask verbatim, so it leaks to userland on filesystems that advertise it (nfs, ceph), e.g. stx_attributes_mask = 0x8000000000303000 on NFS.

Add a new mask constant and apply it to both fields.

---
 fs/stat.c            | 6 +++---
 include/linux/stat.h | 3 +++
 2 files changed, 6 insertions(+), 3 deletions(-)
fs/stat.c +3 -3
index 3bc049f0bc3dd..484b61ccc1152 100644
@@ -718,8 +718,7 @@ cp_statx(const struct kstat *stat, struct statx __user *buffer)
 	/* STATX_CHANGE_COOKIE is kernel-only for now */
 	tmp.stx_mask = stat->result_mask & ~STATX_CHANGE_COOKIE;
 	tmp.stx_blksize = stat->blksize;
-	/* STATX_ATTR_CHANGE_MONOTONIC is kernel-only for now */
-	tmp.stx_attributes = stat->attributes & ~STATX_ATTR_CHANGE_MONOTONIC;
+	tmp.stx_attributes = stat->attributes & ~STATX_ATTR_INTERNAL_MASK;
 	tmp.stx_nlink = stat->nlink;
 	tmp.stx_uid = from_kuid_munged(current_user_ns(), stat->uid);
 	tmp.stx_gid = from_kgid_munged(current_user_ns(), stat->gid);
@@ -727,7 +726,8 @@ cp_statx(const struct kstat *stat, struct statx __user *buffer)
 	tmp.stx_ino = stat->ino;
 	tmp.stx_size = stat->size;
 	tmp.stx_blocks = stat->blocks;
-	tmp.stx_attributes_mask = stat->attributes_mask;
+	tmp.stx_attributes_mask = stat->attributes_mask &
+				  ~STATX_ATTR_INTERNAL_MASK;
 	tmp.stx_atime.tv_sec = stat->atime.tv_sec;
 	tmp.stx_atime.tv_nsec = stat->atime.tv_nsec;
 	tmp.stx_btime.tv_sec = stat->btime.tv_sec;
include/linux/stat.h +3 -0
index e3d00e7bb26d9..3f4364808b7f0 100644
@@ -69,4 +69,7 @@ struct kstat {
 /* file attribute values */
 #define STATX_ATTR_CHANGE_MONOTONIC	0x8000000000000000ULL /* version monotonically increases */
 
+/* mask of STATX_ATTR_* bits that is private to the kernel */
+#define STATX_ATTR_INTERNAL_MASK	(STATX_ATTR_CHANGE_MONOTONIC)
+
 #endif
Signature · 1 line
2.53.0
author maintainer
#307 lore raw

PATCH 306/990 fs: reject negative offsets for SEEK_DATA and SEEK_HOLE in default_llseek()

In reply to Greg Kroah-Hartman

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

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

From: Siddharth Chintamaneni <[email protected]>

[ Upstream commit 7a5783cfac71b3c12e7fb1c2894dd4538d57d513 ]

In default_llseek(), the range checks for SEEK_DATA and SEEK_HOLE compare the signed loff_t offset directly against inode->i_size:

	if (offset >= inode->i_size) {
		retval = -ENXIO;
		goto out;
	}

When a negative offset is supplied to SEEK_HOLE (e.g. lseek(fd, -10, SEEK_HOLE) on a sysctl file in /proc/sys), the signed comparison evaluates to false and execution proceeds to:

	offset = inode->i_size;

This overwrites the negative offset with a non-negative value before the final if (offset >= 0 || unsigned_offsets(file)) check, causing default_llseek() to update file->f_pos and return inode->i_size instead of failing with -ENXIO. Similarly, for SEEK_DATA on a file with FOP_UNSIGNED_OFFSET, a negative offset bypasses the range check and succeeds via unsigned_offsets(file).

Read the inode size once via i_size_read(inode) after acquiring the inode lock and compare (unsigned long long)offset >= eof for both SEEK_DATA and SEEK_HOLE, matching must_set_pos().

---
 fs/read_write.c | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)
fs/read_write.c +6 -4
index 011fe55c94cdb..96528614d4f33 100644
@@ -331,13 +331,15 @@ loff_t default_llseek(struct file *file, loff_t offset, int whence)
 {
 	struct inode *inode = file_inode(file);
 	loff_t retval;
+	loff_t eof;
 
 	retval = inode_lock_killable(inode);
 	if (retval)
 		return retval;
+	eof = i_size_read(inode);
 	switch (whence) {
 		case SEEK_END:
-			offset += i_size_read(inode);
+			offset += eof;
 			break;
 		case SEEK_CUR:
 			if (offset == 0) {
@@ -352,7 +354,7 @@ loff_t default_llseek(struct file *file, loff_t offset, int whence)
 			 * long as offset isn't at the end of the file then the
 			 * offset is data.
 			 */
-			if (offset >= inode->i_size) {
+			if ((unsigned long long)offset >= eof) {
 				retval = -ENXIO;
 				goto out;
 			}
@@ -363,11 +365,11 @@ loff_t default_llseek(struct file *file, loff_t offset, int whence)
 			 * as long as offset isn't i_size or larger, return
 			 * i_size.
 			 */
-			if (offset >= inode->i_size) {
+			if ((unsigned long long)offset >= eof) {
 				retval = -ENXIO;
 				goto out;
 			}
-			offset = inode->i_size;
+			offset = eof;
 			break;
 	}
 	retval = -EINVAL;
Signature · 1 line
2.53.0
author maintainer
#308 lore raw

PATCH 307/990 perf: Add perf_event_attr::config4

In reply to Greg Kroah-Hartman

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

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

From: James Clark <[email protected]>

[ Upstream commit cbbfba4847b8a5299d36e002bf864b21bb83295d ]

Arm FEAT_SPE_FDS adds the ability to filter on the data source of a packet using another 64-bits of event filtering control. As the existing perf_event_attr::configN fields are all used up for SPE PMU, an additional field is needed. Add a new 'config4' field.

Stable-dep-of: b61c12527223 ("perf/amd/ibs: Fix kernel address leak via REGS_USER and REGS_INTR")

---
 include/uapi/linux/perf_event.h | 2 ++
 1 file changed, 2 insertions(+)
include/uapi/linux/perf_event.h +2 -0
index 78a362b800277..0d0ed85ad8cb3 100644
@@ -382,6 +382,7 @@ enum perf_event_read_format {
 #define PERF_ATTR_SIZE_VER6			120	/* Add: aux_sample_size */
 #define PERF_ATTR_SIZE_VER7			128	/* Add: sig_data */
 #define PERF_ATTR_SIZE_VER8			136	/* Add: config3 */
+#define PERF_ATTR_SIZE_VER9			144	/* add: config4 */
 
 /*
  * 'struct perf_event_attr' contains various attributes that define
@@ -543,6 +544,7 @@ struct perf_event_attr {
 	__u64	sig_data;
 
 	__u64	config3; /* extension of config2 */
+	__u64	config4; /* extension of config3 */
 };
 
 /*
Signature · 1 line
2.53.0
author maintainer
#309 lore raw

PATCH 308/990 perf: Add APIs to create/release mediated guest vPMUs

In reply to Greg Kroah-Hartman

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

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

From: Kan Liang <[email protected]>

[ Upstream commit eff95e170275d9e80b968f335cd03d0ac250d2d1 ]

Currently, exposing PMU capabilities to a KVM guest is done by emulating guest PMCs via host perf events, i.e. by having KVM be "just" another user of perf. As a result, the guest and host are effectively competing for resources, and emulating guest accesses to vPMU resources requires expensive actions (expensive relative to the native instruction). The overhead and resource competition results in degraded guest performance and ultimately very poor vPMU accuracy.

To address the issues with the perf-emulated vPMU, introduce a "mediated vPMU", where the data plane (PMCs and enable/disable knobs) is exposed directly to the guest, but the control plane (event selectors and access to fixed counters) is managed by KVM (via MSR interceptions). To allow host perf usage of the PMU to (partially) co-exist with KVM/guest usage of the PMU, KVM and perf will coordinate to a world switch between host perf context and guest vPMU context near VM-Enter/VM-Exit.

Add two exported APIs, perf_{create,release}_mediated_pmu(), to allow KVM to create and release a mediated PMU instance (per VM). Because host perf context will be deactivated while the guest is running, mediated PMU usage will be mutually exclusive with perf analysis of the guest, i.e. perf events that do NOT exclude the guest will not behave as expected.

To avoid silent failure of !exclude_guest perf events, disallow creating a mediated PMU if there are active !exclude_guest events, and on the perf side, disallowing creating new !exclude_guest perf events while there is at least one active mediated PMU.

Exempt PMU resources that do not support mediated PMU usage, i.e. that are outside the scope/view of KVM's vPMU and will not be swapped out while the guest is running.

Guard mediated PMU with a new kconfig to help readers identify code paths that are unique to mediated PMU support, and to allow for adding arch- specific hooks without stubs. KVM x86 is expected to be the only KVM architecture to support a mediated PMU in the near future (e.g. arm64 is trending toward a partitioned PMU implementation), and KVM x86 will select PERF_GUEST_MEDIATED_PMU unconditionally, i.e. won't need stubs.

Immediately select PERF_GUEST_MEDIATED_PMU when KVM x86 is enabled so that all paths are compile tested. Full KVM support is on its way...

Stable-dep-of: b61c12527223 ("perf/amd/ibs: Fix kernel address leak via REGS_USER and REGS_INTR")

---
 arch/x86/kvm/Kconfig       |  1 +
 include/linux/perf_event.h |  6 +++
 init/Kconfig               |  4 ++
 kernel/events/core.c       | 82 ++++++++++++++++++++++++++++++++++++++
 4 files changed, 93 insertions(+)
arch/x86/kvm/Kconfig +1 -0
index 278f08194ec87..d916bd766c94d 100644
@@ -37,6 +37,7 @@ config KVM_X86
 	select SCHED_INFO
 	select PERF_EVENTS
 	select GUEST_PERF_EVENTS
+	select PERF_GUEST_MEDIATED_PMU
 	select HAVE_KVM_MSI
 	select HAVE_KVM_CPU_RELAX_INTERCEPT
 	select HAVE_KVM_NO_POLL
include/linux/perf_event.h +6 -0
index c8acdb026c627..5fb17c4f52f12 100644
@@ -305,6 +305,7 @@ struct perf_event_pmu_context;
 #define PERF_PMU_CAP_EXTENDED_HW_TYPE	0x0100
 #define PERF_PMU_CAP_AUX_PAUSE		0x0200
 #define PERF_PMU_CAP_AUX_PREFER_LARGE	0x0400
+#define PERF_PMU_CAP_MEDIATED_VPMU	0x0800
 
 /**
  * pmu::scope
@@ -1915,6 +1916,11 @@ extern int perf_event_account_interrupt(struct perf_event *event);
 extern int perf_event_period(struct perf_event *event, u64 value);
 extern u64 perf_event_pause(struct perf_event *event, bool reset);
 
+#ifdef CONFIG_PERF_GUEST_MEDIATED_PMU
+int perf_create_mediated_pmu(void);
+void perf_release_mediated_pmu(void);
+#endif
+
 #else /* !CONFIG_PERF_EVENTS: */
 
 static inline void *
init/Kconfig +4 -0
index 1858e55bfd7cd..78d4277990e94 100644
@@ -2018,6 +2018,10 @@ config GUEST_PERF_EVENTS
 	bool
 	depends on HAVE_PERF_EVENTS
 
+config PERF_GUEST_MEDIATED_PMU
+	bool
+	depends on GUEST_PERF_EVENTS
+
 config PERF_USE_VMALLOC
 	bool
 	help
kernel/events/core.c +82 -0

106 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#310 lore raw

PATCH 309/990 perf: Eliminate duplicate arch-specific function definitions

In reply to Greg Kroah-Hartman

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

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

From: Dapeng Mi <[email protected]>

[ Upstream commit cb388bd530cc518b0e245fb4eabc40f3de538e4f ]

Define default common __weak functions for perf_reg_value(), perf_reg_validate(), perf_reg_abi() and perf_get_regs_user(). This helps to eliminate the duplicated arch-specific definitions.

No function changes intended.

Stable-dep-of: b61c12527223 ("perf/amd/ibs: Fix kernel address leak via REGS_USER and REGS_INTR")

---
 arch/arm/kernel/perf_regs.c       |  6 ------
 arch/arm64/kernel/perf_regs.c     |  6 ------
 arch/csky/kernel/perf_regs.c      |  6 ------
 arch/loongarch/kernel/perf_regs.c |  6 ------
 arch/mips/kernel/perf_regs.c      |  6 ------
 arch/parisc/kernel/perf_regs.c    |  6 ------
 arch/riscv/kernel/perf_regs.c     |  6 ------
 arch/x86/kernel/perf_regs.c       |  6 ------
 include/linux/perf_regs.h         | 32 ++++++-------------------------
 kernel/events/core.c              | 22 +++++++++++++++++++++
 10 files changed, 28 insertions(+), 74 deletions(-)
arch/arm/kernel/perf_regs.c +0 -6
index 0529f90395c94..d575a4c3ca56f 100644
@@ -31,9 +31,3 @@ u64 perf_reg_abi(struct task_struct *task)
 	return PERF_SAMPLE_REGS_ABI_32;
 }
 
-void perf_get_regs_user(struct perf_regs *regs_user,
-			struct pt_regs *regs)
-{
-	regs_user->regs = task_pt_regs(current);
-	regs_user->abi = perf_reg_abi(current);
-}
arch/arm64/kernel/perf_regs.c +0 -6
index b4eece3eb17d0..70e2f13f587f5 100644
@@ -98,9 +98,3 @@ u64 perf_reg_abi(struct task_struct *task)
 		return PERF_SAMPLE_REGS_ABI_64;
 }
 
-void perf_get_regs_user(struct perf_regs *regs_user,
-			struct pt_regs *regs)
-{
-	regs_user->regs = task_pt_regs(current);
-	regs_user->abi = perf_reg_abi(current);
-}
arch/csky/kernel/perf_regs.c +0 -6
index 09b7f88a2d6ad..94601f37b596d 100644
@@ -31,9 +31,3 @@ u64 perf_reg_abi(struct task_struct *task)
 	return PERF_SAMPLE_REGS_ABI_32;
 }
 
-void perf_get_regs_user(struct perf_regs *regs_user,
-			struct pt_regs *regs)
-{
-	regs_user->regs = task_pt_regs(current);
-	regs_user->abi = perf_reg_abi(current);
-}
arch/loongarch/kernel/perf_regs.c +0 -6
index 263ac4ab5af68..8dd604f017454 100644
@@ -45,9 +45,3 @@ u64 perf_reg_value(struct pt_regs *regs, int idx)
 	return regs->regs[idx];
 }
 
-void perf_get_regs_user(struct perf_regs *regs_user,
-			struct pt_regs *regs)
-{
-	regs_user->regs = task_pt_regs(current);
-	regs_user->abi = perf_reg_abi(current);
-}
arch/mips/kernel/perf_regs.c +0 -6
index e686780d1647a..7736d3c5ebd2c 100644
@@ -60,9 +60,3 @@ u64 perf_reg_value(struct pt_regs *regs, int idx)
 	return (s64)v; /* Sign extend if 32-bit. */
 }
 
-void perf_get_regs_user(struct perf_regs *regs_user,
-			struct pt_regs *regs)
-{
-	regs_user->regs = task_pt_regs(current);
-	regs_user->abi = perf_reg_abi(current);
-}
arch/parisc/kernel/perf_regs.c +0 -6
index 68458e2f6197e..87e6990569a76 100644
@@ -53,9 +53,3 @@ u64 perf_reg_abi(struct task_struct *task)
 	return PERF_SAMPLE_REGS_ABI_64;
 }
 
-void perf_get_regs_user(struct perf_regs *regs_user,
-			struct pt_regs *regs)
-{
-	regs_user->regs = task_pt_regs(current);
-	regs_user->abi = perf_reg_abi(current);
-}
arch/riscv/kernel/perf_regs.c +0 -6
index fd304a248de68..3bba8deababbf 100644
@@ -35,9 +35,3 @@ u64 perf_reg_abi(struct task_struct *task)
 #endif
 }
 
-void perf_get_regs_user(struct perf_regs *regs_user,
-			struct pt_regs *regs)
-{
-	regs_user->regs = task_pt_regs(current);
-	regs_user->abi = perf_reg_abi(current);
-}
arch/x86/kernel/perf_regs.c +0 -6
index 624703af80a19..81204cb7f7239 100644
@@ -100,12 +100,6 @@ u64 perf_reg_abi(struct task_struct *task)
 	return PERF_SAMPLE_REGS_ABI_32;
 }
 
-void perf_get_regs_user(struct perf_regs *regs_user,
-			struct pt_regs *regs)
-{
-	regs_user->regs = task_pt_regs(current);
-	regs_user->abi = perf_reg_abi(current);
-}
 #else /* CONFIG_X86_64 */
 #define REG_NOSUPPORT ((1ULL << PERF_REG_X86_DS) | \
 		       (1ULL << PERF_REG_X86_ES) | \
include/linux/perf_regs.h +6 -26
index f632c5725f162..144bcc3ff19fe 100644
@@ -9,6 +9,12 @@ struct perf_regs {
 	struct pt_regs	*regs;
 };
 
+u64 perf_reg_value(struct pt_regs *regs, int idx);
+int perf_reg_validate(u64 mask);
+u64 perf_reg_abi(struct task_struct *task);
+void perf_get_regs_user(struct perf_regs *regs_user,
+			struct pt_regs *regs);
+
 #ifdef CONFIG_HAVE_PERF_REGS
 #include <asm/perf_regs.h>
 
@@ -16,35 +22,9 @@ struct perf_regs {
 #define PERF_REG_EXTENDED_MASK	0
 #endif
 
-u64 perf_reg_value(struct pt_regs *regs, int idx);
-int perf_reg_validate(u64 mask);
-u64 perf_reg_abi(struct task_struct *task);
-void perf_get_regs_user(struct perf_regs *regs_user,
-			struct pt_regs *regs);
 #else
 
 #define PERF_REG_EXTENDED_MASK	0
 
-static inline u64 perf_reg_value(struct pt_regs *regs, int idx)
-{
-	return 0;
-}
-
-static inline int perf_reg_validate(u64 mask)
-{
-	return mask ? -ENOSYS : 0;
-}
-
-static inline u64 perf_reg_abi(struct task_struct *task)
-{
-	return PERF_SAMPLE_REGS_ABI_NONE;
-}
-
-static inline void perf_get_regs_user(struct perf_regs *regs_user,
-				      struct pt_regs *regs)
-{
-	regs_user->regs = task_pt_regs(current);
-	regs_user->abi = perf_reg_abi(current);
-}
 #endif /* CONFIG_HAVE_PERF_REGS */
 #endif /* _LINUX_PERF_REGS_H */
kernel/events/core.c +22 -0
index 6e194e4ce4a03..e7e052f62204b 100644
@@ -7606,6 +7606,28 @@ unsigned long perf_instruction_pointer(struct perf_event *event,
 		0 : perf_arch_instruction_pointer(regs);
 }
 
+u64 __weak perf_reg_value(struct pt_regs *regs, int idx)
+{
+	return 0;
+}
+
+int __weak perf_reg_validate(u64 mask)
+{
+	return mask ? -ENOSYS : 0;
+}
+
+u64 __weak perf_reg_abi(struct task_struct *task)
+{
+	return PERF_SAMPLE_REGS_ABI_NONE;
+}
+
+void __weak perf_get_regs_user(struct perf_regs *regs_user,
+			       struct pt_regs *regs)
+{
+	regs_user->regs = task_pt_regs(current);
+	regs_user->abi = perf_reg_abi(current);
+}
+
 static void
 perf_output_sample_regs(struct perf_output_handle *handle,
 			struct pt_regs *regs, u64 mask)
Signature · 1 line
2.53.0
author maintainer
#311 lore raw

PATCH 310/990 perf: Move and enhance has_extended_regs() for arch-specific use

In reply to Greg Kroah-Hartman

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

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

From: Kan Liang <[email protected]>

[ Upstream commit 05fe8825796e6b5557656c6c984486f0e66154fe ]

Move has_extended_regs() to include/linux/perf_event.h so it can be used by arch-specific code.

While moving it, enhance the check logic and rename it to event_has_extended_regs() to match existing perf event helper naming.

Stable-dep-of: b61c12527223 ("perf/amd/ibs: Fix kernel address leak via REGS_USER and REGS_INTR")

---
 include/linux/perf_event.h | 10 ++++++++++
 kernel/events/core.c       |  8 +-------
 2 files changed, 11 insertions(+), 7 deletions(-)
include/linux/perf_event.h +10 -0
index 5fb17c4f52f12..b822fa661d11a 100644
@@ -1528,6 +1528,16 @@ perf_event__output_id_sample(struct perf_event *event,
 extern void
 perf_log_lost_samples(struct perf_event *event, u64 lost);
 
+static inline bool event_has_extended_regs(struct perf_event *event)
+{
+	struct perf_event_attr *attr = &event->attr;
+
+	return ((attr->sample_type & PERF_SAMPLE_REGS_USER) &&
+		(attr->sample_regs_user & PERF_REG_EXTENDED_MASK)) ||
+	       ((attr->sample_type & PERF_SAMPLE_REGS_INTR) &&
+		(attr->sample_regs_intr & PERF_REG_EXTENDED_MASK));
+}
+
 static inline bool event_has_any_exclude_flag(struct perf_event *event)
 {
 	struct perf_event_attr *attr = &event->attr;
kernel/events/core.c +1 -7
index e7e052f62204b..a2f1cb4478263 100644
@@ -12792,12 +12792,6 @@ int perf_pmu_unregister(struct pmu *pmu)
 }
 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
 
-static inline bool has_extended_regs(struct perf_event *event)
-{
-	return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
-	       (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
-}
-
 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
 {
 	struct perf_event_context *ctx = NULL;
@@ -12832,7 +12826,7 @@ static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
 		goto err_pmu;
 
 	if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
-	    has_extended_regs(event)) {
+	    event_has_extended_regs(event)) {
 		ret = -EOPNOTSUPP;
 		goto err_destroy;
 	}
Signature · 1 line
2.53.0
author maintainer
#312 lore raw

PATCH 311/990 perf: Add sampling support for SIMD registers

In reply to Greg Kroah-Hartman

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

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

From: Kan Liang <[email protected]>

[ Upstream commit 918b7d6d1729952d51da4fa81db7b366a207de8f ]

Users may be interested in sampling SIMD registers during profiling. The current sample_regs_* structure does not have sufficient space for all SIMD registers.

To address this, new attribute fields sample_simd_{pred,vec}_reg_* are added to struct perf_event_attr to represent the SIMD registers that are expected to be sampled.

Currently, the perf/x86 code supports XMM registers in sample_regs_*. To unify the configuration of SIMD registers and ensure a consistent method for configuring XMM and other SIMD registers, a new event attribute field, sample_simd_regs_enabled, is introduced. When sample_simd_regs_enabled is set, it indicates that all SIMD registers, including XMM, will be represented by the newly introduced sample_simd_{pred|vec}_reg_* fields. The original XMM space in sample_regs_* is reserved for future uses.

Since SIMD registers are wider than 64 bits, a new output format is introduced. The number and width of SIMD registers are dumped first, followed by the register values. The number and width are based on the user's configuration.

A new ABI, PERF_SAMPLE_REGS_ABI_SIMD, is added to indicate the new format. The enum perf_sample_regs_abi is now a bitmap. This change should not impact existing tools, as the version and bitmap remain the same for values 1 and 2.

Additionally, two new __weak functions are introduced:
- perf_simd_reg_value(): Retrieves the value of the requested SIMD register.
- perf_simd_reg_validate(): Validates the configuration of the SIMD registers.

A new flag, PERF_PMU_CAP_SIMD_REGS, is added to indicate that the PMU supports SIMD register dumping. An error is generated if sample_simd_{pred|vec}_reg_* is mistakenly set for a PMU that does not support this capability.

Stable-dep-of: b61c12527223 ("perf/amd/ibs: Fix kernel address leak via REGS_USER and REGS_INTR")

---
 include/linux/perf_event.h      |  12 +++
 include/linux/perf_regs.h       |   4 +
 include/uapi/linux/perf_event.h |  49 ++++++++++-
 kernel/events/core.c            | 141 +++++++++++++++++++++++++++++---
 4 files changed, 192 insertions(+), 14 deletions(-)
include/linux/perf_event.h +12 -0
index b822fa661d11a..d698a232df114 100644
@@ -306,6 +306,7 @@ struct perf_event_pmu_context;
 #define PERF_PMU_CAP_AUX_PAUSE		0x0200
 #define PERF_PMU_CAP_AUX_PREFER_LARGE	0x0400
 #define PERF_PMU_CAP_MEDIATED_VPMU	0x0800
+#define PERF_PMU_CAP_SIMD_REGS		0x1000
 
 /**
  * pmu::scope
@@ -1528,6 +1529,17 @@ perf_event__output_id_sample(struct perf_event *event,
 extern void
 perf_log_lost_samples(struct perf_event *event, u64 lost);
 
+static inline bool event_has_simd_regs(struct perf_event *event)
+{
+	struct perf_event_attr *attr = &event->attr;
+
+	if (!(event->attr.sample_type &
+	      (PERF_SAMPLE_REGS_INTR | PERF_SAMPLE_REGS_USER)))
+		return false;
+
+	return attr->sample_simd_regs_enabled != 0;
+}
+
 static inline bool event_has_extended_regs(struct perf_event *event)
 {
 	struct perf_event_attr *attr = &event->attr;
include/linux/perf_regs.h +4 -0
index 144bcc3ff19fe..518f28c6a7d4b 100644
@@ -14,6 +14,10 @@ int perf_reg_validate(u64 mask);
 u64 perf_reg_abi(struct task_struct *task);
 void perf_get_regs_user(struct perf_regs *regs_user,
 			struct pt_regs *regs);
+int perf_simd_reg_validate(u16 vec_qwords, u64 vec_mask,
+			   u16 pred_qwords, u32 pred_mask);
+u64 perf_simd_reg_value(struct pt_regs *regs, int idx,
+			u16 qwords_idx, bool pred);
 
 #ifdef CONFIG_HAVE_PERF_REGS
 #include <asm/perf_regs.h>
include/uapi/linux/perf_event.h +45 -4

79 lines not on this page · raw message

kernel/events/core.c +131 -10

226 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#313 lore raw

PATCH 312/990 perf/amd/ibs: Fix kernel address leak via REGS_USER and REGS_INTR

In reply to Greg Kroah-Hartman

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

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

From: Ravi Bangoria <[email protected]>

[ Upstream commit b61c12527223423ab66891b2e8131da0d66537c4 ]

IBS hardware captures a sample and raises an NMI. Since the NMI can be delivered with a delay, a privilege change may occur between sample capture and NMI delivery. Because IBS only provides the sample RIP, the kernel records GPRs from the NMI pt_regs, which may reflect kernel mode if a privilege switch occurred in the interim. This can leak kernel addresses to unprivileged users through PERF_SAMPLE_REGS_USER and/or PERF_SAMPLE_REGS_INTR.

Fix this by using interrupt regs while preparing PERF_SAMPLE_REGS_USER and PERF_SAMPLE_REGS_INTR. With the change, when IBS samples a user mode instruction but the NMI is delivered in kernel mode, PERF_SAMPLE_REGS_USER will source its register state from task_pt_regs(current) and PERF_SAMPLE_REGS_INTR will be omitted from the data sent to userspace.

In addition to fixing the kernel address leak, this change also ensures GPR snapshot consistency, which resolves the DWARF unwinding issue with IBS.

---
 arch/x86/events/amd/ibs.c  | 50 ++++++++++++++++++++++++++++++++++++++
 include/linux/perf_event.h |  6 +++++
 kernel/events/core.c       | 10 ++++----
 3 files changed, 61 insertions(+), 5 deletions(-)
arch/x86/events/amd/ibs.c +50 -0
index 23d834e7b565e..d57b34a72dddf 100644
@@ -1339,6 +1339,56 @@ static int perf_ibs_handle_irq(struct perf_ibs *perf_ibs, struct pt_regs *iregs)
 		throttle = perf_event_account_interrupt(event);
 		goto out;
 	}
+
+	/*
+	 * IBS captured RIP is out of sync with NMI pt_regs due to NMI
+	 * delivery latency. Use NMI pt_regs for PERF_SAMPLE_REGS_USER.
+	 *
+	 * Note: Valid user regs are required for PERF_SAMPLE_STACK_USER.
+	 */
+	if (event->attr.sample_type & (PERF_SAMPLE_REGS_USER |
+				       PERF_SAMPLE_STACK_USER)) {
+		perf_sample_regs_user(&data.regs_user, iregs);
+
+		/*
+		 * Don't update dyn_size if user has not requested for
+		 * PERF_SAMPLE_REGS_USER.
+		 */
+		if (event->attr.sample_type & PERF_SAMPLE_REGS_USER) {
+			/* regs dump ABI info */
+			int size = sizeof(u64);
+
+			if (data.regs_user.regs) {
+				u64 mask = event->attr.sample_regs_user;
+				size += hweight64(mask) * sizeof(u64);
+			}
+
+			data.dyn_size += size;
+		}
+
+		data.sample_flags |= PERF_SAMPLE_REGS_USER;
+	}
+
+	/*
+	 * IBS captured RIP is out of sync with NMI pt_regs due to NMI
+	 * delivery latency. Use NMI pt_regs for PERF_SAMPLE_REGS_INTR.
+	 */
+	if (event->attr.sample_type & PERF_SAMPLE_REGS_INTR) {
+		/* regs dump ABI info */
+		int size = sizeof(u64);
+
+		perf_sample_regs_intr(&data.regs_intr, iregs,
+				      event->attr.exclude_kernel);
+
+		if (data.regs_intr.regs) {
+			u64 mask = event->attr.sample_regs_intr;
+			size += hweight64(mask) * sizeof(u64);
+		}
+
+		data.dyn_size += size;
+		data.sample_flags |= PERF_SAMPLE_REGS_INTR;
+	}
+
 	/*
 	 * Prevent leaking physical addresses to unprivileged users. Skip
 	 * PERF_SAMPLE_PHYS_ADDR check since generic code prevents it for
include/linux/perf_event.h +6 -0
index d698a232df114..23444b1b2503b 100644
@@ -1829,6 +1829,12 @@ extern unsigned long perf_misc_flags(struct perf_event *event, struct pt_regs *r
 extern unsigned long perf_instruction_pointer(struct perf_event *event,
 					      struct pt_regs *regs);
 
+extern void perf_sample_regs_user(struct perf_regs *regs_user,
+				  struct pt_regs *regs);
+extern void perf_sample_regs_intr(struct perf_regs *regs_intr,
+				  struct pt_regs *regs,
+				  bool exclude_kernel);
+
 #ifndef perf_arch_misc_flags
 # define perf_arch_misc_flags(regs) \
 		(user_mode(regs) ? PERF_RECORD_MISC_USER : PERF_RECORD_MISC_KERNEL)
kernel/events/core.c +5 -5
index 42057df334af3..6d3fe508b7406 100644
@@ -7682,8 +7682,8 @@ perf_output_sample_simd_regs(struct perf_output_handle *handle,
 	}
 }
 
-static void perf_sample_regs_user(struct perf_regs *regs_user,
-				  struct pt_regs *regs)
+void perf_sample_regs_user(struct perf_regs *regs_user,
+			   struct pt_regs *regs)
 {
 	if (user_mode(regs)) {
 		regs_user->abi = perf_reg_abi(current);
@@ -7696,9 +7696,9 @@ static void perf_sample_regs_user(struct perf_regs *regs_user,
 	}
 }
 
-static void perf_sample_regs_intr(struct perf_regs *regs_intr,
-				  struct pt_regs *regs,
-				  bool exclude_kernel)
+void perf_sample_regs_intr(struct perf_regs *regs_intr,
+			   struct pt_regs *regs,
+			   bool exclude_kernel)
 {
 	/*
 	 * Hardware skid can lead to a scenario where a PMI is
Signature · 1 line
2.53.0
author maintainer
#314 lore raw

PATCH 313/990 sched/pelt: Fix u32 truncation of the PELT period count

In reply to Greg Kroah-Hartman

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

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

From: Hui Su <[email protected]>

[ Upstream commit a0c755e574e37fddb59edf175f27dc3877e7fe23 ]

accumulate_sum() computes the number of elapsed PELT periods in a u64 but returns u32. When the count is a multiple of 2^32, it is truncated to zero even though the PELT sums have been updated.

The caller interprets zero as no period boundary crossed and skips recomputing the averages, leaving *_avg stale relative to *_sum.

Return the period count as u64 so the caller can test it without truncation.

---
 kernel/sched/pelt.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/sched/pelt.c +1 -1
index fa83bbaf4f3e8..75a48236ec463 100644
@@ -99,7 +99,7 @@ static u32 __accumulate_pelt_segments(u64 periods, u32 d1, u32 d3)
  *      d1 y^p + 1024 \Sum y^n + d3 y^0		(Step 2)
  *                     n=1
  */
-static __always_inline u32
+static __always_inline u64
 accumulate_sum(u64 delta, struct sched_avg *sa,
 	       unsigned long load, unsigned long runnable, int running)
 {
Signature · 1 line
2.53.0
author maintainer
#315 lore raw

PATCH 314/990 sched/topology: Balance cluster static-key updates

In reply to Greg Kroah-Hartman

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

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

From: Hui Su <[email protected]>

[ Upstream commit 5ebdfe12ab96368d0339593129d4ce0bc2bd06f5 ]

build_sched_domains() increments sched_cluster_active once per newly built partition that contains an SD_CLUSTER domain. detach_destroy_domains() instead tested the global static key before decrementing it, so destroying a cluster-less partition could drop a reference owned by another partition and disable cluster-aware scheduling while SD_CLUSTER domains remained installed.

Check the installed domains before detaching them, only while the key is enabled, and decrement only when the removed partition contains an SD_CLUSTER domain.

With two cluster-bearing partitions installed, removing a singleton partition left the baseline count at 1 where 2 partitions still carried SD_CLUSTER; the fixed kernel correctly reports 2. On an asymmetric cluster topology where the parent partition gains no cluster domain, the baseline count drops to 0 while a cluster partition remains installed; the fixed kernel keeps it at 1.

---
 kernel/sched/topology.c | 16 ++++++++++++++--
 1 file changed, 14 insertions(+), 2 deletions(-)
kernel/sched/topology.c +14 -2
index 35478aa2536fc..e3bf754e081c5 100644
@@ -2714,13 +2714,25 @@ int __init sched_init_domains(const struct cpumask *cpu_map)
 static void detach_destroy_domains(const struct cpumask *cpu_map)
 {
 	unsigned int cpu = cpumask_any(cpu_map);
+	bool has_cluster = false;
 	int i;
 
 	if (rcu_access_pointer(per_cpu(sd_asym_cpucapacity, cpu)))
 		static_branch_dec_cpuslocked(&sched_asym_cpucapacity);
 
-	if (static_branch_unlikely(&sched_cluster_active))
-		static_branch_dec_cpuslocked(&sched_cluster_active);
+	if (static_branch_unlikely(&sched_cluster_active)) {
+		rcu_read_lock();
+		for_each_cpu(i, cpu_map) {
+			if (lowest_flag_domain(i, SD_CLUSTER)) {
+				has_cluster = true;
+				break;
+			}
+		}
+		rcu_read_unlock();
+
+		if (has_cluster)
+			static_branch_dec_cpuslocked(&sched_cluster_active);
+	}
 
 	rcu_read_lock();
 	for_each_cpu(i, cpu_map)
Signature · 1 line
2.53.0
author maintainer
#316 lore raw

PATCH 315/990 tcp: bound snd_cwnd_clamp to TCP_MAX_SND_CWND

In reply to Greg Kroah-Hartman

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

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

From: Eric Dumazet <[email protected]>

[ Upstream commit 475ff14ba558bb8857bca878f1d593784ccc4f0f ]

snd_cwnd has no practical upper bound: snd_cwnd_clamp defaults to ~0, and RTAX_INITCWND, a locked RTAX_CWND metric, TCP_BPF_IW and TCP_BPF_SNDCWND_CLAMP accept any positive value.

Congestion control modules do u32 arithmetic on cwnd that assumes much smaller values. For instance, ssthresh() handlers compute:

CUBIC, BIC, ROCCET: cwnd * (BICTCP_BETA_SCALE + beta), up to 2047
DCTCP: cwnd * dctcp_alpha, up to 1024
CDG, NV, CUBIC, ...: cwnd * beta, below 1024

With a large initcwnd route or TCP_BPF_IW, cwnd is set directly to such values, and the next RTO or recovery calls ->ssthresh() with it. The product then wraps: DCTCP with cwnd = 2^24 and alpha = 1024 gets ssthresh == cwnd, and CUBIC computes a wrong ssthresh and Wmax. CUBIC bictcp_update() also expects cwnd below about one million packets.

The paths that can grow cwnd by large amounts (tcp_slow_start(), tcp_cong_avoid_ai(), bbr_set_cwnd() and tcp_init_cwnd()) already bound it by snd_cwnd_clamp, so give snd_cwnd_clamp a finite default of 2^20 packets, and cap the metric and BPF paths that set it or set cwnd directly.

2^20 packets do not limit real flows: with the maximum window scale of 14, a peer can not advertise more than 65535 << 14 bytes (~1GB), which is less than 2^20 packets for any MSS of 1024 bytes or more.

---
 include/net/tcp.h      | 9 +++++++++
 net/core/filter.c      | 3 ++-
 net/ipv4/tcp.c         | 2 +-
 net/ipv4/tcp_metrics.c | 3 ++-
 4 files changed, 14 insertions(+), 3 deletions(-)
include/net/tcp.h +9 -0
index f9bcfa8773a3a..3bf508ceae7b0 100644
@@ -1430,6 +1430,15 @@ static inline unsigned int tcp_packets_in_flight(const struct tcp_sock *tp)
 
 #define TCP_INFINITE_SSTHRESH	0x7fffffff
 
+/* Default and maximum snd_cwnd_clamp, in packets.
+ * A peer can not advertise more than 65535 << 14 bytes, so a larger
+ * cwnd is useless with any MSS of 1024 bytes or more.
+ * Congestion control modules multiply cwnd by u32 factors up to 2047
+ * (cwnd * (BICTCP_BETA_SCALE + beta) in CUBIC), and CUBIC's
+ * bictcp_update() expects cwnd to stay below about one million packets.
+ */
+#define TCP_MAX_SND_CWND	(1U << 20)
+
 static inline u32 tcp_snd_cwnd(const struct tcp_sock *tp)
 {
 	return tp->snd_cwnd;
net/core/filter.c +2 -1
index c6677657656c9..8b76dd1201038 100644
@@ -5498,11 +5498,12 @@ static int bpf_sol_tcp_setsockopt(struct sock *sk, int optname,
 	case TCP_BPF_IW:
 		if (val <= 0 || tp->data_segs_out > tp->syn_data)
 			return -EINVAL;
-		tcp_snd_cwnd_set(tp, val);
+		tcp_snd_cwnd_set(tp, min_t(u32, val, tp->snd_cwnd_clamp));
 		break;
 	case TCP_BPF_SNDCWND_CLAMP:
 		if (val <= 0)
 			return -EINVAL;
+		val = min_t(u32, val, TCP_MAX_SND_CWND);
 		tp->snd_cwnd_clamp = val;
 		WRITE_ONCE(tp->snd_ssthresh, val);
 		break;
net/ipv4/tcp.c +1 -1
index aa860cbd3a442..5f983535bc1d6 100644
@@ -472,7 +472,7 @@ void tcp_init_sock(struct sock *sk)
 	 * initialization of these values.
 	 */
 	tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
-	tp->snd_cwnd_clamp = ~0;
+	tp->snd_cwnd_clamp = TCP_MAX_SND_CWND;
 	tp->mss_cache = TCP_MSS_DEFAULT;
 
 	tp->reordering = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_reordering);
net/ipv4/tcp_metrics.c +2 -1
index 276127902f154..5a83f09cdbd7d 100644
@@ -495,7 +495,8 @@ void tcp_init_metrics(struct sock *sk)
 	}
 
 	if (tcp_metric_locked(tm, TCP_METRIC_CWND))
-		tp->snd_cwnd_clamp = tcp_metric_get(tm, TCP_METRIC_CWND);
+		tp->snd_cwnd_clamp = min(tcp_metric_get(tm, TCP_METRIC_CWND),
+					 TCP_MAX_SND_CWND);
 
 	val = READ_ONCE(net->ipv4.sysctl_tcp_no_ssthresh_metrics_save) ?
 	      0 : tcp_metric_get(tm, TCP_METRIC_SSTHRESH);
Signature · 1 line
2.53.0
author maintainer
#317 lore raw

PATCH 316/990 x86/kcfi: Dont emit KCFI_REFERENCE() in modules

In reply to Greg Kroah-Hartman

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

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

From: Ridge Lomont <[email protected]>

[ Upstream commit fb685de78e6bf79e49854e7d149f69b125583de5 ]

KCFI_REFERENCE() takes the address of a symbol so that the compiler emits its __kcfi_typeid_ symbol, which the SYM_TYPED_FUNC_START() assembly implementing it needs. It is used from arch/x86 headers for __clear_pages_unrolled(), copy_page(), __memset() and __memmove(), and all of that assembly is built into vmlinux.

Modules include the same headers, so with CONFIG_CFI=y every module also gets an __ADDRESSABLE() reference to each of these symbols in .discard.addressable. This serves no purpose there, and since __clear_pages_unrolled() is EXPORT_SYMBOL_GPL, modpost now rejects any GPL-incompatible module that includes <linux/mm.h>:

ERROR: modpost: GPL-incompatible module repro.ko uses GPL-only symbol '__clear_pages_unrolled'

even though the module never uses the symbol. This makes OpenZFS impossible to build against CFI kernels; its configure checks fail in the same way and are misreported as CONFIG_DEBUG_LOCK_ALLOC.

scripts/module.lds.S does not help here: modpost checks <module>.o before the final link, and even after it the discarded section only loses its relocations, the undefined symbols stay in .symtab, where the module loader resolves them with the same license check.

Only emit the reference when building vmlinux.

Tested on x86_64 with clang 23.1.3 and CONFIG_CFI=y, with both CONFIG_LTO_CLANG_FULL=y (the configuration from the Fixes: commit) and CONFIG_LTO_CLANG_THIN=y: vmlinux links without warnings and still contains __kcfi_typeid___clear_pages_unrolled, __kcfi_typeid_copy_page, __kcfi_typeid___memset and __kcfi_typeid___memmove. It boots in QEMU with no CFI failures. A minimal module with MODULE_LICENSE("Proprietary") including <linux/mm.h> fails modpost before this change and builds and loads after it. OpenZFS builds against a CFI kernel with this change, and its pool, encryption, checksum and send/recv operations run without CFI failures, in QEMU and on a desktop with CFI enforcing.

Fixes 9b041a4b66b3 ("x86/mm: Ensure clear_page() variants always have __kcfi_typeid_ symbols")
Assisted-by LLM
---
 include/linux/compiler.h | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
include/linux/compiler.h +5 -2
index 5b45ea7dff3e5..2911b9e622929 100644
@@ -248,10 +248,13 @@ void ftrace_likely_update(struct ftrace_likely_data *f, int val,
 
 #endif /* __KERNEL__ */
 
-#if defined(CONFIG_CFI) && !defined(__DISABLE_EXPORTS) && !defined(BUILD_VDSO)
+#if defined(CONFIG_CFI) && !defined(__DISABLE_EXPORTS) && !defined(BUILD_VDSO) && \
+	!defined(MODULE)
 /*
  * Force a reference to the external symbol so the compiler generates
- * __kcfi_typid.
+ * __kcfi_typid. Only vmlinux needs it, as that is where the assembly
+ * using the typeid lives; in a module it would only add a reference to
+ * the symbol, which fails modpost if the symbol is GPL-only.
  */
 #define KCFI_REFERENCE(sym) __ADDRESSABLE(sym)
 #else
Signature · 1 line
2.53.0
author maintainer
#318 lore raw

PATCH 317/990 net/mlx5e: TC, Fix double free of branch in failure

In reply to Greg Kroah-Hartman

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

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

From: Thomas Fourier <[email protected]>

[ Upstream commit 31f9b43a3bb3d2201eadd147440252d0912dab21 ]

When allocating the false branch fails in parse_branch_ctrl(), the already allocated true branch is freed but attr->branch_true is left pointing to it. The caller parse_tc_actions() fails the flow, and free_flow_post_acts(), mlx5_free_flow_attr_actions() which calls again free_branch_attr() on attr->branch_true.

Clear the pointer after freeing it.

This bug is theoretical and was compile tested only.

Fixes f86488cb4685 ("net/mlx5e: TC, initialize branch flow attributes")
---
 drivers/net/ethernet/mellanox/mlx5/core/en_tc.c | 1 +
 1 file changed, 1 insertion(+)
drivers/net/ethernet/mellanox/mlx5/core/en_tc.c +1 -0
index e2de3a9a647c3..83e3e51420afc 100644
@@ -4013,6 +4013,7 @@ parse_branch_ctrl(struct flow_action_entry *act, struct mlx5e_tc_act *tc_act,
 
 err_branch_false:
 	free_branch_attr(flow, attr->branch_true);
+	attr->branch_true = NULL;
 out_err:
 	return err;
 }
Signature · 1 line
2.53.0
author maintainer
#319 lore raw

PATCH 318/990 locking/osq: Switch osq_wait_next()/atomic_cmpxchg() ordering

In reply to Greg Kroah-Hartman

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

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

From: Peter Zijlstra <[email protected]>

[ Upstream commit 1b9e01fcc47aff00d2fd64693c5dcd620eff5865 ]

The atomic_cmpxchg() in osq_wait_next() removes the current CPU's node from the tail of the queue and puts @old_cpu back.

This is very much like an 'unlock', which is RELEASE, rather than ACQUIRE.

Additionally, on success (the only case where the ordering is effective), this returns NULL which means both callsites will do nothing more, there are no subsequent operations to order against.

Furthermore, the osq_lock() caller will then return false, indicating failure to acquire -- the mutex must go block. Again, not making a case for ACQUIRE. Neither atomics nor locks provide ordering on failure.

Since ACQUIRE makes no sense, while RELEASE makes it more symmetric with osq_unlock(), switch the ordering. This then makes osq_unlock() consistently RELEASE.

Fixes c55a6ffa6285 ("locking/osq: Relax atomic semantics")
Cc Linus Torvalds <[email protected]>
Cc Waiman Long <[email protected]>
---
 kernel/locking/osq_lock.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/locking/osq_lock.c +1 -1
index b4233dc2c2b04..98b12d7b79964 100644
@@ -59,7 +59,7 @@ osq_wait_next(struct optimistic_spin_queue *lock,
 
 	for (;;) {
 		if (atomic_read(&lock->tail) == curr &&
-		    atomic_cmpxchg_acquire(&lock->tail, curr, old_cpu) == curr) {
+		    atomic_cmpxchg_release(&lock->tail, curr, old_cpu) == curr) {
 			/*
 			 * We were the last queued, we moved @lock back. @prev
 			 * will now observe @lock and will complete its
Signature · 1 line
2.53.0
author maintainer
#320 lore raw

PATCH 319/990 locking/osq: Fix unlink queue corruption

In reply to Greg Kroah-Hartman

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

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

From: Peter Zijlstra <[email protected]>

[ Upstream commit 408b129aac48b574c0c9d11137a89eefba825d5d ]

Very similar to commit 50972fe78f24 ("locking/osq_lock: Fix osq_lock queue corruption"), make sure to order the prev->next store against the next->prev store.

Fixes 50972fe78f24 ("locking/osq_lock: Fix osq_lock queue corruption")
Cc Linus Torvalds <[email protected]>
Cc Waiman Long <[email protected]>
---
 kernel/locking/osq_lock.c | 60 +++++++++++++++++++++++++++++----------
 1 file changed, 45 insertions(+), 15 deletions(-)
kernel/locking/osq_lock.c +45 -15
index 98b12d7b79964..2bcc148eb2ddb 100644
@@ -90,6 +90,49 @@ osq_wait_next(struct optimistic_spin_queue *lock,
 	}
 }
 
+/*
+ * Set prev->next; this is the counterpart of osq_wait_next() in that
+ * by setting ->next the wait is terminated and progress is resumed.
+ */
+static inline void osq_link_next(struct optimistic_spin_node *prev,
+				 struct optimistic_spin_node *next)
+{
+	/*
+	 * Suppose:
+	 *
+	 *                   tail
+	 *                    |
+	 *                    V
+	 *   CPU1 -> CPU2 -> CPU3:
+	 *   n: 2    n: 3    n: nil
+	 *   p: nil  p: 1    p: 2
+	 *
+	 * And this is CPU2 doing the self-unqueue concurrent against CPU1s
+	 * unlock()/unqueue(). Since 'prev->next == NULL' and CPU1 will be
+	 * stuck in osq_wait_next() until the below store of 'prev->next'.
+	 *
+	 * CPU2				CPU1
+	 *
+	 * next->prev = prev;		osq_wait_next()
+	 * WMB				MB
+	 * prev->next = next;		next->prev = prev
+	 *
+	 * Without the WMB it would be possible to have conflicting stores
+	 * like:
+	 *
+	 * CPU2				CPU1
+	 *
+	 * prev->next = next // CPU1.n = 3
+	 *				next = osq_wait_next() // = 3
+	 *				next->prev = prev // CPU3.p = nil
+	 * next->prev = prev // CPU3.p = 1
+	 *
+	 * Which would result in list corruption.
+	 */
+	smp_wmb();
+	WRITE_ONCE(prev->next, next);
+}
+
 bool osq_lock(struct optimistic_spin_queue *lock)
 {
 	struct optimistic_spin_node *node = this_cpu_ptr(&osq_node);
@@ -113,20 +156,7 @@ bool osq_lock(struct optimistic_spin_queue *lock)
 
 	prev = decode_cpu(old);
 	node->prev = prev;
-
-	/*
-	 * osq_lock()			unqueue
-	 *
-	 * node->prev = prev		osq_wait_next()
-	 * WMB				MB
-	 * prev->next = node		next->prev = prev // unqueue-C
-	 *
-	 * Here 'node->prev' and 'next->prev' are the same variable and we need
-	 * to ensure these stores happen in-order to avoid corrupting the list.
-	 */
-	smp_wmb();
-
-	WRITE_ONCE(prev->next, node);
+	osq_link_next(prev, node);
 
 	/*
 	 * Normally @prev is untouchable after the above store; because at that
@@ -202,7 +232,7 @@ bool osq_lock(struct optimistic_spin_queue *lock)
 	 */
 
 	WRITE_ONCE(next->prev, prev);
-	WRITE_ONCE(prev->next, next);
+	osq_link_next(prev, next);
 
 	return false;
 }
Signature · 1 line
2.53.0
author maintainer
#321 lore raw

PATCH 320/990 perf/x86/amd/uncore: Avoid context migration from non-owners

In reply to Greg Kroah-Hartman

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

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

From: Sandipan Das <[email protected]>

[ Upstream commit 0ae655bce1934857fa3e316ddcb4be38c30dbd38 ]

Each uncore context is owned by a single CPU that hosts all events for the corresponding uncore domain and is advertised through the sysfs cpumask attribute. When a CPU goes offline, the context is migrated to an online sibling if the departing CPU is the owner.

Before commit d6389d3ccc13 ("perf/x86/amd/uncore: Refactor uncore management"), uncore_down_prepare() checked whether the CPU going offline owned the context. The check was lost when the function was replaced by amd_uncore_ctx_move(). Hence, when a CPU that is not the owner goes offline, ownership is always handed over to the first online sibling in the uncore domain irrespective of whether another sibling already owns it. This goes unnoticed as long as the owner is the lowest-numbered online CPU in the domain, since the first online sibling is then the owner itself. Once ownership has moved, that no longer holds.

For example, consider an L3 domain spanning CPUs 8-15,136-143 and owned by CPU 8.

  $ cat /sys/bus/event_source/devices/amd_l3/cpumask
  0,8,16,24,32,40,48,56,64,72,80,88,96,104,112,120
  $ echo 0 | sudo tee /sys/devices/system/cpu/cpu8/online
  $ cat /sys/bus/event_source/devices/amd_l3/cpumask
  0,9,16,24,32,40,48,56,64,72,80,88,96,104,112,120
  $ echo 1 | sudo tee /sys/devices/system/cpu/cpu8/online
  $ cat /sys/bus/event_source/devices/amd_l3/cpumask
  0,9,16,24,32,40,48,56,64,72,80,88,96,104,112,120
  $ echo 0 | sudo tee /sys/devices/system/cpu/cpu10/online
  $ cat /sys/bus/event_source/devices/amd_l3/cpumask
  0,8-9,16,24,32,40,48,56,64,72,80,88,96,104,112,120

Offlining CPU 8 correctly moves ownership to CPU 9 and onlining it again leaves CPU 9 as the owner. However, offlining CPU 10 then makes CPU 8 the owner while existing events remain on CPU 9. Both CPUs are now advertised for the same domain, so tools that open an event on every CPU in the cpumask count the domain twice, and the context gets modified from two CPUs without any synchronization.

Restore the ownership check that was lost during the refactor.

---
 arch/x86/events/amd/uncore.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/x86/events/amd/uncore.c +1 -1
index c960481222727..8714e4b36ff31 100644
@@ -609,7 +609,7 @@ static void amd_uncore_ctx_move(struct amd_uncore *uncore, unsigned int cpu)
 	for (i = 0; i < uncore->num_pmus; i++) {
 		pmu = &uncore->pmus[i];
 		curr = *per_cpu_ptr(pmu->ctx, cpu);
-		if (!curr)
+		if (!curr || curr->cpu != cpu)
 			continue;
 
 		/* Migrate to a shared sibling if possible */
Signature · 1 line
2.53.0
author maintainer
#322 lore raw

PATCH 321/990 perf: Fix racy update of cpc->hrtimer_interval

In reply to Greg Kroah-Hartman

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

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

From: Benjamin Segall <[email protected]>

[ Upstream commit 3bbd85b2f67aff58f2cbec9a7fb705677b94473b ]

Updates to cpc->hrtimer_interval can race with reads either in the hrtimer itself, or other calls to perf_mux_hrtimer_restart. This is not exactly expected to be a common config change, but it's easy enough to fix.

Since there's already an IPI to each cpu to restart the timer, and all reads are with irqs disabled, just move the update onto the target cpu.

---
 kernel/events/core.c | 22 +++++++++++-----------
 1 file changed, 11 insertions(+), 11 deletions(-)
kernel/events/core.c +11 -11
index 6d3fe508b7406..0f367ffef6deb 100644
@@ -1231,14 +1231,19 @@ static int perf_mux_hrtimer_restart(struct perf_cpu_pmu_context *cpc)
 	return 0;
 }
 
-static int perf_mux_hrtimer_restart_ipi(void *arg)
+static __always_inline struct perf_cpu_pmu_context *this_cpc(struct pmu *pmu)
 {
-	return perf_mux_hrtimer_restart(arg);
+	return *this_cpu_ptr(pmu->cpu_pmu_context);
 }
 
-static __always_inline struct perf_cpu_pmu_context *this_cpc(struct pmu *pmu)
+static int perf_mux_hrtimer_interval_ipi(void *arg)
 {
-	return *this_cpu_ptr(pmu->cpu_pmu_context);
+	struct pmu *pmu = arg;
+	struct perf_cpu_pmu_context *cpc = this_cpc(pmu);
+	int ms = pmu->hrtimer_interval_ms;
+
+	cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * ms);
+	return perf_mux_hrtimer_restart(cpc);
 }
 
 void perf_pmu_disable(struct pmu *pmu)
@@ -12453,13 +12458,8 @@ perf_event_mux_interval_ms_store(struct device *dev,
 
 	/* update all cpuctx for this PMU */
 	cpus_read_lock();
-	for_each_online_cpu(cpu) {
-		struct perf_cpu_pmu_context *cpc;
-		cpc = *per_cpu_ptr(pmu->cpu_pmu_context, cpu);
-		cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
-
-		cpu_function_call(cpu, perf_mux_hrtimer_restart_ipi, cpc);
-	}
+	for_each_online_cpu(cpu)
+		cpu_function_call(cpu, perf_mux_hrtimer_interval_ipi, pmu);
 	cpus_read_unlock();
 	mutex_unlock(&mux_interval_mutex);
 
Signature · 1 line
2.53.0
author maintainer
#323 lore raw

PATCH 322/990 iommu/amd: Clear amd_iommu_snp_en if snp_rmptable_init() fails

In reply to Greg Kroah-Hartman

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

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

From: Dheeraj Kumar Srivastava <[email protected]>

[ Upstream commit ec91bb159dc24eefe144ef8867937f4a055dd0e2 ]

iommu_snp_enable() checks that the IOMMU can support SNP and sets amd_iommu_snp_en, then calls snp_rmptable_init() to map the RMP table. If that call fails, CC_ATTR_HOST_SEV_SNP is cleared but amd_iommu_snp_en is left set. Later IOMMU initialization uses amd_iommu_snp_en to configure the IOMMU for SNP, on the assumption that RMP setup succeeded.

Clear amd_iommu_snp_en along with CC_ATTR_HOST_SEV_SNP.

Fixes 409f45387c93 ("x86/sev: Fix broken SNP support with KVM module built-in")
---
 drivers/iommu/amd/init.c | 1 +
 1 file changed, 1 insertion(+)
drivers/iommu/amd/init.c +1 -0
index c4694ff364dbf..3768be55b8e67 100644
@@ -3486,6 +3486,7 @@ static __init void iommu_snp_enable(void)
 	return;
 
 disable_snp:
+	amd_iommu_snp_en = false;
 	cc_platform_clear(CC_ATTR_HOST_SEV_SNP);
 #endif
 }
Signature · 1 line
2.53.0
author maintainer
#324 lore raw

PATCH 323/990 cpufreq: Return -EOPNOTSUPP if no policy supports boost

In reply to Greg Kroah-Hartman

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

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

From: Lifeng Zheng <[email protected]>

[ Upstream commit 77cf053b041fe13d1fdd2e572e16ee7776ff687d ]

In cpufreq_boost_trigger_state(), if none of the the policies support boost, policy_set_boost() will not be called and this function will return 0.

But it is better to return an error to indicate that the platform doesn't support boost.

Stable-dep-of: a0cde2b601bc ("cpufreq: Preserve global boost state on failed updates")

---
 drivers/cpufreq/cpufreq.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/cpufreq/cpufreq.c +5 -1
index 002afd47d2d59..46cf3d49b0636 100644
@@ -2809,7 +2809,7 @@ static int cpufreq_boost_trigger_state(int state)
 {
 	struct cpufreq_policy *policy;
 	unsigned long flags;
-	int ret = 0;
+	int ret = -EOPNOTSUPP;
 
 	/*
 	 * Don't compare 'cpufreq_driver->boost_enabled' with 'state' here to
@@ -2831,6 +2831,10 @@ static int cpufreq_boost_trigger_state(int state)
 		if (ret)
 			goto err_reset_state;
 	}
+
+	if (ret)
+		goto err_reset_state;
+
 	cpus_read_unlock();
 
 	return 0;
Signature · 1 line
2.53.0